diff --git a/android/build.gradle b/android/build.gradle index e723adba..39ec218a 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -1,5 +1,5 @@ buildscript { - ext.kotlin_version = '1.7.20' + ext.kotlin_version = '1..20' repositories { google() jcenter() @@ -42,7 +42,7 @@ subprojects { project.evaluationDependsOn(':app') } -task clean(type: Delete) { +tasks.register("clean", Delete) { delete rootProject.buildDir } diff --git a/flutter_tts-voice_enhancement/.github/ISSUE_TEMPLATE/bug_report.md b/flutter_tts-voice_enhancement/.github/ISSUE_TEMPLATE/bug_report.md deleted file mode 100644 index 614a6708..00000000 --- a/flutter_tts-voice_enhancement/.github/ISSUE_TEMPLATE/bug_report.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -name: Bug report -about: Create a report to help us improve - ---- - -## 🐛 Bug Report - - - -### Expected behavior - -### Reproduction steps - -### Configuration - -**Version:** 0.1.x - -**Platform:** -- [ ] :iphone: iOS -- [ ] :robot: Android diff --git a/flutter_tts-voice_enhancement/.github/ISSUE_TEMPLATE/feature_request.md b/flutter_tts-voice_enhancement/.github/ISSUE_TEMPLATE/feature_request.md deleted file mode 100644 index 35a881a3..00000000 --- a/flutter_tts-voice_enhancement/.github/ISSUE_TEMPLATE/feature_request.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -name: Feature request -about: Suggest an idea for this project - ---- - -## 🚀 Feature Requests - - - -### Contextualize the feature - - -### Describe the feature - - -### Platforms affected (mark all that apply) -- [ ] :iphone: iOS -- [ ] :robot: Android diff --git a/flutter_tts-voice_enhancement/.github/ISSUE_TEMPLATE/questions-and-help.md b/flutter_tts-voice_enhancement/.github/ISSUE_TEMPLATE/questions-and-help.md deleted file mode 100644 index ba501f3c..00000000 --- a/flutter_tts-voice_enhancement/.github/ISSUE_TEMPLATE/questions-and-help.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -name: Questions and Help -about: If you have questions, please use this for support - ---- - -## 💬 Questions and Help - -Provide question related to this flutter plugin. diff --git a/flutter_tts-voice_enhancement/.github/workflows/main.yml b/flutter_tts-voice_enhancement/.github/workflows/main.yml deleted file mode 100644 index 832dd069..00000000 --- a/flutter_tts-voice_enhancement/.github/workflows/main.yml +++ /dev/null @@ -1,34 +0,0 @@ -name: github pages - -on: - push: - branches: - - master - -jobs: - deploy: - runs-on: ubuntu-18.04 - steps: - - uses: actions/checkout@v2 - - - name: Setup Flutter - run: | - git clone https://github.com/flutter/flutter.git --depth 1 -b beta _flutter - echo "::add-path::${GITHUB_WORKSPACE}/_flutter/bin" - - - name: Install - run: | - cd example - flutter config --enable-web - flutter pub get - - - name: Build - run: | - cd example - flutter build web - - - name: Deploy - uses: peaceiris/actions-gh-pages@v3 - with: - github_token: ${{ secrets.GITHUB_TOKEN }} - publish_dir: ./example/build/web diff --git a/flutter_tts-voice_enhancement/.gitignore b/flutter_tts-voice_enhancement/.gitignore deleted file mode 100644 index bc0883df..00000000 --- a/flutter_tts-voice_enhancement/.gitignore +++ /dev/null @@ -1,94 +0,0 @@ -# Miscellaneous -*.class -*.lock -*.log -*.pyc -*.swp -.DS_Store -.atom/ -.buildlog/ -.history -.project -.svn/ -bin/ - -# IntelliJ related -*.iml -*.ipr -*.iws -.idea/ - -# Android Studio related -android/.classpath -android/.settings/ - -# Visual Studio Code related -.vscode/ - -# Flutter repo-specific -/bin/cache/ -/bin/mingit/ -/dev/benchmarks/mega_gallery/ -/dev/bots/.recipe_deps -/dev/bots/android_tools/ -/dev/docs/doc/ -/dev/docs/lib/ -/dev/docs/pubspec.yaml -/packages/flutter/coverage/ -version - -# Flutter/Dart/Pub related -**/doc/api/ -.dart_tool/ -.flutter-plugins -.packages -.pub-cache/ -.pub/ -build/ -flutter_*.png -linked_*.ds -unlinked.ds -unlinked_spec.ds - -# Android related -**/android/**/gradle-wrapper.jar -**/android/.gradle -**/android/captures/ -**/android/gradlew -**/android/gradlew.bat -**/android/local.properties -**/android/**/GeneratedPluginRegistrant.java - -# iOS/XCode related -**/ios/**/*.mode1v3 -**/ios/**/*.mode2v3 -**/ios/**/*.moved-aside -**/ios/**/*.pbxuser -**/ios/**/*.perspectivev3 -**/ios/**/*sync/ -**/ios/**/.sconsign.dblite -**/ios/**/.tags* -**/ios/**/.vagrant/ -**/ios/**/DerivedData/ -**/ios/**/Icon? -**/ios/**/Pods/ -**/ios/**/.symlinks/ -**/ios/**/profile -**/ios/**/xcuserdata -**/ios/.generated/ -**/ios/Flutter/App.framework -**/ios/Flutter/Flutter.framework -**/ios/Flutter/Generated.xcconfig -**/ios/Flutter/app.flx -**/ios/Flutter/app.zip -**/ios/Flutter/flutter_assets/ -**/ios/ServiceDefinitions.json -**/ios/Runner/GeneratedPluginRegistrant.* - -# Exceptions to above rules. -!**/ios/**/default.mode1v3 -!**/ios/**/default.mode2v3 -!**/ios/**/default.pbxuser -!**/ios/**/default.perspectivev3 -!/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages -example/ios/Flutter/flutter_export_environment.sh diff --git a/flutter_tts-voice_enhancement/CHANGELOG.md b/flutter_tts-voice_enhancement/CHANGELOG.md deleted file mode 100644 index bff8b759..00000000 --- a/flutter_tts-voice_enhancement/CHANGELOG.md +++ /dev/null @@ -1,197 +0,0 @@ -# ChangeLog - -## 1.3.0 - -- All: Adding await speak completion - -## 1.2.7 - -- iOS: Adding utterance settings to synthesizeToFile -- Android: Fix crash when utterance completes after Engine is detached - -## 1.2.6 - -- Android: Fixing new API onAttachedToEngine call - -## 1.2.5 - -- macOS: Adding support - -## 1.2.4 - -- iOS: Deactivate audio session only when needed -- Android: Better exception handling for getLanguages -- Android: Adding getEngines -- Android: Adding new Android plugin APIs - -## 1.2.3 - -- iOS: Adding synthesize to file -- iOS: Fix set category ios - -## 1.2.2 - -- Web: Adding pause and continue - -## 1.2.1 - -- iOS: Fix setting iOS Category -- iOS/Android: Adding additional platform calls - -## 1.2.0 - -- iOS: Adding Set Audio Session Category -- Android: Bug fixes - -## 1.1.0 - -- iOS: Adding Pause -- iOS: Adding set Shared Instance - -## 1.0.0 - -- iOS/Android: Feature - Speech marks -- iOS/Android: Breaking changes to Speech rate - -## 0.9.2 - -- iOS: Changing audio session to playAndRecord - -## 0.9.1 - -- Android: Fixing method call error - -## 0.9.0 - -- Android: Adding synthesize to file - -## 0.8.7 - -- Android: Fix sporadic ANR on initialization - -## 0.8.6 - -- iOS: Reducing volume of other sessions while TTS is playing - -## 0.8.5 - -- Android: Fix Android async platform initialization -- Android: Removing initHandler - -## 0.8.2 - -- Web: Adding isLanguageAvailable method -- All: Fixing isLanguageAvailable platform channel and making it case insensitive - -## 0.8.0 - -- Web: Adding Web Support - -## 0.7.0 - -- iOS: Adding Swift version 4.2 to podspec and correct audio playback category - -## 0.6.0 - -- Android: AndroidX support - -## 0.5.2 - -- Android: Bug Fix on isLanguageAvailable - -## 0.5.1 - -- Applying flutter format to fix health suggestion - -## 0.5.0 - -- Android: Adding silence before speak -- Android: Removing deprecated API - -## 0.2.6 - -- IOS: Add voice selection implementation - -## 0.2.5 - -- Android: Ensure invokeMethod runs on main thread - -## 0.2.4 - -- Android: setting minSDK back to 21 and adding instructions to readme -- Android: Adding fallback for getLanguages and defaultLanguage - -## 0.2.3 - -- IOS: Audio continues with the Ring/Silent switch set to silent - -## 0.2.2 - -- Android: Fixing Locale bug - -## 0.2.1 - -- IOS: Fixing getLanguages bug - -## 0.2.0 - -- Android: Adding exception catch for samsung devices -- Android: Using default com.google.android.tts engine -- Android: Get and Set Voice -- Android: InitHandler -- Cleaning up the example - -## 0.1.2 - -- Support for Android background execution -- Updating Android build gradle version to 3.2.1 - -## 0.1.1 - -- Fixing TTS bound error in the example -- Fixing default voice language not found error on Android - -## 0.1.0 - -- Updating version for improved maintenance score -- Updating package description for improved maintenance score - -## 0.0.8 - -- Adding analysis_options.yaml for improved health score -- Fixing info/errors from flutter analyze - -## 0.0.7 - -- Updating SDK version in pubspec.yaml -- Adding package link to README -- Fixing language string warning received from xcode - -## 0.0.6 - -- Android: Upgrading Gradle 4.1 to 4.4 -- Android: Setting minSdk version to 21 -- Android: Adding try/catch to getAvailableLanguages & getDefaultVoice methods (Issues with API 21 & 22) - -## 0.0.5 - -- Adding IOS/Android isLanguageAvailable -- Rename setRate to setSpeechRate - -## 0.0.4 - -- Simplify podspec for Cocoapods 1.5.0 - -## 0.0.3 - -- Adding IOS/Android speech pitch and volume - -## 0.0.2 - -- Flutter formatting and fixing pubspec sdk versioning - -## 0.0.1 - -- first POC : - - methods : speak, stop, setRate, setLangauge, getLanguages - - a globalHandler for completion diff --git a/flutter_tts-voice_enhancement/CODE_OF_CONDUCT.md b/flutter_tts-voice_enhancement/CODE_OF_CONDUCT.md deleted file mode 100644 index 43989576..00000000 --- a/flutter_tts-voice_enhancement/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,46 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at eyedea32@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ diff --git a/flutter_tts-voice_enhancement/LICENSE b/flutter_tts-voice_enhancement/LICENSE deleted file mode 100644 index 56dcdf22..00000000 --- a/flutter_tts-voice_enhancement/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2018 Daniel Lutton - -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/flutter_tts-voice_enhancement/README.md b/flutter_tts-voice_enhancement/README.md deleted file mode 100644 index 4e32d45d..00000000 --- a/flutter_tts-voice_enhancement/README.md +++ /dev/null @@ -1,194 +0,0 @@ -# Text To Speech - -[![pub package](https://img.shields.io/pub/v/flutter_tts.svg?style=for-the-badge&colorB=green)](https://pub.dartlang.org/packages/flutter_tts) - -A flutter text to speech plugin (Swift,Java) - -## Features - -- [x] Android, iOS, Web, & macOS - - [x] speak - - [x] stop - - [x] get languages - - [x] set language - - [x] set speech rate - - [x] set speech volume - - [x] set speech pitch - - [x] is language available -- [x] Android, iOS - - [x] get voices - - [x] set voice - - [x] speech marks (requires iOS 7+ and Android 26+) - - [x] synthesize to file (requires iOS 13+) -- [x] iOS, Web - - [x] pause -- [x] Android - - [x] set Silence -- [x] iOS - - [x] set shared instance - - [x] set audio session category - -## Usage - -## macOS - -```bash -OSX version: 10.15 -``` - -[Example App](https://github.com/dlutton/flutter_tts/tree/macOS_app) from the macOS_app branch - -## Web - -[Website](https://dlutton.github.io/flutter_tts) from the example directory. - -## Android - -Change the minimum Android sdk version to 21 (or higher) in your `android/app/build.gradle` file. - -```java -minSdkVersion 21 -``` - -## iOS - -There's a known issue with integrating plugins that use Swift into a Flutter project created with the Objective-C template. [Flutter#16049](https://github.com/flutter/flutter/issues/16049) - -[Example](https://github.com/dlutton/flutter_tts/blob/master/example/lib/main.dart) - -To use this plugin : - -- add the dependency to your [pubspec.yaml](https://github.com/dlutton/flutter_tts/blob/master/example/pubspec.yaml) file. - -```yaml - dependencies: - flutter: - sdk: flutter - flutter_tts: -``` - -- instantiate FlutterTts - -```dart -FlutterTts flutterTts = FlutterTts(); - -``` - -To set shared audio [instance](https://developer.apple.com/documentation/avfoundation/avaudiosession/1616504-sharedinstance) (iOS only): - -```dart -await flutterTts.setSharedInstance(true); -``` - -To set audio [category and options](https://developer.apple.com/documentation/avfoundation/avaudiosession) (iOS only): - -```dart -await flutterTts - .setIosAudioCategory(IosTextToSpeechAudioCategory.playAndRecord, [ - IosTextToSpeechAudioCategoryOptions.allowBluetooth, - IosTextToSpeechAudioCategoryOptions.allowBluetoothA2DP, - IosTextToSpeechAudioCategoryOptions.mixWithOthers - ]); -``` - -To await speak completion. - -```dart -await flutterTts.awaitSpeakCompletion(true); -``` - -### speak, stop, getLanguages, setLanguage, setSpeechRate, setVoice, setVolume, setPitch, isLanguageAvailable, setSharedInstance - -```dart -Future _speak() async{ - var result = await flutterTts.speak("Hello World"); - if (result == 1) setState(() => ttsState = TtsState.playing); -} - -Future _stop() async{ - var result = await flutterTts.stop(); - if (result == 1) setState(() => ttsState = TtsState.stopped); -} - -List languages = await flutterTts.getLanguages; - -await flutterTts.setLanguage("en-US"); - -await flutterTts.setSpeechRate(1.0); - -await flutterTts.setVolume(1.0); - -await flutterTts.setPitch(1.0); - -await flutterTts.isLanguageAvailable("en-US"); - -// iOS and Web only -await flutterTts.pause(); - -// iOS, macOS, and Android only -await flutterTts.synthesizeToFile("Hello World", Platform.isAndroid ? "tts.wav" : "tts.caf"); - -await flutterTts.setVoice({"name": "Karen", "locale": "en-AU"}); - -// iOS only -await flutterTts.setSharedInstance(true); - -// Android only -await flutterTts.setSilence(2); - -await flutterTts.getEngines(); -``` - -### Listening for platform calls - -```dart -flutterTts.setStartHandler(() { - setState(() { - ttsState = TtsState.playing; - }); -}); - -flutterTts.setCompletionHandler(() { - setState(() { - ttsState = TtsState.stopped; - }); -}); - -flutterTts.setProgressHandler((String text, int startOffset, int endOffset, String word) { - setState(() { - _currentWord = word; - }); -}); - -flutterTts.setErrorHandler((msg) { - setState(() { - ttsState = TtsState.stopped; - }); -}); - -flutterTts.setCancelHandler((msg) { - setState(() { - ttsState = TtsState.stopped; - }); -}); - -// iOS and Web -flutterTts.setPauseHandler((msg) { - setState(() { - ttsState = TtsState.paused; - }); -}); - -flutterTts.setContinueHandler((msg) { - setState(() { - ttsState = TtsState.continued; - }); -}); -``` - -## Getting Started - -For help getting started with Flutter, view our online -[documentation](https://flutter.dev/). - -For help on editing plugin code, view the [documentation](https://flutter.dev/platform-plugins/#edit-code). diff --git a/flutter_tts-voice_enhancement/analysis_options.yaml b/flutter_tts-voice_enhancement/analysis_options.yaml deleted file mode 100644 index e8779c50..00000000 --- a/flutter_tts-voice_enhancement/analysis_options.yaml +++ /dev/null @@ -1,35 +0,0 @@ -analyzer: - strong-mode: - implicit-casts: false - errors: - unused_import: error - unused_local_variable: error - dead_code: error -linter: - rules: - - avoid_empty_else - - comment_references - - control_flow_in_finally - - empty_statements - - hash_and_equals - - only_throw_errors - - test_types_in_equals - - throw_in_finally - - unrelated_type_equality_checks - - valid_regexps - - avoid_init_to_null - - avoid_return_types_on_setters - - await_only_futures - - camel_case_types - - directives_ordering - - empty_catches - - empty_constructor_bodies - - library_names - - library_prefixes - - non_constant_identifier_names - - omit_local_variable_types - - prefer_final_fields - - prefer_is_not_empty - - prefer_typing_uninitialized_variables - - slash_for_doc_comments - - type_init_formals \ No newline at end of file diff --git a/flutter_tts-voice_enhancement/android/.gitignore b/flutter_tts-voice_enhancement/android/.gitignore deleted file mode 100644 index c6cbe562..00000000 --- a/flutter_tts-voice_enhancement/android/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -*.iml -.gradle -/local.properties -/.idea/workspace.xml -/.idea/libraries -.DS_Store -/build -/captures diff --git a/flutter_tts-voice_enhancement/android/build.gradle b/flutter_tts-voice_enhancement/android/build.gradle deleted file mode 100644 index 1308c920..00000000 --- a/flutter_tts-voice_enhancement/android/build.gradle +++ /dev/null @@ -1,48 +0,0 @@ -def PLUGIN = "flutter_tts"; -def ANDROIDX_WARNING = "flutterPluginsAndroidXWarning"; -gradle.buildFinished { buildResult -> - if (buildResult.failure && !rootProject.ext.has(ANDROIDX_WARNING)) { - println ' *********************************************************' - println 'WARNING: This version of ' + PLUGIN + ' will break your Android build if it or its dependencies aren\'t compatible with AndroidX.' - println ' See https://goo.gl/CP92wY for more information on the problem and how to fix it.' - println ' This warning prints for all Android build failures. The real root cause of the error may be unrelated.' - println ' *********************************************************' - rootProject.ext.set(ANDROIDX_WARNING, true); - } -} - -group 'com.tundralabs.fluttertts' -version '1.0-SNAPSHOT' - -buildscript { - repositories { - google() - jcenter() - } - - dependencies { - classpath 'com.android.tools.build:gradle:3.4.2' - } -} - -rootProject.allprojects { - repositories { - google() - jcenter() - } -} - -apply plugin: 'com.android.library' - -android { - compileSdkVersion 28 - - defaultConfig { - minSdkVersion 21 - testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" - targetSdkVersion 27 - } - lintOptions { - disable 'InvalidPackage' - } -} diff --git a/flutter_tts-voice_enhancement/android/gradle.properties b/flutter_tts-voice_enhancement/android/gradle.properties deleted file mode 100644 index a6738207..00000000 --- a/flutter_tts-voice_enhancement/android/gradle.properties +++ /dev/null @@ -1,4 +0,0 @@ -org.gradle.jvmargs=-Xmx1536M -android.useAndroidX=true -android.enableJetifier=true -android.enableR8=true diff --git a/flutter_tts-voice_enhancement/android/gradle/wrapper/gradle-wrapper.properties b/flutter_tts-voice_enhancement/android/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 8d9c8a3f..00000000 --- a/flutter_tts-voice_enhancement/android/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,6 +0,0 @@ -#Fri Sep 27 12:18:40 PDT 2019 -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zip diff --git a/flutter_tts-voice_enhancement/android/settings.gradle b/flutter_tts-voice_enhancement/android/settings.gradle deleted file mode 100644 index 26aeb433..00000000 --- a/flutter_tts-voice_enhancement/android/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = 'flutter_tts' diff --git a/flutter_tts-voice_enhancement/android/src/main/AndroidManifest.xml b/flutter_tts-voice_enhancement/android/src/main/AndroidManifest.xml deleted file mode 100644 index 9cad3a1b..00000000 --- a/flutter_tts-voice_enhancement/android/src/main/AndroidManifest.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - diff --git a/flutter_tts-voice_enhancement/android/src/main/java/com/tundralabs/fluttertts/FlutterTtsPlugin.java b/flutter_tts-voice_enhancement/android/src/main/java/com/tundralabs/fluttertts/FlutterTtsPlugin.java deleted file mode 100644 index 92e6a092..00000000 --- a/flutter_tts-voice_enhancement/android/src/main/java/com/tundralabs/fluttertts/FlutterTtsPlugin.java +++ /dev/null @@ -1,454 +0,0 @@ -package com.tundralabs.fluttertts; - -import android.content.Context; -import android.os.Build; -import android.os.Bundle; -import android.os.Handler; -import android.os.Looper; -import android.speech.tts.TextToSpeech; -import android.speech.tts.UtteranceProgressListener; -import android.speech.tts.Voice; -import android.util.Log; -import androidx.annotation.NonNull; -import io.flutter.embedding.engine.plugins.FlutterPlugin; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugin.common.MethodCall; -import io.flutter.plugin.common.MethodChannel; -import io.flutter.plugin.common.MethodChannel.MethodCallHandler; -import io.flutter.plugin.common.MethodChannel.Result; -import io.flutter.plugin.common.PluginRegistry.Registrar; -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Locale; -import java.util.MissingResourceException; -import java.util.UUID; - -/** FlutterTtsPlugin */ -public class FlutterTtsPlugin implements MethodCallHandler, FlutterPlugin { - private Handler handler; - private MethodChannel methodChannel; - private MethodChannel.Result speakResult; - private boolean awaitSpeakCompletion = false; - private boolean speaking = false; - private Context context; - private TextToSpeech tts; - private final String tag = "TTS"; - private final String googleTtsEngine = "com.google.android.tts"; - private boolean isTtsInitialized = false; - private ArrayList pendingMethodCalls = new ArrayList<>(); - private final HashMap utterances = new HashMap<>(); - Bundle bundle; - private int silencems; - private static final String SILENCE_PREFIX = "SIL_"; - private static final String SYNTHESIZE_TO_FILE_PREFIX = "STF_"; - - /** Plugin registration. */ - public static void registerWith(Registrar registrar) { - FlutterTtsPlugin instance = new FlutterTtsPlugin(); - instance.initInstance(registrar.messenger(), registrar.activeContext()); - } - - private void initInstance(BinaryMessenger messenger, Context context) { - this.context = context; - methodChannel = new MethodChannel(messenger, "flutter_tts"); - methodChannel.setMethodCallHandler(this); - handler = new Handler(Looper.getMainLooper()); - bundle = new Bundle(); - tts = new TextToSpeech(context, onInitListener, googleTtsEngine); - } - - /** Android Plugin APIs */ - @Override - public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) { - initInstance(binding.getBinaryMessenger(), binding.getApplicationContext()); - } - - @Override - public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) { - stop(); - tts.shutdown(); - context = null; - methodChannel.setMethodCallHandler(null); - methodChannel = null; - } - - private UtteranceProgressListener utteranceProgressListener = - new UtteranceProgressListener() { - @Override - public void onStart(String utteranceId) { - if (utteranceId != null && utteranceId.startsWith(SYNTHESIZE_TO_FILE_PREFIX)) { - invokeMethod("synth.onStart", true); - } else { - Log.d(tag, "Utterance ID has started: " + utteranceId); - invokeMethod("speak.onStart", true); - } - if (Build.VERSION.SDK_INT < 26) { - this.onProgress(utteranceId, 0, utterances.get(utteranceId).length()); - } - } - - @Override - public void onDone(String utteranceId) { - if (utteranceId != null && utteranceId.startsWith(SILENCE_PREFIX)) return; - if (utteranceId != null && utteranceId.startsWith(SYNTHESIZE_TO_FILE_PREFIX)) { - invokeMethod("synth.onComplete", true); - } else { - Log.d(tag, "Utterance ID has completed: " + utteranceId); - if (awaitSpeakCompletion) { - speakCompletion(1); - } - invokeMethod("speak.onComplete", true); - } - utterances.remove(utteranceId); - } - - @Override - public void onStop(String utteranceId, boolean interrupted) { - Log.d( - tag, - "Utterance ID has been stopped: " + utteranceId + ". Interrupted: " + interrupted); - if (awaitSpeakCompletion) { - speaking = false; - } - invokeMethod("speak.onCancel", true); - } - - private void onProgress(String utteranceId, int startAt, int endAt) { - if (utteranceId != null && !utteranceId.startsWith(SYNTHESIZE_TO_FILE_PREFIX)) { - final String text = utterances.get(utteranceId); - final HashMap data = new HashMap<>(); - data.put("text", text); - data.put("start", Integer.toString(startAt)); - data.put("end", Integer.toString(endAt)); - data.put("word", text.substring(startAt, endAt)); - invokeMethod("speak.onProgress", data); - } - } - - // Requires Android 26 or later - @Override - public void onRangeStart(String utteranceId, int startAt, int endAt, int frame) { - if (utteranceId != null && !utteranceId.startsWith(SYNTHESIZE_TO_FILE_PREFIX)) { - super.onRangeStart(utteranceId, startAt, endAt, frame); - this.onProgress(utteranceId, startAt, endAt); - } - } - - @Override - @Deprecated - public void onError(String utteranceId) { - if (utteranceId != null && utteranceId.startsWith(SYNTHESIZE_TO_FILE_PREFIX)) { - invokeMethod("synth.onError", "Error from TextToSpeech (synth)"); - } else { - if (awaitSpeakCompletion) { - speaking = false; - } - invokeMethod("speak.onError", "Error from TextToSpeech (speak)"); - } - } - - @Override - public void onError(String utteranceId, int errorCode) { - if (utteranceId != null && utteranceId.startsWith(SYNTHESIZE_TO_FILE_PREFIX)) { - invokeMethod("synth.onError", "Error from TextToSpeech (synth) - " + errorCode); - } else { - if (awaitSpeakCompletion) { - speaking = false; - } - invokeMethod("speak.onError", "Error from TextToSpeech (speak) - " + errorCode); - } - } - }; - - void speakCompletion(final int success) { - speaking = false; - handler.post( - new Runnable() { - @Override - public void run() { - speakResult.success(success); - } - }); - } - - private TextToSpeech.OnInitListener onInitListener = - new TextToSpeech.OnInitListener() { - @Override - public void onInit(int status) { - if (status == TextToSpeech.SUCCESS) { - tts.setOnUtteranceProgressListener(utteranceProgressListener); - - try { - Locale locale = tts.getDefaultVoice().getLocale(); - if (isLanguageAvailable(locale)) { - tts.setLanguage(locale); - } - } catch (NullPointerException | IllegalArgumentException e) { - Log.e(tag, "getDefaultLocale: " + e.getMessage()); - } - - // Handle pending method calls (sent while TTS was initializing) - isTtsInitialized = true; - for (Runnable call : pendingMethodCalls) { - call.run(); - } - } else { - Log.e(tag, "Failed to initialize TextToSpeech"); - } - } - }; - - @Override - public void onMethodCall(@NonNull final MethodCall call, @NonNull final Result result) { - // If TTS is still loading - if (!isTtsInitialized) { - // Suspend method call until the TTS engine is ready - final Runnable suspendedCall = - new Runnable() { - public void run() { - onMethodCall(call, result); - } - }; - pendingMethodCalls.add(suspendedCall); - return; - } - switch (call.method) { - case "speak": - { - String text = call.arguments.toString(); - if (this.speaking) { - result.success(0); - break; - } - speak(text); - if (this.awaitSpeakCompletion) { - this.speaking = true; - this.speakResult = result; - } else { - result.success(1); - } - break; - } - case "awaitSpeakCompletion": - { - this.awaitSpeakCompletion = Boolean.parseBoolean(call.arguments.toString()); - result.success(1); - break; - } - case "synthesizeToFile": - { - String text = call.argument("text"); - String fileName = call.argument("fileName"); - synthesizeToFile(text, fileName); - result.success(1); - break; - } - case "stop": - stop(); - result.success(1); - break; - case "setSpeechRate": - String rate = call.arguments.toString(); - setSpeechRate(Float.parseFloat(rate)); - result.success(1); - break; - case "setVolume": - String volume = call.arguments.toString(); - setVolume(Float.parseFloat(volume), result); - break; - case "setPitch": - String pitch = call.arguments.toString(); - setPitch(Float.parseFloat(pitch), result); - break; - case "setLanguage": - { - String language = call.arguments.toString(); - setLanguage(language, result); - break; - } - case "getLanguages": - getLanguages(result); - break; - case "getVoices": - getVoices(result); - break; - case "getSpeechRateValidRange": - getSpeechRateValidRange(result); - break; - case "getEngines": - getEngines(result); - break; - case "setVoice": - HashMap voice = call.arguments(); - setVoice(voice, result); - break; - case "isLanguageAvailable": - { - String language = call.arguments().toString(); - Locale locale = Locale.forLanguageTag(language); - result.success(isLanguageAvailable(locale)); - break; - } - case "setSilence": - String silencems = call.arguments.toString(); - this.silencems = Integer.parseInt(silencems); - break; - case "setSharedInstance": - result.success(1); - break; - default: - result.notImplemented(); - break; - } - } - - void setSpeechRate(float rate) { - tts.setSpeechRate(rate); - } - - Boolean isLanguageAvailable(Locale locale) { - return tts.isLanguageAvailable(locale) >= TextToSpeech.LANG_AVAILABLE; - } - - void setLanguage(String language, Result result) { - Locale locale = Locale.forLanguageTag(language); - if (isLanguageAvailable(locale)) { - tts.setLanguage(locale); - result.success(1); - } else { - result.success(0); - } - } - - void setVoice(HashMap voice, Result result) { - for (Voice ttsVoice : tts.getVoices()) { - if (ttsVoice.getName().equals(voice.get("name")) && ttsVoice.getLocale().toLanguageTag().equals(voice.get("locale"))) { - tts.setVoice(ttsVoice); - result.success(1); - return; - } - } - Log.d(tag, "Voice name not found: " + voice); - result.success(0); - } - - void setVolume(float volume, Result result) { - if (volume >= 0.0F && volume <= 1.0F) { - bundle.putFloat(TextToSpeech.Engine.KEY_PARAM_VOLUME, volume); - result.success(1); - } else { - Log.d(tag, "Invalid volume " + volume + " value - Range is from 0.0 to 1.0"); - result.success(0); - } - } - - void setPitch(float pitch, Result result) { - if (pitch >= 0.5F && pitch <= 2.0F) { - tts.setPitch(pitch); - result.success(1); - } else { - Log.d(tag, "Invalid pitch " + pitch + " value - Range is from 0.5 to 2.0"); - result.success(0); - } - } - - void getVoices(Result result) { - ArrayList> voices = new ArrayList<>(); - try { - for (Voice voice : tts.getVoices()) { - HashMap voiceMap = new HashMap<>(); - voiceMap.put("name", voice.getName()); - voiceMap.put("locale", voice.getLocale().toLanguageTag()); - voices.add(voiceMap); - } - result.success(voices); - } catch (NullPointerException e) { - Log.d(tag, "getVoices: " + e.getMessage()); - result.success(null); - } - } - - void getLanguages(Result result) { - ArrayList locales = new ArrayList<>(); - try { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - // While this method was introduced in API level 21, it seems that it - // has not been implemented in the speech service side until API Level 23. - for (Locale locale : tts.getAvailableLanguages()) { - locales.add(locale.toLanguageTag()); - } - } else { - for (Locale locale : Locale.getAvailableLocales()) { - if (locale.getVariant().isEmpty() && isLanguageAvailable(locale)) { - locales.add(locale.toLanguageTag()); - } - } - } - } catch (MissingResourceException | NullPointerException e) { - Log.d(tag, "getLanguages: " + e.getMessage()); - } - result.success(locales); - } - - void getEngines(Result result) { - ArrayList engines = new ArrayList<>(); - try { - for (TextToSpeech.EngineInfo engineInfo : tts.getEngines()) { - engines.add(engineInfo.name); - } - } catch (Exception e) { - Log.d(tag, "getEngines: " + e.getMessage()); - } - result.success(engines); - } - - void getSpeechRateValidRange(Result result) { - // Valid values available in the android documentation. - // https://developer.android.com/reference/android/speech/tts/TextToSpeech#setSpeechRate(float) - final HashMap data = new HashMap(); - data.put("min", "0"); - data.put("normal", "1"); - data.put("max", "3"); - data.put("platform", "android"); - result.success(data); - } - - private void speak(String text) { - String uuid = UUID.randomUUID().toString(); - utterances.put(uuid, text); - if (silencems > 0) { - tts.playSilentUtterance(silencems, TextToSpeech.QUEUE_FLUSH, SILENCE_PREFIX + uuid); - tts.speak(text, TextToSpeech.QUEUE_ADD, bundle, uuid); - } else { - tts.speak(text, TextToSpeech.QUEUE_FLUSH, bundle, uuid); - } - } - - private void stop() { - tts.stop(); - } - - private void synthesizeToFile(String text, String fileName) { - File file = new File(context.getExternalFilesDir(null), fileName); - String uuid = UUID.randomUUID().toString(); - bundle.putString(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, SYNTHESIZE_TO_FILE_PREFIX + uuid); - - int result = tts.synthesizeToFile(text, bundle, file, SYNTHESIZE_TO_FILE_PREFIX + uuid); - if (result == TextToSpeech.SUCCESS) { - Log.d(tag, "Successfully created file : " + file.getPath()); - } else { - Log.d(tag, "Failed creating file : " + file.getPath()); - } - } - - private void invokeMethod(final String method, final Object arguments) { - handler.post( - new Runnable() { - @Override - public void run() { - if (methodChannel != null) methodChannel.invokeMethod(method, arguments); - } - }); - } -} diff --git a/flutter_tts-voice_enhancement/example/.gitignore b/flutter_tts-voice_enhancement/example/.gitignore deleted file mode 100644 index 7e6bbd47..00000000 --- a/flutter_tts-voice_enhancement/example/.gitignore +++ /dev/null @@ -1,11 +0,0 @@ -.DS_Store -.dart_tool/ - -.packages -.pub/ - -build/ - -.flutter-plugins -.flutter-plugins-dependencies -lib/generated_plugin_registrant.dart \ No newline at end of file diff --git a/flutter_tts-voice_enhancement/example/.metadata b/flutter_tts-voice_enhancement/example/.metadata deleted file mode 100644 index 3c0dd2c8..00000000 --- a/flutter_tts-voice_enhancement/example/.metadata +++ /dev/null @@ -1,8 +0,0 @@ -# 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: b397406561f5e7a9c94e28f58d9e49fca0dd58b7 - channel: beta diff --git a/flutter_tts-voice_enhancement/example/README.md b/flutter_tts-voice_enhancement/example/README.md deleted file mode 100644 index a1356260..00000000 --- a/flutter_tts-voice_enhancement/example/README.md +++ /dev/null @@ -1,16 +0,0 @@ -# example - -A new Flutter project. - -## Getting Started - -This project is a starting point for a Flutter application. - -A few resources to get you started if this is your first Flutter project: - -- [Lab: Write your first Flutter app](https://flutter.dev/docs/get-started/codelab) -- [Cookbook: Useful Flutter samples](https://flutter.dev/docs/cookbook) - -For help getting started with Flutter, view our -[online documentation](https://flutter.dev/docs), which offers tutorials, -samples, guidance on mobile development, and a full API reference. diff --git a/flutter_tts-voice_enhancement/example/android/.gitignore b/flutter_tts-voice_enhancement/example/android/.gitignore deleted file mode 100644 index 65b7315a..00000000 --- a/flutter_tts-voice_enhancement/example/android/.gitignore +++ /dev/null @@ -1,10 +0,0 @@ -*.iml -*.class -.gradle -/local.properties -/.idea/workspace.xml -/.idea/libraries -.DS_Store -/build -/captures -GeneratedPluginRegistrant.java diff --git a/flutter_tts-voice_enhancement/example/android/.settings/org.eclipse.buildship.core.prefs b/flutter_tts-voice_enhancement/example/android/.settings/org.eclipse.buildship.core.prefs deleted file mode 100644 index 9f105273..00000000 --- a/flutter_tts-voice_enhancement/example/android/.settings/org.eclipse.buildship.core.prefs +++ /dev/null @@ -1,2 +0,0 @@ -#Sat Apr 14 11:55:40 PDT 2018 -connection.project.dir= diff --git a/flutter_tts-voice_enhancement/example/android/app/.classpath b/flutter_tts-voice_enhancement/example/android/app/.classpath deleted file mode 100644 index 8d8d85f1..00000000 --- a/flutter_tts-voice_enhancement/example/android/app/.classpath +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/flutter_tts-voice_enhancement/example/android/app/.settings/org.eclipse.buildship.core.prefs b/flutter_tts-voice_enhancement/example/android/app/.settings/org.eclipse.buildship.core.prefs deleted file mode 100644 index 0601ea50..00000000 --- a/flutter_tts-voice_enhancement/example/android/app/.settings/org.eclipse.buildship.core.prefs +++ /dev/null @@ -1,2 +0,0 @@ -#Sat Apr 14 11:55:40 PDT 2018 -connection.project.dir=.. diff --git a/flutter_tts-voice_enhancement/example/android/app/build.gradle b/flutter_tts-voice_enhancement/example/android/app/build.gradle deleted file mode 100644 index 563b8f89..00000000 --- a/flutter_tts-voice_enhancement/example/android/app/build.gradle +++ /dev/null @@ -1,50 +0,0 @@ -def localProperties = new Properties() -def localPropertiesFile = rootProject.file('local.properties') -if (localPropertiesFile.exists()) { - localPropertiesFile.withReader('UTF-8') { reader -> - localProperties.load(reader) - } -} - -def flutterRoot = localProperties.getProperty('flutter.sdk') -if (flutterRoot == null) { - throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") -} - -apply plugin: 'com.android.application' -apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" - -android { - compileSdkVersion 28 - - lintOptions { - disable 'InvalidPackage' - } - - defaultConfig { - applicationId "com.tundralabs.flutterttsexample" - minSdkVersion 21 - targetSdkVersion 28 - versionCode 1 - versionName "1.0" - testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" - } - - 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 { - testImplementation 'junit:junit:4.12' - androidTestImplementation 'androidx.test:runner:1.1.0' - androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0' -} diff --git a/flutter_tts-voice_enhancement/example/android/app/src/debug/AndroidManifest.xml b/flutter_tts-voice_enhancement/example/android/app/src/debug/AndroidManifest.xml deleted file mode 100644 index 49f10e46..00000000 --- a/flutter_tts-voice_enhancement/example/android/app/src/debug/AndroidManifest.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - diff --git a/flutter_tts-voice_enhancement/example/android/app/src/main/AndroidManifest.xml b/flutter_tts-voice_enhancement/example/android/app/src/main/AndroidManifest.xml deleted file mode 100644 index 1caca009..00000000 --- a/flutter_tts-voice_enhancement/example/android/app/src/main/AndroidManifest.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/flutter_tts-voice_enhancement/example/android/app/src/main/res/drawable/launch_background.xml b/flutter_tts-voice_enhancement/example/android/app/src/main/res/drawable/launch_background.xml deleted file mode 100644 index 304732f8..00000000 --- a/flutter_tts-voice_enhancement/example/android/app/src/main/res/drawable/launch_background.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - diff --git a/flutter_tts-voice_enhancement/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/flutter_tts-voice_enhancement/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png deleted file mode 100644 index db77bb4b..00000000 Binary files a/flutter_tts-voice_enhancement/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/flutter_tts-voice_enhancement/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png deleted file mode 100644 index 17987b79..00000000 Binary files a/flutter_tts-voice_enhancement/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/flutter_tts-voice_enhancement/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png deleted file mode 100644 index 09d43914..00000000 Binary files a/flutter_tts-voice_enhancement/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/flutter_tts-voice_enhancement/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png deleted file mode 100644 index d5f1c8d3..00000000 Binary files a/flutter_tts-voice_enhancement/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/flutter_tts-voice_enhancement/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png deleted file mode 100644 index 4d6372ee..00000000 Binary files a/flutter_tts-voice_enhancement/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/android/app/src/main/res/values/styles.xml b/flutter_tts-voice_enhancement/example/android/app/src/main/res/values/styles.xml deleted file mode 100644 index 1f83a33f..00000000 --- a/flutter_tts-voice_enhancement/example/android/app/src/main/res/values/styles.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - diff --git a/flutter_tts-voice_enhancement/example/android/app/src/profile/AndroidManifest.xml b/flutter_tts-voice_enhancement/example/android/app/src/profile/AndroidManifest.xml deleted file mode 100644 index 49f10e46..00000000 --- a/flutter_tts-voice_enhancement/example/android/app/src/profile/AndroidManifest.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - diff --git a/flutter_tts-voice_enhancement/example/android/build.gradle b/flutter_tts-voice_enhancement/example/android/build.gradle deleted file mode 100644 index cd23eff8..00000000 --- a/flutter_tts-voice_enhancement/example/android/build.gradle +++ /dev/null @@ -1,29 +0,0 @@ -buildscript { - repositories { - google() - jcenter() - } - - dependencies { - classpath 'com.android.tools.build:gradle:4.0.0' - } -} - -allprojects { - repositories { - google() - jcenter() - } -} - -rootProject.buildDir = '../build' -subprojects { - project.buildDir = "${rootProject.buildDir}/${project.name}" -} -subprojects { - project.evaluationDependsOn(':app') -} - -task clean(type: Delete) { - delete rootProject.buildDir -} diff --git a/flutter_tts-voice_enhancement/example/android/gradle.properties b/flutter_tts-voice_enhancement/example/android/gradle.properties deleted file mode 100644 index b6e61b62..00000000 --- a/flutter_tts-voice_enhancement/example/android/gradle.properties +++ /dev/null @@ -1,4 +0,0 @@ -android.enableJetifier=true -android.useAndroidX=true -org.gradle.jvmargs=-Xmx1536M -android.enableR8=true diff --git a/flutter_tts-voice_enhancement/example/android/gradle/wrapper/gradle-wrapper.properties b/flutter_tts-voice_enhancement/example/android/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 495eba36..00000000 --- a/flutter_tts-voice_enhancement/example/android/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,6 +0,0 @@ -#Tue Jul 07 01:11:38 PDT 2020 -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip diff --git a/flutter_tts-voice_enhancement/example/android/settings.gradle b/flutter_tts-voice_enhancement/example/android/settings.gradle deleted file mode 100644 index 5a2f14fb..00000000 --- a/flutter_tts-voice_enhancement/example/android/settings.gradle +++ /dev/null @@ -1,15 +0,0 @@ -include ':app' - -def flutterProjectRoot = rootProject.projectDir.parentFile.toPath() - -def plugins = new Properties() -def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins') -if (pluginsFile.exists()) { - pluginsFile.withReader('UTF-8') { reader -> plugins.load(reader) } -} - -plugins.each { name, path -> - def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile() - include ":$name" - project(":$name").projectDir = pluginDirectory -} diff --git a/flutter_tts-voice_enhancement/example/android/settings_aar.gradle b/flutter_tts-voice_enhancement/example/android/settings_aar.gradle deleted file mode 100644 index e7b4def4..00000000 --- a/flutter_tts-voice_enhancement/example/android/settings_aar.gradle +++ /dev/null @@ -1 +0,0 @@ -include ':app' diff --git a/flutter_tts-voice_enhancement/example/ios/.gitignore b/flutter_tts-voice_enhancement/example/ios/.gitignore deleted file mode 100644 index 1e1aafd6..00000000 --- a/flutter_tts-voice_enhancement/example/ios/.gitignore +++ /dev/null @@ -1,42 +0,0 @@ -.idea/ -.vagrant/ -.sconsign.dblite -.svn/ - -.DS_Store -*.swp -profile - -DerivedData/ -build/ -GeneratedPluginRegistrant.h -GeneratedPluginRegistrant.m - -*.pbxuser -*.mode1v3 -*.mode2v3 -*.perspectivev3 - -!default.pbxuser -!default.mode1v3 -!default.mode2v3 -!default.perspectivev3 - -xcuserdata - -*.moved-aside - -*.pyc -*sync/ -Icon? -.tags* - -/Flutter/app.flx -/Flutter/app.zip -/Flutter/flutter_assets/ -/Flutter/App.framework -/Flutter/Flutter.framework -/Flutter/Generated.xcconfig -/ServiceDefinitions.json - -Pods/ diff --git a/flutter_tts-voice_enhancement/example/ios/Flutter/.last_build_id b/flutter_tts-voice_enhancement/example/ios/Flutter/.last_build_id deleted file mode 100644 index bfaaeba1..00000000 --- a/flutter_tts-voice_enhancement/example/ios/Flutter/.last_build_id +++ /dev/null @@ -1 +0,0 @@ -b443c2d1b6b1e4df6c6fcc277a981410 \ No newline at end of file diff --git a/flutter_tts-voice_enhancement/example/ios/Flutter/AppFrameworkInfo.plist b/flutter_tts-voice_enhancement/example/ios/Flutter/AppFrameworkInfo.plist deleted file mode 100644 index 6c2de808..00000000 --- a/flutter_tts-voice_enhancement/example/ios/Flutter/AppFrameworkInfo.plist +++ /dev/null @@ -1,30 +0,0 @@ - - - - - CFBundleDevelopmentRegion - en - CFBundleExecutable - App - CFBundleIdentifier - io.flutter.flutter.app - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - App - CFBundlePackageType - FMWK - CFBundleShortVersionString - 1.0 - CFBundleSignature - ???? - CFBundleVersion - 1.0 - UIRequiredDeviceCapabilities - - arm64 - - MinimumOSVersion - 8.0 - - diff --git a/flutter_tts-voice_enhancement/example/ios/Flutter/Debug.xcconfig b/flutter_tts-voice_enhancement/example/ios/Flutter/Debug.xcconfig deleted file mode 100644 index e8efba11..00000000 --- a/flutter_tts-voice_enhancement/example/ios/Flutter/Debug.xcconfig +++ /dev/null @@ -1,2 +0,0 @@ -#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" -#include "Generated.xcconfig" diff --git a/flutter_tts-voice_enhancement/example/ios/Flutter/Flutter.podspec b/flutter_tts-voice_enhancement/example/ios/Flutter/Flutter.podspec deleted file mode 100644 index 5ca30416..00000000 --- a/flutter_tts-voice_enhancement/example/ios/Flutter/Flutter.podspec +++ /dev/null @@ -1,18 +0,0 @@ -# -# NOTE: This podspec is NOT to be published. It is only used as a local source! -# - -Pod::Spec.new do |s| - s.name = 'Flutter' - s.version = '1.0.0' - s.summary = 'High-performance, high-fidelity mobile apps.' - s.description = <<-DESC -Flutter provides an easy and productive way to build and deploy high-performance mobile apps for Android and iOS. - DESC - s.homepage = 'https://flutter.io' - s.license = { :type => 'MIT' } - s.author = { 'Flutter Dev Team' => 'flutter-dev@googlegroups.com' } - s.source = { :git => 'https://github.com/flutter/engine', :tag => s.version.to_s } - s.ios.deployment_target = '8.0' - s.vendored_frameworks = 'Flutter.framework' -end diff --git a/flutter_tts-voice_enhancement/example/ios/Flutter/Release.xcconfig b/flutter_tts-voice_enhancement/example/ios/Flutter/Release.xcconfig deleted file mode 100644 index 399e9340..00000000 --- a/flutter_tts-voice_enhancement/example/ios/Flutter/Release.xcconfig +++ /dev/null @@ -1,2 +0,0 @@ -#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" -#include "Generated.xcconfig" diff --git a/flutter_tts-voice_enhancement/example/ios/Podfile b/flutter_tts-voice_enhancement/example/ios/Podfile deleted file mode 100644 index 1e8c3c90..00000000 --- a/flutter_tts-voice_enhancement/example/ios/Podfile +++ /dev/null @@ -1,41 +0,0 @@ -# Uncomment this line to define a global platform for your project -# platform :ios, '9.0' - -# CocoaPods analytics sends network stats synchronously affecting flutter build latency. -ENV['COCOAPODS_DISABLE_STATS'] = 'true' - -project 'Runner', { - 'Debug' => :debug, - 'Profile' => :release, - 'Release' => :release, -} - -def flutter_root - generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) - unless File.exist?(generated_xcode_build_settings_path) - raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" - end - - File.foreach(generated_xcode_build_settings_path) do |line| - matches = line.match(/FLUTTER_ROOT\=(.*)/) - return matches[1].strip if matches - end - raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" -end - -require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) - -flutter_ios_podfile_setup - -target 'Runner' do - use_frameworks! - use_modular_headers! - - flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) -end - -post_install do |installer| - installer.pods_project.targets.each do |target| - flutter_additional_ios_build_settings(target) - end -end diff --git a/flutter_tts-voice_enhancement/example/ios/Runner.xcodeproj/project.pbxproj b/flutter_tts-voice_enhancement/example/ios/Runner.xcodeproj/project.pbxproj deleted file mode 100644 index 28d4b795..00000000 --- a/flutter_tts-voice_enhancement/example/ios/Runner.xcodeproj/project.pbxproj +++ /dev/null @@ -1,488 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 46; - objects = { - -/* Begin PBXBuildFile section */ - 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; - 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; - 72BCD356E80F9F5F32A2B586 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BE3436CECE15DEA290DCD6B6 /* Pods_Runner.framework */; }; - 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; - 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; - 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; - 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; -/* End PBXBuildFile section */ - -/* Begin PBXCopyFilesBuildPhase section */ - 9705A1C41CF9048500538489 /* Embed Frameworks */ = { - isa = PBXCopyFilesBuildPhase; - buildActionMask = 2147483647; - dstPath = ""; - dstSubfolderSpec = 10; - files = ( - ); - name = "Embed Frameworks"; - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXCopyFilesBuildPhase section */ - -/* Begin PBXFileReference section */ - 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; - 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; - 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; - 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; - 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; - 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; - 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; - 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; - 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; - 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; - 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; - 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; - 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - BE3436CECE15DEA290DCD6B6 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - CED86603210BC43D753C699B /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; - CF068A80D9BD19FC43D3FE99 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 97C146EB1CF9000F007C117D /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 72BCD356E80F9F5F32A2B586 /* Pods_Runner.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 04223708A30129901099FE16 /* Frameworks */ = { - isa = PBXGroup; - children = ( - BE3436CECE15DEA290DCD6B6 /* Pods_Runner.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; - 1ED2DC2A248FC04D7FB5EA8C /* Pods */ = { - isa = PBXGroup; - children = ( - CF068A80D9BD19FC43D3FE99 /* Pods-Runner.debug.xcconfig */, - CED86603210BC43D753C699B /* Pods-Runner.release.xcconfig */, - ); - name = Pods; - sourceTree = ""; - }; - 9740EEB11CF90186004384FC /* Flutter */ = { - isa = PBXGroup; - children = ( - 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, - 9740EEB21CF90195004384FC /* Debug.xcconfig */, - 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, - 9740EEB31CF90195004384FC /* Generated.xcconfig */, - ); - name = Flutter; - sourceTree = ""; - }; - 97C146E51CF9000F007C117D = { - isa = PBXGroup; - children = ( - 9740EEB11CF90186004384FC /* Flutter */, - 97C146F01CF9000F007C117D /* Runner */, - 97C146EF1CF9000F007C117D /* Products */, - 1ED2DC2A248FC04D7FB5EA8C /* Pods */, - 04223708A30129901099FE16 /* Frameworks */, - ); - sourceTree = ""; - }; - 97C146EF1CF9000F007C117D /* Products */ = { - isa = PBXGroup; - children = ( - 97C146EE1CF9000F007C117D /* Runner.app */, - ); - name = Products; - sourceTree = ""; - }; - 97C146F01CF9000F007C117D /* Runner */ = { - isa = PBXGroup; - children = ( - 97C146FA1CF9000F007C117D /* Main.storyboard */, - 97C146FD1CF9000F007C117D /* Assets.xcassets */, - 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, - 97C147021CF9000F007C117D /* Info.plist */, - 97C146F11CF9000F007C117D /* Supporting Files */, - 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, - 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, - 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, - 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, - ); - path = Runner; - sourceTree = ""; - }; - 97C146F11CF9000F007C117D /* Supporting Files */ = { - isa = PBXGroup; - children = ( - ); - name = "Supporting Files"; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - 97C146ED1CF9000F007C117D /* Runner */ = { - isa = PBXNativeTarget; - buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; - buildPhases = ( - 3B0CA933DCDA45D4F71410D4 /* [CP] Check Pods Manifest.lock */, - 9740EEB61CF901F6004384FC /* Run Script */, - 97C146EA1CF9000F007C117D /* Sources */, - 97C146EB1CF9000F007C117D /* Frameworks */, - 97C146EC1CF9000F007C117D /* Resources */, - 9705A1C41CF9048500538489 /* Embed Frameworks */, - 3B06AD1E1E4923F5004D2608 /* Thin Binary */, - 46F7EA90EF3F4667EDB9E562 /* [CP] Embed Pods Frameworks */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = Runner; - productName = Runner; - productReference = 97C146EE1CF9000F007C117D /* Runner.app */; - productType = "com.apple.product-type.application"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 97C146E61CF9000F007C117D /* Project object */ = { - isa = PBXProject; - attributes = { - LastUpgradeCheck = 0940; - ORGANIZATIONNAME = "The Chromium Authors"; - TargetAttributes = { - 97C146ED1CF9000F007C117D = { - CreatedOnToolsVersion = 7.3.1; - LastSwiftMigration = 0910; - }; - }; - }; - buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; - compatibilityVersion = "Xcode 3.2"; - developmentRegion = English; - hasScannedForEncodings = 0; - knownRegions = ( - en, - Base, - ); - mainGroup = 97C146E51CF9000F007C117D; - productRefGroup = 97C146EF1CF9000F007C117D /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 97C146ED1CF9000F007C117D /* Runner */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 97C146EC1CF9000F007C117D /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, - 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, - 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, - 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXShellScriptBuildPhase section */ - 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - ); - name = "Thin Binary"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; - }; - 3B0CA933DCDA45D4F71410D4 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - 46F7EA90EF3F4667EDB9E562 /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh", - "${PODS_ROOT}/../Flutter/Flutter.framework", - ); - name = "[CP] Embed Pods Frameworks"; - outputPaths = ( - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Flutter.framework", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; - 9740EEB61CF901F6004384FC /* Run Script */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - ); - name = "Run Script"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; - }; -/* End PBXShellScriptBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 97C146EA1CF9000F007C117D /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, - 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXVariantGroup section */ - 97C146FA1CF9000F007C117D /* Main.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 97C146FB1CF9000F007C117D /* Base */, - ); - name = Main.storyboard; - sourceTree = ""; - }; - 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 97C147001CF9000F007C117D /* Base */, - ); - name = LaunchScreen.storyboard; - sourceTree = ""; - }; -/* End PBXVariantGroup section */ - -/* Begin XCBuildConfiguration section */ - 97C147031CF9000F007C117D /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = dwarf; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_DYNAMIC_NO_PIC = NO; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - MTL_ENABLE_DEBUG_INFO = YES; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = iphoneos; - TARGETED_DEVICE_FAMILY = "1,2"; - }; - name = Debug; - }; - 97C147041CF9000F007C117D /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - MTL_ENABLE_DEBUG_INFO = NO; - SDKROOT = iphoneos; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - }; - name = Release; - }; - 97C147061CF9000F007C117D /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CLANG_ENABLE_MODULES = YES; - CURRENT_PROJECT_VERSION = 1; - ENABLE_BITCODE = NO; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); - INFOPLIST_FILE = Runner/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.tundralabs.flutterTtsExample; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_SWIFT3_OBJC_INFERENCE = On; - SWIFT_VERSION = 4.0; - VERSIONING_SYSTEM = "apple-generic"; - }; - name = Debug; - }; - 97C147071CF9000F007C117D /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CLANG_ENABLE_MODULES = YES; - CURRENT_PROJECT_VERSION = 1; - ENABLE_BITCODE = NO; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); - INFOPLIST_FILE = Runner/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.tundralabs.flutterTtsExample; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; - SWIFT_SWIFT3_OBJC_INFERENCE = On; - SWIFT_VERSION = 4.0; - VERSIONING_SYSTEM = "apple-generic"; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 97C147031CF9000F007C117D /* Debug */, - 97C147041CF9000F007C117D /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 97C147061CF9000F007C117D /* Debug */, - 97C147071CF9000F007C117D /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 97C146E61CF9000F007C117D /* Project object */; -} diff --git a/flutter_tts-voice_enhancement/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/flutter_tts-voice_enhancement/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index 1d526a16..00000000 --- a/flutter_tts-voice_enhancement/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,7 +0,0 @@ - - - - - diff --git a/flutter_tts-voice_enhancement/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/flutter_tts-voice_enhancement/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist deleted file mode 100644 index 18d98100..00000000 --- a/flutter_tts-voice_enhancement/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +++ /dev/null @@ -1,8 +0,0 @@ - - - - - IDEDidComputeMac32BitWarning - - - diff --git a/flutter_tts-voice_enhancement/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/flutter_tts-voice_enhancement/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings deleted file mode 100644 index f9b0d7c5..00000000 --- a/flutter_tts-voice_enhancement/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings +++ /dev/null @@ -1,8 +0,0 @@ - - - - - PreviewsEnabled - - - diff --git a/flutter_tts-voice_enhancement/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/flutter_tts-voice_enhancement/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme deleted file mode 100644 index 4bafc458..00000000 --- a/flutter_tts-voice_enhancement/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ /dev/null @@ -1,91 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/flutter_tts-voice_enhancement/example/ios/Runner.xcworkspace/contents.xcworkspacedata b/flutter_tts-voice_enhancement/example/ios/Runner.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index 21a3cc14..00000000 --- a/flutter_tts-voice_enhancement/example/ios/Runner.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - diff --git a/flutter_tts-voice_enhancement/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/flutter_tts-voice_enhancement/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist deleted file mode 100644 index 18d98100..00000000 --- a/flutter_tts-voice_enhancement/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +++ /dev/null @@ -1,8 +0,0 @@ - - - - - IDEDidComputeMac32BitWarning - - - diff --git a/flutter_tts-voice_enhancement/example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/flutter_tts-voice_enhancement/example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings deleted file mode 100644 index f9b0d7c5..00000000 --- a/flutter_tts-voice_enhancement/example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings +++ /dev/null @@ -1,8 +0,0 @@ - - - - - PreviewsEnabled - - - diff --git a/flutter_tts-voice_enhancement/example/ios/Runner/AppDelegate.swift b/flutter_tts-voice_enhancement/example/ios/Runner/AppDelegate.swift deleted file mode 100644 index 71cc41e3..00000000 --- a/flutter_tts-voice_enhancement/example/ios/Runner/AppDelegate.swift +++ /dev/null @@ -1,13 +0,0 @@ -import UIKit -import Flutter - -@UIApplicationMain -@objc class AppDelegate: FlutterAppDelegate { - override func application( - _ application: UIApplication, - didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]? - ) -> Bool { - GeneratedPluginRegistrant.register(with: self) - return super.application(application, didFinishLaunchingWithOptions: launchOptions) - } -} diff --git a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json deleted file mode 100644 index d36b1fab..00000000 --- a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json +++ /dev/null @@ -1,122 +0,0 @@ -{ - "images" : [ - { - "size" : "20x20", - "idiom" : "iphone", - "filename" : "Icon-App-20x20@2x.png", - "scale" : "2x" - }, - { - "size" : "20x20", - "idiom" : "iphone", - "filename" : "Icon-App-20x20@3x.png", - "scale" : "3x" - }, - { - "size" : "29x29", - "idiom" : "iphone", - "filename" : "Icon-App-29x29@1x.png", - "scale" : "1x" - }, - { - "size" : "29x29", - "idiom" : "iphone", - "filename" : "Icon-App-29x29@2x.png", - "scale" : "2x" - }, - { - "size" : "29x29", - "idiom" : "iphone", - "filename" : "Icon-App-29x29@3x.png", - "scale" : "3x" - }, - { - "size" : "40x40", - "idiom" : "iphone", - "filename" : "Icon-App-40x40@2x.png", - "scale" : "2x" - }, - { - "size" : "40x40", - "idiom" : "iphone", - "filename" : "Icon-App-40x40@3x.png", - "scale" : "3x" - }, - { - "size" : "60x60", - "idiom" : "iphone", - "filename" : "Icon-App-60x60@2x.png", - "scale" : "2x" - }, - { - "size" : "60x60", - "idiom" : "iphone", - "filename" : "Icon-App-60x60@3x.png", - "scale" : "3x" - }, - { - "size" : "20x20", - "idiom" : "ipad", - "filename" : "Icon-App-20x20@1x.png", - "scale" : "1x" - }, - { - "size" : "20x20", - "idiom" : "ipad", - "filename" : "Icon-App-20x20@2x.png", - "scale" : "2x" - }, - { - "size" : "29x29", - "idiom" : "ipad", - "filename" : "Icon-App-29x29@1x.png", - "scale" : "1x" - }, - { - "size" : "29x29", - "idiom" : "ipad", - "filename" : "Icon-App-29x29@2x.png", - "scale" : "2x" - }, - { - "size" : "40x40", - "idiom" : "ipad", - "filename" : "Icon-App-40x40@1x.png", - "scale" : "1x" - }, - { - "size" : "40x40", - "idiom" : "ipad", - "filename" : "Icon-App-40x40@2x.png", - "scale" : "2x" - }, - { - "size" : "76x76", - "idiom" : "ipad", - "filename" : "Icon-App-76x76@1x.png", - "scale" : "1x" - }, - { - "size" : "76x76", - "idiom" : "ipad", - "filename" : "Icon-App-76x76@2x.png", - "scale" : "2x" - }, - { - "size" : "83.5x83.5", - "idiom" : "ipad", - "filename" : "Icon-App-83.5x83.5@2x.png", - "scale" : "2x" - }, - { - "size" : "1024x1024", - "idiom" : "ios-marketing", - "filename" : "Icon-App-1024x1024@1x.png", - "scale" : "1x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} diff --git a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png deleted file mode 100644 index 3d43d11e..00000000 Binary files a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png deleted file mode 100644 index 28c6bf03..00000000 Binary files a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png deleted file mode 100644 index 2ccbfd96..00000000 Binary files a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png deleted file mode 100644 index f091b6b0..00000000 Binary files a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png deleted file mode 100644 index 4cde1211..00000000 Binary files a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png deleted file mode 100644 index d0ef06e7..00000000 Binary files a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png deleted file mode 100644 index dcdc2306..00000000 Binary files a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png deleted file mode 100644 index 2ccbfd96..00000000 Binary files a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png deleted file mode 100644 index c8f9ed8f..00000000 Binary files a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png deleted file mode 100644 index a6d6b860..00000000 Binary files a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png deleted file mode 100644 index a6d6b860..00000000 Binary files a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png deleted file mode 100644 index 75b2d164..00000000 Binary files a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png deleted file mode 100644 index c4df70d3..00000000 Binary files a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png deleted file mode 100644 index 6a84f41e..00000000 Binary files a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png deleted file mode 100644 index d0e1f585..00000000 Binary files a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json deleted file mode 100644 index 0bedcf2f..00000000 --- a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "LaunchImage.png", - "scale" : "1x" - }, - { - "idiom" : "universal", - "filename" : "LaunchImage@2x.png", - "scale" : "2x" - }, - { - "idiom" : "universal", - "filename" : "LaunchImage@3x.png", - "scale" : "3x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} diff --git a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png deleted file mode 100644 index 9da19eac..00000000 Binary files a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png deleted file mode 100644 index 9da19eac..00000000 Binary files a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png deleted file mode 100644 index 9da19eac..00000000 Binary files a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md deleted file mode 100644 index 89c2725b..00000000 --- a/flutter_tts-voice_enhancement/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# Launch Screen Assets - -You can customize the launch screen with your own desired assets by replacing the image files in this directory. - -You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/flutter_tts-voice_enhancement/example/ios/Runner/Base.lproj/LaunchScreen.storyboard b/flutter_tts-voice_enhancement/example/ios/Runner/Base.lproj/LaunchScreen.storyboard deleted file mode 100644 index f2e259c7..00000000 --- a/flutter_tts-voice_enhancement/example/ios/Runner/Base.lproj/LaunchScreen.storyboard +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/flutter_tts-voice_enhancement/example/ios/Runner/Base.lproj/Main.storyboard b/flutter_tts-voice_enhancement/example/ios/Runner/Base.lproj/Main.storyboard deleted file mode 100644 index f3c28516..00000000 --- a/flutter_tts-voice_enhancement/example/ios/Runner/Base.lproj/Main.storyboard +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/flutter_tts-voice_enhancement/example/ios/Runner/Info.plist b/flutter_tts-voice_enhancement/example/ios/Runner/Info.plist deleted file mode 100644 index dd2d9263..00000000 --- a/flutter_tts-voice_enhancement/example/ios/Runner/Info.plist +++ /dev/null @@ -1,49 +0,0 @@ - - - - - CFBundleDevelopmentRegion - en - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - flutter_tts_example - CFBundlePackageType - APPL - CFBundleShortVersionString - 1.0 - CFBundleSignature - ???? - CFBundleVersion - 1 - LSRequiresIPhoneOS - - UILaunchStoryboardName - LaunchScreen - UIMainStoryboardFile - Main - UIRequiredDeviceCapabilities - - arm64 - - UISupportedInterfaceOrientations - - UIInterfaceOrientationPortrait - UIInterfaceOrientationLandscapeLeft - UIInterfaceOrientationLandscapeRight - - UISupportedInterfaceOrientations~ipad - - UIInterfaceOrientationPortrait - UIInterfaceOrientationPortraitUpsideDown - UIInterfaceOrientationLandscapeLeft - UIInterfaceOrientationLandscapeRight - - UIViewControllerBasedStatusBarAppearance - - - diff --git a/flutter_tts-voice_enhancement/example/ios/Runner/Runner-Bridging-Header.h b/flutter_tts-voice_enhancement/example/ios/Runner/Runner-Bridging-Header.h deleted file mode 100644 index 7335fdf9..00000000 --- a/flutter_tts-voice_enhancement/example/ios/Runner/Runner-Bridging-Header.h +++ /dev/null @@ -1 +0,0 @@ -#import "GeneratedPluginRegistrant.h" \ No newline at end of file diff --git a/flutter_tts-voice_enhancement/example/lib/main.dart b/flutter_tts-voice_enhancement/example/lib/main.dart deleted file mode 100644 index 97530bbb..00000000 --- a/flutter_tts-voice_enhancement/example/lib/main.dart +++ /dev/null @@ -1,292 +0,0 @@ -import 'dart:async'; -import 'dart:io' show Platform; -import 'package:flutter/foundation.dart' show kIsWeb; - -import 'package:flutter/material.dart'; -import 'package:flutter_tts/flutter_tts.dart'; - -void main() => runApp(MyApp()); - -class MyApp extends StatefulWidget { - @override - _MyAppState createState() => _MyAppState(); -} - -enum TtsState { playing, stopped, paused, continued } - -class _MyAppState extends State { - FlutterTts flutterTts; - dynamic languages; - String language; - double volume = 0.5; - double pitch = 1.0; - double rate = 0.5; - - String _newVoiceText; - - TtsState ttsState = TtsState.stopped; - - get isPlaying => ttsState == TtsState.playing; - - get isStopped => ttsState == TtsState.stopped; - - get isPaused => ttsState == TtsState.paused; - - get isContinued => ttsState == TtsState.continued; - - @override - initState() { - super.initState(); - initTts(); - } - - initTts() { - flutterTts = FlutterTts(); - - _getLanguages(); - - if (!kIsWeb) { - if (Platform.isAndroid) { - _getEngines(); - } - } - - flutterTts.setStartHandler(() { - setState(() { - print("Playing"); - ttsState = TtsState.playing; - }); - }); - - flutterTts.setCompletionHandler(() { - setState(() { - print("Complete"); - ttsState = TtsState.stopped; - }); - }); - - flutterTts.setCancelHandler(() { - setState(() { - print("Cancel"); - ttsState = TtsState.stopped; - }); - }); - - if (kIsWeb || Platform.isIOS) { - flutterTts.setPauseHandler(() { - setState(() { - print("Paused"); - ttsState = TtsState.paused; - }); - }); - - flutterTts.setContinueHandler(() { - setState(() { - print("Continued"); - ttsState = TtsState.continued; - }); - }); - } - - flutterTts.setErrorHandler((msg) { - setState(() { - print("error: $msg"); - ttsState = TtsState.stopped; - }); - }); - } - - Future _getLanguages() async { - languages = await flutterTts.getLanguages; - if (languages != null) setState(() => languages); - } - - Future _getEngines() async { - var engines = await flutterTts.getEngines; - if (engines != null) { - for (dynamic engine in engines) { - print(engine); - } - } - } - - Future _speak() async { - await flutterTts.setVolume(volume); - await flutterTts.setSpeechRate(rate); - await flutterTts.setPitch(pitch); - - if (_newVoiceText != null) { - if (_newVoiceText.isNotEmpty) { - await flutterTts.awaitSpeakCompletion(true); - await flutterTts.speak(_newVoiceText); - } - } - } - - Future _stop() async { - var result = await flutterTts.stop(); - if (result == 1) setState(() => ttsState = TtsState.stopped); - } - - Future _pause() async { - var result = await flutterTts.pause(); - if (result == 1) setState(() => ttsState = TtsState.paused); - } - - @override - void dispose() { - super.dispose(); - flutterTts.stop(); - } - - List> getLanguageDropDownMenuItems() { - var items = List>(); - for (dynamic type in languages) { - items.add( - DropdownMenuItem(value: type as String, child: Text(type as String))); - } - return items; - } - - void changedLanguageDropDownItem(String selectedType) { - setState(() { - language = selectedType; - flutterTts.setLanguage(language); - }); - } - - void _onChange(String text) { - setState(() { - _newVoiceText = text; - }); - } - - @override - Widget build(BuildContext context) { - return MaterialApp( - home: Scaffold( - appBar: AppBar( - title: Text('Flutter TTS'), - ), - body: SingleChildScrollView( - scrollDirection: Axis.vertical, - child: Column(children: [ - _inputSection(), - _btnSection(), - languages != null ? _languageDropDownSection() : Text(""), - _buildSliders() - ])))); - } - - Widget _inputSection() => Container( - alignment: Alignment.topCenter, - padding: EdgeInsets.only(top: 25.0, left: 25.0, right: 25.0), - child: TextField( - onChanged: (String value) { - _onChange(value); - }, - )); - - Widget _btnSection() { - if (!kIsWeb && Platform.isAndroid) { - return Container( - padding: EdgeInsets.only(top: 50.0), - child: - Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ - _buildButtonColumn(Colors.green, Colors.greenAccent, - Icons.play_arrow, 'PLAY', _speak), - _buildButtonColumn( - Colors.red, Colors.redAccent, Icons.stop, 'STOP', _stop), - ])); - } else { - return Container( - padding: EdgeInsets.only(top: 50.0), - child: - Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ - _buildButtonColumn(Colors.green, Colors.greenAccent, - Icons.play_arrow, 'PLAY', _speak), - _buildButtonColumn( - Colors.red, Colors.redAccent, Icons.stop, 'STOP', _stop), - _buildButtonColumn( - Colors.blue, Colors.blueAccent, Icons.pause, 'PAUSE', _pause), - ])); - } - } - - Widget _languageDropDownSection() => Container( - padding: EdgeInsets.only(top: 50.0), - child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [ - DropdownButton( - value: language, - items: getLanguageDropDownMenuItems(), - onChanged: changedLanguageDropDownItem, - ) - ])); - - Column _buildButtonColumn(Color color, Color splashColor, IconData icon, - String label, Function func) { - return Column( - mainAxisSize: MainAxisSize.min, - mainAxisAlignment: MainAxisAlignment.center, - children: [ - IconButton( - icon: Icon(icon), - color: color, - splashColor: splashColor, - onPressed: () => func()), - Container( - margin: const EdgeInsets.only(top: 8.0), - child: Text(label, - style: TextStyle( - fontSize: 12.0, - fontWeight: FontWeight.w400, - color: color))) - ]); - } - - Widget _buildSliders() { - return Column( - children: [_volume(), _pitch(), _rate()], - ); - } - - Widget _volume() { - return Slider( - value: volume, - onChanged: (newVolume) { - setState(() => volume = newVolume); - }, - min: 0.0, - max: 1.0, - divisions: 10, - label: "Volume: $volume"); - } - - Widget _pitch() { - return Slider( - value: pitch, - onChanged: (newPitch) { - setState(() => pitch = newPitch); - }, - min: 0.5, - max: 2.0, - divisions: 15, - label: "Pitch: $pitch", - activeColor: Colors.red, - ); - } - - Widget _rate() { - return Slider( - value: rate, - onChanged: (newRate) { - setState(() => rate = newRate); - }, - min: 0.0, - max: 1.0, - divisions: 10, - label: "Rate: $rate", - activeColor: Colors.green, - ); - } -} diff --git a/flutter_tts-voice_enhancement/example/macos/.gitignore b/flutter_tts-voice_enhancement/example/macos/.gitignore deleted file mode 100644 index d2fd3772..00000000 --- a/flutter_tts-voice_enhancement/example/macos/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -# Flutter-related -**/Flutter/ephemeral/ -**/Pods/ - -# Xcode-related -**/xcuserdata/ diff --git a/flutter_tts-voice_enhancement/example/macos/Flutter/Flutter-Debug.xcconfig b/flutter_tts-voice_enhancement/example/macos/Flutter/Flutter-Debug.xcconfig deleted file mode 100644 index 785633d3..00000000 --- a/flutter_tts-voice_enhancement/example/macos/Flutter/Flutter-Debug.xcconfig +++ /dev/null @@ -1,2 +0,0 @@ -#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" -#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/flutter_tts-voice_enhancement/example/macos/Flutter/Flutter-Release.xcconfig b/flutter_tts-voice_enhancement/example/macos/Flutter/Flutter-Release.xcconfig deleted file mode 100644 index 5fba960c..00000000 --- a/flutter_tts-voice_enhancement/example/macos/Flutter/Flutter-Release.xcconfig +++ /dev/null @@ -1,2 +0,0 @@ -#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" -#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/flutter_tts-voice_enhancement/example/macos/Flutter/GeneratedPluginRegistrant.swift b/flutter_tts-voice_enhancement/example/macos/Flutter/GeneratedPluginRegistrant.swift deleted file mode 100644 index 1e6ac53b..00000000 --- a/flutter_tts-voice_enhancement/example/macos/Flutter/GeneratedPluginRegistrant.swift +++ /dev/null @@ -1,12 +0,0 @@ -// -// Generated file. Do not edit. -// - -import FlutterMacOS -import Foundation - -import flutter_tts - -func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { - FlutterTtsPlugin.register(with: registry.registrar(forPlugin: "FlutterTtsPlugin")) -} diff --git a/flutter_tts-voice_enhancement/example/macos/Podfile b/flutter_tts-voice_enhancement/example/macos/Podfile deleted file mode 100644 index 5bf4307c..00000000 --- a/flutter_tts-voice_enhancement/example/macos/Podfile +++ /dev/null @@ -1,82 +0,0 @@ -platform :osx, '10.15' - -# CocoaPods analytics sends network stats synchronously affecting flutter build latency. -ENV['COCOAPODS_DISABLE_STATS'] = 'true' - -project 'Runner', { - 'Debug' => :debug, - 'Profile' => :release, - 'Release' => :release, -} - -def parse_KV_file(file, separator='=') - file_abs_path = File.expand_path(file) - if !File.exists? file_abs_path - return []; - end - pods_ary = [] - skip_line_start_symbols = ["#", "/"] - File.foreach(file_abs_path) { |line| - next if skip_line_start_symbols.any? { |symbol| line =~ /^\s*#{symbol}/ } - plugin = line.split(pattern=separator) - if plugin.length == 2 - podname = plugin[0].strip() - path = plugin[1].strip() - podpath = File.expand_path("#{path}", file_abs_path) - pods_ary.push({:name => podname, :path => podpath}); - else - puts "Invalid plugin specification: #{line}" - end - } - return pods_ary -end - -def pubspec_supports_macos(file) - file_abs_path = File.expand_path(file) - if !File.exists? file_abs_path - return false; - end - File.foreach(file_abs_path) { |line| - return true if line =~ /^\s*macos:/ - } - return false -end - -target 'Runner' do - use_frameworks! - use_modular_headers! - - # Prepare symlinks folder. We use symlinks to avoid having Podfile.lock - # referring to absolute paths on developers' machines. - ephemeral_dir = File.join('Flutter', 'ephemeral') - symlink_dir = File.join(ephemeral_dir, '.symlinks') - symlink_plugins_dir = File.join(symlink_dir, 'plugins') - system("rm -rf #{symlink_dir}") - system("mkdir -p #{symlink_plugins_dir}") - - # Flutter Pods - generated_xcconfig = parse_KV_file(File.join(ephemeral_dir, 'Flutter-Generated.xcconfig')) - if generated_xcconfig.empty? - puts "Flutter-Generated.xcconfig must exist. If you're running pod install manually, make sure flutter packages get is executed first." - end - generated_xcconfig.map { |p| - if p[:name] == 'FLUTTER_FRAMEWORK_DIR' - symlink = File.join(symlink_dir, 'flutter') - File.symlink(File.dirname(p[:path]), symlink) - pod 'FlutterMacOS', :path => File.join(symlink, File.basename(p[:path])) - end - } - - # Plugin Pods - plugin_pods = parse_KV_file('../.flutter-plugins') - plugin_pods.map { |p| - symlink = File.join(symlink_plugins_dir, p[:name]) - File.symlink(p[:path], symlink) - if pubspec_supports_macos(File.join(symlink, 'pubspec.yaml')) - pod p[:name], :path => File.join(symlink, 'macos') - end - } -end - -# Prevent Cocoapods from embedding a second Flutter framework and causing an error with the new Xcode build system. -install! 'cocoapods', :disable_input_output_paths => true diff --git a/flutter_tts-voice_enhancement/example/macos/Runner.xcodeproj/project.pbxproj b/flutter_tts-voice_enhancement/example/macos/Runner.xcodeproj/project.pbxproj deleted file mode 100644 index 39fbd18c..00000000 --- a/flutter_tts-voice_enhancement/example/macos/Runner.xcodeproj/project.pbxproj +++ /dev/null @@ -1,656 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 51; - objects = { - -/* Begin PBXAggregateTarget section */ - 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { - isa = PBXAggregateTarget; - buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; - buildPhases = ( - 33CC111E2044C6BF0003C045 /* ShellScript */, - ); - dependencies = ( - ); - name = "Flutter Assemble"; - productName = FLX; - }; -/* End PBXAggregateTarget section */ - -/* Begin PBXBuildFile section */ - 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; - 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; - 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; - 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; - 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; - 33D1A10422148B71006C7A3E /* FlutterMacOS.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 33D1A10322148B71006C7A3E /* FlutterMacOS.framework */; }; - 33D1A10522148B93006C7A3E /* FlutterMacOS.framework in Bundle Framework */ = {isa = PBXBuildFile; fileRef = 33D1A10322148B71006C7A3E /* FlutterMacOS.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; - 3640FC23D5951A8FB0D6ECA0 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A470206CCCE0007DE0E2807A /* Pods_Runner.framework */; }; - D73912F022F37F9E000D13A0 /* App.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D73912EF22F37F9E000D13A0 /* App.framework */; }; - D73912F222F3801D000D13A0 /* App.framework in Bundle Framework */ = {isa = PBXBuildFile; fileRef = D73912EF22F37F9E000D13A0 /* App.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; -/* End PBXBuildFile section */ - -/* Begin PBXContainerItemProxy section */ - 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 33CC10E52044A3C60003C045 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 33CC111A2044C6BA0003C045; - remoteInfo = FLX; - }; -/* End PBXContainerItemProxy section */ - -/* Begin PBXCopyFilesBuildPhase section */ - 33CC110E2044A8840003C045 /* Bundle Framework */ = { - isa = PBXCopyFilesBuildPhase; - buildActionMask = 2147483647; - dstPath = ""; - dstSubfolderSpec = 10; - files = ( - D73912F222F3801D000D13A0 /* App.framework in Bundle Framework */, - 33D1A10522148B93006C7A3E /* FlutterMacOS.framework in Bundle Framework */, - ); - name = "Bundle Framework"; - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXCopyFilesBuildPhase section */ - -/* Begin PBXFileReference section */ - 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; - 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; - 33CC10ED2044A3C60003C045 /* example.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = example.app; sourceTree = BUILT_PRODUCTS_DIR; }; - 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; - 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; - 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; - 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; - 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; - 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; - 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; - 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; - 33D1A10322148B71006C7A3E /* FlutterMacOS.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = FlutterMacOS.framework; path = Flutter/ephemeral/FlutterMacOS.framework; sourceTree = SOURCE_ROOT; }; - 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; - 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; - 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; - 517AA5C8DE31A9B49D27971F /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; - 66FE8AA741C2B7FC12BF1304 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; - 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; - 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; - A470206CCCE0007DE0E2807A /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - C15A67B64555E7FFE7AD8B76 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; - D73912EF22F37F9E000D13A0 /* App.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = App.framework; path = Flutter/ephemeral/App.framework; sourceTree = SOURCE_ROOT; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 33CC10EA2044A3C60003C045 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - D73912F022F37F9E000D13A0 /* App.framework in Frameworks */, - 33D1A10422148B71006C7A3E /* FlutterMacOS.framework in Frameworks */, - 3640FC23D5951A8FB0D6ECA0 /* Pods_Runner.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 33BA886A226E78AF003329D5 /* Configs */ = { - isa = PBXGroup; - children = ( - 33E5194F232828860026EE4D /* AppInfo.xcconfig */, - 9740EEB21CF90195004384FC /* Debug.xcconfig */, - 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, - 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, - ); - path = Configs; - sourceTree = ""; - }; - 33CC10E42044A3C60003C045 = { - isa = PBXGroup; - children = ( - 33FAB671232836740065AC1E /* Runner */, - 33CEB47122A05771004F2AC0 /* Flutter */, - 33CC10EE2044A3C60003C045 /* Products */, - D73912EC22F37F3D000D13A0 /* Frameworks */, - 5F9F48FBDE9334256A3D8D1C /* Pods */, - ); - sourceTree = ""; - }; - 33CC10EE2044A3C60003C045 /* Products */ = { - isa = PBXGroup; - children = ( - 33CC10ED2044A3C60003C045 /* example.app */, - ); - name = Products; - sourceTree = ""; - }; - 33CC11242044D66E0003C045 /* Resources */ = { - isa = PBXGroup; - children = ( - 33CC10F22044A3C60003C045 /* Assets.xcassets */, - 33CC10F42044A3C60003C045 /* MainMenu.xib */, - 33CC10F72044A3C60003C045 /* Info.plist */, - ); - name = Resources; - path = ..; - sourceTree = ""; - }; - 33CEB47122A05771004F2AC0 /* Flutter */ = { - isa = PBXGroup; - children = ( - 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, - 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, - 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, - 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, - D73912EF22F37F9E000D13A0 /* App.framework */, - 33D1A10322148B71006C7A3E /* FlutterMacOS.framework */, - ); - path = Flutter; - sourceTree = ""; - }; - 33FAB671232836740065AC1E /* Runner */ = { - isa = PBXGroup; - children = ( - 33CC10F02044A3C60003C045 /* AppDelegate.swift */, - 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, - 33E51913231747F40026EE4D /* DebugProfile.entitlements */, - 33E51914231749380026EE4D /* Release.entitlements */, - 33CC11242044D66E0003C045 /* Resources */, - 33BA886A226E78AF003329D5 /* Configs */, - ); - path = Runner; - sourceTree = ""; - }; - 5F9F48FBDE9334256A3D8D1C /* Pods */ = { - isa = PBXGroup; - children = ( - 66FE8AA741C2B7FC12BF1304 /* Pods-Runner.debug.xcconfig */, - 517AA5C8DE31A9B49D27971F /* Pods-Runner.release.xcconfig */, - C15A67B64555E7FFE7AD8B76 /* Pods-Runner.profile.xcconfig */, - ); - path = Pods; - sourceTree = ""; - }; - D73912EC22F37F3D000D13A0 /* Frameworks */ = { - isa = PBXGroup; - children = ( - A470206CCCE0007DE0E2807A /* Pods_Runner.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - 33CC10EC2044A3C60003C045 /* Runner */ = { - isa = PBXNativeTarget; - buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; - buildPhases = ( - 9A62F257D3FF7C7C94E365B2 /* [CP] Check Pods Manifest.lock */, - 33CC10E92044A3C60003C045 /* Sources */, - 33CC10EA2044A3C60003C045 /* Frameworks */, - 33CC10EB2044A3C60003C045 /* Resources */, - 33CC110E2044A8840003C045 /* Bundle Framework */, - 3399D490228B24CF009A79C7 /* ShellScript */, - F7AADAC6A864E8BF8890B1EC /* [CP] Embed Pods Frameworks */, - ); - buildRules = ( - ); - dependencies = ( - 33CC11202044C79F0003C045 /* PBXTargetDependency */, - ); - name = Runner; - productName = Runner; - productReference = 33CC10ED2044A3C60003C045 /* example.app */; - productType = "com.apple.product-type.application"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 33CC10E52044A3C60003C045 /* Project object */ = { - isa = PBXProject; - attributes = { - LastSwiftUpdateCheck = 0920; - LastUpgradeCheck = 1150; - ORGANIZATIONNAME = "The Flutter Authors"; - TargetAttributes = { - 33CC10EC2044A3C60003C045 = { - CreatedOnToolsVersion = 9.2; - LastSwiftMigration = 1100; - ProvisioningStyle = Automatic; - SystemCapabilities = { - com.apple.Sandbox = { - enabled = 1; - }; - }; - }; - 33CC111A2044C6BA0003C045 = { - CreatedOnToolsVersion = 9.2; - ProvisioningStyle = Manual; - }; - }; - }; - buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; - compatibilityVersion = "Xcode 8.0"; - developmentRegion = en; - hasScannedForEncodings = 0; - knownRegions = ( - en, - Base, - ); - mainGroup = 33CC10E42044A3C60003C045; - productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 33CC10EC2044A3C60003C045 /* Runner */, - 33CC111A2044C6BA0003C045 /* Flutter Assemble */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 33CC10EB2044A3C60003C045 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, - 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXShellScriptBuildPhase section */ - 3399D490228B24CF009A79C7 /* ShellScript */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - ); - outputFileListPaths = ( - ); - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename\n"; - }; - 33CC111E2044C6BF0003C045 /* ShellScript */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - Flutter/ephemeral/FlutterInputs.xcfilelist, - ); - inputPaths = ( - Flutter/ephemeral/tripwire, - ); - outputFileListPaths = ( - Flutter/ephemeral/FlutterOutputs.xcfilelist, - ); - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh\ntouch Flutter/ephemeral/tripwire\n"; - }; - 9A62F257D3FF7C7C94E365B2 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - F7AADAC6A864E8BF8890B1EC /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - name = "[CP] Embed Pods Frameworks"; - outputFileListPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; -/* End PBXShellScriptBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 33CC10E92044A3C60003C045 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, - 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, - 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXTargetDependency section */ - 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; - targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; - }; -/* End PBXTargetDependency section */ - -/* Begin PBXVariantGroup section */ - 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { - isa = PBXVariantGroup; - children = ( - 33CC10F52044A3C60003C045 /* Base */, - ); - name = MainMenu.xib; - path = Runner; - sourceTree = ""; - }; -/* End PBXVariantGroup section */ - -/* Begin XCBuildConfiguration section */ - 338D0CE9231458BD00FA5F75 /* Profile */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CODE_SIGN_IDENTITY = "-"; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.15; - MTL_ENABLE_DEBUG_INFO = NO; - SDKROOT = macosx; - SWIFT_COMPILATION_MODE = wholemodule; - SWIFT_OPTIMIZATION_LEVEL = "-O"; - }; - name = Profile; - }; - 338D0CEA231458BD00FA5F75 /* Profile */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CLANG_ENABLE_MODULES = YES; - CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; - CODE_SIGN_IDENTITY = "-"; - CODE_SIGN_STYLE = Automatic; - COMBINE_HIDPI_IMAGES = YES; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter/ephemeral", - ); - INFOPLIST_FILE = Runner/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/../Frameworks", - ); - PROVISIONING_PROFILE_SPECIFIER = ""; - SWIFT_VERSION = 5.0; - }; - name = Profile; - }; - 338D0CEB231458BD00FA5F75 /* Profile */ = { - isa = XCBuildConfiguration; - buildSettings = { - CODE_SIGN_STYLE = Manual; - PRODUCT_NAME = "$(TARGET_NAME)"; - }; - name = Profile; - }; - 33CC10F92044A3C60003C045 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CODE_SIGN_IDENTITY = "-"; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = dwarf; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_DYNAMIC_NO_PIC = NO; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.15; - MTL_ENABLE_DEBUG_INFO = YES; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = macosx; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - }; - name = Debug; - }; - 33CC10FA2044A3C60003C045 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CODE_SIGN_IDENTITY = "-"; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.15; - MTL_ENABLE_DEBUG_INFO = NO; - SDKROOT = macosx; - SWIFT_COMPILATION_MODE = wholemodule; - SWIFT_OPTIMIZATION_LEVEL = "-O"; - }; - name = Release; - }; - 33CC10FC2044A3C60003C045 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CLANG_ENABLE_MODULES = YES; - CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; - CODE_SIGN_IDENTITY = "-"; - CODE_SIGN_STYLE = Automatic; - COMBINE_HIDPI_IMAGES = YES; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter/ephemeral", - ); - INFOPLIST_FILE = Runner/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/../Frameworks", - ); - PROVISIONING_PROFILE_SPECIFIER = ""; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 5.0; - }; - name = Debug; - }; - 33CC10FD2044A3C60003C045 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CLANG_ENABLE_MODULES = YES; - CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; - CODE_SIGN_IDENTITY = "-"; - CODE_SIGN_STYLE = Automatic; - COMBINE_HIDPI_IMAGES = YES; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter/ephemeral", - ); - INFOPLIST_FILE = Runner/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/../Frameworks", - ); - PROVISIONING_PROFILE_SPECIFIER = ""; - SWIFT_VERSION = 5.0; - }; - name = Release; - }; - 33CC111C2044C6BA0003C045 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - CODE_SIGN_STYLE = Manual; - PRODUCT_NAME = "$(TARGET_NAME)"; - }; - name = Debug; - }; - 33CC111D2044C6BA0003C045 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - CODE_SIGN_STYLE = Automatic; - PRODUCT_NAME = "$(TARGET_NAME)"; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 33CC10F92044A3C60003C045 /* Debug */, - 33CC10FA2044A3C60003C045 /* Release */, - 338D0CE9231458BD00FA5F75 /* Profile */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 33CC10FC2044A3C60003C045 /* Debug */, - 33CC10FD2044A3C60003C045 /* Release */, - 338D0CEA231458BD00FA5F75 /* Profile */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 33CC111C2044C6BA0003C045 /* Debug */, - 33CC111D2044C6BA0003C045 /* Release */, - 338D0CEB231458BD00FA5F75 /* Profile */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 33CC10E52044A3C60003C045 /* Project object */; -} diff --git a/flutter_tts-voice_enhancement/example/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/flutter_tts-voice_enhancement/example/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist deleted file mode 100644 index 18d98100..00000000 --- a/flutter_tts-voice_enhancement/example/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +++ /dev/null @@ -1,8 +0,0 @@ - - - - - IDEDidComputeMac32BitWarning - - - diff --git a/flutter_tts-voice_enhancement/example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/flutter_tts-voice_enhancement/example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme deleted file mode 100644 index 6111bd0a..00000000 --- a/flutter_tts-voice_enhancement/example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ /dev/null @@ -1,97 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/flutter_tts-voice_enhancement/example/macos/Runner.xcworkspace/contents.xcworkspacedata b/flutter_tts-voice_enhancement/example/macos/Runner.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index 21a3cc14..00000000 --- a/flutter_tts-voice_enhancement/example/macos/Runner.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - diff --git a/flutter_tts-voice_enhancement/example/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/flutter_tts-voice_enhancement/example/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist deleted file mode 100644 index 18d98100..00000000 --- a/flutter_tts-voice_enhancement/example/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +++ /dev/null @@ -1,8 +0,0 @@ - - - - - IDEDidComputeMac32BitWarning - - - diff --git a/flutter_tts-voice_enhancement/example/macos/Runner/AppDelegate.swift b/flutter_tts-voice_enhancement/example/macos/Runner/AppDelegate.swift deleted file mode 100644 index d53ef643..00000000 --- a/flutter_tts-voice_enhancement/example/macos/Runner/AppDelegate.swift +++ /dev/null @@ -1,9 +0,0 @@ -import Cocoa -import FlutterMacOS - -@NSApplicationMain -class AppDelegate: FlutterAppDelegate { - override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { - return true - } -} diff --git a/flutter_tts-voice_enhancement/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/flutter_tts-voice_enhancement/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json deleted file mode 100644 index a2ec33f1..00000000 --- a/flutter_tts-voice_enhancement/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "images" : [ - { - "size" : "16x16", - "idiom" : "mac", - "filename" : "app_icon_16.png", - "scale" : "1x" - }, - { - "size" : "16x16", - "idiom" : "mac", - "filename" : "app_icon_32.png", - "scale" : "2x" - }, - { - "size" : "32x32", - "idiom" : "mac", - "filename" : "app_icon_32.png", - "scale" : "1x" - }, - { - "size" : "32x32", - "idiom" : "mac", - "filename" : "app_icon_64.png", - "scale" : "2x" - }, - { - "size" : "128x128", - "idiom" : "mac", - "filename" : "app_icon_128.png", - "scale" : "1x" - }, - { - "size" : "128x128", - "idiom" : "mac", - "filename" : "app_icon_256.png", - "scale" : "2x" - }, - { - "size" : "256x256", - "idiom" : "mac", - "filename" : "app_icon_256.png", - "scale" : "1x" - }, - { - "size" : "256x256", - "idiom" : "mac", - "filename" : "app_icon_512.png", - "scale" : "2x" - }, - { - "size" : "512x512", - "idiom" : "mac", - "filename" : "app_icon_512.png", - "scale" : "1x" - }, - { - "size" : "512x512", - "idiom" : "mac", - "filename" : "app_icon_1024.png", - "scale" : "2x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} diff --git a/flutter_tts-voice_enhancement/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/flutter_tts-voice_enhancement/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png deleted file mode 100644 index 3c4935a7..00000000 Binary files a/flutter_tts-voice_enhancement/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/flutter_tts-voice_enhancement/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png deleted file mode 100644 index ed4cc164..00000000 Binary files a/flutter_tts-voice_enhancement/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/flutter_tts-voice_enhancement/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png deleted file mode 100644 index 483be613..00000000 Binary files a/flutter_tts-voice_enhancement/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/flutter_tts-voice_enhancement/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png deleted file mode 100644 index bcbf36df..00000000 Binary files a/flutter_tts-voice_enhancement/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/flutter_tts-voice_enhancement/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png deleted file mode 100644 index 9c0a6528..00000000 Binary files a/flutter_tts-voice_enhancement/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/flutter_tts-voice_enhancement/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png deleted file mode 100644 index e71a7261..00000000 Binary files a/flutter_tts-voice_enhancement/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/flutter_tts-voice_enhancement/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png deleted file mode 100644 index 8a31fe2d..00000000 Binary files a/flutter_tts-voice_enhancement/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/macos/Runner/Base.lproj/MainMenu.xib b/flutter_tts-voice_enhancement/example/macos/Runner/Base.lproj/MainMenu.xib deleted file mode 100644 index 537341ab..00000000 --- a/flutter_tts-voice_enhancement/example/macos/Runner/Base.lproj/MainMenu.xib +++ /dev/null @@ -1,339 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/flutter_tts-voice_enhancement/example/macos/Runner/Configs/AppInfo.xcconfig b/flutter_tts-voice_enhancement/example/macos/Runner/Configs/AppInfo.xcconfig deleted file mode 100644 index f960fd48..00000000 --- a/flutter_tts-voice_enhancement/example/macos/Runner/Configs/AppInfo.xcconfig +++ /dev/null @@ -1,14 +0,0 @@ -// Application-level settings for the Runner target. -// -// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the -// future. If not, the values below would default to using the project name when this becomes a -// 'flutter create' template. - -// The application's name. By default this is also the title of the Flutter window. -PRODUCT_NAME = example - -// The application's bundle identifier -PRODUCT_BUNDLE_IDENTIFIER = com.tundralabs.example - -// The copyright displayed in application information -PRODUCT_COPYRIGHT = Copyright © 2020 com.tundralabs. All rights reserved. diff --git a/flutter_tts-voice_enhancement/example/macos/Runner/Configs/Debug.xcconfig b/flutter_tts-voice_enhancement/example/macos/Runner/Configs/Debug.xcconfig deleted file mode 100644 index 36b0fd94..00000000 --- a/flutter_tts-voice_enhancement/example/macos/Runner/Configs/Debug.xcconfig +++ /dev/null @@ -1,2 +0,0 @@ -#include "../../Flutter/Flutter-Debug.xcconfig" -#include "Warnings.xcconfig" diff --git a/flutter_tts-voice_enhancement/example/macos/Runner/Configs/Release.xcconfig b/flutter_tts-voice_enhancement/example/macos/Runner/Configs/Release.xcconfig deleted file mode 100644 index dff4f495..00000000 --- a/flutter_tts-voice_enhancement/example/macos/Runner/Configs/Release.xcconfig +++ /dev/null @@ -1,2 +0,0 @@ -#include "../../Flutter/Flutter-Release.xcconfig" -#include "Warnings.xcconfig" diff --git a/flutter_tts-voice_enhancement/example/macos/Runner/Configs/Warnings.xcconfig b/flutter_tts-voice_enhancement/example/macos/Runner/Configs/Warnings.xcconfig deleted file mode 100644 index 42bcbf47..00000000 --- a/flutter_tts-voice_enhancement/example/macos/Runner/Configs/Warnings.xcconfig +++ /dev/null @@ -1,13 +0,0 @@ -WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings -GCC_WARN_UNDECLARED_SELECTOR = YES -CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES -CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE -CLANG_WARN__DUPLICATE_METHOD_MATCH = YES -CLANG_WARN_PRAGMA_PACK = YES -CLANG_WARN_STRICT_PROTOTYPES = YES -CLANG_WARN_COMMA = YES -GCC_WARN_STRICT_SELECTOR_MATCH = YES -CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES -CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES -GCC_WARN_SHADOW = YES -CLANG_WARN_UNREACHABLE_CODE = YES diff --git a/flutter_tts-voice_enhancement/example/macos/Runner/DebugProfile.entitlements b/flutter_tts-voice_enhancement/example/macos/Runner/DebugProfile.entitlements deleted file mode 100644 index dddb8a30..00000000 --- a/flutter_tts-voice_enhancement/example/macos/Runner/DebugProfile.entitlements +++ /dev/null @@ -1,12 +0,0 @@ - - - - - com.apple.security.app-sandbox - - com.apple.security.cs.allow-jit - - com.apple.security.network.server - - - diff --git a/flutter_tts-voice_enhancement/example/macos/Runner/Info.plist b/flutter_tts-voice_enhancement/example/macos/Runner/Info.plist deleted file mode 100644 index 4789daa6..00000000 --- a/flutter_tts-voice_enhancement/example/macos/Runner/Info.plist +++ /dev/null @@ -1,32 +0,0 @@ - - - - - CFBundleDevelopmentRegion - $(DEVELOPMENT_LANGUAGE) - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIconFile - - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - $(PRODUCT_NAME) - CFBundlePackageType - APPL - CFBundleShortVersionString - $(FLUTTER_BUILD_NAME) - CFBundleVersion - $(FLUTTER_BUILD_NUMBER) - LSMinimumSystemVersion - $(MACOSX_DEPLOYMENT_TARGET) - NSHumanReadableCopyright - $(PRODUCT_COPYRIGHT) - NSMainNibFile - MainMenu - NSPrincipalClass - NSApplication - - diff --git a/flutter_tts-voice_enhancement/example/macos/Runner/MainFlutterWindow.swift b/flutter_tts-voice_enhancement/example/macos/Runner/MainFlutterWindow.swift deleted file mode 100644 index 2722837e..00000000 --- a/flutter_tts-voice_enhancement/example/macos/Runner/MainFlutterWindow.swift +++ /dev/null @@ -1,15 +0,0 @@ -import Cocoa -import FlutterMacOS - -class MainFlutterWindow: NSWindow { - override func awakeFromNib() { - let flutterViewController = FlutterViewController.init() - let windowFrame = self.frame - self.contentViewController = flutterViewController - self.setFrame(windowFrame, display: true) - - RegisterGeneratedPlugins(registry: flutterViewController) - - super.awakeFromNib() - } -} diff --git a/flutter_tts-voice_enhancement/example/macos/Runner/Release.entitlements b/flutter_tts-voice_enhancement/example/macos/Runner/Release.entitlements deleted file mode 100644 index 852fa1a4..00000000 --- a/flutter_tts-voice_enhancement/example/macos/Runner/Release.entitlements +++ /dev/null @@ -1,8 +0,0 @@ - - - - - com.apple.security.app-sandbox - - - diff --git a/flutter_tts-voice_enhancement/example/pubspec.yaml b/flutter_tts-voice_enhancement/example/pubspec.yaml deleted file mode 100644 index 54cbe6ed..00000000 --- a/flutter_tts-voice_enhancement/example/pubspec.yaml +++ /dev/null @@ -1,59 +0,0 @@ -name: flutter_tts_example -description: Demonstrates how to use the flutter_tts plugin. - -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: ^0.1.2 - -dev_dependencies: - flutter_test: - sdk: flutter - - flutter_tts: - path: ../ - -# For information on the generic Dart part of this file, see the -# following page: https://www.dartlang.org/tools/pub/pubspec - -# The following section is specific to Flutter. -flutter: - - # The following line ensures that the Material Icons font is - # included with your application, so that you can use the icons in - # the material Icons class. - uses-material-design: true - - # To add assets to your application, add an assets section, like this: - # assets: - # - images/a_dot_burr.jpeg - # - images/a_dot_ham.jpeg - - # An image asset can refer to one or more resolution-specific "variants", see - # https://flutter.io/assets-and-images/#resolution-aware. - - # For details regarding adding assets from package dependencies, see - # https://flutter.io/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.io/custom-fonts/#from-packages diff --git a/flutter_tts-voice_enhancement/example/test/widget_test.dart b/flutter_tts-voice_enhancement/example/test/widget_test.dart deleted file mode 100644 index 6db856cd..00000000 --- a/flutter_tts-voice_enhancement/example/test/widget_test.dart +++ /dev/null @@ -1,30 +0,0 @@ -// This is a basic Flutter widget test. -// -// To perform an interaction with a widget in your test, use the WidgetTester -// utility that Flutter provides. For example, you can send tap and scroll -// gestures. You can also use WidgetTester to find child widgets in the widget -// tree, read text, and verify that the values of widget properties are correct. - -import 'package:flutter/material.dart'; -import 'package:flutter_test/flutter_test.dart'; - -import '../lib/main.dart'; - -void main() { - testWidgets('Counter increments smoke test', (WidgetTester tester) async { - // Build our app and trigger a frame. - await tester.pumpWidget(MyApp()); - - // Verify that our counter starts at 0. - expect(find.text('0'), findsOneWidget); - expect(find.text('1'), findsNothing); - - // Tap the '+' icon and trigger a frame. - await tester.tap(find.byIcon(Icons.add)); - await tester.pump(); - - // Verify that our counter has incremented. - expect(find.text('0'), findsNothing); - expect(find.text('1'), findsOneWidget); - }); -} diff --git a/flutter_tts-voice_enhancement/example/web/favicon.png b/flutter_tts-voice_enhancement/example/web/favicon.png deleted file mode 100644 index 8aaa46ac..00000000 Binary files a/flutter_tts-voice_enhancement/example/web/favicon.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/web/icons/Icon-192.png b/flutter_tts-voice_enhancement/example/web/icons/Icon-192.png deleted file mode 100644 index b749bfef..00000000 Binary files a/flutter_tts-voice_enhancement/example/web/icons/Icon-192.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/web/icons/Icon-512.png b/flutter_tts-voice_enhancement/example/web/icons/Icon-512.png deleted file mode 100644 index 88cfd48d..00000000 Binary files a/flutter_tts-voice_enhancement/example/web/icons/Icon-512.png and /dev/null differ diff --git a/flutter_tts-voice_enhancement/example/web/index.html b/flutter_tts-voice_enhancement/example/web/index.html deleted file mode 100644 index 20b0c00a..00000000 --- a/flutter_tts-voice_enhancement/example/web/index.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - - Flutter TTS example - - - - - diff --git a/flutter_tts-voice_enhancement/example/web/manifest.json b/flutter_tts-voice_enhancement/example/web/manifest.json deleted file mode 100644 index 8c012917..00000000 --- a/flutter_tts-voice_enhancement/example/web/manifest.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "example", - "short_name": "example", - "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" - } - ] -} diff --git a/flutter_tts-voice_enhancement/ios/.gitignore b/flutter_tts-voice_enhancement/ios/.gitignore deleted file mode 100644 index 956c87f3..00000000 --- a/flutter_tts-voice_enhancement/ios/.gitignore +++ /dev/null @@ -1,31 +0,0 @@ -.idea/ -.vagrant/ -.sconsign.dblite -.svn/ - -.DS_Store -*.swp -profile - -DerivedData/ -build/ - -*.pbxuser -*.mode1v3 -*.mode2v3 -*.perspectivev3 - -!default.pbxuser -!default.mode1v3 -!default.mode2v3 -!default.perspectivev3 - -xcuserdata - -*.moved-aside - -*.pyc -*sync/ -Icon? -.tags* - diff --git a/flutter_tts-voice_enhancement/ios/Assets/.gitkeep b/flutter_tts-voice_enhancement/ios/Assets/.gitkeep deleted file mode 100644 index e69de29b..00000000 diff --git a/flutter_tts-voice_enhancement/ios/Classes/AudioCategory.swift b/flutter_tts-voice_enhancement/ios/Classes/AudioCategory.swift deleted file mode 100644 index 74e8ea0b..00000000 --- a/flutter_tts-voice_enhancement/ios/Classes/AudioCategory.swift +++ /dev/null @@ -1,21 +0,0 @@ -import AVFoundation - -enum AudioCategory: String { - case iosAudioCategoryAmbientSolo - case iosAudioCategoryAmbient - case iosAudioCategoryPlayback - case iosAudioCategoryPlaybackAndRecord - - func toAVAudioSessionCategory() -> AVAudioSession.Category { - switch self { - case .iosAudioCategoryAmbientSolo: - return .soloAmbient - case .iosAudioCategoryAmbient: - return .ambient - case .iosAudioCategoryPlayback: - return .playback - case .iosAudioCategoryPlaybackAndRecord: - return .playAndRecord - } - } -} diff --git a/flutter_tts-voice_enhancement/ios/Classes/AudioCategoryOptions.swift b/flutter_tts-voice_enhancement/ios/Classes/AudioCategoryOptions.swift deleted file mode 100644 index f593bfdb..00000000 --- a/flutter_tts-voice_enhancement/ios/Classes/AudioCategoryOptions.swift +++ /dev/null @@ -1,42 +0,0 @@ -import AVFoundation - -enum AudioCategoryOptions: String { - case iosAudioCategoryOptionsMixWithOthers - case iosAudioCategoryOptionsDuckOthers - case iosAudioCategoryOptionsInterruptSpokenAudioAndMixWithOthers - case iosAudioCategoryOptionsAllowBluetooth - case iosAudioCategoryOptionsAllowBluetoothA2DP - case iosAudioCategoryOptionsAllowAirPlay - case iosAudioCategoryOptionsDefaultToSpeaker - - func toAVAudioSessionCategoryOptions() -> AVAudioSession.CategoryOptions? { - switch self { - case .iosAudioCategoryOptionsMixWithOthers: - return .mixWithOthers - case .iosAudioCategoryOptionsDuckOthers: - return .duckOthers - case .iosAudioCategoryOptionsInterruptSpokenAudioAndMixWithOthers: - if #available(iOS 9.0, *) { - return .interruptSpokenAudioAndMixWithOthers - } else { - return nil - } - case .iosAudioCategoryOptionsAllowBluetooth: - return .allowBluetooth - case .iosAudioCategoryOptionsAllowBluetoothA2DP: - if #available(iOS 10.0, *) { - return .allowBluetoothA2DP - } else { - return nil - } - case .iosAudioCategoryOptionsAllowAirPlay: - if #available(iOS 10.0, *) { - return .allowAirPlay - } else { - return nil - } - case .iosAudioCategoryOptionsDefaultToSpeaker: - return .defaultToSpeaker - } - } -} diff --git a/flutter_tts-voice_enhancement/ios/Classes/FlutterTtsPlugin.h b/flutter_tts-voice_enhancement/ios/Classes/FlutterTtsPlugin.h deleted file mode 100644 index 13e3a21a..00000000 --- a/flutter_tts-voice_enhancement/ios/Classes/FlutterTtsPlugin.h +++ /dev/null @@ -1,4 +0,0 @@ -#import - -@interface FlutterTtsPlugin : NSObject -@end diff --git a/flutter_tts-voice_enhancement/ios/Classes/FlutterTtsPlugin.m b/flutter_tts-voice_enhancement/ios/Classes/FlutterTtsPlugin.m deleted file mode 100644 index 3a1f187c..00000000 --- a/flutter_tts-voice_enhancement/ios/Classes/FlutterTtsPlugin.m +++ /dev/null @@ -1,8 +0,0 @@ -#import "FlutterTtsPlugin.h" -#import - -@implementation FlutterTtsPlugin -+ (void)registerWithRegistrar:(NSObject*)registrar { - [SwiftFlutterTtsPlugin registerWithRegistrar:registrar]; -} -@end diff --git a/flutter_tts-voice_enhancement/ios/Classes/SwiftFlutterTtsPlugin.swift b/flutter_tts-voice_enhancement/ios/Classes/SwiftFlutterTtsPlugin.swift deleted file mode 100644 index 5c78c135..00000000 --- a/flutter_tts-voice_enhancement/ios/Classes/SwiftFlutterTtsPlugin.swift +++ /dev/null @@ -1,386 +0,0 @@ -import Flutter -import UIKit -import AVFoundation - -public class SwiftFlutterTtsPlugin: NSObject, FlutterPlugin, AVSpeechSynthesizerDelegate { - final var iosAudioCategoryKey = "iosAudioCategoryKey" - final var iosAudioCategoryOptionsKey = "iosAudioCategoryOptionsKey" - - let synthesizer = AVSpeechSynthesizer() - var language: String = AVSpeechSynthesisVoice.currentLanguageCode() - var rate: Float = AVSpeechUtteranceDefaultSpeechRate - var languages = Set() - var volume: Float = 1.0 - var pitch: Float = 1.0 - var voice: AVSpeechSynthesisVoice? - var awaitSpeakCompletion: Bool = false - var speakResult: FlutterResult! - - var channel = FlutterMethodChannel() - lazy var audioSession = AVAudioSession.sharedInstance() - init(channel: FlutterMethodChannel) { - super.init() - self.channel = channel - synthesizer.delegate = self - setLanguages() - - // Allow audio playback when the Ring/Silent switch is set to silent - do { - try audioSession.setCategory(.playAndRecord, options: [.defaultToSpeaker]) - } catch { - print(error) - } - } - - private func setLanguages() { - for voice in AVSpeechSynthesisVoice.speechVoices(){ - self.languages.insert(voice.language) - } - } - - public static func register(with registrar: FlutterPluginRegistrar) { - let channel = FlutterMethodChannel(name: "flutter_tts", binaryMessenger: registrar.messenger()) - let instance = SwiftFlutterTtsPlugin(channel: channel) - registrar.addMethodCallDelegate(instance, channel: channel) - } - - public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { - switch call.method { - case "speak": - let text: String = call.arguments as! String - self.speak(text: text, result: result) - break - case "awaitSpeakCompletion": - self.awaitSpeakCompletion = call.arguments as! Bool - result(1) - break - case "synthesizeToFile": - guard let args = call.arguments as? [String: Any] else { - result("iOS could not recognize flutter arguments in method: (sendParams)") - return - } - let text = args["text"] as! String - let fileName = args["fileName"] as! String - self.synthesizeToFile(text: text, fileName: fileName, result: result) - break - case "pause": - self.pause(result: result) - break - case "setLanguage": - let language: String = call.arguments as! String - self.setLanguage(language: language, result: result) - break - case "setSpeechRate": - let rate: Double = call.arguments as! Double - self.setRate(rate: Float(rate)) - result(1) - break - case "setVolume": - let volume: Double = call.arguments as! Double - self.setVolume(volume: Float(volume), result: result) - break - case "setPitch": - let pitch: Double = call.arguments as! Double - self.setPitch(pitch: Float(pitch), result: result) - break - case "stop": - self.stop() - result(1) - break - case "getLanguages": - self.getLanguages(result: result) - break - case "getSpeechRateValidRange": - self.getSpeechRateValidRange(result: result) - break - case "isLanguageAvailable": - let language: String = call.arguments as! String - self.isLanguageAvailable(language: language, result: result) - break - case "getVoices": - self.getVoices(result: result) - break - case "setVoice": - guard let args = call.arguments as? [String: String] else { - result("iOS could not recognize flutter arguments in method: (sendParams)") - return - } - self.setVoice(voice: args, result: result) - break - case "setSharedInstance": - let sharedInstance = call.arguments as! Bool - self.setSharedInstance(sharedInstance: sharedInstance, result: result) - break - case "setIosAudioCategory": - guard let args = call.arguments as? [String: Any] else { - result("iOS could not recognize flutter arguments in method: (sendParams)") - return - } - let audioCategory = args["iosAudioCategoryKey"] as? String - let audioOptions = args[iosAudioCategoryOptionsKey] as? Array - self.setAudioCategory(audioCategory: audioCategory, audioOptions: audioOptions, result: result) - break - default: - result(FlutterMethodNotImplemented) - } - } - - private func speak(text: String, result: @escaping FlutterResult) { - if (self.synthesizer.isPaused) { - if (self.synthesizer.continueSpeaking()) { - if self.awaitSpeakCompletion { - self.speakResult = result - } else { - result(1) - } - } else { - result(0) - } - } else { - let utterance = AVSpeechUtterance(string: text) - if self.voice != nil { - utterance.voice = self.voice! - } else { - utterance.voice = AVSpeechSynthesisVoice(language: self.language) - } - utterance.rate = self.rate - utterance.volume = self.volume - utterance.pitchMultiplier = self.pitch - - self.synthesizer.speak(utterance) - if self.awaitSpeakCompletion { - self.speakResult = result - } else { - result(1) - } - } - } - - private func synthesizeToFile(text: String, fileName: String, result: FlutterResult) { - var output: AVAudioFile? - var failed = false - let utterance = AVSpeechUtterance(string: text) - - if self.voice != nil { - utterance.voice = self.voice! - } else { - utterance.voice = AVSpeechSynthesisVoice(language: self.language) - } - utterance.rate = self.rate - utterance.volume = self.volume - utterance.pitchMultiplier = self.pitch - - if #available(iOS 13.0, *) { - self.synthesizer.write(utterance) { (buffer: AVAudioBuffer) in - guard let pcmBuffer = buffer as? AVAudioPCMBuffer else { - NSLog("unknow buffer type: \(buffer)") - failed = true - return - } - print(pcmBuffer.format) - if pcmBuffer.frameLength == 0 { - // finished - } else { - // append buffer to file - let fileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent(fileName) - NSLog("Saving utterance to file: \(fileURL.absoluteString)") - - if output == nil { - do { - output = try AVAudioFile( - forWriting: fileURL, - settings: pcmBuffer.format.settings, - commonFormat: .pcmFormatInt16, - interleaved: false) - } catch { - NSLog(error.localizedDescription) - failed = true - return - } - } - - try! output!.write(from: pcmBuffer) - } - } - } else { - result("Unsupported iOS version") - } - if failed { - result(0) - } - result(1) - } - - private func pause(result: FlutterResult) { - if (self.synthesizer.pauseSpeaking(at: AVSpeechBoundary.word)) { - result(1) - } else { - result(0) - } - } - - private func setLanguage(language: String, result: FlutterResult) { - if !(self.languages.contains(where: {$0.range(of: language, options: [.caseInsensitive, .anchored]) != nil})) { - result(0) - } else { - self.language = language - self.voice = nil - result(1) - } - } - - private func setRate(rate: Float) { - self.rate = rate - } - - private func setVolume(volume: Float, result: FlutterResult) { - if (volume >= 0.0 && volume <= 1.0) { - self.volume = volume - result(1) - } else { - result(0) - } - } - - private func setPitch(pitch: Float, result: FlutterResult) { - if (volume >= 0.5 && volume <= 2.0) { - self.pitch = pitch - result(1) - } else { - result(0) - } - } - - private func setSharedInstance(sharedInstance: Bool, result: FlutterResult) { - do { - try AVAudioSession.sharedInstance().setActive(sharedInstance) - result(1) - } catch { - result(0) - } - } - - private func setAudioCategory(audioCategory: String?, audioOptions: Array?, result: FlutterResult){ - let category: AVAudioSession.Category = AudioCategory(rawValue: audioCategory ?? "")?.toAVAudioSessionCategory() ?? audioSession.category - let options: AVAudioSession.CategoryOptions = audioOptions?.reduce([], { (result, option) -> AVAudioSession.CategoryOptions in - return result.union(AudioCategoryOptions(rawValue: option)?.toAVAudioSessionCategoryOptions() ?? []) - }) ?? [] - - do { - try audioSession.setCategory(category, options: options) - result(1) - } catch { - print(error) - result(0) - } - } - - private func stop() { - self.synthesizer.stopSpeaking(at: AVSpeechBoundary.immediate) - } - - private func getLanguages(result: FlutterResult) { - result(Array(self.languages)) - } - - private func getSpeechRateValidRange(result: FlutterResult) { - let validSpeechRateRange: [String:String] = [ - "min": String(AVSpeechUtteranceMinimumSpeechRate), - "normal": String(AVSpeechUtteranceDefaultSpeechRate), - "max": String(AVSpeechUtteranceMaximumSpeechRate), - "platform": "ios" - ] - result(validSpeechRateRange) - } - - private func isLanguageAvailable(language: String, result: FlutterResult) { - var isAvailable: Bool = false - if (self.languages.contains(where: {$0.range(of: language, options: [.caseInsensitive, .anchored]) != nil})) { - isAvailable = true - } - result(isAvailable); - } - - private func getVoices(result: FlutterResult) { - if #available(iOS 9.0, *) { - let voices = NSMutableArray() - var voiceDict: [String: String] = [:] - for voice in AVSpeechSynthesisVoice.speechVoices() { - voiceDict["name"] = voice.name - voiceDict["locale"] = voice.language - voices.add(voiceDict) - } - result(voices) - } else { - // Since voice selection is not supported below iOS 9, make voice getter and setter - // have the same bahavior as language selection. - getLanguages(result: result) - } - } - - private func setVoice(voice: [String:String], result: FlutterResult) { - if #available(iOS 9.0, *) { - if let voice = AVSpeechSynthesisVoice.speechVoices().first(where: { $0.name == voice["name"]! && $0.language == voice["locale"]! }) { - self.voice = voice - self.language = voice.language - result(1) - return - } - result(0) - } else { - setLanguage(language: voice["name"]!, result: result) - } - } - - private func shouldDeactivateAndNotifyOthers(_ session: AVAudioSession) -> Bool { - var options: AVAudioSession.CategoryOptions = .duckOthers - if #available(iOS 9.0, *) { - options.insert(.interruptSpokenAudioAndMixWithOthers) - } - options.remove(.mixWithOthers) - - return !options.isDisjoint(with: session.categoryOptions) - } - - public func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) { - if shouldDeactivateAndNotifyOthers(audioSession) { - do { - try audioSession.setActive(false, options: .notifyOthersOnDeactivation) - } catch { - print(error) - } - } - if self.awaitSpeakCompletion { - self.speakResult(1) - } - self.channel.invokeMethod("speak.onComplete", arguments: nil) - } - - public func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didStart utterance: AVSpeechUtterance) { - self.channel.invokeMethod("speak.onStart", arguments: nil) - } - - public func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didPause utterance: AVSpeechUtterance) { - self.channel.invokeMethod("speak.onPause", arguments: nil) - } - - public func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didContinue utterance: AVSpeechUtterance) { - self.channel.invokeMethod("speak.onContinue", arguments: nil) - } - - public func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didCancel utterance: AVSpeechUtterance) { - self.channel.invokeMethod("speak.onCancel", arguments: nil) - } - - public func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, willSpeakRangeOfSpeechString characterRange: NSRange, utterance: AVSpeechUtterance) { - let nsWord = utterance.speechString as NSString - let data: [String:String] = [ - "text": utterance.speechString, - "start": String(characterRange.location), - "end": String(characterRange.location + characterRange.length), - "word": nsWord.substring(with: characterRange) - ] - self.channel.invokeMethod("speak.onProgress", arguments: data) - } - -} diff --git a/flutter_tts-voice_enhancement/ios/flutter_tts.podspec b/flutter_tts-voice_enhancement/ios/flutter_tts.podspec deleted file mode 100644 index 03099f45..00000000 --- a/flutter_tts-voice_enhancement/ios/flutter_tts.podspec +++ /dev/null @@ -1,22 +0,0 @@ -# -# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html -# -Pod::Spec.new do |s| - s.name = 'flutter_tts' - s.version = '0.0.1' - s.summary = 'A flutter text to speech plugin.' - s.description = <<-DESC -A flutter text to speech plugin - DESC - s.homepage = 'https://github.com/dlutton/flutter_tts' - s.license = { :file => '../LICENSE' } - s.author = { 'tundralabs' => 'eyedea32@gmail.com' } - s.source = { :path => '.' } - s.source_files = 'Classes/**/*' - s.public_header_files = 'Classes/**/*.h' - s.dependency 'Flutter' - s.ios.deployment_target = '8.0' - s.swift_version = '4.2' - s.static_framework = true -end - diff --git a/flutter_tts-voice_enhancement/lib/flutter_tts.dart b/flutter_tts-voice_enhancement/lib/flutter_tts.dart deleted file mode 100644 index c823a91d..00000000 --- a/flutter_tts-voice_enhancement/lib/flutter_tts.dart +++ /dev/null @@ -1,342 +0,0 @@ -import 'dart:async'; -import 'dart:io' show Platform; - -import 'package:flutter/foundation.dart'; -import 'package:flutter/services.dart'; - -typedef void ErrorHandler(dynamic message); -typedef ProgressHandler = void Function( - String text, int start, int end, String word); - -const String iosAudioCategoryOptionsKey = 'iosAudioCategoryOptionsKey'; -const String iosAudioCategoryKey = 'iosAudioCategoryKey'; -const String iosAudioCategoryAmbientSolo = 'iosAudioCategoryAmbientSolo'; -const String iosAudioCategoryAmbient = 'iosAudioCategoryAmbient'; -const String iosAudioCategoryPlayback = 'iosAudioCategoryPlayback'; -const String iosAudioCategoryPlaybackAndRecord = - 'iosAudioCategoryPlaybackAndRecord'; - -const String iosAudioCategoryOptionsMixWithOthers = - 'iosAudioCategoryOptionsMixWithOthers'; -const String iosAudioCategoryOptionsDuckOthers = - 'iosAudioCategoryOptionsDuckOthers'; -const String iosAudioCategoryOptionsInterruptSpokenAudioAndMixWithOthers = - 'iosAudioCategoryOptionsInterruptSpokenAudioAndMixWithOthers'; -const String iosAudioCategoryOptionsAllowBluetooth = - 'iosAudioCategoryOptionsAllowBluetooth'; -const String iosAudioCategoryOptionsAllowBluetoothA2DP = - 'iosAudioCategoryOptionsAllowBluetoothA2DP'; -const String iosAudioCategoryOptionsAllowAirPlay = - 'iosAudioCategoryOptionsAllowAirPlay'; -const String iosAudioCategoryOptionsDefaultToSpeaker = - 'iosAudioCategoryOptionsDefaultToSpeaker'; - -enum TextToSpeechPlatform { android, ios } - -enum IosTextToSpeechAudioCategory { - /// Audio is silenced by screen lock and the silent switch; audio will not mix - /// with other apps' audio. - ambientSolo, - - /// Audio is silenced by screen lock and the silent switch; audio will mix - /// with other apps' (mixable) audio. - ambient, - - /// Audio is not silenced by screen lock or silent switch; audio will not mix - /// with other apps' audio. - /// - playback, - - /// The category for recording (input) and playback (output) of audio, - /// such as for a Voice over Internet Protocol (VoIP) app. - /// The default value. - playAndRecord, -} - -enum IosTextToSpeechAudioCategoryOptions { - /// An option that indicates whether audio from this session mixes with audio - /// from active sessions in other audio apps. - mixWithOthers, - - /// An option that reduces the volume of other audio session while audio - /// from this session plays. - duckOthers, - - /// An option that determines whether to pause spoken audio content - /// from other sessions when your app plays its audio. - interruptSpokenAudioAndMixWithOthers, - - ///An option that determines whether Bluetooth hands-free devices - /// appear as available input routes. - allowBluetooth, - - ///An option that determines whether you can stream audio - /// from this session to Bluetooth devices that support the Advanced Audio Distribution Profile (A2DP). - allowBluetoothA2DP, - - ///An option that determines whether you can stream audio - /// from this session to AirPlay devices. - allowAirPlay, - - ///An option that determines whether audio - /// from the session defaults to the built-in speaker instead of the receiver. - /// The default value. - defaultToSpeaker, -} - -class SpeechRateValidRange { - final double min; - final double normal; - final double max; - final TextToSpeechPlatform platform; - - SpeechRateValidRange(this.min, this.normal, this.max, this.platform); -} - -// Provides Platform specific TTS services (Android: TextToSpeech, IOS: AVSpeechSynthesizer) -class FlutterTts { - static const MethodChannel _channel = const MethodChannel('flutter_tts'); - - VoidCallback startHandler; - VoidCallback completionHandler; - VoidCallback pauseHandler; - VoidCallback continueHandler; - VoidCallback cancelHandler; - ProgressHandler progressHandler; - ErrorHandler errorHandler; - - FlutterTts() { - _channel.setMethodCallHandler(platformCallHandler); - } - - /// [Future] which sets speak's future to return on completion of the utterance - Future awaitSpeakCompletion(bool awaitCompletion) async => - _channel.invokeMethod('awaitSpeakCompletion', awaitCompletion); - - /// [Future] which invokes the platform specific method for speaking - Future speak(String text) async => - _channel.invokeMethod('speak', text); - - /// [Future] which invokes the platform specific method for pause - /// ***iOS supported only*** - Future pause() async => _channel.invokeMethod('pause'); - - /// [Future] which invokes the platform specific method for synthesizeToFile - /// ***Android and iOS supported only*** - Future synthesizeToFile(String text, String fileName) async => - _channel.invokeMethod('synthesizeToFile', { - "text": text, - "fileName": fileName, - }); - - /// [Future] which invokes the platform specific method for setLanguage - Future setLanguage(String language) async => - _channel.invokeMethod('setLanguage', language); - - /// [Future] which invokes the platform specific method for setSpeechRate - /// Allowed values are in the range from 0.0 (slowest) to 1.0 (fastest) - Future setSpeechRate(double rate) async => - _channel.invokeMethod('setSpeechRate', rate); - - /// [Future] which invokes the platform specific method for setVolume - /// Allowed values are in the range from 0.0 (silent) to 1.0 (loudest) - Future setVolume(double volume) async => - _channel.invokeMethod('setVolume', volume); - - /// [Future] which invokes the platform specific method for shared instance - /// ***iOS supported only*** - Future setSharedInstance(bool sharedSession) async => - _channel.invokeMethod('setSharedInstance', sharedSession); - - /// [Future] which invokes the platform specific method for setting audio category - /// ***Ios supported only*** - Future setIosAudioCategory(IosTextToSpeechAudioCategory category, - List options) async { - const categoryToString = { - IosTextToSpeechAudioCategory.ambientSolo: iosAudioCategoryAmbientSolo, - IosTextToSpeechAudioCategory.ambient: iosAudioCategoryAmbient, - IosTextToSpeechAudioCategory.playback: iosAudioCategoryPlayback - }; - const optionsToString = { - IosTextToSpeechAudioCategoryOptions.mixWithOthers: - 'iosAudioCategoryOptionsMixWithOthers', - IosTextToSpeechAudioCategoryOptions.duckOthers: - 'iosAudioCategoryOptionsDuckOthers', - IosTextToSpeechAudioCategoryOptions.interruptSpokenAudioAndMixWithOthers: - 'iosAudioCategoryOptionsInterruptSpokenAudioAndMixWithOthers', - IosTextToSpeechAudioCategoryOptions.allowBluetooth: - 'iosAudioCategoryOptionsAllowBluetooth', - IosTextToSpeechAudioCategoryOptions.allowBluetoothA2DP: - 'iosAudioCategoryOptionsAllowBluetoothA2DP', - IosTextToSpeechAudioCategoryOptions.allowAirPlay: - 'iosAudioCategoryOptionsAllowAirPlay', - IosTextToSpeechAudioCategoryOptions.defaultToSpeaker: - 'iosAudioCategoryOptionsDefaultToSpeaker', - }; - if (!Platform.isIOS) return; - try { - return _channel - .invokeMethod('setIosAudioCategory', { - iosAudioCategoryKey: categoryToString[category], - iosAudioCategoryOptionsKey: - options.map((o) => optionsToString[o]).toList(), - }); - } on PlatformException catch (e) { - print( - 'setIosAudioCategory error, category: $category, error: ${e.message}'); - } - } - - /// [Future] which invokes the platform specific method for setPitch - /// 1.0 is default and ranges from .5 to 2.0 - Future setPitch(double pitch) async => - _channel.invokeMethod('setPitch', pitch); - - /// [Future] which invokes the platform specific method for setVoice - /// ***Android, iOS, and macOS supported only*** - Future setVoice(Map voice) async => - _channel.invokeMethod('setVoice', voice); - - /// [Future] which invokes the platform specific method for stop - Future stop() async => _channel.invokeMethod('stop'); - - /// [Future] which invokes the platform specific method for getLanguages - /// Android issues with API 21 & 22 - /// Returns a list of available languages - Future get getLanguages async { - final languages = await _channel.invokeMethod('getLanguages'); - return languages; - } - - /// [Future] which invokes the platform specific method for getEngines - /// Returns a list of installed TTS engines - /// ***Android supported only*** - Future get getEngines async { - final engines = await _channel.invokeMethod('getEngines'); - return engines; - } - - /// [Future] which invokes the platform specific method for getVoices - /// Returns a `List` of `Maps` containing a voice name and locale - /// ***Android, iOS, and macOS supported only*** - Future get getVoices async { - final voices = await _channel.invokeMethod('getVoices'); - return voices; - } - - /// [Future] which invokes the platform specific method for isLanguageAvailable - /// Returns `true` or `false` - Future isLanguageAvailable(String language) async => - _channel.invokeMethod('isLanguageAvailable', language); - - Future get getSpeechRateValidRange async { - final validRange = await _channel.invokeMethod('getSpeechRateValidRange') - as Map; - final min = double.parse(validRange['min'].toString()); - final normal = double.parse(validRange['normal'].toString()); - final max = double.parse(validRange['max'].toString()); - final platformStr = validRange['platform'].toString(); - final platform = TextToSpeechPlatform.values - .firstWhere((e) => describeEnum(e) == platformStr); - - return SpeechRateValidRange(min, normal, max, platform); - } - - /// [Future] which invokes the platform specific method for setSilence - /// 0 means start the utterance immediately. If the value is greater than zero a silence period in milliseconds is set according to the parameter - /// ***Android supported only*** - Future setSilence(int timems) async => - _channel.invokeMethod('setSilence', timems ?? 0); - - void setStartHandler(VoidCallback callback) { - startHandler = callback; - } - - void setCompletionHandler(VoidCallback callback) { - completionHandler = callback; - } - - void setContinueHandler(VoidCallback callback) { - continueHandler = callback; - } - - void setPauseHandler(VoidCallback callback) { - pauseHandler = callback; - } - - void setCancelHandler(VoidCallback callback) { - cancelHandler = callback; - } - - void setProgressHandler(ProgressHandler callback) { - progressHandler = callback; - } - - void setErrorHandler(ErrorHandler handler) { - errorHandler = handler; - } - - /// Platform listeners - Future platformCallHandler(MethodCall call) async { - switch (call.method) { - case "speak.onStart": - if (startHandler != null) { - startHandler(); - } - break; - case "synth.onStart": - if (startHandler != null) { - startHandler(); - } - break; - case "speak.onComplete": - if (completionHandler != null) { - completionHandler(); - } - break; - case "synth.onComplete": - if (completionHandler != null) { - completionHandler(); - } - break; - case "speak.onPause": - if (pauseHandler != null) { - pauseHandler(); - } - break; - case "speak.onContinue": - if (continueHandler != null) { - continueHandler(); - } - break; - case "speak.onCancel": - if (cancelHandler != null) { - cancelHandler(); - } - break; - case "speak.onError": - if (errorHandler != null) { - errorHandler(call.arguments); - } - break; - case 'speak.onProgress': - if (progressHandler != null) { - final args = call.arguments as Map; - progressHandler( - args['text'].toString(), - int.parse(args['start'].toString()), - int.parse(args['end'].toString()), - args['word'].toString(), - ); - } - break; - case "synth.onError": - if (errorHandler != null) { - errorHandler(call.arguments); - } - break; - default: - print('Unknowm method ${call.method}'); - } - } -} diff --git a/flutter_tts-voice_enhancement/lib/flutter_tts_web.dart b/flutter_tts-voice_enhancement/lib/flutter_tts_web.dart deleted file mode 100644 index 182e9dfa..00000000 --- a/flutter_tts-voice_enhancement/lib/flutter_tts_web.dart +++ /dev/null @@ -1,184 +0,0 @@ -import 'dart:async'; -import 'dart:html' as html; -import 'dart:js'; - -import 'package:flutter/services.dart'; -import 'package:flutter_web_plugins/flutter_web_plugins.dart'; - -enum TtsState { playing, stopped, paused, continued } - -class FlutterTtsPlugin { - static const String PLATFORM_CHANNEL = "flutter_tts"; - static MethodChannel channel; - bool awaitSpeakCompletion = false; - - TtsState ttsState = TtsState.stopped; - - get isPlaying => ttsState == TtsState.playing; - - get isStopped => ttsState == TtsState.stopped; - - get isPaused => ttsState == TtsState.paused; - - get isContinued => ttsState == TtsState.continued; - - static void registerWith(Registrar registrar) { - channel = MethodChannel( - PLATFORM_CHANNEL, const StandardMethodCodec(), registrar.messenger); - final instance = FlutterTtsPlugin(); - channel.setMethodCallHandler(instance.handleMethodCall); - } - - html.SpeechSynthesis synth; - html.SpeechSynthesisUtterance utterance; - List voices; - List languages; - - FlutterTtsPlugin() { - utterance = html.SpeechSynthesisUtterance(); - synth = html.window.speechSynthesis; - - _listeners(); - } - - void _listeners() { - utterance.onStart.listen((e) { - ttsState = TtsState.playing; - channel.invokeMethod("speak.onStart", null); - }); - utterance.onEnd.listen((e) { - ttsState = TtsState.stopped; - channel.invokeMethod("speak.onComplete", null); - if (awaitSpeakCompletion) { - return 1; - } - }); - utterance.onPause.listen((e) { - ttsState = TtsState.paused; - channel.invokeMethod("speak.onPause", null); - }); - utterance.onResume.listen((e) { - ttsState = TtsState.continued; - channel.invokeMethod("speak.onContinue", null); - }); - utterance.onError.listen((e) { - channel.invokeMethod("speak.onError", e); - if (awaitSpeakCompletion) { - return 0; - } - }); - } - - Future handleMethodCall(MethodCall call) async { - switch (call.method) { - case 'speak': - final text = call.arguments as String; - _speak(text); - if (!awaitSpeakCompletion) { - return 1; - } - break; - case 'awaitSpeakCompletion': - awaitSpeakCompletion = call.arguments as bool; - return 1; - break; - case 'stop': - _stop(); - return 1; - break; - case 'pause': - _pause(); - return 1; - break; - case 'setLanguage': - final language = call.arguments as String; - _setLanguage(language); - return 1; - break; - case 'getLanguages': - return _getLanguages(); - break; - case 'setSpeechRate': - final rate = call.arguments as num; - _setRate(rate); - return 1; - break; - case 'setVolume': - final volume = call.arguments as num; - _setVolume(volume); - return 1; - break; - case 'setPitch': - final pitch = call.arguments as num; - _setPitch(pitch); - return 1; - break; - case 'isLanguageAvailable': - final lang = call.arguments as String; - return _isLanguageAvailable(lang); - break; - default: - throw PlatformException( - code: 'Unimplemented', - details: "The flutter_tts plugin for web doesn't implement " - "the method '${call.method}'"); - } - } - - void _speak(String text) { - if (ttsState == TtsState.stopped || ttsState == TtsState.paused) { - utterance.text = text; - if (ttsState == TtsState.paused) { - synth.resume(); - } else { - synth.speak(utterance); - } - } - } - - void _stop() { - if (ttsState != TtsState.stopped) { - synth.cancel(); - } - } - - void _pause() { - if (ttsState == TtsState.playing || ttsState == TtsState.continued) { - synth.pause(); - } - } - - void _setRate(num rate) => utterance.rate = rate * 2.0; - void _setVolume(num volume) => utterance.volume = volume; - void _setPitch(num pitch) => utterance.pitch = pitch; - void _setLanguage(String language) => utterance.lang = language; - - bool _isLanguageAvailable(String language) { - if (voices?.isEmpty ?? true) _setVoices(); - if (languages?.isEmpty ?? true) _setLanguages(); - for (var lang in languages) { - if (lang.toLowerCase() == language.toLowerCase()) return true; - } - return false; - } - - List _getLanguages() { - if (voices?.isEmpty ?? true) _setVoices(); - if (languages?.isEmpty ?? true) _setLanguages(); - return languages; - } - - void _setVoices() { - voices = - context['speechSynthesis'].callMethod('getVoices') as JsArray; - } - - void _setLanguages() { - var langs = Set(); - for (var v in voices) { - langs.add(v['lang'] as String); - } - - languages = langs.toList(); - } -} diff --git a/flutter_tts-voice_enhancement/macos/Classes/FlutterTtsPlugin.swift b/flutter_tts-voice_enhancement/macos/Classes/FlutterTtsPlugin.swift deleted file mode 100644 index ec4bffa1..00000000 --- a/flutter_tts-voice_enhancement/macos/Classes/FlutterTtsPlugin.swift +++ /dev/null @@ -1,315 +0,0 @@ -import FlutterMacOS -import Foundation -import AVFoundation - -public class FlutterTtsPlugin: NSObject, FlutterPlugin, AVSpeechSynthesizerDelegate { - final var iosAudioCategoryKey = "iosAudioCategoryKey" - final var iosAudioCategoryOptionsKey = "iosAudioCategoryOptionsKey" - - let synthesizer = AVSpeechSynthesizer() - var language: String = AVSpeechSynthesisVoice.currentLanguageCode() - var rate: Float = AVSpeechUtteranceDefaultSpeechRate - var languages = Set() - var volume: Float = 1.0 - var pitch: Float = 1.0 - var voice: AVSpeechSynthesisVoice? - var awaitSpeakCompletion: Bool = false - var speakResult: FlutterResult! - - var channel = FlutterMethodChannel() - init(channel: FlutterMethodChannel) { - super.init() - self.channel = channel - synthesizer.delegate = self - setLanguages() - } - - private func setLanguages() { - for voice in AVSpeechSynthesisVoice.speechVoices(){ - self.languages.insert(voice.language) - } - } - - public static func register(with registrar: FlutterPluginRegistrar) { - let channel = FlutterMethodChannel(name: "flutter_tts", binaryMessenger: registrar.messenger) - let instance = FlutterTtsPlugin(channel: channel) - registrar.addMethodCallDelegate(instance, channel: channel) - } - - public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { - switch call.method { - case "speak": - let text: String = call.arguments as! String - self.speak(text: text, result: result) - break - case "awaitSpeakCompletion": - self.awaitSpeakCompletion = call.arguments as! Bool - result(1) - break - case "synthesizeToFile": - guard let args = call.arguments as? [String: Any] else { - result("iOS could not recognize flutter arguments in method: (sendParams)") - return - } - let text = args["text"] as! String - let fileName = args["fileName"] as! String - self.synthesizeToFile(text: text, fileName: fileName, result: result) - break - case "pause": - self.pause(result: result) - break - case "setLanguage": - let language: String = call.arguments as! String - self.setLanguage(language: language, result: result) - break - case "setSpeechRate": - let rate: Double = call.arguments as! Double - self.setRate(rate: Float(rate)) - result(1) - break - case "setVolume": - let volume: Double = call.arguments as! Double - self.setVolume(volume: Float(volume), result: result) - break - case "setPitch": - let pitch: Double = call.arguments as! Double - self.setPitch(pitch: Float(pitch), result: result) - break - case "stop": - self.stop() - result(1) - break - case "getLanguages": - self.getLanguages(result: result) - break - case "getSpeechRateValidRange": - self.getSpeechRateValidRange(result: result) - break - case "isLanguageAvailable": - let language: String = call.arguments as! String - self.isLanguageAvailable(language: language, result: result) - break - case "getVoices": - self.getVoices(result: result) - break - case "setVoice": - guard let args = call.arguments as? [String: String] else { - result("iOS could not recognize flutter arguments in method: (sendParams)") - return - } - self.setVoice(voice: args, result: result) - break - default: - result(FlutterMethodNotImplemented) - } - } - - private func speak(text: String, result: @escaping FlutterResult) { - if (self.synthesizer.isPaused) { - if (self.synthesizer.continueSpeaking()) { - if self.awaitSpeakCompletion { - self.speakResult = result - } else { - result(1) - } - } else { - result(0) - } - } else { - let utterance = AVSpeechUtterance(string: text) - if self.voice != nil { - utterance.voice = self.voice! - } else { - utterance.voice = AVSpeechSynthesisVoice(language: self.language) - } - utterance.rate = self.rate - utterance.volume = self.volume - utterance.pitchMultiplier = self.pitch - - self.synthesizer.speak(utterance) - if self.awaitSpeakCompletion { - self.speakResult = result - } else { - result(1) - } - } - } - - private func synthesizeToFile(text: String, fileName: String, result: FlutterResult) { - var output: AVAudioFile? - var failed = false - let utterance = AVSpeechUtterance(string: text) - - if #available(iOS 13.0, *) { - self.synthesizer.write(utterance) { (buffer: AVAudioBuffer) in - guard let pcmBuffer = buffer as? AVAudioPCMBuffer else { - NSLog("unknow buffer type: \(buffer)") - failed = true - return - } - print(pcmBuffer.format) - if pcmBuffer.frameLength == 0 { - // finished - } else { - // append buffer to file - let fileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent(fileName) - NSLog("Saving utterance to file: \(fileURL.absoluteString)") - - if output == nil { - do { - output = try AVAudioFile( - forWriting: fileURL, - settings: pcmBuffer.format.settings, - commonFormat: .pcmFormatInt16, - interleaved: false) - } catch { - NSLog(error.localizedDescription) - failed = true - return - } - } - - try! output!.write(from: pcmBuffer) - } - } - } else { - result("Unsupported iOS version") - } - if failed { - result(0) - } - result(1) - } - - private func pause(result: FlutterResult) { - if (self.synthesizer.pauseSpeaking(at: AVSpeechBoundary.word)) { - result(1) - } else { - result(0) - } - } - - private func setLanguage(language: String, result: FlutterResult) { - if !(self.languages.contains(where: {$0.range(of: language, options: [.caseInsensitive, .anchored]) != nil})) { - result(0) - } else { - self.language = language - self.voice = nil - result(1) - } - } - - private func setRate(rate: Float) { - self.rate = rate - } - - private func setVolume(volume: Float, result: FlutterResult) { - if (volume >= 0.0 && volume <= 1.0) { - self.volume = volume - result(1) - } else { - result(0) - } - } - - private func setPitch(pitch: Float, result: FlutterResult) { - if (volume >= 0.5 && volume <= 2.0) { - self.pitch = pitch - result(1) - } else { - result(0) - } - } - - private func stop() { - self.synthesizer.stopSpeaking(at: AVSpeechBoundary.immediate) - } - - private func getLanguages(result: FlutterResult) { - result(Array(self.languages)) - } - - private func getSpeechRateValidRange(result: FlutterResult) { - let validSpeechRateRange: [String:String] = [ - "min": String(AVSpeechUtteranceMinimumSpeechRate), - "normal": String(AVSpeechUtteranceDefaultSpeechRate), - "max": String(AVSpeechUtteranceMaximumSpeechRate), - "platform": "ios" - ] - result(validSpeechRateRange) - } - - private func isLanguageAvailable(language: String, result: FlutterResult) { - var isAvailable: Bool = false - if (self.languages.contains(where: {$0.range(of: language, options: [.caseInsensitive, .anchored]) != nil})) { - isAvailable = true - } - result(isAvailable); - } - - private func getVoices(result: FlutterResult) { - if #available(iOS 9.0, *) { - let voices = NSMutableArray() - var voiceDict: [String: String] = [:] - for voice in AVSpeechSynthesisVoice.speechVoices() { - voiceDict["name"] = voice.name - voiceDict["locale"] = voice.language - voices.add(voiceDict) - } - result(voices) - } else { - // Since voice selection is not supported below iOS 9, make voice getter and setter - // have the same bahavior as language selection. - getLanguages(result: result) - } - } - - private func setVoice(voice: [String:String], result: FlutterResult) { - if #available(iOS 9.0, *) { - if let voice = AVSpeechSynthesisVoice.speechVoices().first(where: { $0.name == voice["name"]! && $0.language == voice["locale"]! }) { - self.voice = voice - self.language = voice.language - result(1) - return - } - result(0) - } else { - setLanguage(language: voice["name"]!, result: result) - } - } - - public func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) { - if self.awaitSpeakCompletion { - self.speakResult(1) - } - self.channel.invokeMethod("speak.onComplete", arguments: nil) - } - - public func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didStart utterance: AVSpeechUtterance) { - self.channel.invokeMethod("speak.onStart", arguments: nil) - } - - public func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didPause utterance: AVSpeechUtterance) { - self.channel.invokeMethod("speak.onPause", arguments: nil) - } - - public func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didContinue utterance: AVSpeechUtterance) { - self.channel.invokeMethod("speak.onContinue", arguments: nil) - } - - public func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didCancel utterance: AVSpeechUtterance) { - self.channel.invokeMethod("speak.onCancel", arguments: nil) - } - - public func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, willSpeakRangeOfSpeechString characterRange: NSRange, utterance: AVSpeechUtterance) { - let nsWord = utterance.speechString as NSString - let data: [String:String] = [ - "text": utterance.speechString, - "start": String(characterRange.location), - "end": String(characterRange.location + characterRange.length), - "word": nsWord.substring(with: characterRange) - ] - self.channel.invokeMethod("speak.onProgress", arguments: data) - } - -} diff --git a/flutter_tts-voice_enhancement/macos/flutter_tts.podspec b/flutter_tts-voice_enhancement/macos/flutter_tts.podspec deleted file mode 100644 index 2838eb07..00000000 --- a/flutter_tts-voice_enhancement/macos/flutter_tts.podspec +++ /dev/null @@ -1,22 +0,0 @@ -# -# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html -# -Pod::Spec.new do |s| - s.name = 'flutter_tts' - s.version = '0.0.1' - s.summary = 'macOS implementation of the flutter_tts plugin.' - s.description = <<-DESC - A flutter text to speech plugin - DESC - s.homepage = 'https://github.com/dlutton/flutter_tts' - s.license = { :file => '../LICENSE' } - s.author = { 'Daniel Lutton' => 'eyedea32@gmail.com' } - s.source = { :path => '.' } - s.source_files = 'Classes/**/*' - s.dependency 'FlutterMacOS' - - s.platform = :osx, '10.15' - s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' } - s.swift_version = '5.0' - - end \ No newline at end of file diff --git a/flutter_tts-voice_enhancement/pubspec.yaml b/flutter_tts-voice_enhancement/pubspec.yaml deleted file mode 100644 index 06e93f33..00000000 --- a/flutter_tts-voice_enhancement/pubspec.yaml +++ /dev/null @@ -1,28 +0,0 @@ -name: flutter_tts -description: A flutter plugin for Text to Speech. This plugin is supported on iOS, Android, Web, & macOS. -version: 1.3.0 -homepage: https://github.com/dlutton/flutter_tts - -dependencies: - flutter: - sdk: flutter - flutter_web_plugins: - sdk: flutter - -flutter: - plugin: - platforms: - android: - package: com.tundralabs.fluttertts - pluginClass: FlutterTtsPlugin - ios: - pluginClass: FlutterTtsPlugin - macos: - pluginClass: FlutterTtsPlugin - web: - pluginClass: FlutterTtsPlugin - fileName: flutter_tts_web.dart - -environment: - sdk: ">=2.1.0 <3.0.0" - flutter: ">=1.12.13+hotfix.5 <2.0.0" diff --git a/hms-plugins/flutter-hms-location/.docs/images/homeScreen.jpg b/hms-plugins/flutter-hms-location/.docs/images/homeScreen.jpg deleted file mode 100644 index abfc5b99..00000000 Binary files a/hms-plugins/flutter-hms-location/.docs/images/homeScreen.jpg and /dev/null differ diff --git a/hms-plugins/flutter-hms-location/CHANGELOG.md b/hms-plugins/flutter-hms-location/CHANGELOG.md deleted file mode 100644 index 8c43b7b8..00000000 --- a/hms-plugins/flutter-hms-location/CHANGELOG.md +++ /dev/null @@ -1,12 +0,0 @@ -## 5.0.0+301 - -* Added the getNavigationContextState function. -* Added the enableLogger and disableLogger methods. - -## 4.0.4+1/4.0.4+300 - -* Fix minor issues. - -## 4.0.4 - -* Initial release. diff --git a/hms-plugins/flutter-hms-location/LICENSE b/hms-plugins/flutter-hms-location/LICENSE deleted file mode 100644 index 7783de53..00000000 --- a/hms-plugins/flutter-hms-location/LICENSE +++ /dev/null @@ -1,53 +0,0 @@ -Apache License - -Version 2.0, January 2004 - -http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - -"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. - -"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. - -"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. - -"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. - -"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. - -"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. - -"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). - -"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. - -"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." - -"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: - -You must give any other recipients of the Work or Derivative Works a copy of this License; and -You must cause any modified files to carry prominent notices stating that You changed the files; and -You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and -If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. - -You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. -5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS diff --git a/hms-plugins/flutter-hms-location/README.md b/hms-plugins/flutter-hms-location/README.md deleted file mode 100644 index cb69c34a..00000000 --- a/hms-plugins/flutter-hms-location/README.md +++ /dev/null @@ -1,1737 +0,0 @@ -# Huawei Location Kit Flutter Plugin - -## Table of Contents -* [Introduction](#introduction) -* [Installation Guide](#installation-guide) - * [Creating Project in App Gallery Connect](#creating-project-in-app-gallery-connect) - * [Configuring the Signing Certificate Fingerprint](#configuring-the-signing-certificate-fingerprint) - * [Integrating the Flutter Location Plugin](#integrating-the-flutter-location-plugin) -* [API Reference](#api-reference) - * [Overview](#overview) - * [FusedLocationProviderClient](#fusedlocationproviderclient) - * [Location](#location) - * [HWLocation](#hwlocation) - * [LocationAvailability](#locationavailability) - * [LocationCallback](#locationcallback) - * [LocationRequest](#locationrequest) - * [LocationResult](#locationresult) - * [LocationSettingsRequest](#locationsettingsrequest) - * [LocationSettingsStates](#locationsettingsstates) - * [NavigationResult](#navigationresult) - * [NavigationRequest](#navigationrequest) - * [ActivityIdentificationService](#activityidentificationservice) - * [ActivityConversionData](#activityconversiondata) - * [ActivityConversionInfo](#activityconversioninfo) - * [ActivityConversionResponse](#activityconversionresponse) - * [ActivityIdentificationData](#activityidentificationdata) - * [ActivityIdentificationResponse](#activityidentificationresponse) - * [Geofence Service](#geofence-service) - * [GeofenceData](#geofencedata) - * [GeofenceRequest](#geofencerequest) - * [PermissionHandler](#permissionhandler) - * [HMSLogger](#hmslogger) - -* [Configuration Description](#configuration-description) -* [Sample Project](#sample-project) -* [Questions or Issues](#questions-or-issues) -* [Licensing and Terms](#licensing-and-terms) - -## Introduction - -This plugin enables communication between Huawei Location SDK and Flutter platform. Huawei Location Kit combines the GPS, Wi-Fi, and base station locations to help you quickly obtain precise user locations, build up global positioning capabilities, and reach a wide range of users around the globe.Currently, it provides the four main capabilities: fused location, location semantics, activity identification, and geofence. You can call relevant capabilities as needed. - -Huawei Location Kit provides the following core capabilities: -- **Fused location**: Provides a set of simple and easy-to-use APIs for you to quickly obtain the device location based on the GPS, Wi-Fi, and base station location data. -- **Activity identification**: Identifies user motion status through the acceleration sensor, cellular network information, and magnetometer, helping you adjust your app based on user behavior. -- **Geofence**: Allows you to set an interested area through an API so that your app can receive a notification when a specified action (such as leaving, entering, or lingering in the area) occurs. - -## Installation Guide - -- Before you get started, you must register as a HUAWEI developer and complete identity verification on the [HUAWEI Developer](https://developer.huawei.com/consumer/en/) website. For details, please refer to [Register a HUAWEI ID](https://developer.huawei.com/consumer/en/doc/10104). - -- Create an app in your project is required in AppGallery Connect in order to communicate with Huawei services. To create an app, perform the following steps: - -### Creating Project in App Gallery Connect - -**Step 1.** Sign in to [AppGallery Connect](https://developer.huawei.com/consumer/en) and select My projects. - -**Step 2.** Click your project from the project list. - -**Step 3.** Go to **Project Setting** > **General information**, and click **Add app**. -If an app exists in the project, and you need to add a new one, expand the app selection area on the top of the page and click **Add app**. - -**Step 4.** On the **Add app** page, enter app information, and click **OK**. - -- A signing certificate fingerprint is used to verify the authenticity of an app when it attempts to access an HMS Core service through the HMS Core SDK. Before using HMS Core (APK), you must locally generate a signing certificate fingerprint and configure it in AppGallery Connect. Ensure that the JDK has been installed on your computer. - -### Configuring the Signing Certificate Fingerprint -**Step 1:** Go to **Project Setting** > **General information**. In the **App information** field, click the icon next to SHA-256 certificate fingerprint, and enter the obtained **SHA256 certificate fingerprint**. - -**Step 2:** After completing the configuration, click **OK**. (Check mark icon) - -### Integrating Flutter Location Plugin - -**Step 1:** Sign in [AppGallery Connect](https://developer.huawei.com/consumer/en/service/josp/agc/index.html) to AppGallery Connect and select **My projects**. - -**Step 2:** Find your app project, and click the desired app name. - -**Step 3:** Go to **Project Setting > > General information**. In the **App information** field, click **agconnect-service.json** to download configuration file. - -**Step 4:** Create a Flutter project if you do not have one. - -**Step 5:** Copy the **agconnect-service.json** file to the **android/app** directory of your Flutter project. - -**Step 6:** Copy the signature file that is generated in **Generating a Signature File** to the android/app directory of your Flutter project. - -**Step 7:** Check whether the **agconnect-services.json** file and signature file are successfully added to the **android/app** directory of the Flutter project. - - - -**Step 8:** Open the **build.gradle** file in the **android** directory of your Flutter project. - - Go to **buildscript** then configure the Maven repository address and agconnect plugin for the HMS SDK. - - ```gradle - buildscript { - repositories { - google() - jcenter() - maven { url 'https://developer.huawei.com/repo/' } - } - - dependencies { - /* - * - */ - classpath 'com.huawei.agconnect:agcp:1.4.1.300' - } - } - ``` - - - Go to **allprojects** then configure the Maven repository address for the HMS SDK. - - ```gradle - allprojects { - repositories { - google() - jcenter() - maven { url 'https://developer.huawei.com/repo/' } - } - } - ``` - -**Step 9:** Open the **build.gradle** file in the **android/app** directory. -- Add `apply plugin: 'com.huawei.agconnect'` line after other `apply` entries. - - ```gradle - apply plugin: 'com.android.application' - apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" - apply plugin: 'com.huawei.agconnect' - ``` - - - Set your package name in **defaultConfig** > **applicationId** and set **minSdkVersion** to **19** or **higher**. - Package name must match with the **package_name** entry in **agconnect-services.json** file. - - ```gradle - defaultConfig { - applicationId "" - minSdkVersion 17 - /* - * - */ - } - ``` - - Copy the signature file that generated in [Generating a Signing Certificate](https://developer.huawei.com/consumer/en/codelab/HMSPreparation/index.html#3) to **android/app** directory. - - - Configure the signature in **android** according to the signature file information. - -```gradle -signingConfigs { - config { - keyAlias keystoreProperties['keyAlias'] - keyPassword keystoreProperties['keyPassword'] - storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null - storePassword keystoreProperties['storePassword'] - } -} -buildTypes { - debug { - signingConfig signingConfigs.config - } - release { - signingConfig signingConfigs.config - } -} -``` - -**Step 10:** On your Flutter project directory find and open your **pubspec.yaml** file and add library to dependencies. For more details please refer the [Using packages](https://flutter.dev/docs/development/packages-and-plugins/using-packages#dependencies-on-unpublished-packages) document. - - ```yaml - dependencies: - huawei_location: - # Replace {library path} with actual library path of Huawei Push Kit Location for Flutter. - path: {library path} - ``` - --**Step 11:** Run following command to update package info. - -``` -[project_path]> flutter pub get -``` - -**Step 12:** Run following command to start the app. - -``` -[project_path]> flutter run -``` - -## API Reference - -### Overview - -| Module | Description | -|----------------------------------|------------------------------------------------------------------------------------------------| -| FusedLocationProviderClient | With this module you can check the device location settings, get the last known location information once or continuously, set mock location and others. | -| ActivityIdentificationService | If your app needs to obtain the activity status of the user's device (for example, walking, running, or bicycling) or your app needs to detect activity status change of a user, you can use this module. | -| GeofenceService | If you are interested in a place, you can create a geofence based on the place. When the device enters the geofence or stays for a duration of time, a notification can be sent to your app. | - -### FusedLocationProviderClient - -#### Public Constructor Summary - -| Constructor | Description | -|----------------------------------|------------------------------------------------------------------------------------------------ -| FusedLocationProviderClient() | Default constructor. | - -#### Public Method Summary - -| Method | Return Type | Description | -|------------------------------------------------------------------------------------------------|-----------------------------------|-------------| -| checkLocationSettings(LocationSettingsRequest locationSettingsRequest) | Future\ | This API is used to check location settings of the device. | -| getLastLocation() | Future\ | This API is used to obtain the last requested available location. This API does not proactively request the location. Instead, it uses the location cached for the last request. | -| getLastLocationWithAddress(LocationRequest locationRequest) | Future\ | This API is used to obtain the available location of the last request, including the detailed address information. | -| getLocationAvailability() | Future\ | This API is used to check whether the location data is available. | -| setMockMode(bool mockMode) | Future\ | This API is used to specify whether the location provider uses the location mock mode. If yes, the GPS or network location is not used and the location set through setMockLocation (Location) is directly returned. | -| setMockLocation(Location location) | Future\ | This API is used to set the specific mock location. You must call the setMockMode(boolean) method and set the flag to true before calling this method. | -| requestLocationUpdates(LocationRequest locationRequest) | Future\ | This API is used to continuously request location updates. | -| requestLocationUpdatesCb(LocationRequest locationRequest, LocationCallback locationCallback) | Future\ | This API is used to request location updates using the callback. | -| requestLocationUpdatesExCb(LocationRequest locationRequest, LocationCallback locationCallback) | Future\ | This API is an extended location information service API. It supports high-precision location and is compatible with common location APIs. If the device does not support high-precision location or the app does not request the high-precision location permission, this API returns common location information similar to that returned by the requestLocationUpdates API. | -| removeLocationUpdates(int requestCode) | Future\ | This API is used to remove location updates from the specified requestCode. | -| removeLocationUpdatesCb(int callbackId) | Future\ | This API is used to remove location updates of the specified callbackId. | -| onLocationData | Future\Location\> | This API is used to listen location updates that comes from requestLocationUpdates API method. | -| getNavigationContextState(int type) | Future\ | Obtains the requested navigation type. | - -#### Public Constructors - -##### FusedLocationProviderClient() - -Constructor for *FusedLocationProviderClient* object. - -#### Public Methods - -##### Future\ checkLocationSettings(LocationSettingsRequest locationSettingsRequest) *async* - -Checks location settings of the device. - -| Parameter | Description | -|-------------------------|-------------| -| locationSettingsRequest | Location setting request object. | - -| Return Type | Description | -|----------------------------------|-------------| -| Future\ | LocationSettingsStates object if the operation is successful; PlatformException otherwise. | - -##### Future\ getLastLocation() *async* - -Obtains the available location of the last request. Instead of proactively requesting a location, this method uses the location cached during the last request. - -The value null may be returned in the following scenarios: -- The location function has never been used. -- The location function is disabled. -- The device is restored to factory settings. - -If real-time location is required, you are advised to proactively call requestLocationUpdates instead of this method. To receive a location once only, you can set numUpdates in LocationRequest to 1. - -| Return Type | Description | -|----------------------------------|-------------| -| Future\ | Location object if the operation is successful; PlatformException otherwise. | - -##### Future\ getLastLocationWithAddress(LocationRequest locationRequest) *async* - -Obtains the available location of the last request, including the detailed address information. If no location is available, null is returned. - -| Parameter | Description | -|-------------------------|-------------| -| locationRequest | Location request object. | - -| Return Type | Description | -|----------------------------------|-------------| -| Future\ | HWLocation object if the operation is successful; PlatformException otherwise. | - -##### Future\ getLocationAvailability() *async* - -Checks whether the location data is available. - -| Return Type | Description | -|----------------------------------|-------------| -| Future\ | LocationAvailability object if the operation is successful; PlatformException otherwise. | - -##### Future\ setMockMode(bool mockMode) *async* - -Sets whether the location provider uses the mock mode. If yes, the GPS or network location is not used and the location set through setMockLocation is directly returned. - -| Parameter | Description | -|-------------------------|-------------| -| mockMode | Indicates whether the location provider uses the mock mode. true: yes; false: no. | - -| Return Type | Description | -|----------------------------------|-------------| -| Future\ | No return value if the operation is successful; PlatformException otherwise. | - -##### Future\ setMockLocation(Location location) *async* - -Sets whether the location provider uses the mock mode. If yes, the GPS or network location is not used and the location set through setMockLocation is directly returned. - -| Parameter | Description | -|-------------------------|-------------| -| location | Mock location. | - -| Return Type | Description | -|----------------------------------|-------------| -| Future\ | No return value if the operation is successful; PlatformException otherwise. | - -##### Future\ requestLocationUpdates(LocationRequest locationRequest) *async* - -Continuously requests location updates. You can call the onLocationData API method to listen for location updates. - -| Parameter | Description | -|-------------------------|-------------| -| locationRequest | Location update request. | - -| Return Type | Description | -|----------------------------------|-------------| -| Future\ | Request code if the operation is successful; PlatformException otherwise. The request code can be used to call the removeLocationUpdates method. | - -##### Future\ requestLocationUpdatesCb(LocationRequest locationRequest, LocationCallback locationCallback) *async* - -Requests location updates using the callback. - -| Parameter | Description | -|-------------------------|-------------| -| locationRequest | Location update request. | -| locationCallback | Location update callback.| - -| Return Type | Description | -|----------------------------------|-------------| -| Future\ | Callback ID if the operation is successful; PlatformException otherwise. The callback ID can be used to call the removeLocationUpdatesCb method. | - -##### Future\ requestLocationUpdatesExCb(LocationRequest locationRequest, LocationCallback locationCallback) *async* - -Continuously requests location updates. This method is an extended location information service API. It supports high-precision location and is compatible with common location APIs. If the device does not support high-precision location or the app does not request the high-precision location, this method returns common location information similar to that returned by the requestLocationUpdatesCb method. - -| Parameter | Description | -|-------------------------|-------------| -| locationRequest | Location update request. | -| locationCallback | Location update callback.| - -| Return Type | Description | -|----------------------------------|-------------| -| Future\ | Callback ID if the operation is successful; PlatformException otherwise. The callback ID can be used to call the removeLocationUpdatesCb method. | - -##### Future\ removeLocationUpdates(int requestCode) *async* - -Removes location updates based on the specified request code. - -| Parameter | Description | -|-------------------------|-------------| -| requestCode | Request code returned by the requestLocationUpdates method. | - -| Return Type | Description | -|----------------------------------|-------------| -| Future\ | No return value if the operation is successful; PlatformException otherwise. | - -##### Future\ removeLocationUpdatesCb(int callbackId) *async* - -Removes location updates based on the specified callback ID. - -| Parameter | Description | -|-------------------------|-------------| -| callbackId | Callback ID returned by the requestLocationUpdatesCb or requestLocationUpdatesExCb method. | - -| Return Type | Description | -|----------------------------------|-------------| -| Future\ | No return value if the operation is successful; PlatformException otherwise. | - -##### Stream\ onLocationData - -Listens for location updates that come from the requestLocationUpdates method. - -| Return Type | Description | -|----------------------------------|-------------| -| Stream\ | Stream of Location object. You can call the .listen() method to subscribe to this stream and listen for updates. | - -##### Future\ getNavigationContextState(int type) *async* - -Removes location updates based on the specified callback ID. - -| Parameter | Description | -|-------------------------|-------------| -| type | Requested navigation type. | - -| Return Type | Description | -|----------------------------------|-------------| -| Future\ | NavigationResult object if the operation is successful; PlatformException otherwise. | - -### Location - -#### Public Properties - -| Properties | Type | Description | -|------------------------------|--------|-------------------------------------------------------------------------------------------------------------------------| -| provider | String | Location provider, such as network location, GPS, Wi-Fi, and Bluetooth. | -| latitude | double | Latitude of a location. If no latitude is available, 0.0 is returned. | -| longitude | double | Longitude of a location. If no longitude is available, 0.0 is returned. | -| altitude | double | Altitude of a location. If no altitude is available, 0.0 is returned. | -| speed | double | Speed of a device at the current location, in meters per second. If no speed is available, 0.0 is returned. | -| bearing | double | Bearing of a device at the current location, in degrees. If no bearing is available, 0.0 is returned. | -| horizontalAccuracyMeters | double | Horizontal error of a location, in meters. If no horizontal error is available, 0.0 is returned. | -| verticalAccuracyMeters | double | Vertical error of a location, in meters. If no vertical error is available, 0.0 is returned. | -| speedAccuracyMetersPerSecond | double | Speed error of a device at the current location, in meters per second. If no speed error is available, 0.0 is returned. | -| bearingAccuracyDegrees | double | Bearing error of the current location, in degrees. If no bearing error is available, 0.0 is returned. | -| time | int | Current timestamp, in milliseconds. | -| elapsedRealtimeNanos | int | Time elapsed since the system was started, in nanoseconds | - -#### Public Constructor Summary - -| Constructor | Description | -|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------| -| Location({String provider, double latitude, double longitude, double altitude, double speed, double bearing, double horizontalAccuracyMeters, double verticalAccuracyMeters, double speedAccuracyMetersPerSecond, double bearingAccuracyDegrees, int time, int elapsedRealtimeNanos}) | Default constructor. | -| Location.fromMap(Map\ map) | Creates a Location object from a map. | -| Location.fromJson(String source) | Creates a Location object from a JSON string. | - -#### Public Constructors - -##### Location({String provider, double latitude, double longitude, double altitude, double speed, double bearing, double horizontalAccuracyMeters, double verticalAccuracyMeters, double speedAccuracyMetersPerSecond, double bearingAccuracyDegrees, int time, int elapsedRealtimeNanos}) - -Constructor for Location object. - -| Parameter | Type | Description | -|------------------------------|--------|-------------------------------------------------------------------------------------------------------------------------| -| provider | String | Location provider, such as network location, GPS, Wi-Fi, and Bluetooth. | -| latitude | double | Latitude of a location. If no latitude is available, 0.0 is returned. | -| longitude | double | Longitude of a location. If no longitude is available, 0.0 is returned. | -| altitude | double | Altitude of a location. If no altitude is available, 0.0 is returned. | -| speed | double | Speed of a device at the current location, in meters per second. If no speed is available, 0.0 is returned. | -| bearing | double | Bearing of a device at the current location, in degrees. If no bearing is available, 0.0 is returned. | -| horizontalAccuracyMeters | double | Horizontal error of a location, in meters. If no horizontal error is available, 0.0 is returned. | -| verticalAccuracyMeters | double | Vertical error of a location, in meters. If no vertical error is available, 0.0 is returned. | -| speedAccuracyMetersPerSecond | double | Speed error of a device at the current location, in meters per second. If no speed error is available, 0.0 is returned. | -| bearingAccuracyDegrees | double | Bearing error of the current location, in degrees. If no bearing error is available, 0.0 is returned. | -| time | int | Current timestamp, in milliseconds. | -| elapsedRealtimeNanos | int | Time elapsed since the system was started, in nanoseconds | - -##### Location.fromMap(Map\ map) - -Creates a Location object from a map. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| map | Map\| Map as a source. | - -##### Location.fromJson(String source) - -Creates a Location object from a JSON string. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| source | String | JSON string as a source. | - - -### HWLocation - -#### Public Properties - -| Properties | Type | Description | -|------------------------------|------------------------|-------------------------------------------------------------------------------------------------------------------------| -| provider | String | Location provider, such as network location, GPS, Wi-Fi, and Bluetooth. | -| latitude | double | Latitude of a location. If no latitude is available, 0.0 is returned. | -| longitude | double | Longitude of a location. If no longitude is available, 0.0 is returned. | -| altitude | double | Altitude of a location. If no altitude is available, 0.0 is returned. | -| speed | double | Speed of a device at the current location, in meters per second. If no speed is available, 0.0 is returned. | -| bearing | double | Bearing of a device at the current location, in degrees. If no bearing is available, 0.0 is returned. | -| horizontalAccuracyMeters | double | Horizontal error of a location, in meters. If no horizontal error is available, 0.0 is returned. | -| verticalAccuracyMeters | double | Vertical error of a location, in meters. If no vertical error is available, 0.0 is returned. | -| speedAccuracyMetersPerSecond | double | Speed error of a device at the current location, in meters per second. If no speed error is available, 0.0 is returned. | -| bearingAccuracyDegrees | double | Bearing error of the current location, in degrees. If no bearing error is available, 0.0 is returned. | -| time | int | Current timestamp, in milliseconds. | -| elapsedRealtimeNanos | int | Time elapsed since the system was started, in nanoseconds | -| countryCode | String | Country code. The value is a two-letter code complying with the ISO 3166-1 standard. | -| countryName | String | Country name. | -| state | String | Administrative region. | -| city | String | City of the current location. | -| county | String | County of the current location. | -| street | String | Street of the current location. | -| featureName | String | Landmark building at the current location. | -| postalCode | String | Postal code of the current location. | -| phone | String | Phone number of the landmark building (such as a store or company) at the current location. | -| url | String | Website of the landmark building (such as a store or company) at the current location. | -| extraInfo | Map\ | Additional information, which is a key-value pair. | - - -#### Public Constructor Summary - -| Constructor | Description | -|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------| -| HWLocation({String provider, double latitude, double longitude, double altitude, double speed, double bearing, double horizontalAccuracyMeters, double verticalAccuracyMeters, double speedAccuracyMetersPerSecond, double bearingAccuracyDegrees, int time, int elapsedRealtimeNanos, String countryCode, String countryName, String state, String city, String county, String street, String featureName, String postalCode, String phone, String url, Map extraInfo}) | Default constructor. | -| HWLocation.fromMap(Map\ map) | Creates a HWLocation object from a map. | -| HWLocation.fromJson(String source) | Creates a HWLocation object from a JSON string. | - -#### Public Constructors - -##### HwLocation({String provider, double latitude, double longitude, double altitude, double speed, double bearing, double horizontalAccuracyMeters, double verticalAccuracyMeters, double speedAccuracyMetersPerSecond, double bearingAccuracyDegrees, int time, int elapsedRealtimeNanos}) - -Constructor for Location object. - -| Parameter | Type | Description | -|------------------------------|------------------------|-------------------------------------------------------------------------------------------------------------------------| -| provider | String | Location provider, such as network location, GPS, Wi-Fi, and Bluetooth. | -| latitude | double | Latitude of a location. If no latitude is available, 0.0 is returned. | -| longitude | double | Longitude of a location. If no longitude is available, 0.0 is returned. | -| altitude | double | Altitude of a location. If no altitude is available, 0.0 is returned. | -| speed | double | Speed of a device at the current location, in meters per second. If no speed is available, 0.0 is returned. | -| bearing | double | Bearing of a device at the current location, in degrees. If no bearing is available, 0.0 is returned. | -| horizontalAccuracyMeters | double | Horizontal error of a location, in meters. If no horizontal error is available, 0.0 is returned. | -| verticalAccuracyMeters | double | Vertical error of a location, in meters. If no vertical error is available, 0.0 is returned. | -| speedAccuracyMetersPerSecond | double | Speed error of a device at the current location, in meters per second. If no speed error is available, 0.0 is returned. | -| bearingAccuracyDegrees | double | Bearing error of the current location, in degrees. If no bearing error is available, 0.0 is returned. | -| time | int | Current timestamp, in milliseconds. | -| elapsedRealtimeNanos | int | Time elapsed since the system was started, in nanoseconds | -| countryCode | String | Country code. The value is a two-letter code complying with the ISO 3166-1 standard. | -| countryName | String | Country name. | -| state | String | Administrative region. | -| city | String | City of the current location. | -| county | String | County of the current location. | -| street | String | Street of the current location. | -| featureName | String | Landmark building at the current location. | -| postalCode | String | Postal code of the current location. | -| phone | String | Phone number of the landmark building (such as a store or company) at the current location. | -| url | String | Website of the landmark building (such as a store or company) at the current location. | -| extraInfo | Map\ | Additional information, which is a key-value pair. | - -##### HWLocation.fromMap(Map map) - -Creates a HWLocation object from a map. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| map | Map\| Map as a source. | - -##### HWLocation.fromJson(String source) - -Creates a HWLocation object from a JSON string. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| source | String | JSON string as a source. | - -### LocationAvailability - -Device location availability. - -#### Public Properties - -| Properties | Type | Description | -|-------------------|------|-----------------------------------------------------------------------------------------------------------| -| cellStatus | int | Availability status code of cell location. Currently not provided. Value is always **0**. | -| wifiStatus | int | Availability status code of wifi location. Currently not provided. Value is always **0**. | -| elapsedRealtimeNs | int | Time elapsed since the system was started, in nanoseconds. Currently not provided. Value is always **0**. | -| locationStatus | int | Location status code. If the value of smaller than 1000, then device location is available. | - -**NOTE:** - -Currently, cellStatus, wifiStatus and elapsedRealtimeNs are not provided and have a fixed value of 0. - -#### Public Constructor Summary - -| Constructor | Description | -|---------------------------------------------------------------------------------------------------|----------------------| -| LocationAvailability({int cellStatus, int wifiStatus, int elapsedRealtimeNs, int locationStatus}) | Default constructor. | -| LocationAvailability.fromMap(Map\ map) | Creates a LocationAvailability object from a map. | -| LocationAvailability.fromJson(String source) | Creates a LocationAvailability object from a JSON string. | - -#### Public Method Summary - -| Methods | Return Type | Description | -|---------------------|-------------|------------------------------------------------| -| isLocationAvailable | bool | Indicates if the location is available or not. | - -#### Public Constructors - -##### LocationAvailability({int cellStatus, int wifiStatus, int elapsedRealtimeNs, int locationStatus}) - -Constructor for LocationAvailability object. - -| Parameter | Type | Description | -|-------------------|------|-----------------------------------------------------------------------------------------------------------| -| cellStatus | int | Availability status code of cell location. Currently not provided. Value is always **0**. | -| wifiStatus | int | Availability status code of wifi location. Currently not provided. Value is always **0**. | -| elapsedRealtimeNs | int | Time elapsed since the system was started, in nanoseconds. Currently not provided. Value is always **0**. | -| locationStatus | int | Location status code. If the value of smaller than 1000, then device location is available. | - -##### LocationAvailability.fromMap(Map\ map) - -Creates a LocationAvailability object from a map. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| map | Map\| Map as a source. | - -##### LocationAvailability.fromJson(String source) - -Creates a LocationAvailability object from a JSON string. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| source | String | JSON string as a source. | - -#### Public Methods - -##### bool isLocationAvaible - -Checks whether the device location is available. If yes, the value true is returned. A number of causes may result in failure to determine the location, such as that the location function is disabled or sensor data cannot be obtained from the device. - -| Return Type | Description | -|------------------------------|----------------------| -| String | JSON string as a source. | - -### LocationCallback - -#### Public Properties - -| Properties | Type | Description | -|------------------------|----------------------------------------------------------|------------------------------------------------------------| -| onLocationAvailability | void Function(LocationAvailability locationAvailability) | Callback function to listen location availability changes. | -| onLocationResult | void Function(LocationResult locationResult) | Callback function to listen location updates. | - -#### Public Constructor Summary - -| Constructor | Description | -|------------------------------------------------------------------------------------------|----------------------| -| LocationCallback({void Function onLocationResult, void Function onLocationAvailability}) | Default constructor. | - -#### Public Constructors - -##### LocationCallback({void Function onLocationResult, void Function onLocationAvailability}) - -Constructor for LocationCallback object. - -| Parameter | Type | Description | -|------------------------------|---------------|-------------------------------------------------------------------------------------------------------------------------| -| onLocationResult | void Function | Callback function to trigger when the device location is available. | -| onLocationAvailability | void Function | Callback function to trigger when the device location availability changes. | - -### LocationRequest - -Location request class. - -#### Public Properties - -| Properties | Type | Description | -|----------------------|--------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| priority | int | Request priority. The default value is 100. | -| interval | int | Request interval, in milliseconds. The default value is 3600000. | -| fastestInterval | int | Shortest request interval, in milliseconds. The default value is 600000. If another app initiates a location request, the location is also reported to the app at the interval specified in fastestInterval. | -| expirationTime | int | Request expiration time, in milliseconds. | -| numUpdates | int | Number of requested location updates. | -| smallestDisplacement | double | Minimum displacement between location updates, in meters. | -| maxWaitTime | int | Maximum waiting timeIndicates whether to return the address information. The default value is false. | -| needAddress | bool | Indicates whether to return the address information. The default value is false. | -| language | String | Language. The value consists of two letters and complies with the ISO 639-1 international standard. By default, the value is empty. | -| countryCode | String | Country code. The value consists of two letters and complies with the ISO 3166-1 international standard. By default, the value is empty. | - -#### Public Constants - -| Constants | Type | Value | Description | -|----------------------------------|------|-------|----------------------------------------------------------------------------------------------------------------------------------------------| -| PRIORITY_HIGH_ACCURACY | int | 100 | Used to request the most accurate location. | -| PRIORITY_BALANCED_POWER_ACCURACY | int | 102 | Used to request the block-level location. | -| PRIORITY_LOW_POWER | int | 104 | Used to request the city-level location. | -| PRIORITY_NO_POWER | int | 105 | Used to request the location with the optimal accuracy without additional power consumption. | -| PRIORITY_HD_ACCURACY | int | 200 | Used to request the high-precision location information. Currently, this parameter is available only for the requestLocationUpdatesExCb API. | - -#### Public Constructor Summary - -| Constructor | Description | -|-------------------------------------------------------|----------------------| -| LocationRequest() | Default constructor. | -| LocationRequest.fromMap(Map\ map) | Creates a Location object from a map. | -| LocationRequest.fromJson(String source) | Creates a Location object from a JSON string. | - -#### Public Method Summary - -| Return Type | Method | Description | -|-----------------|--------------------------------|-------------| -| bool | isFastestIntervalExplicitlySet | Indicates whether the fastest interval explicitly set or default value is being used. | - - -#### Public Constructors - -##### LocationRequest() - -Constructor for Location object. - -##### LocationRequest.fromMap(Map\ map) - -Creates a Location object from a map. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| map | Map\| Map as a source. | - -##### LocationRequest.fromJson(String source) - -Creates a Location object from a JSON string. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| source | String | JSON string as a source. | - -#### Public Methods - -##### bool isFastestIntervalExplicitlySet - -Checks whether the shortest interval is used. - -| Methods | Return Type | Description | -|--------------------------------|-------------|---------------------------------------------------------------------------------------| -| isFastestIntervalExplicitlySet | bool | Indicates whether the fastest interval explicitly set or default value is being used. | - -### LocationResult - -Location data information class. - -#### Public Properties - -| Properties | Type | Description | -|----------------|--------------------|-------------------------------------------------------------------------------------------------------| -| locations | List\ | Available locations, which are ordered from oldest to newest. | -| hwLocations | List\ | List of available locations sorted from oldest to newest, including the detailed address information. | -| lastLocation | Location | Available location of the last request. | -| lastHWLocation | HWLocation | Available location of the last request, including the detailed address information. | - -#### Public Constructor Summary - -| Constructor | Description | -|----------------------------------------------------------------------------------------------------------------------------|----------------------| -| LocationResult({List locations, List hwLocations, Location lastLocation, HWLocation lastHWLocation}) | Default constructor. | -| LocationResult.fromMap(Map\ map) | Creates a Location object from a map. | -| LocationResult.fromJson(String source) | Creates a Location object from a JSON string. | - -#### Public Constructors - -##### LocationResult({List locations, List hwLocations, Location lastLocation, HWLocation lastHWLocation}) - -Constructor for LocationResult object. - -| Parameter | Type | Description | -|------------------------------|--------------------|-------------------------------------------------------------------------------------------------------------------------| -| locations | List\ | Available locations, which are sorted from oldest to newest. | -| hwLocations | List\ | List of available locations sorted from oldest to newest, including the detailed address. | -| lastLocation | Location | Available location of the last request. | -| lastHWLocation | HWLocation | Available location of the last request, including the detailed address. | - - -##### LocationResult.fromMap(Map\ map) - -Creates a LocationResult object from a map. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| map | Map\| Map as a source. | - -##### LocationResult.fromJson(String source) - -Creates a LocationResult object from a JSON string. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| source | String | JSON string as a source. | - - - - -### LocationSettingsRequest - -Class for specifying the location service types and checking the location settings to obtain optimal functionality of all requested services. - -#### Public Properties - -| Properties | Type | Description | -|------------|-------------------------|--------------------------------------------------------------------------------------------------------------| -| requests | List\ | Collection of LocationRequest object. | -| alwaysShow | bool | Indicates whether BLE scanning needs to be enabled. The options are true (yes) and false (no). | -| needBle | bool | Indicates whether a location is required for the app to continue. The options are true (yes) and false (no). | - -#### Public Constructor Summary - -| Constructor | Description | -|--------------------------------------------------------------------------------------------|----------------------| -| LocationSettingsRequest({List\ requests, bool alwaysShow, bool needBle}) | Default constructor. | -| LocationSettingsRequest.fromMap(Map\ map) | Creates a LocationSettingsRequest object from a map. | -| LocationSettingsRequest.fromJson(String source) | Creates a LocationSettingsRequest object from a JSON string. | - -#### Public Constructors - -##### LocationSettingsRequest({List\ requests, bool alwaysShow, bool needBle}) - -Constructor for LocationSettingsRequest object. - -| Parameter | Type | Description | -|-----------------------------|-------------------------|-------------------------------------------------------------------------------------------------------------------------| -| requests | List\ | Collection of LocationRequest objects. | -| alwaysShow | bool | Indicates whether BLE scanning needs to be enabled. The options are true (yes) and false (no). | -| needBle | bool | Indicates whether a location is required for the app to continue. The options are true (yes) and false (no). | - -##### LocationSettingsRequest.fromMap(Map\ map) - -Creates a LocationSettingsRequest object from a map. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| map | Map\| Map as a source. | - -##### LocationSettingsRequest.fromJson(String source) - -Creates a LocationSettingsRequest object from a JSON string. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| source | String | JSON string as a source. | - -### LocationSettingsStates - -Current location-related setting status. - -#### Public Properties - -| Properties | Type | Description | -|------------------------|------|----------------------------------------------------------------------------------------| -| blePresent | bool | Indicates whether the BLE exists on the device. | -| bleUsable | bool | Indicates whether the BLE is enabled and can be used by the app. | -| gpsPresent | bool | Indicates whether the GPS provider exists on the device. | -| gpsUsable | bool | Indicates whether the GPS provider is enabled and can be used by the app. | -| locationPresent | bool | Indicates whether the location provider exists on the device. | -| locationUsable | bool | Indicates whether the location provider is enabled and can be used by the app. | -| networkLocationPresent | bool | Indicates whether the network location provider exists on the device. | -| networkLocationUsable | bool | Indicates whether the network location provider is enabled and can be used by the app. | - -#### Public Constructor Summary - -| Constructor | Description | -|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------| -| LocationSettingsStates({bool blePresent, bool bleUsable, bool gpsPresent, bool gpsUsable, bool locationPresent, bool locationUsable, bool networkLocationPresent, bool networkLocationUsable}) | Default constructor. | -| LocationSettingsStates.fromMap(Map\ map) | Creates a LocationSettingsStates object from a map. | -| LocationSettingsStates.fromJson(String source) | Creates a LocationSettingsStates object from a JSON string. | - -#### Public Constructors - -##### LocationSettingsStates({bool blePresent, bool bleUsable, bool gpsPresent, bool gpsUsable, bool locationPresent, bool locationUsable, bool networkLocationPresent, bool networkLocationUsable}) - -Constructor for LocationSettingsStates object. - -| Parameter | Type | Description | -|------------------------|------|----------------------------------------------------------------------------------------| -| blePresent | bool | Indicates whether the BLE exists on the device. | -| bleUsable | bool | Indicates whether the BLE is enabled and can be used by the app. | -| gpsPresent | bool | Indicates whether the GPS provider exists on the device. | -| gpsUsable | bool | Indicates whether the GPS provider is enabled and can be used by the app. | -| locationPresent | bool | Indicates whether the location provider exists on the device. | -| locationUsable | bool | Indicates whether the location provider is enabled and can be used by the app. | -| networkLocationPresent | bool | Indicates whether the network location provider exists on the device. | -| networkLocationUsable | bool | Indicates whether the network location provider is enabled and can be used by the app. | - -##### LocationSettingsStates.fromMap(Map\ map) - -Creates a Location object from a map. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| map | Map\| Map as a source. | - -##### LocationSettingsStates.fromJson(String source) - -Creates a Location object from a JSON string. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| source | String | JSON string as a source. | - -### NavigationResult - -#### Public Properties - -| Methods | Return Type | Description | -|-------------------|-------------|----------------------------------------------------------------| -| possibility | int | Obtains the confidence of the status information. The value ranges from 0 to 100. A larger value indicates more reliable result authenticity. | -| state | int | Status information.If the navigation type is IS_SUPPORT_EX, the return values are described as follows: 11: The user device supports high-precision location.12: The user device does not support high-precision location. | - -#### Public Constructor Summary - -| Constructor | Description | -|-------------------------------------------------------|----------------------| -| NavigationResult({state, possibility}) | Default constructor. | -| NavigationResult.fromMap(Map\ map) | Creates a NavigationResult object from a map. | -| NavigationResult.fromJson(String source) | Creates a NavigationResult object from a JSON string. | - - -#### Public Constructors - -##### NavigationResult({state, possibility}) - -Constructor for NavigationResult object. - -| Parameter | Return Type | Description | -|-------------------|-------------|----------------------------------------------------------------| -| possibility | int | Obtains the confidence of the status information. The value ranges from 0 to 100. A larger value indicates more reliable result authenticity. | -| state | int | Status information.If the navigation type is IS_SUPPORT_EX, the return values are described as follows: 11: The user device supports high-precision location.12: The user device does not support high-precision location. | - - -##### NavigationResult.fromMap(Map\ map) - -Creates a NavigationResult object from a map. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| map | Map\| Map as a source. | - -##### NavigationResult.fromJson(String source) - -Creates a NavigationResult object from a JSON string. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| source | String | JSON string as a source. | - -### NavigationRequest - -#### Public Properties - -| Properties | Type | Description | -|--------------------------|----------------|--------------------------------------------| -| type | int | Requested navigation type. | - -#### Public Constants - -| Constants | Type | Value | Description | -|---------------------------|------|-------|----------------------------------------------------- | -| IS_SUPPORT_EX | int | 2 | Used to check whether the device supports high-precision location. | - -### ActivityIdentificationService - -Interaction access point of activity identification. - -#### Public Constructor Summary - -| Constructor | Description | -|------------------------------------------------|----------------------| -| ActivityIdentificationService() | Default constructor. | - -#### Public Method Summary - -| Return Type | Method | Description | -|------------------------------------------|-------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| Future\ | createActivityIdentificationUpdates(int detectionIntervalMillis) | This API is used to register for activity identification updates. | -| Future\ | createActivityConversionUpdates(List\ activityConversions) | This API is used to activity conversions (entering and exit), for example, detecting user status change from walking to bicycling.The Conversion API supports the following activity parameters. | -| Future\ | deleteActivityIdentificationUpdates(int requestCode) | This API is used to remove all activity identification updates from the specified **requestCode**. | -| Future\ | deleteActivityConversionUpdates(int requestCode) | This API is used to remove all activity conversion updates from the specified **requestCode**. | -| Stream\ | onActivityIdentification | This API is used to listen activity identification updates that comes from createActivityIdentificationUpdates API method. | -| Stream\ | onActivityConversion | This API is used to listen activity conversion updates that comes from createActivityConversionUpdates API method. | - - -#### Public Constructors - -##### ActivityIdentificationService() - -Constructor for ActivityIdentificationService object. - -#### Public Methods - -##### Future\ createActivityIdentificationUpdates(int detectionIntervalMillis) *async* - -Registers for activity identification updates. - -| Parameter | Description | -|-------------------------|-------------| -| detectionIntervalMillis | Interval for activity identification updates, in milliseconds. A larger value will result in a lower activity identification frequency, while a smaller value will result in a higher activity identification frequency. | - -| Return Type | Description | -|----------------------------------|-------------| -| Future\ | Request code if the operation is successful; PlatformException otherwise. The request code can be used to call the deleteActivityIdentificationUpdates method. | - -##### Future\ createActivityConversionUpdates(List\ activityConversions) *async* - -Registers for activity conversion updates (entering and exit), for example, detecting user status change from walking to bicycling. - -| Parameter | Description | -|---------------------|-------------| -| activityConversions | Activity conversion list. | - -| Return Type | Description | -|----------------------------------|-------------| -| Future\ | Request code if the operation is successful; PlatformException otherwise. The request code can be used to call the deleteActivityConversionUpdates method. | - -##### Future\ deleteActivityIdentificationUpdates(int requestCode) *async* - -Removes activity identification updates based on the specified request code. - -| Parameter | Description | -|-------------|-------------| -| requestCode | Request code returned by the createActivityIdentificationUpdates method. | - -| Return Type | Description | -|----------------------------------|-------------| -| Future\ | No return value if the operation is successful; PlatformException otherwise. | - -##### Future\ deleteActivityConversionUpdates(int requestCode) *async* - -Removes activity conversion updates based on the specified request code. - -| Parameter | Description | -|-------------|-------------| -| requestCode | Request code returned by the createActivityConversionUpdates method. | - -| Return Type | Description | -|----------------------------------|-------------| -| Future\ | No return value if the operation is successful; PlatformException otherwise. | - -##### Stream\ onActivityIdentification - -Listens for activity identification updates that come from the createActivityIdentificationUpdates method. - -| Return Type | Description | -|------------------------------------------|-------------| -| Stream\ | Stream of ActivityIdentificationResponse object. You can call the .listen() method to subscribe to this stream and listen for updates. | - -##### Stream\ onActivityConversion - -Listens for activity conversion updates that come from the createActivityConversionUpdates method. - -| Return Type | Description | -|--------------------------------------|-------------| -| Stream\ | Stream of ActivityConversionResponse object. You can call the .listen() method to subscribe to this stream and listen for updates. | - -### ActivityConversionData - -Activity conversion event. - -#### Public Properties - -| Properties | Type | Description | -|-----------------------|------|--------------------------------------------------------------------------------------------------------------------------------------------------------| -| activityType | int | Activity type of the conversion. The value is one of the activity types defined in ActivityIdentificationData. | -| conversionType | int | Activity conversion information. The options are ActivityConversionInfo.ENTER_ACTIVITY_CONVERSION and ActivityConversionInfo.EXIT_ACTIVITY_CONVERSION. | -| elapsedTimeFromReboot | int | Elapsed real time (in milliseconds) of this conversion since boot. | - -#### Public Constructor Summary - -| Constructor | Description | -|-------------------------------------------------------------------------------------------|----------------------| -| ActivityConversionData({int activityType, int conversionType, int elapsedTimeFromReboot}) | Default constructor. | -| ActivityConversionData.fromMap(Map\ map) | Creates a ActivityConversionData object from a map. | -| ActivityConversionData.fromJson(String source) | Creates a ActivityConversionData object from a JSON string. | - -#### Public Constructors - -##### ActivityConversionData({int activityType, int conversionType, int elapsedTimeFromReboot}) - -Constructor for ActivityConversionData object. - -| Parameter | Type | Description | -|-----------------------|------|--------------------------------------------------------------------------------------------------------------------------------------------------------| -| activityType | int | Activity type of the conversion. The value is one of the activity types defined in ActivityIdentificationData. | -| conversionType | int | Activity conversion information. The options are ActivityConversionInfo.ENTER_ACTIVITY_CONVERSION and ActivityConversionInfo.EXIT_ACTIVITY_CONVERSION. | -| elapsedTimeFromReboot | int | Elapsed real time (in milliseconds) of this conversion since boot. | - -##### ActivityConversionData.fromMap(Map\ map) - -Creates a ActivityConversionData object from a map. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| map | Map\| Map as a source. | - -##### ActivityConversionData.fromJson(String source) - -Creates a ActivityConversionData object from a JSON string. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| source | String | JSON string as a source. | - -### ActivityConversionInfo - -Activity conversion information. - -#### Public Properties - -| Properties | Type | Description | -|----------------|------|---------------------------------------------------------------------------------------------------------------------------------------------------------| -| activityType | int | Activity type of the conversion. The value is one of the activity types defined in ActivityIdentificationData. | -| conversionType | int | Activity conversion information. The options are ActivityConversionInfo.ENTER_ACTIVITY_CONVERSION and ActivityConversionInfo.EXIT_ACTIVITY_CONVERSION. | - -#### Public Constants - -| Constants | Type | Value | Description | -|---------------------------|------|-------|-----------------------------------| -| ENTER_ACTIVITY_CONVERSION | int | 0 | A user enters the given activity. | -| EXIT_ACTIVITY_CONVERSION | int | 1 | A user exits the given activity. | - -#### Public Constructor Summary - -| Constructor | Description | -|----------------------------------------------------------------|----------------------| -| ActivityConversionInfo({int activityType, int conversionType}) | Default constructor. | -| ActivityConversionInfo.fromMap(Map\ map) | Creates a ActivityConversionInfo object from a map. | -| ActivityConversionInfo.fromJson(String source) | Creates a ActivityConversionInfo object from a JSON string. | - -#### Public Constructors - -##### ActivityConversionInfo({int activityType, int conversionType}) - -Constructor for ActivityConversionInfo object. - -| Properties | Type | Description | -|----------------|------|---------------------------------------------------------------------------------------------------------------------------------------------------------| -| activityType | int | Activity type of the conversion. The value is one of the activity types defined in ActivityIdentificationData. | -| conversionType | int | Activity conversion information. The options are ActivityConversionInfo.ENTER_ACTIVITY_CONVERSION and ActivityConversionInfo.EXIT_ACTIVITY_CONVERSION. | - -##### ActivityConversionInfo.fromMap(Map\ map) - -Creates a ActivityConversionInfo object from a map. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| map | Map\| Map as a source. | - -##### ActivityConversionInfo.fromJson(String source) - -Creates a ActivityConversionInfo object from a JSON string. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| source | String | JSON string as a source. | - -### ActivityConversionResponse - -Activity conversion result. - -#### Public Properties - -| Properties | Type | Description | -|-------------------------|--------------------------------|-------------------------------------------------------------------------------------------------------------------| -| activityConversionDatas | List\ | All activity conversion events in the result. The obtained activity events are sorted by time in ascending order. | - -#### Public Constructor Summary - -| Constructor | Description | -|--------------------------------------------------------------------------------------|----------------------| -| ActivityConversionResponse({List\ activityConversionDatas}) | Default constructor. | -| ActivityConversionResponse.fromMap(Map\ map) | Creates a ActivityConversionResponse object from a map. | -| ActivityConversionResponse.fromJson(String source) | Creates a ActivityConversionResponse object from a JSON string. | - -#### Public Constructors - -##### ActivityConversionResponse({List\ activityConversionDatas}) - -Constructor for ActivityConversionResponse object. - -| Parameter | Type | Description | -|------------------------------|--------------------------------|-------------------------------------------------------------------------------------------------------------------------| -| activityConversionDatas | List\ | All activity conversion events in the result. The obtained activity events are sorted by time in ascending order. | - - -##### ActivityConversionResponse.fromMap(Map\ map) - -Creates a ActivityConversionResponse object from a map. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| map | Map\| Map as a source. | - -##### ActivityConversionResponse.fromJson(String source) - -Creates a ActivityConversionResponse object from a JSON string. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| source | String | JSON string as a source. | - -### ActivityIdentificationData - -Class for detecting the activity. - -#### Public Properties - -| Properties | Type | Description | -|------------------------|------|---------------------------------------------------------------------------------------------------------------------------------------------------------| -| identificationActivity | int | Type of the detected activity. | -| possibility | int | The confidence for the user to execute the activity. The confidence ranges from 0 to 100. A larger value indicates more reliable activity authenticity. | - -#### Public Constants - -| Constants | Type | Value | Description | -|-----------|------|-------|-----------------------------------------------------------------| -| VEHICLE | int | 100 | The device is in a vehicle, such as a car. | -| BIKE | int | 101 | The device is on a bicycle. | -| FOOT | int | 102 | The device user is walking or running. | -| STILL | int | 103 | The device is still. | -| OTHERS | int | 104 | The current activity cannot be detected. | -| TILTING | int | 105 | The device has an obvious tilt change. | -| WALKING | int | 107 | The user of the device is walking,it is a sub-activity of FOOT. | -| RUNNING | int | 108 | The user of the device is running,it is a sub-activity of FOOT. | - -#### Public Constructor Summary - -| Constructor | Description | -|-----------------------------------------------------------------|----------------------| -| ActivityIdentificationData({int identificationActivity, int possibility}) | Default constructor. | -| ActivityIdentificationData.fromMap(Map\ map) | Creates a ActivityIdentificationData object from a map. | -| ActivityIdentificationData.fromJson(String source) | Creates a ActivityIdentificationData object from a JSON string. | - -#### Public Method Summary - -| Methods | Return Type | Description | -|------------------------------|-------------|----------------------------------------------------------------| -| static isValidType(int type) | bool | Checks that given activity type is one of the valid constants. | - -#### Public Constructors - -##### ActivityIdentificationData({int identificationActivity, int possibility}) - -Constructor for ActivityIdentificationData object. - -| Parameter | Type | Description | -|------------------------|------|---------------------------------------------------------------------------------------------------------------------------------------------------------| -| identificationActivity | int | Type of the detected activity. | -| possibility | int | The confidence for the user to execute the activity. The confidence ranges from 0 to 100. A larger value indicates more reliable activity authenticity. | - -##### ActivityIdentificationData.fromMap(Map\ map) - -Creates a ActivityIdentificationData object from a map. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| map | Map\| Map as a source. | - -##### ActivityIdentificationData.fromJson(String source) - -Creates a ActivityIdentificationData object from a JSON string. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| source | String | JSON string as a source. | - -#### Public Methods - -##### bool isValidType - -Checks whether the specified activity type is a valid constant. - -| Return Type | Description | -|-----------------|-------------| -| bool | true if the specified activity type is a valid constant; false otherwise. | - -### ActivityIdentificationResponse - -Activity identification result. - -#### Public Properties - -| Properties | Type | Description | -|-----------------------------|------------------------------------|-----------------------------------------------------------------------------------------------------------------| -| time | int | Time of this identification, which is in milliseconds since January 1, 1970. | -| elapsedTimeFromReboot | int | Elapsed real time (in milliseconds) of this identification since boot. | -| activityIdentificationDatas | List\ | List of activitiy identification list. The activity identifications are sorted by most probable activity first. | - -#### Public Constructor Summary - -| Constructor | Description | -|---------------------------------------------------------------------------------------------------------------------------------------|----------------------| -| ActivityIdentificationResponse({int time, int elapsedTimeFromReboot, List\ activityIdentificationDatas}) | Default constructor. | -| ActivityIdentificationResponse.fromMap(Map\ map) | Creates a ActivityIdentificationResponse object from a map. | -| ActivityIdentificationResponse.fromJson(String source) | Creates a ActivityIdentificationResponse object from a JSON string. | - -#### Public Method Summary - -| Methods | Return Type | Description | -|------------------------------------------|----------------------------|-----------------------------------------------------------------------------------| -| mostActivityIdentification | ActivityIdentificationData | This API is used to obtain the most probable activity identification of the user. | -| getActivityPossibility(int activityType) | int | This API is used to obtain the confidence of an activity type. | - -#### Public Constructors - -##### ActivityIdentificationResponse({int time, int elapsedTimeFromReboot, List\ activityIdentificationDatas}) - -Constructor for ActivityIdentificationResponse object. - -| Parameter | Type | Description | -|-----------------------------|------------------------------------|-----------------------------------------------------------------------------------------------------------------| -| time | int | Time of this identification, which is in milliseconds since January 1, 1970. | -| elapsedTimeFromReboot | int | Elapsed real time (in milliseconds) of this identification since boot. | -| activityIdentificationDatas | List\ | List of activitiy identification list. The activity identifications are sorted by most probable activity first. | - -##### ActivityIdentificationResponse.fromMap(Map\ map) - -Creates a ActivityIdentificationResponse object from a map. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| map | Map\| Map as a source. | - -##### ActivityIdentificationResponse.fromJson(String source) - -Creates a Location object from a JSON string. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| source | String | JSON string as a source. | - -#### Public Methods - -##### ActivityIdentificationData mostActivityIdentification - -Obtains the most possible activity of a user. - -| Return Type | Description | -|----------------------------------|-------------| -| ActivityIdentificationData | Identified activity. | - -##### int getActivityPossibility - -Obtains the confidence of an activity type. - -| Parameter | Description | -|-------------------------|-------------| -| activityType | Activity type. | - -| Return Type | Description | -|----------------------------------|-------------| -| int | Confidence of the activity type. | - -### Geofence Service - -Interaction access point of geofence. - -#### Public Constructor Summary - -| Constructor | Description | -|----------------------------------------|----------------------| -| GeofenceService() | Default constructor. | - -#### Public Method Summary - -| Return Type | Method | Description | -|------------------------|-------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------| -| Future\ | createGeofenceList(GeofenceRequest geofenceRequest) | This API is used to add geofences. When a geofence is triggered, a notification can be listened through **onGeofenceData** API method. | -| Future\ | deleteGeofenceList(int requestCode) | This API is used to remove geofences associated with a **requestCode**. | -| Future\ | deleteGeofenceListWithIds(List\ geofenceIds) | This API is used to remove geofences by their unique IDs. | -| Stream\ | onGeofenceData | This API is used to listen geofence updates that comes from createGeofenceList API method. | - -#### Public Constructors - -##### GeofenceService() - -Constructor for GeofenceService object. - -#### Public Methods - -##### Future\ createGeofenceList(GeofenceRequest geofenceRequest) *async* - -Adds geofences. When a geofence is triggered, the onGeofenceData method can listen for a notification. - -| Parameter | Description | -|-------------------------|-------------| -| geofenceRequest | Geofence request object. | - -| Return Type | Description | -|----------------------------------|-------------| -| Future\ | Request code if the operation is successful; PlatformException otherwise. The request code can be used to call the deleteGeofenceList method. | - -##### Future\ deleteGeofenceList(int requestCode) *async* - -Removes geofences associated with a request code. - -| Parameter | Description | -|-------------------------|-------------| -| requestCode | Request code returned by the createGeofenceList method. | - -| Return Type | Description | -|----------------------------------|-------------| -| Future\ | No return value if the operation is successful; PlatformException otherwise. | - -##### Future\ deleteGeofenceListWithIds(List\ geofenceIds) *async* - -Removes geofences by their unique IDs. - -| Parameter | Description | -|-------------------------|-------------| -| geofenceIds | Unique IDs of geofences to be removed. | - -| Return Type | Description | -|----------------------------------|-------------| -| Future\ | No return value if the operation is successful; PlatformException otherwise. | - -##### Stream\ onGeofenceData - -Listens for geofence updates that come from the createGeofenceList method. - -| Parameter | Description | -|-------------------------|-------------| -| geofenceIds | Unique IDs of geofences to be removed. | - -| Return Type | Description | -|----------------------------------|-------------| -| Stream\ | Stream of GeofenceData object. You can call the .listen() method to subscribe to this stream and listen for updates. | - -### Geofence - -Class that contains information about geofences. - -#### Public Properties - -| Properties | Type | Description | -|----------------------|--------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| uniqueId | String | Unique ID. If the unique ID already exists, the new geofence will overwrite the old one. | -| conversions | int | Geofence conversions. The bitwise-OR operation is supported. | -| validDuration | int | Geofence timeout interval, in milliseconds. The geofence will be automatically deleted after this amount of time. | -| latitude | double | Latitude. The value range is [-90,90]. | -| longitude | double | Longitude. The value range is [-180,180]. | -| radius | double | Radius, in meters. | -| notificationInterval | int | Notification response capability. The default value is **0**. Setting it to a larger value can reduce power consumption accordingly. However, reporting of geofence events may be delayed. | -| dwellDelayTime | int | Lingering duration for converting a geofence event, in milliseconds. A geofence event is converted when a user lingers in a geofence for this amount of time. | - -#### Public Constants - -| Constants | Type | Value | Description | -|---------------------------|------|-------|-----------------------------------------------------| -| ENTER_GEOFENCE_CONVERSION | int | 1 | A user enters the geofence. | -| EXIT_GEOFENCE_CONVERSION | int | 2 | A user exits the geofence. | -| DWELL_GEOFENCE_CONVERSION | int | 4 | A user lingers in the geofence. | -| GEOFENCE_NEVER_EXPIRE | int | -1 | No timeout interval is configured for the geofence. | - -#### Public Constructor Summary - -| Constructor | Description | -|-----------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------| -| Geofence({String uniqueId, int conversions, int validDuration, double latitude, double longitude, double radius, int notificationInterval, int dwellDelayTime}) | Default constructor. | -| Geofence.fromMap(Map\ map) | Creates a Geofence object from a map. | -| Geofence.fromJson(String source) | Creates a Geofence object from a JSON string. | - -### Public Constructors - -##### Geofence({String uniqueId, int conversions, int validDuration, double latitude, double longitude, double radius, int notificationInterval, int dwellDelayTime}) - -Constructor for Geofence object. - -| Parameter | Type | Description | -|----------------------|--------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| uniqueId | String | Unique ID. If the unique ID already exists, the new geofence will overwrite the old one. | -| conversions | int | Geofence conversions. The bitwise-OR operation is supported. | -| validDuration | int | Geofence timeout interval, in milliseconds. The geofence will be automatically deleted after this amount of time. | -| latitude | double | Latitude. The value range is [-90,90]. | -| longitude | double | Longitude. The value range is [-180,180]. | -| radius | double | Radius, in meters. | -| notificationInterval | int | Notification response capability. The default value is **0**. Setting it to a larger value can reduce power consumption accordingly. However, reporting of geofence events may be delayed. | -| dwellDelayTime | int | Lingering duration for converting a geofence event, in milliseconds. A geofence event is converted when a user lingers in a geofence for this amount of time. | - -##### Geofence.fromMap(Map\ map) - -Creates a Geofence object from a map. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| map | Map\| Map as a source. | - -##### Geofence.fromJson(String source) - -Creates a Geofence object from a JSON string. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| source | String | JSON string as a source. | - -### GeofenceData - -Geofence event. - -#### Public Properties - -| Properties | Type | Description | -|--------------------------|----------------|--------------------------------------------| -| errorCode | int | Error code. | -| conversion | int | Geofence convert type. | -| convertingGeofenceIdList | List\ | List of converted geofence unique IDs. | -| convertingLocation | Location | The location when a geofence is converted. | - -#### Public Constructor Summary - -| Constructor | Description | -|-------------------------------------------------------------------------------------------------------------------|----------------------| -| GeofenceData({int errorCode, int conversion, List convertingGeofenceIdList, Location convertingLocation}) | Default constructor. | -| GeofenceData.fromMap(Map\ map) | Creates a GeofenceData object from a map. | -| GeofenceData.fromJson(String source) | Creates a GeofenceData object from a JSON string. | - -#### Public Constructors - -##### GeofenceData({int errorCode, int conversion, List convertingGeofenceIdList, Location convertingLocation}) - -Constructor for GeofenceData object. - -| Properties | Type | Description | -|--------------------------|----------------|--------------------------------------------| -| errorCode | int | Error code. | -| conversion | int | Geofence convert type. | -| convertingGeofenceIdList | List\ | List of converted geofence unique IDs. | -| convertingLocation | Location | The location when a geofence is converted. | - -##### GeofenceData.fromMap(Map\ map) - -Creates a GeofenceData object from a map. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| map | Map\| Map as a source. | - -##### GeofenceData.fromJson(String source) - -Creates a GeofenceData object from a JSON string. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| source | String | JSON string as a source. | - -### GeofenceRequest - -Geofence request class. - -#### Public Properties - -| Properties | Type | Description | -|-----------------|------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| geofenceList | List\ | List of geofences to be monitored. | -| initConversions | int | Initial conversion type. This parameter is invalid if it is set to 0. The default value is GeofenceRequest.ENTER_INIT_CONVERSION | GeofenceRequest.DWELL_INIT_CONVERSION. | -| coordinateType | int | Coordinate type of geofences. Defaults to GeofenceRequest.COORDINATE_TYPE_WGS_84. | - -#### Public Constants - -| Constants | Type | Value | Description | -|------------------------|------|-------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| ENTER_INIT_CONVERSION | int | 1 | ENTER_INIT_CONVERSION is converted immediately when a request is initiated to add the geofence where a user device has already entered. | -| EXIT_INIT_CONVERSION | int | 2 | EXIT_INIT_CONVERSION is converted immediately when a request is initiated to add the geofence where a user device has already exit. | -| DWELL_INIT_CONVERSION | int | 4 | DWELL_INIT_CONVERSION is converted immediately when a request is initiated to add the geofence where a user device has already entered and stayed for the specified duration. | -| COORDINATE_TYPE_WGS_84 | int | 1 | WGS_84 coordinate system. | -| COORDINATE_TYPE_GCJ_02 | int | 0 | GCJ-02 coordinate system. | - -#### Public Constructor Summary - -| Constructor | Description | -|-------------------------------------------------------------------------------------------|----------------------| -| GeofenceRequest({List\ geofenceList, int initConversions, int coordinateType}) | Default constructor. | -| GeofenceRequest.fromMap(Map\ map) | Creates a GeofenceRequest object from a map. | -| GeofenceRequest.fromJson(String source) | Creates a GeofenceRequest object from a JSON string. | - -#### Public Constructors - -##### GeofenceRequest({List\ geofenceList, int initConversions, int coordinateType}) - -Constructor for GeofenceRequest object. - -| Properties | Type | Description | -|-----------------|------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| geofenceList | List\ | List of geofences to be monitored. | -| initConversions | int | Initial conversion type. This parameter is invalid if it is set to 0. The default value is GeofenceRequest.ENTER_INIT_CONVERSION | GeofenceRequest.DWELL_INIT_CONVERSION. | -| coordinateType | int | Coordinate type of geofences. Defaults to GeofenceRequest.COORDINATE_TYPE_WGS_84. | - -##### GeofenceRequest.fromMap(Map\ map) - -Creates a GeofenceRequest object from a map. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| map | Map\| Map as a source. | - -##### GeofenceRequest.fromJson(String source) - -Creates a GeofenceRequest object from a JSON string. - -| Parameter | Type | Description | -|------------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------| -| source | String | JSON string as a source. | - -### PermissionHandler - -Checks or requests required permissions. - -#### Public Constructor Summary - -| Constructor | Description | -|------------------------------------------------|----------------------| -| PermissionHandler() | Default constructor. | - -#### Public Method Summary - -| Return Type | Method | Description | -|----------------|----------------------------------------|-------------------------------------------------------------------------------------------------------------------------| -| Future\ | hasLocationPermission() | This API is used to check location permission is available or not. | -| Future\ | hasBackgroundLocationPermission() | This API is used to check background location permission is available or not. | -| Future\ | hasActivityRecognitionPermission() | This API is used to check activity permission is available or not. | -| Future\ | requestLocationPermission() | This API is used to request location permission. Returns true if permission is granted, else returns false. | -| Future\ | requestBackgroundLocationPermission() | This API is used to request background location permission. Returns true if permission is granted, else returns false. | -| Future\ | requestActivityRecognitionPermission() | This API is used to request activity recognition permission. Returns true if permission is granted, else returns false. | - -#### Public Constructors - -##### PermissionHandler() - -Constructor for PermissionHandler object. - -#### Public Methods - -##### Future\ hasLocationPermission() *async* - -Checks whether the location permission is available. - -| Return Type | Description | -|----------------------------------|-------------| -| Future\ | true or false if the operation is successful; PlatformException otherwise. | - -##### Future\ hasBackgroundLocationPermission() *async* - -Checks whether the background location permission is available. - -| Return Type | Description | -|----------------------------------|-------------| -| Future\ | true or false if the operation is successful; PlatformException otherwise. | - -##### Future\ hasActivityRecognitionPermission() *async* - -Checks whether the activity permission is available. - -| Return Type | Description | -|----------------------------------|-------------| -| Future\ | true or false if the operation is successful; PlatformException otherwise. | - -##### Future\ requestLocationPermission() *async* - -Requests the location permission. The value true is returned if the permission is granted. Otherwise, false is returned. - -| Return Type | Description | -|----------------------------------|-------------| -| Future\ | true or false if the operation is successful; PlatformException otherwise. | - -##### Future\ requestBackgroundLocationPermission() *async* - -Requests the background location permission. The value true is returned if the permission is granted. Otherwise, false is returned - -| Return Type | Description | -|----------------------------------|-------------| -| Future\ | true or false if the operation is successful; PlatformException otherwise. | - -##### Future\ requestActivityRecognitionPermission() *async* - -Requests the activity permission. The value true is returned if the permission is granted. Otherwise, false is returned. - -| Return Type | Description | -|----------------------------------|-------------| -| Future\ | true or false if the operation is successful; PlatformException otherwise. | - -### HMSLogger - -#### Public Method Summary - -| Return Type | Method | Description | -|----------------|----------------------------------------|-------------------------------------------------------------------------------------------------------------------------| -| Future\ | enableLogger() | This method enables the HMSLogger capability which is used for sending usage analytics of Location SDK's methods to improve the service quality.. | -| Future\ | disableLogger() | This method disables the HMSLogger capability which is used for sending usage analytics of Location SDK's methods to improve the service quality. | - -#### Public Methods - -##### Future\ enableLogger() *async* - -This method enables the HMSLogger capability which is used for sending usage analytics of Location SDK's methods to improve the service quality. HMSLogger is enabled by default, it can be disabled with the disableLogger method. - -| Return Type | Description | -|----------------------------------|-------------| -| Future\ | Future result of an execution that returns no value. | - -##### Future\ disableLogger() *async* - -This method disables the HMSLogger capability which is used for sending usage analytics of Location SDK's methods to improve the service quality. - -| Return Type | Description | -|----------------------------------|-------------| -| Future\ | Future result of an execution that returns no value. | - - -## Configuration Description - - -### Preparing for Release - -Before building a release version of your app you may need to customize the **proguard-rules.pro** obfuscation configuration file to prevent the HMS Core SDK from being obfuscated. Add the configurations below to exclude the HMS Core SDK from obfuscation. For more information on this topic refer to [this Android developer guide](https://developer.android.com/studio/build/shrink-code). - -**/android/app/proguard-rules. pro** - -``` --ignorewarnings --keepattributes *Annotation* --keepattributes Exceptions --keepattributes InnerClasses --keepattributes Signature --keepattributes SourceFile,LineNumberTable --keep class com.hianalytics.android.**{*;} --keep class com.huawei.updatesdk.**{*;} --keep class com.huawei.hms.**{*;} - -``` - -**/android/app/build.gradle** - -```gradle -buildTypes { - debug { - signingConfig signingConfigs.config - } - release { - - // Enables code shrinking, obfuscation and optimization for release builds - minifyEnabled true - // Unused resources will be removed, resources defined in the res/raw/keep.xml will be kept. - shrinkResources true - proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' - - signingConfig signingConfigs.config - } -} -``` - - -## Sample Project -This plugin includes a demo project in the **example** folder, there you can find more usage examples. - - - -## Questions or Issues - -If you have questions about how to use HMS samples, try the following options: - -- [Stack Overflow](https://stackoverflow.com/questions/tagged/huawei-mobile-services) is the best place for any programming questions. Be sure to tag your question with **huawei-mobile-services**. -- [Github](https://github.com/HMS-Core/hms-flutter-plugin) is the official repository for these plugins, You can open an issue or submit your ideas. -- [Huawei Developer Forum](https://forums.developer.huawei.com/forumPortal/en/home?fid=0101187876626530001) HMS Core Module is great for general questions, or seeking recommendations and opinions. -- [Huawei Developer Docs](https://developer.huawei.com/consumer/en/doc/overview/HMS-Core-Plugin) is place to official documentation for all HMS Core Kits, you can find detailed documentations in there. - -If you run into a bug in our samples, please submit an issue to the Github Repository. - - -## Licensing and Terms - -Huawei Location Kit Flutter Plugin uses the Apache 2.0 license. \ No newline at end of file diff --git a/hms-plugins/flutter-hms-location/android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java b/hms-plugins/flutter-hms-location/android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java deleted file mode 100644 index 975e9019..00000000 --- a/hms-plugins/flutter-hms-location/android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java +++ /dev/null @@ -1,25 +0,0 @@ -package io.flutter.plugins; - -import io.flutter.plugin.common.PluginRegistry; -import com.huawei.hms.flutter.location.LocationPlugin; - -/** - * Generated file. Do not edit. - */ -public final class GeneratedPluginRegistrant { - public static void registerWith(PluginRegistry registry) { - if (alreadyRegisteredWith(registry)) { - return; - } - LocationPlugin.registerWith(registry.registrarFor("com.huawei.hms.flutter.location.LocationPlugin")); - } - - private static boolean alreadyRegisteredWith(PluginRegistry registry) { - final String key = GeneratedPluginRegistrant.class.getCanonicalName(); - if (registry.hasPlugin(key)) { - return true; - } - registry.registrarFor(key); - return false; - } -} diff --git a/hms-plugins/flutter-hms-location/android/build.gradle b/hms-plugins/flutter-hms-location/android/build.gradle deleted file mode 100644 index 228af211..00000000 --- a/hms-plugins/flutter-hms-location/android/build.gradle +++ /dev/null @@ -1,45 +0,0 @@ -group 'com.huawei.hms.flutter.location' -version '1.0' - -buildscript { - repositories { - google() - jcenter() - maven { url 'https://developer.huawei.com/repo/' } - } - - dependencies { - classpath 'com.android.tools.build:gradle:3.6.0' - } -} - -rootProject.allprojects { - repositories { - google() - jcenter() - maven { url 'https://developer.huawei.com/repo/' } - } -} - -apply plugin: 'com.android.library' - -android { - compileSdkVersion 29 - buildToolsVersion "29.0.3" - - defaultConfig { - minSdkVersion 19 - targetSdkVersion 29 - } - compileOptions { - sourceCompatibility JavaVersion.VERSION_1_8 - targetCompatibility JavaVersion.VERSION_1_8 - } - lintOptions { - disable 'InvalidPackage' - } -} - -dependencies { - implementation 'com.huawei.hms:location:5.0.0.301' -} diff --git a/hms-plugins/flutter-hms-location/android/gradle.properties b/hms-plugins/flutter-hms-location/android/gradle.properties deleted file mode 100644 index 38c8d454..00000000 --- a/hms-plugins/flutter-hms-location/android/gradle.properties +++ /dev/null @@ -1,4 +0,0 @@ -org.gradle.jvmargs=-Xmx1536M -android.enableR8=true -android.useAndroidX=true -android.enableJetifier=true diff --git a/hms-plugins/flutter-hms-location/android/gradle/wrapper/gradle-wrapper.properties b/hms-plugins/flutter-hms-location/android/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index a4b44297..00000000 --- a/hms-plugins/flutter-hms-location/android/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,5 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/hms-plugins/flutter-hms-location/android/gradlew b/hms-plugins/flutter-hms-location/android/gradlew deleted file mode 100644 index 2fe81a7d..00000000 --- a/hms-plugins/flutter-hms-location/android/gradlew +++ /dev/null @@ -1,183 +0,0 @@ -#!/usr/bin/env sh - -# -# Copyright 2015 the original author or authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn () { - echo "$*" -} - -die () { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=`expr $i + 1` - done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -exec "$JAVACMD" "$@" diff --git a/hms-plugins/flutter-hms-location/android/gradlew.bat b/hms-plugins/flutter-hms-location/android/gradlew.bat deleted file mode 100644 index 62bd9b9c..00000000 --- a/hms-plugins/flutter-hms-location/android/gradlew.bat +++ /dev/null @@ -1,103 +0,0 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/hms-plugins/flutter-hms-location/android/local.properties b/hms-plugins/flutter-hms-location/android/local.properties deleted file mode 100644 index c6cb6fc0..00000000 --- a/hms-plugins/flutter-hms-location/android/local.properties +++ /dev/null @@ -1,2 +0,0 @@ -sdk.dir=C:\\Users\\sultan.khan\\AppData\\Local\\Android\\Sdk -flutter.sdk=C:\\Program Files\\flutter \ No newline at end of file diff --git a/hms-plugins/flutter-hms-location/android/settings.gradle b/hms-plugins/flutter-hms-location/android/settings.gradle deleted file mode 100644 index 2a0347f0..00000000 --- a/hms-plugins/flutter-hms-location/android/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = 'huawei_location' diff --git a/hms-plugins/flutter-hms-location/android/src/main/AndroidManifest.xml b/hms-plugins/flutter-hms-location/android/src/main/AndroidManifest.xml deleted file mode 100644 index d54dab86..00000000 --- a/hms-plugins/flutter-hms-location/android/src/main/AndroidManifest.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - diff --git a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/LocationPlugin.java b/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/LocationPlugin.java deleted file mode 100644 index 4e98a26d..00000000 --- a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/LocationPlugin.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -package com.huawei.hms.flutter.location; - -import android.app.Activity; -import android.content.Context; - -import androidx.annotation.NonNull; - -import com.huawei.hms.flutter.location.constants.Channel; -import com.huawei.hms.flutter.location.handlers.ActivityConversionStreamHandler; -import com.huawei.hms.flutter.location.handlers.ActivityIdentificationMethodHandler; -import com.huawei.hms.flutter.location.handlers.ActivityIdentificationStreamHandler; -import com.huawei.hms.flutter.location.handlers.FusedLocationMethodHandler; -import com.huawei.hms.flutter.location.handlers.FusedLocationStreamHandler; -import com.huawei.hms.flutter.location.handlers.GeofenceMethodHandler; -import com.huawei.hms.flutter.location.handlers.GeofenceStreamHandler; -import com.huawei.hms.flutter.location.handlers.HMSLoggerMethodHandler; -import com.huawei.hms.flutter.location.handlers.PermissionHandler; - -import io.flutter.embedding.engine.plugins.FlutterPlugin; -import io.flutter.embedding.engine.plugins.activity.ActivityAware; -import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugin.common.EventChannel; -import io.flutter.plugin.common.MethodChannel; -import io.flutter.plugin.common.PluginRegistry.Registrar; - -public class LocationPlugin implements FlutterPlugin, ActivityAware { - private MethodChannel permissionMethodChannel; - private MethodChannel fusedLocationMethodChannel; - private MethodChannel geofenceMethodChannel; - private MethodChannel activityIdentificationMethodChannel; - private MethodChannel locationEnhanceMethodChannel; - private MethodChannel hmsLoggerMethodChannel; - private EventChannel mFusedLocationEventChannel; - private EventChannel mGeofenceEventChannel; - private EventChannel mActivityIdentificationEventChannel; - private EventChannel mActivityConversionEventChannel; - private PermissionHandler permissionHandler; - private EventChannel.StreamHandler mFusedLocationStreamHandler; - private EventChannel.StreamHandler mGeofenceStreamHandler; - private EventChannel.StreamHandler mActivityIdentificationStreamHandler; - private EventChannel.StreamHandler mActivityConversionStreamHandler; - private FusedLocationMethodHandler fusedLocationMethodHandler; - private GeofenceMethodHandler geofenceMethodHandler; - private ActivityIdentificationMethodHandler activityIdentificationMethodHandler; - private HMSLoggerMethodHandler hmsLoggerMethodHandler; - - public static void registerWith(final Registrar registrar) { - final LocationPlugin instance = new LocationPlugin(); - final Activity activity = registrar.activity(); - final Context context = activity.getApplicationContext(); - final BinaryMessenger messenger = registrar.messenger(); - - instance.onAttachedToEngine(context, messenger); - instance.permissionHandler = new PermissionHandler(activity); - instance.permissionMethodChannel.setMethodCallHandler(instance.permissionHandler); - instance.fusedLocationMethodHandler = new FusedLocationMethodHandler(activity, - instance.fusedLocationMethodChannel); - instance.fusedLocationMethodChannel.setMethodCallHandler(instance.fusedLocationMethodHandler); - instance.geofenceMethodHandler = new GeofenceMethodHandler(activity); - instance.geofenceMethodChannel.setMethodCallHandler(instance.geofenceMethodHandler); - instance.activityIdentificationMethodHandler = new ActivityIdentificationMethodHandler(activity); - instance.activityIdentificationMethodChannel.setMethodCallHandler(instance.activityIdentificationMethodHandler); - instance.hmsLoggerMethodHandler = new HMSLoggerMethodHandler(context); - instance.hmsLoggerMethodChannel.setMethodCallHandler(instance.hmsLoggerMethodHandler); - registrar.addRequestPermissionsResultListener(instance.permissionHandler); - registrar.addActivityResultListener(instance.fusedLocationMethodHandler); - } - - private void initChannels(final BinaryMessenger messenger) { - permissionMethodChannel = new MethodChannel(messenger, Channel.PERMISSON_METHOD.id()); - fusedLocationMethodChannel = new MethodChannel(messenger, Channel.FUSED_LOCATION_METHOD.id()); - geofenceMethodChannel = new MethodChannel(messenger, Channel.GEOFENCE_METHOD.id()); - activityIdentificationMethodChannel = new MethodChannel(messenger, Channel.ACTIVITY_IDENTIFICATION_METHOD.id()); - locationEnhanceMethodChannel = new MethodChannel(messenger, Channel.LOCATION_ENHANCE_METHOD.id()); - hmsLoggerMethodChannel = new MethodChannel(messenger, Channel.HMSLOGGER_METHOD.id()); - mFusedLocationEventChannel = new EventChannel(messenger, Channel.FUSED_LOCATION_EVENT.id()); - mGeofenceEventChannel = new EventChannel(messenger, Channel.GEOFENCE_EVENT.id()); - mActivityIdentificationEventChannel = new EventChannel(messenger, Channel.ACTIVITY_IDENTIFICATION_EVENT.id()); - mActivityConversionEventChannel = new EventChannel(messenger, Channel.ACTIVITY_CONVERSION_EVENT.id()); - } - - private void initStreamHandlers(final Context context) { - mFusedLocationStreamHandler = new FusedLocationStreamHandler(context); - mGeofenceStreamHandler = new GeofenceStreamHandler(context); - mActivityIdentificationStreamHandler = new ActivityIdentificationStreamHandler(context); - mActivityConversionStreamHandler = new ActivityConversionStreamHandler(context); - } - - private void setStreamHandlers() { - mFusedLocationEventChannel.setStreamHandler(mFusedLocationStreamHandler); - mGeofenceEventChannel.setStreamHandler(mGeofenceStreamHandler); - mActivityIdentificationEventChannel.setStreamHandler(mActivityIdentificationStreamHandler); - mActivityConversionEventChannel.setStreamHandler(mActivityConversionStreamHandler); - } - - private void resetStreamHandlers() { - mFusedLocationEventChannel.setStreamHandler(null); - mGeofenceEventChannel.setStreamHandler(null); - mActivityIdentificationEventChannel.setStreamHandler(null); - mActivityConversionEventChannel.setStreamHandler(null); - } - - private void removeStreamHandlers() { - mFusedLocationStreamHandler = null; - mGeofenceStreamHandler = null; - mActivityIdentificationStreamHandler = null; - mActivityConversionStreamHandler = null; - } - - private void removeChannels() { - permissionMethodChannel = null; - fusedLocationMethodChannel = null; - geofenceMethodChannel = null; - activityIdentificationMethodChannel = null; - locationEnhanceMethodChannel = null; - hmsLoggerMethodChannel = null; - mFusedLocationEventChannel = null; - mGeofenceEventChannel = null; - mActivityIdentificationEventChannel = null; - mActivityConversionEventChannel = null; - } - - private void onAttachedToEngine(final Context context, final BinaryMessenger messenger) { - initChannels(messenger); - initStreamHandlers(context); - setStreamHandlers(); - } - - @Override - public void onAttachedToEngine(@NonNull final FlutterPluginBinding binding) { - onAttachedToEngine(binding.getApplicationContext(), binding.getBinaryMessenger()); - } - - @Override - public void onDetachedFromEngine(@NonNull final FlutterPluginBinding binding) { - resetStreamHandlers(); - removeStreamHandlers(); - removeChannels(); - } - - @Override - public void onAttachedToActivity(@NonNull final ActivityPluginBinding binding) { - final Activity activity = binding.getActivity(); - - permissionHandler = new PermissionHandler(activity); - fusedLocationMethodHandler = new FusedLocationMethodHandler(activity, fusedLocationMethodChannel); - geofenceMethodHandler = new GeofenceMethodHandler(activity); - activityIdentificationMethodHandler = new ActivityIdentificationMethodHandler(activity); - hmsLoggerMethodHandler = new HMSLoggerMethodHandler(activity.getApplicationContext()); - - binding.addRequestPermissionsResultListener(permissionHandler); - binding.addActivityResultListener(fusedLocationMethodHandler); - - permissionMethodChannel.setMethodCallHandler(permissionHandler); - fusedLocationMethodChannel.setMethodCallHandler(fusedLocationMethodHandler); - geofenceMethodChannel.setMethodCallHandler(geofenceMethodHandler); - activityIdentificationMethodChannel.setMethodCallHandler(activityIdentificationMethodHandler); - hmsLoggerMethodChannel.setMethodCallHandler(hmsLoggerMethodHandler); - } - - @Override - public void onDetachedFromActivityForConfigChanges() { - onDetachedFromActivity(); - } - - @Override - public void onReattachedToActivityForConfigChanges(@NonNull final ActivityPluginBinding binding) { - onAttachedToActivity(binding); - } - - @Override - public void onDetachedFromActivity() { - activityIdentificationMethodChannel.setMethodCallHandler(null); - geofenceMethodChannel.setMethodCallHandler(null); - fusedLocationMethodChannel.setMethodCallHandler(null); - locationEnhanceMethodChannel.setMethodCallHandler(null); - hmsLoggerMethodChannel.setMethodCallHandler(null); - activityIdentificationMethodHandler = null; - geofenceMethodHandler = null; - fusedLocationMethodHandler = null; - permissionHandler = null; - hmsLoggerMethodHandler = null; - } -} diff --git a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/constants/Action.java b/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/constants/Action.java deleted file mode 100644 index 9a83e743..00000000 --- a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/constants/Action.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -package com.huawei.hms.flutter.location.constants; - -public interface Action { - String PROCESS_LOCATION = "com.huawei.hms.flutter.location.ACTION_PROCESS_LOCATION"; - String PROCESS_GEOFENCE = "com.huawei.hms.flutter.location.ACTION_PROCESS_GEOFENCE"; - String PROCESS_CONVERSION = "com.huawei.hms.flutter.location.ACTION_PROCESS_CONVERSION"; - String PROCESS_IDENTIFICATION = "com.huawei.hms.flutter.location.ACTION_PROCESS_IDENTIFICATION"; -} diff --git a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/constants/Channel.java b/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/constants/Channel.java deleted file mode 100644 index 3e21a60f..00000000 --- a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/constants/Channel.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -package com.huawei.hms.flutter.location.constants; - -public enum Channel { - PERMISSON_METHOD("com.huawei.flutter.location/permission_methodchannel"), - FUSED_LOCATION_METHOD("com.huawei.flutter.location/fusedlocation_methodchannel"), - FUSED_LOCATION_EVENT("com.huawei.flutter.location/fusedlocation_eventchannel"), - GEOFENCE_METHOD("com.huawei.flutter.location/geofence_methodchannel"), - GEOFENCE_EVENT("com.huawei.flutter.location/geofence_eventchannel"), - ACTIVITY_IDENTIFICATION_METHOD("com.huawei.flutter.location/activityidentification_methodchannel"), - ACTIVITY_IDENTIFICATION_EVENT("com.huawei.flutter.location/activityidentification_eventchannel"), - ACTIVITY_CONVERSION_EVENT("com.huawei.flutter.location/activityconversion_eventchannel"), - LOCATION_ENHANCE_METHOD("com.huawei.flutter.location/locationenhance_methodchannel"), - HMSLOGGER_METHOD("com.huawei.flutter.location/hmslogger_methodchannel"); - - private final String id; - - Channel(final String id) { - this.id = id; - } - - public String id() { - return id; - } -} diff --git a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/constants/Error.java b/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/constants/Error.java deleted file mode 100644 index 35f42ea8..00000000 --- a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/constants/Error.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -package com.huawei.hms.flutter.location.constants; - -public enum Error { - LOCATION_SETTINGS_NOT_AVAILABLE("Unable to get location settings"), - NON_EXISTING_REQUEST_ID("Request ID does not exists"), - SEND_INTENT_EXCEPTION("Unable to send intent"); - - private final String message; - - Error(final String message) { - this.message = message; - } - - public String message() { - return message; - } -} diff --git a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/handlers/ActivityConversionStreamHandler.java b/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/handlers/ActivityConversionStreamHandler.java deleted file mode 100644 index f761e0ca..00000000 --- a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/handlers/ActivityConversionStreamHandler.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -package com.huawei.hms.flutter.location.handlers; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.IntentFilter; - -import com.huawei.hms.flutter.location.constants.Action; -import com.huawei.hms.flutter.location.logger.HMSLogger; -import com.huawei.hms.flutter.location.receivers.ActivityConversionBroadcastReceiver; - -import io.flutter.plugin.common.EventChannel.EventSink; -import io.flutter.plugin.common.EventChannel.StreamHandler; - -public class ActivityConversionStreamHandler implements StreamHandler { - private final Context context; - private BroadcastReceiver broadcastReceiver; - - public ActivityConversionStreamHandler(final Context context) { - this.context = context; - } - - @Override - public void onListen(final Object arguments, final EventSink events) { - broadcastReceiver = new ActivityConversionBroadcastReceiver(events); - context.registerReceiver(broadcastReceiver, new IntentFilter(Action.PROCESS_CONVERSION)); - - HMSLogger.getInstance(context).sendSingleEvent("ActivityConversionStreamHandler.onListen"); - } - - @Override - public void onCancel(final Object arguments) { - context.unregisterReceiver(broadcastReceiver); - broadcastReceiver = null; - - HMSLogger.getInstance(context).sendSingleEvent("ActivityConversionStreamHandler.onCancel"); - } -} diff --git a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/handlers/ActivityIdentificationMethodHandler.java b/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/handlers/ActivityIdentificationMethodHandler.java deleted file mode 100644 index ab502248..00000000 --- a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/handlers/ActivityIdentificationMethodHandler.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -package com.huawei.hms.flutter.location.handlers; - -import android.app.Activity; -import android.app.PendingIntent; -import android.content.Intent; - -import androidx.annotation.NonNull; -import androidx.core.util.Pair; - -import com.huawei.hms.flutter.location.constants.Action; -import com.huawei.hms.flutter.location.constants.Error; -import com.huawei.hms.flutter.location.listeners.DefaultFailureListener; -import com.huawei.hms.flutter.location.listeners.RemoveUpdatesSuccessListener; -import com.huawei.hms.flutter.location.listeners.RequestUpdatesFailureListener; -import com.huawei.hms.flutter.location.listeners.RequestUpdatesSuccessListener; -import com.huawei.hms.flutter.location.logger.HMSLogger; -import com.huawei.hms.flutter.location.utils.ActivityUtils; -import com.huawei.hms.location.ActivityConversionRequest; -import com.huawei.hms.location.ActivityIdentification; -import com.huawei.hms.location.ActivityIdentificationService; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import io.flutter.plugin.common.MethodCall; -import io.flutter.plugin.common.MethodChannel.MethodCallHandler; -import io.flutter.plugin.common.MethodChannel.Result; - -public class ActivityIdentificationMethodHandler implements MethodCallHandler { - private final Activity activity; - private final Map requests; - private final ActivityIdentificationService service; - - private int requestCode = 0; - - public ActivityIdentificationMethodHandler(final Activity activity) { - this.activity = activity; - service = ActivityIdentification.getService(activity); - requests = new HashMap<>(); - } - - private void createActivityIdentificationUpdates(final MethodCall call, final Result result) { - final Pair intentData = buildPendingIntent(Action.PROCESS_IDENTIFICATION); - - service.createActivityIdentificationUpdates(call.arguments(), intentData.second) - .addOnSuccessListener(new RequestUpdatesSuccessListener(call.method, activity, result, intentData.first)) - .addOnFailureListener( - new RequestUpdatesFailureListener<>(call.method, activity, result, intentData.first, requests)); - } - - private void createActivityConversionUpdates(final MethodCall call, final Result result) { - final List> args = call.arguments(); - final Pair intentData = buildPendingIntent(Action.PROCESS_CONVERSION); - final ActivityConversionRequest request - = ActivityUtils.fromActivityConversionInfoListToActivityConversionRequest(args); - - service.createActivityConversionUpdates(request, intentData.second) - .addOnSuccessListener(new RequestUpdatesSuccessListener(call.method, activity, result, intentData.first)) - .addOnFailureListener( - new RequestUpdatesFailureListener<>(call.method, activity, result, intentData.first, requests)); - } - - private void deleteActivityIdentificationUpdates(final MethodCall call, final Result result) { - final int incomingRequestCode = call.arguments(); - - if (!requests.containsKey(incomingRequestCode)) { - result.error(Error.NON_EXISTING_REQUEST_ID.name(), Error.NON_EXISTING_REQUEST_ID.message(), null); - } else { - service.deleteActivityIdentificationUpdates(requests.get(incomingRequestCode)) - .addOnSuccessListener( - new RemoveUpdatesSuccessListener<>(call.method, activity, result, incomingRequestCode, requests)) - .addOnFailureListener(new DefaultFailureListener(call.method, activity, result)); - } - } - - private void deleteActivityConversionUpdates(final MethodCall call, final Result result) { - final int incomingRequestCode = call.arguments(); - - if (!requests.containsKey(incomingRequestCode)) { - result.error(Error.NON_EXISTING_REQUEST_ID.name(), Error.NON_EXISTING_REQUEST_ID.message(), null); - } else { - service.deleteActivityConversionUpdates(requests.get(incomingRequestCode)) - .addOnSuccessListener( - new RemoveUpdatesSuccessListener<>(call.method, activity, result, incomingRequestCode, requests)) - .addOnFailureListener(new DefaultFailureListener(call.method, activity, result)); - } - } - - private Pair buildPendingIntent(final String action) { - final Intent intent = new Intent(); - - intent.setPackage(activity.getPackageName()); - intent.setAction(action); - - final PendingIntent pendingIntent = PendingIntent.getBroadcast(activity.getApplicationContext(), ++requestCode, - intent, PendingIntent.FLAG_UPDATE_CURRENT); - - requests.put(requestCode, pendingIntent); - return Pair.create(requestCode, pendingIntent); - } - - @Override - public void onMethodCall(@NonNull final MethodCall call, @NonNull final Result result) { - HMSLogger.getInstance(activity).startMethodExecutionTimer(call.method); - - switch (call.method) { - case "createActivityIdentificationUpdates": - createActivityIdentificationUpdates(call, result); - break; - case "createActivityConversionUpdates": - createActivityConversionUpdates(call, result); - break; - case "deleteActivityIdentificationUpdates": - deleteActivityIdentificationUpdates(call, result); - break; - case "deleteActivityConversionUpdates": - deleteActivityConversionUpdates(call, result); - break; - default: - result.notImplemented(); - break; - } - } -} diff --git a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/handlers/ActivityIdentificationStreamHandler.java b/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/handlers/ActivityIdentificationStreamHandler.java deleted file mode 100644 index 8a2303d4..00000000 --- a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/handlers/ActivityIdentificationStreamHandler.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -package com.huawei.hms.flutter.location.handlers; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.IntentFilter; - -import com.huawei.hms.flutter.location.constants.Action; -import com.huawei.hms.flutter.location.logger.HMSLogger; -import com.huawei.hms.flutter.location.receivers.ActivityIdentificationBroadcastReceiver; - -import io.flutter.plugin.common.EventChannel.EventSink; -import io.flutter.plugin.common.EventChannel.StreamHandler; - -public class ActivityIdentificationStreamHandler implements StreamHandler { - private final Context context; - private BroadcastReceiver broadcastReceiver; - - public ActivityIdentificationStreamHandler(final Context context) { - this.context = context; - } - - @Override - public void onListen(final Object arguments, final EventSink events) { - broadcastReceiver = new ActivityIdentificationBroadcastReceiver(events); - context.registerReceiver(broadcastReceiver, new IntentFilter(Action.PROCESS_IDENTIFICATION)); - - HMSLogger.getInstance(context).sendSingleEvent("ActivityIdentificationStreamHandler.onListen"); - } - - @Override - public void onCancel(final Object arguments) { - context.unregisterReceiver(broadcastReceiver); - broadcastReceiver = null; - - HMSLogger.getInstance(context).sendSingleEvent("ActivityIdentificationStreamHandler.onCancel"); - } -} diff --git a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/handlers/FusedLocationMethodHandler.java b/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/handlers/FusedLocationMethodHandler.java deleted file mode 100644 index d4ec83a0..00000000 --- a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/handlers/FusedLocationMethodHandler.java +++ /dev/null @@ -1,265 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -package com.huawei.hms.flutter.location.handlers; - -import android.app.Activity; -import android.app.PendingIntent; -import android.content.Intent; -import android.os.Looper; -import android.util.Pair; - -import androidx.annotation.NonNull; - -import com.huawei.hms.flutter.location.constants.Action; -import com.huawei.hms.flutter.location.constants.Error; -import com.huawei.hms.flutter.location.listeners.DefaultFailureListener; -import com.huawei.hms.flutter.location.listeners.DefaultSuccessListener; -import com.huawei.hms.flutter.location.listeners.LocationSettingsFailureListener; -import com.huawei.hms.flutter.location.listeners.RemoveUpdatesSuccessListener; -import com.huawei.hms.flutter.location.listeners.RequestUpdatesFailureListener; -import com.huawei.hms.flutter.location.listeners.RequestUpdatesSuccessListener; -import com.huawei.hms.flutter.location.logger.HMSLogger; -import com.huawei.hms.flutter.location.utils.LocationUtils; -import com.huawei.hms.location.FusedLocationProviderClient; -import com.huawei.hms.location.LocationEnhanceService; -import com.huawei.hms.location.LocationRequest; -import com.huawei.hms.location.LocationServices; -import com.huawei.hms.location.LocationSettingsRequest; -import com.huawei.hms.location.LocationSettingsStates; -import com.huawei.hms.location.NavigationRequest; -import com.huawei.hms.location.SettingsClient; - -import java.util.HashMap; -import java.util.Map; - -import io.flutter.plugin.common.MethodCall; -import io.flutter.plugin.common.MethodChannel; -import io.flutter.plugin.common.PluginRegistry.ActivityResultListener; - -public class FusedLocationMethodHandler implements MethodChannel.MethodCallHandler, ActivityResultListener { - private final Activity activity; - private final MethodChannel channel; - private final Map callbacks; - private final Map requests; - private final SettingsClient settingsClient; - private final FusedLocationProviderClient service; - private final LocationEnhanceService enhanceService; - - private int requestCode = 0; - private MethodChannel.Result result; - - public FusedLocationMethodHandler(final Activity activity, final MethodChannel channel) { - this.activity = activity; - this.channel = channel; - callbacks = new HashMap<>(); - requests = new HashMap<>(); - settingsClient = LocationServices.getSettingsClient(activity); - service = LocationServices.getFusedLocationProviderClient(activity); - enhanceService = LocationServices.getLocationEnhanceService(activity); - } - - private void checkLocationSettings(final MethodCall call, final MethodChannel.Result result) { - final LocationSettingsRequest request = LocationUtils.fromMapToLocationSettingsRequest(call.arguments()); - this.result = result; - - settingsClient.checkLocationSettings(request) - .addOnSuccessListener(new DefaultSuccessListener<>(call.method, activity, result)) - .addOnFailureListener(new LocationSettingsFailureListener(result, activity)); - } - - private void getLastLocation(final MethodCall call, final MethodChannel.Result result) { - service.getLastLocation() - .addOnSuccessListener(new DefaultSuccessListener<>(call.method, activity, result)) - .addOnFailureListener(new DefaultFailureListener(call.method, activity, result)); - } - - private void getLastLocationWithAddress(final MethodCall call, final MethodChannel.Result result) { - service.getLastLocationWithAddress( - LocationUtils.fromMapToLocationRequest(call.>arguments())) - .addOnSuccessListener(new DefaultSuccessListener<>(call.method, activity, result)) - .addOnFailureListener(new DefaultFailureListener(call.method, activity, result)); - } - - private void getLocationAvailability(final MethodCall call, final MethodChannel.Result result) { - service.getLocationAvailability() - .addOnSuccessListener(new DefaultSuccessListener<>(call.method, activity, result)) - .addOnFailureListener(new DefaultFailureListener(call.method, activity, result)); - } - - private void setMockMode(final MethodCall call, final MethodChannel.Result result) { - service.setMockMode(call.arguments()) - .addOnSuccessListener(new DefaultSuccessListener<>(call.method, activity, result)) - .addOnFailureListener(new DefaultFailureListener(call.method, activity, result)); - } - - private void setMockLocation(final MethodCall call, final MethodChannel.Result result) { - service.setMockLocation(LocationUtils.fromMapToLocation(call.arguments())) - .addOnSuccessListener(new DefaultSuccessListener<>(call.method, activity, result)) - .addOnFailureListener(new DefaultFailureListener(call.method, activity, result)); - } - - private void requestLocationUpdates(final MethodCall call, final MethodChannel.Result result) { - final Pair intentData = buildLocationIntent(); - final LocationRequest request = LocationUtils.fromMapToLocationRequest(call.>arguments()); - - service.requestLocationUpdates(request, intentData.second) - .addOnSuccessListener(new RequestUpdatesSuccessListener(call.method, activity, result, intentData.first)) - .addOnFailureListener( - new RequestUpdatesFailureListener<>(call.method, activity, result, intentData.first, requests)); - } - - private void requestLocationUpdatesCb(final MethodCall call, final MethodChannel.Result result) { - final LocationRequest request = LocationUtils.fromMapToLocationRequest(call.>arguments()); - final Pair callbackData = buildCallback(call.method); - - service.requestLocationUpdates(request, callbackData.second, Looper.getMainLooper()) - .addOnSuccessListener(new RequestUpdatesSuccessListener(call.method, activity, result, callbackData.first)) - .addOnFailureListener( - new RequestUpdatesFailureListener<>(call.method, activity, result, callbackData.first, callbacks)); - } - - private void requestLocationUpdatesExCb(final MethodCall call, final MethodChannel.Result result) { - final LocationRequest request = LocationUtils.fromMapToLocationRequest(call.>arguments()); - final Pair callbackData = buildCallback(call.method); - - service.requestLocationUpdatesEx(request, callbackData.second, Looper.getMainLooper()) - .addOnSuccessListener(new RequestUpdatesSuccessListener(call.method, activity, result, callbackData.first)) - .addOnFailureListener( - new RequestUpdatesFailureListener<>(call.method, activity, result, callbackData.first, callbacks)); - } - - private void removeLocationUpdates(final MethodCall call, final MethodChannel.Result result) { - final int incomingRequestCode = call.arguments(); - - if (!requests.containsKey(incomingRequestCode)) { - result.error(Error.NON_EXISTING_REQUEST_ID.name(), Error.NON_EXISTING_REQUEST_ID.message(), null); - } else { - service.removeLocationUpdates(requests.get(incomingRequestCode)) - .addOnSuccessListener( - new RemoveUpdatesSuccessListener<>(call.method, activity, result, incomingRequestCode, requests)) - .addOnFailureListener(new DefaultFailureListener(call.method, activity, result)); - } - } - - private void removeLocationUpdatesCb(final MethodCall call, final MethodChannel.Result result) { - final int callbackId = call.arguments(); - - if (!callbacks.containsKey(callbackId)) { - result.error(Error.NON_EXISTING_REQUEST_ID.name(), Error.NON_EXISTING_REQUEST_ID.message(), null); - } else { - service.removeLocationUpdates(callbacks.get(callbackId)) - .addOnSuccessListener( - new RemoveUpdatesSuccessListener<>(call.method, activity, result, callbackId, callbacks)) - .addOnFailureListener(new DefaultFailureListener(call.method, activity, result)); - } - } - - private void getNavigationContextState(final MethodCall call, final MethodChannel.Result result) { - final NavigationRequest request = LocationUtils.fromMapToNavigationRequest(call.arguments()); - - enhanceService.getNavigationState(request) - .addOnSuccessListener(new DefaultSuccessListener<>(call.method, activity, result)) - .addOnFailureListener(new DefaultFailureListener(call.method, activity, result)); - } - - private Pair buildCallback(final String methodName) { - final LocationCallbackHandler callBack = new LocationCallbackHandler(activity.getApplicationContext(), - methodName, ++requestCode, channel); - callbacks.put(requestCode, callBack); - return Pair.create(requestCode, callBack); - } - - private Pair buildLocationIntent() { - final Intent intent = new Intent(); - intent.setPackage(activity.getPackageName()); - intent.setAction(Action.PROCESS_LOCATION); - - final PendingIntent pendingIntent = PendingIntent.getBroadcast(activity.getApplicationContext(), ++requestCode, - intent, PendingIntent.FLAG_UPDATE_CURRENT); - requests.put(requestCode, pendingIntent); - return Pair.create(requestCode, pendingIntent); - } - - @Override - public void onMethodCall(@NonNull final MethodCall call, @NonNull final MethodChannel.Result result) { - HMSLogger.getInstance(activity.getApplicationContext()).startMethodExecutionTimer(call.method); - - switch (call.method) { - case "checkLocationSettings": - checkLocationSettings(call, result); - break; - case "getLastLocation": - getLastLocation(call, result); - break; - case "getLastLocationWithAddress": - getLastLocationWithAddress(call, result); - break; - case "getLocationAvailability": - getLocationAvailability(call, result); - break; - case "setMockMode": - setMockMode(call, result); - break; - case "setMockLocation": - setMockLocation(call, result); - break; - case "requestLocationUpdates": - requestLocationUpdates(call, result); - break; - case "requestLocationUpdatesCb": - requestLocationUpdatesCb(call, result); - break; - case "requestLocationUpdatesExCb": - requestLocationUpdatesExCb(call, result); - break; - case "removeLocationUpdates": - removeLocationUpdates(call, result); - break; - case "removeLocationUpdatesCb": - removeLocationUpdatesCb(call, result); - break; - case "getNavigationContextState": - getNavigationContextState(call, result); - break; - default: - result.notImplemented(); - break; - } - } - - @Override - public boolean onActivityResult(final int requestCode, final int resultCode, final Intent intent) { - final MethodChannel.Result incomingResult = result; - result = null; - - if (incomingResult != null && requestCode == 0) { - if (resultCode == Activity.RESULT_OK) { - final LocationSettingsStates states = LocationSettingsStates.fromIntent(intent); - HMSLogger.getInstance(activity.getApplicationContext()) - .sendSingleEvent("checkLocationSettings.onActivityResult"); - incomingResult.success(LocationUtils.fromLocationSettingsStatesToMap(states)); - } else { - HMSLogger.getInstance(activity.getApplicationContext()) - .sendSingleEvent("checkLocationSettings" + ".onActivityResult", "-1"); - incomingResult.error(Error.LOCATION_SETTINGS_NOT_AVAILABLE.name(), - Error.LOCATION_SETTINGS_NOT_AVAILABLE.message(), null); - } - } - - return true; - } -} diff --git a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/handlers/FusedLocationStreamHandler.java b/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/handlers/FusedLocationStreamHandler.java deleted file mode 100644 index 03d732b0..00000000 --- a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/handlers/FusedLocationStreamHandler.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -package com.huawei.hms.flutter.location.handlers; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.IntentFilter; - -import com.huawei.hms.flutter.location.constants.Action; -import com.huawei.hms.flutter.location.logger.HMSLogger; -import com.huawei.hms.flutter.location.receivers.FusedLocationBroadcastReceiver; - -import io.flutter.plugin.common.EventChannel.EventSink; -import io.flutter.plugin.common.EventChannel.StreamHandler; - -public class FusedLocationStreamHandler implements StreamHandler { - private final Context context; - private BroadcastReceiver broadcastReceiver; - - public FusedLocationStreamHandler(final Context context) { - this.context = context; - } - - @Override - public void onListen(final Object arguments, final EventSink events) { - broadcastReceiver = new FusedLocationBroadcastReceiver(events); - context.registerReceiver(broadcastReceiver, new IntentFilter(Action.PROCESS_LOCATION)); - HMSLogger.getInstance(context).sendSingleEvent("FusedLocationStreamHandler.onListen"); - } - - @Override - public void onCancel(final Object arguments) { - context.unregisterReceiver(broadcastReceiver); - broadcastReceiver = null; - HMSLogger.getInstance(context).sendSingleEvent("FusedLocationStreamHandler.onCancel"); - } -} diff --git a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/handlers/GeofenceMethodHandler.java b/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/handlers/GeofenceMethodHandler.java deleted file mode 100644 index 6c479b35..00000000 --- a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/handlers/GeofenceMethodHandler.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -package com.huawei.hms.flutter.location.handlers; - -import android.app.Activity; -import android.app.PendingIntent; -import android.content.Intent; -import android.util.Pair; - -import androidx.annotation.NonNull; - -import com.huawei.hms.flutter.location.constants.Action; -import com.huawei.hms.flutter.location.constants.Error; -import com.huawei.hms.flutter.location.listeners.DefaultFailureListener; -import com.huawei.hms.flutter.location.listeners.DefaultSuccessListener; -import com.huawei.hms.flutter.location.listeners.RemoveUpdatesSuccessListener; -import com.huawei.hms.flutter.location.listeners.RequestUpdatesFailureListener; -import com.huawei.hms.flutter.location.listeners.RequestUpdatesSuccessListener; -import com.huawei.hms.flutter.location.logger.HMSLogger; -import com.huawei.hms.flutter.location.utils.GeofenceUtils; -import com.huawei.hms.location.GeofenceRequest; -import com.huawei.hms.location.GeofenceService; -import com.huawei.hms.location.LocationServices; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import io.flutter.plugin.common.MethodCall; -import io.flutter.plugin.common.MethodChannel.MethodCallHandler; -import io.flutter.plugin.common.MethodChannel.Result; - -public class GeofenceMethodHandler implements MethodCallHandler { - private final Activity activity; - private final GeofenceService service; - private final Map requests; - - private int requestCode = 0; - - public GeofenceMethodHandler(final Activity activity) { - this.activity = activity; - service = LocationServices.getGeofenceService(activity); - requests = new HashMap<>(); - } - - private void createGeofenceList(@NonNull final MethodCall call, @NonNull final Result result) { - final GeofenceRequest geofenceRequest = GeofenceUtils.fromMapToGeofenceRequest(call.arguments()); - final Pair intentData = buildGeofenceIntent(); - - service.createGeofenceList(geofenceRequest, intentData.second) - .addOnSuccessListener(new RequestUpdatesSuccessListener(call.method, activity, result, intentData.first)) - .addOnFailureListener( - new RequestUpdatesFailureListener<>(call.method, activity, result, intentData.first, requests)); - } - - private void deleteGeofenceList(@NonNull final MethodCall call, @NonNull final Result result) { - final int incomingRequestCode = call.arguments(); - - if (!requests.containsKey(incomingRequestCode)) { - result.error(Error.NON_EXISTING_REQUEST_ID.name(), Error.NON_EXISTING_REQUEST_ID.message(), null); - } else { - service.deleteGeofenceList(requests.get(incomingRequestCode)) - .addOnSuccessListener( - new RemoveUpdatesSuccessListener<>(call.method, activity, result, incomingRequestCode, requests)) - .addOnFailureListener(new DefaultFailureListener(call.method, activity, result)); - } - } - - private void deleteGeofenceListWithIds(@NonNull final MethodCall call, @NonNull final Result result) { - service.deleteGeofenceList(call.>arguments()) - .addOnSuccessListener(new DefaultSuccessListener<>(call.method, activity, result)) - .addOnFailureListener(new DefaultFailureListener(call.method, activity, result)); - } - - private Pair buildGeofenceIntent() { - final Intent intent = new Intent(); - intent.setPackage(activity.getPackageName()); - intent.setAction(Action.PROCESS_GEOFENCE); - - final PendingIntent pendingIntent = PendingIntent.getBroadcast(activity.getApplicationContext(), ++requestCode, - intent, PendingIntent.FLAG_UPDATE_CURRENT); - requests.put(requestCode, pendingIntent); - return Pair.create(requestCode, pendingIntent); - } - - @Override - public void onMethodCall(@NonNull final MethodCall call, @NonNull final Result result) { - HMSLogger.getInstance(activity.getApplicationContext()).startMethodExecutionTimer(call.method); - - switch (call.method) { - case "createGeofenceList": - createGeofenceList(call, result); - break; - case "deleteGeofenceList": - deleteGeofenceList(call, result); - break; - case "deleteGeofenceListWithIds": - deleteGeofenceListWithIds(call, result); - break; - default: - result.notImplemented(); - break; - } - } -} diff --git a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/handlers/GeofenceStreamHandler.java b/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/handlers/GeofenceStreamHandler.java deleted file mode 100644 index d2c24d69..00000000 --- a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/handlers/GeofenceStreamHandler.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -package com.huawei.hms.flutter.location.handlers; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.IntentFilter; - -import com.huawei.hms.flutter.location.constants.Action; -import com.huawei.hms.flutter.location.logger.HMSLogger; -import com.huawei.hms.flutter.location.receivers.GeofenceBroadcastReceiver; - -import io.flutter.plugin.common.EventChannel.EventSink; -import io.flutter.plugin.common.EventChannel.StreamHandler; - -public class GeofenceStreamHandler implements StreamHandler { - private final Context context; - private BroadcastReceiver broadcastReceiver; - - public GeofenceStreamHandler(final Context context) { - this.context = context; - } - - @Override - public void onListen(final Object arguments, final EventSink events) { - broadcastReceiver = new GeofenceBroadcastReceiver(events); - context.registerReceiver(broadcastReceiver, new IntentFilter(Action.PROCESS_GEOFENCE)); - - HMSLogger.getInstance(context).sendSingleEvent("GeofenceStreamHandler.onListen"); - } - - @Override - public void onCancel(final Object arguments) { - context.unregisterReceiver(broadcastReceiver); - broadcastReceiver = null; - - HMSLogger.getInstance(context).sendSingleEvent("GeofenceStreamHandler.onCancel"); - } -} diff --git a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/handlers/HMSLoggerMethodHandler.java b/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/handlers/HMSLoggerMethodHandler.java deleted file mode 100644 index 57d4a65e..00000000 --- a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/handlers/HMSLoggerMethodHandler.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -package com.huawei.hms.flutter.location.handlers; - -import android.content.Context; - -import androidx.annotation.NonNull; - -import com.huawei.hms.flutter.location.logger.HMSLogger; - -import io.flutter.plugin.common.MethodCall; -import io.flutter.plugin.common.MethodChannel.MethodCallHandler; -import io.flutter.plugin.common.MethodChannel.Result; - -public class HMSLoggerMethodHandler implements MethodCallHandler { - private final Context context; - - public HMSLoggerMethodHandler(final Context context) { - this.context = context; - } - - @Override - public void onMethodCall(final MethodCall call, @NonNull final Result result) { - switch (call.method) { - case "enableLogger": - HMSLogger.getInstance(context).enableLogger(); - result.success(null); - break; - case "disableLogger": - HMSLogger.getInstance(context).disableLogger(); - result.success(null); - break; - default: - break; - } - } -} diff --git a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/handlers/LocationCallbackHandler.java b/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/handlers/LocationCallbackHandler.java deleted file mode 100644 index d932988e..00000000 --- a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/handlers/LocationCallbackHandler.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -package com.huawei.hms.flutter.location.handlers; - -import android.content.Context; - -import com.huawei.hms.flutter.location.logger.HMSLogger; -import com.huawei.hms.flutter.location.utils.LocationUtils; -import com.huawei.hms.location.LocationAvailability; -import com.huawei.hms.location.LocationCallback; -import com.huawei.hms.location.LocationResult; - -import java.util.HashMap; -import java.util.Map; - -import io.flutter.plugin.common.MethodChannel; - -public class LocationCallbackHandler extends LocationCallback { - private final Context context; - private final String methodName; - private final int callbackId; - private final MethodChannel channel; - - LocationCallbackHandler(final Context context, final String methodName, final int callbackId, - final MethodChannel channel) { - this.context = context; - this.methodName = methodName; - this.callbackId = callbackId; - this.channel = channel; - } - - @Override - public void onLocationResult(final LocationResult locationResult) { - if (locationResult != null) { - final Map map = new HashMap<>(); - - map.put("callbackId", callbackId); - map.put("locationResult", LocationUtils.fromLocationResultToMap(locationResult)); - - HMSLogger.getInstance(context).sendPeriodicEvent(methodName + ".onLocationResult"); - channel.invokeMethod("onLocationResult", map); - } - } - - @Override - public void onLocationAvailability(final LocationAvailability locationAvailability) { - if (locationAvailability != null) { - final Map map = new HashMap<>(); - - map.put("callbackId", callbackId); - map.put("locationAvailability", LocationUtils.fromLocationAvailabilityToMap(locationAvailability)); - - HMSLogger.getInstance(context).sendPeriodicEvent(methodName + ".onLocationAvailability"); - channel.invokeMethod("onLocationAvailability", map); - } - } -} diff --git a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/handlers/PermissionHandler.java b/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/handlers/PermissionHandler.java deleted file mode 100644 index 7db5a267..00000000 --- a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/handlers/PermissionHandler.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -package com.huawei.hms.flutter.location.handlers; - -import static androidx.core.content.PermissionChecker.PERMISSION_GRANTED; -import static androidx.core.content.PermissionChecker.checkSelfPermission; - -import android.app.Activity; -import android.os.Build; - -import androidx.annotation.NonNull; - -import com.huawei.hms.flutter.location.logger.HMSLogger; - -import io.flutter.plugin.common.MethodCall; -import io.flutter.plugin.common.MethodChannel.MethodCallHandler; -import io.flutter.plugin.common.MethodChannel.Result; -import io.flutter.plugin.common.PluginRegistry.RequestPermissionsResultListener; - -public class PermissionHandler implements MethodCallHandler, RequestPermissionsResultListener { - private static final String HUAWEI_ACTIVITY_RECOGNITION_PERMISSION = "android.permission.ACTIVITY_RECOGNITION"; - private static final String[] BG_LOC_PERMISSION_OLD = { - android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION - }; - private final Activity activity; - private final HMSLogger hmsLogger; - - private Result result; - - public PermissionHandler(final Activity activity) { - this.activity = activity; - hmsLogger = HMSLogger.getInstance(activity.getApplicationContext()); - } - - private boolean hasLocationPermission() { - hmsLogger.sendSingleEvent("hasLocationPermission"); - return isCoarseLocGranted() && isFineLocGranted(); - } - - private boolean hasBackgroundLocationPermission() { - hmsLogger.sendSingleEvent("hasBackgroundLocationPermission"); - - if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) { - return isFineLocGranted() && isBackgroundLocGranted(); - } - return isCoarseLocGranted() || isFineLocGranted(); - } - - private boolean hasActivityRecognitionPermission() { - hmsLogger.sendSingleEvent("hasActivityRecognitionPermission"); - - if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) { - return PERMISSION_GRANTED == checkSelfPermission(activity.getApplicationContext(), - android.Manifest.permission.ACTIVITY_RECOGNITION); - } else { - return PERMISSION_GRANTED == checkSelfPermission(activity.getApplicationContext(), - HUAWEI_ACTIVITY_RECOGNITION_PERMISSION); - } - } - - private void requestLocationPermission() { - hmsLogger.sendSingleEvent("requestLocationPermission"); - if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) { - final String[] permissions = { - android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION, - android.Manifest.permission.ACCESS_BACKGROUND_LOCATION - }; - activity.requestPermissions(permissions, 1); - } else { - if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) { - activity.requestPermissions(BG_LOC_PERMISSION_OLD, 2); - } - } - } - - private void requestBackgroundLocationPermission() { - hmsLogger.sendSingleEvent("requestBackgroundLocationPermission"); - if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) { - final String[] permissions = { - android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION, - android.Manifest.permission.ACCESS_BACKGROUND_LOCATION - }; - activity.requestPermissions(permissions, 3); - } else { - if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) { - activity.requestPermissions(BG_LOC_PERMISSION_OLD, 4); - } - } - } - - private void requestActivityRecognitionPermission() { - hmsLogger.sendSingleEvent("requestActivityRecognitionPermission"); - if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) { - final String[] permissions = {android.Manifest.permission.ACTIVITY_RECOGNITION}; - activity.requestPermissions(permissions, 5); - } else { - if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) { - final String[] permissions = {HUAWEI_ACTIVITY_RECOGNITION_PERMISSION}; - activity.requestPermissions(permissions, 6); - } - } - } - - private boolean isCoarseLocGranted() { - final int coarseLoc = checkSelfPermission(activity, android.Manifest.permission.ACCESS_COARSE_LOCATION); - return coarseLoc == PERMISSION_GRANTED; - } - - private boolean isFineLocGranted() { - final int fineLoc = checkSelfPermission(activity, android.Manifest.permission.ACCESS_FINE_LOCATION); - return fineLoc == PERMISSION_GRANTED; - } - - private boolean isBackgroundLocGranted() { - if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) { - final int backgroundLoc = checkSelfPermission(activity, - android.Manifest.permission.ACCESS_BACKGROUND_LOCATION); - return backgroundLoc == PERMISSION_GRANTED; - } - return true; - } - - private boolean checkGrantStatus(final int[] grantResults) { - for (final int i : grantResults) { - if (i != 0) { - return false; - } - } - return true; - } - - @Override - public void onMethodCall(final MethodCall call, @NonNull final Result result) { - this.result = result; - hmsLogger.startMethodExecutionTimer(call.method); - - switch (call.method) { - case "hasLocationPermission": - result.success(hasLocationPermission()); - break; - case "hasBackgroundLocationPermission": - result.success(hasBackgroundLocationPermission()); - break; - case "hasActivityRecognitionPermission": - result.success(hasActivityRecognitionPermission()); - break; - case "requestLocationPermission": - requestLocationPermission(); - break; - case "requestBackgroundLocationPermission": - requestBackgroundLocationPermission(); - break; - case "requestActivityRecognitionPermission": - requestActivityRecognitionPermission(); - break; - default: - break; - } - } - - @Override - public boolean onRequestPermissionsResult(final int requestCode, final String[] permissions, - final int[] grantResults) { - final Result incomingResult = result; - result = null; - - if (incomingResult != null) { - if (requestCode == 1) { - incomingResult.success(grantResults[0] == 0 || grantResults[1] == 0); - } else if (requestCode == 3) { - incomingResult.success((grantResults[0] == 0 || grantResults[1] == 0) && grantResults[2] == 0); - } else { - incomingResult.success(checkGrantStatus(grantResults)); - } - } - return true; - } -} diff --git a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/listeners/DefaultFailureListener.java b/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/listeners/DefaultFailureListener.java deleted file mode 100644 index c0a45044..00000000 --- a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/listeners/DefaultFailureListener.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -package com.huawei.hms.flutter.location.listeners; - -import android.content.Context; - -import com.huawei.hmf.tasks.OnFailureListener; -import com.huawei.hms.common.ApiException; -import com.huawei.hms.flutter.location.logger.HMSLogger; -import com.huawei.hms.flutter.location.utils.ObjectUtils; - -import io.flutter.plugin.common.MethodChannel.Result; - -public class DefaultFailureListener implements OnFailureListener { - private final String methodName; - private final Context context; - private final Result result; - - public DefaultFailureListener(final String methodName, final Context context, final Result result) { - this.methodName = methodName; - this.context = context; - this.result = result; - } - - @Override - public void onFailure(final Exception e) { - final ApiException ex = ObjectUtils.cast(e, ApiException.class); - final String statusCodeString = Integer.toString(ex.getStatusCode()); - - HMSLogger.getInstance(context).sendSingleEvent(methodName, statusCodeString); - result.error(statusCodeString, ex.getMessage(), null); - } -} diff --git a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/listeners/DefaultSuccessListener.java b/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/listeners/DefaultSuccessListener.java deleted file mode 100644 index 3576ad59..00000000 --- a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/listeners/DefaultSuccessListener.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -package com.huawei.hms.flutter.location.listeners; - -import android.content.Context; -import android.location.Location; - -import com.huawei.hmf.tasks.OnSuccessListener; -import com.huawei.hms.flutter.location.logger.HMSLogger; -import com.huawei.hms.flutter.location.utils.LocationUtils; -import com.huawei.hms.flutter.location.utils.ObjectUtils; -import com.huawei.hms.location.HWLocation; -import com.huawei.hms.location.LocationAvailability; -import com.huawei.hms.location.LocationSettingsResponse; -import com.huawei.hms.location.LocationSettingsStates; -import com.huawei.hms.location.NavigationResult; - -import io.flutter.plugin.common.MethodChannel.Result; - -public class DefaultSuccessListener implements OnSuccessListener { - private final String methodName; - private final Context context; - private final Result result; - - public DefaultSuccessListener(final String methodName, final Context context, final Result result) { - this.methodName = methodName; - this.context = context; - this.result = result; - } - - @Override - public void onSuccess(final T o) { - HMSLogger.getInstance(context).sendSingleEvent(methodName); - - if (o instanceof Void || o == null) { - result.success(null); - } - - if (o instanceof Location) { - final Location location = ObjectUtils.cast(o, Location.class); - result.success(LocationUtils.fromLocationToMap(location)); - } - - if (o instanceof HWLocation) { - final HWLocation hwLocation = ObjectUtils.cast(o, HWLocation.class); - result.success(LocationUtils.fromHWLocationToMap(hwLocation)); - } - - if (o instanceof LocationAvailability) { - final LocationAvailability locationAvailability = ObjectUtils.cast(o, LocationAvailability.class); - result.success(LocationUtils.fromLocationAvailabilityToMap(locationAvailability)); - } - - if (o instanceof LocationSettingsResponse) { - final LocationSettingsResponse response = ObjectUtils.cast(o, LocationSettingsResponse.class); - final LocationSettingsStates locationSettingsStates = response.getLocationSettingsStates(); - result.success(LocationUtils.fromLocationSettingsStatesToMap(locationSettingsStates)); - } - - if (o instanceof NavigationResult) { - final NavigationResult navigationResult = ObjectUtils.cast(o, NavigationResult.class); - result.success(LocationUtils.fromNavigationResultToMap(navigationResult)); - } - } -} diff --git a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/listeners/LocationSettingsFailureListener.java b/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/listeners/LocationSettingsFailureListener.java deleted file mode 100644 index 361e5c8e..00000000 --- a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/listeners/LocationSettingsFailureListener.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -package com.huawei.hms.flutter.location.listeners; - -import static com.huawei.hms.location.LocationSettingsStatusCodes.RESOLUTION_REQUIRED; - -import android.app.Activity; -import android.content.IntentSender.SendIntentException; - -import com.huawei.hmf.tasks.OnFailureListener; -import com.huawei.hms.common.ApiException; -import com.huawei.hms.common.ResolvableApiException; -import com.huawei.hms.flutter.location.constants.Error; -import com.huawei.hms.flutter.location.logger.HMSLogger; -import com.huawei.hms.flutter.location.utils.ObjectUtils; - -import io.flutter.plugin.common.MethodChannel.Result; - -public class LocationSettingsFailureListener implements OnFailureListener { - private final Result result; - private final Activity activity; - - public LocationSettingsFailureListener(final Result result, final Activity activity) { - this.result = result; - this.activity = activity; - } - - @Override - public void onFailure(final Exception e) { - final ApiException apiException = ObjectUtils.cast(e, ApiException.class); - final int statusCode = apiException.getStatusCode(); - final String statusCodeString = Integer.toString(statusCode); - - if (statusCode == RESOLUTION_REQUIRED) { - try { - final ResolvableApiException resolvableApiException = ObjectUtils.cast(e, ResolvableApiException.class); - resolvableApiException.startResolutionForResult(activity, 0); - } catch (final SendIntentException ex) { - HMSLogger.getInstance(activity.getApplicationContext()).sendSingleEvent("checkLocationSettings", "-1"); - result.error(Error.SEND_INTENT_EXCEPTION.name(), ex.getMessage(), null); - } - } else { - HMSLogger.getInstance(activity.getApplicationContext()) - .sendSingleEvent("checkLocationSettings", statusCodeString); - result.error(statusCodeString, apiException.getMessage(), null); - } - } -} diff --git a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/listeners/RemoveUpdatesSuccessListener.java b/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/listeners/RemoveUpdatesSuccessListener.java deleted file mode 100644 index ff83dca9..00000000 --- a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/listeners/RemoveUpdatesSuccessListener.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -package com.huawei.hms.flutter.location.listeners; - -import android.content.Context; - -import com.huawei.hmf.tasks.OnSuccessListener; -import com.huawei.hms.flutter.location.logger.HMSLogger; - -import java.util.Map; - -import io.flutter.plugin.common.MethodChannel.Result; - -public class RemoveUpdatesSuccessListener implements OnSuccessListener { - private final String methodName; - private final Context context; - private final Result result; - private final Integer id; - private final Map map; - - public RemoveUpdatesSuccessListener(final String methodName, final Context context, final Result result, - final Integer id, final Map map) { - this.methodName = methodName; - this.context = context; - this.result = result; - this.id = id; - this.map = map; - } - - @Override - public void onSuccess(final Void avoid) { - map.remove(id); - HMSLogger.getInstance(context).sendSingleEvent(methodName); - result.success(null); - } -} diff --git a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/listeners/RequestUpdatesFailureListener.java b/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/listeners/RequestUpdatesFailureListener.java deleted file mode 100644 index 6bc0131f..00000000 --- a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/listeners/RequestUpdatesFailureListener.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -package com.huawei.hms.flutter.location.listeners; - -import android.content.Context; - -import com.huawei.hmf.tasks.OnFailureListener; -import com.huawei.hms.common.ApiException; -import com.huawei.hms.flutter.location.logger.HMSLogger; -import com.huawei.hms.flutter.location.utils.ObjectUtils; - -import java.util.Map; - -import io.flutter.plugin.common.MethodChannel.Result; - -public class RequestUpdatesFailureListener implements OnFailureListener { - private final String methodName; - private final Context context; - private final Result result; - private final Integer id; - private final Map map; - - public RequestUpdatesFailureListener(final String methodName, final Context context, final Result result, - final Integer id, final Map map) { - this.methodName = methodName; - this.context = context; - this.result = result; - this.id = id; - this.map = map; - } - - @Override - public void onFailure(final Exception e) { - final ApiException ex = ObjectUtils.cast(e, ApiException.class); - final String statusCodeString = Integer.toString(ex.getStatusCode()); - - map.remove(id); - HMSLogger.getInstance(context).sendSingleEvent(methodName, statusCodeString); - result.error(statusCodeString, ex.getMessage(), null); - } -} diff --git a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/listeners/RequestUpdatesSuccessListener.java b/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/listeners/RequestUpdatesSuccessListener.java deleted file mode 100644 index b90fbd2d..00000000 --- a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/listeners/RequestUpdatesSuccessListener.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -package com.huawei.hms.flutter.location.listeners; - -import android.content.Context; - -import com.huawei.hmf.tasks.OnSuccessListener; -import com.huawei.hms.flutter.location.logger.HMSLogger; - -import io.flutter.plugin.common.MethodChannel.Result; - -public class RequestUpdatesSuccessListener implements OnSuccessListener { - private final Result result; - private final Integer requestCode; - private final Context context; - private final String methodName; - - public RequestUpdatesSuccessListener(final String methodName, final Context context, final Result result, - final Integer requestCode) { - this.methodName = methodName; - this.context = context; - this.result = result; - this.requestCode = requestCode; - } - - @Override - public void onSuccess(final Void avoid) { - HMSLogger.getInstance(context).sendSingleEvent(methodName); - result.success(requestCode); - } -} diff --git a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/logger/HMSLogger.java b/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/logger/HMSLogger.java deleted file mode 100644 index 80af0462..00000000 --- a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/logger/HMSLogger.java +++ /dev/null @@ -1,449 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -package com.huawei.hms.flutter.location.logger; - -import static android.os.Build.DEVICE; - -import android.content.Context; -import android.content.pm.PackageManager; -import android.net.ConnectivityManager; -import android.net.NetworkCapabilities; -import android.util.Log; - -import com.huawei.agconnect.config.AGConnectServicesConfig; -import com.huawei.hms.support.hianalytics.HiAnalyticsUtils; -import com.huawei.hms.utils.HMSBIInitializer; - -import java.lang.ref.WeakReference; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; - -public final class HMSLogger { - private static final String TAG = "HMSLogger"; - - private static final String VERSION = "5.0.0.301"; - private static final String SERVICE = "FlutterLocation"; - - private static final String SUCCESS = "0"; - private static final String UNKNOWN = "UNKNOWN"; - private static final String NOT_AVAILABLE = "NOT_AVAILABLE"; - - private static final String SINGLE_EVENT_ID = "60000"; - private static final String PERIODIC_EVENT_ID = "60001"; - - private static final String NETWORK_TYPE_WIFI = "WIFI"; - - private static volatile HMSLogger instance; - - private final WeakReference weakContext; - private final HiAnalyticsUtils hiAnalyticsUtils; - - private final Map singleEventMap = new HashMap<>(); - private final Map periodicEventMap = new HashMap<>(); - private final Map allCountMap = new HashMap<>(); - private final Map failCountMap = new HashMap<>(); - private final Map startTimeMap = new HashMap<>(); - private final Map firstReceiveTimeMap = new HashMap<>(); - private final Map lastReceiveTimeMap = new HashMap<>(); - private final Map> resultCodeCountMap = new HashMap<>(); - private final Map networkTypeMap = createNetworkTypeMap(); - - private boolean isEnabled = true; - - /** - * Private constructor of this class - * - * @param context Application's context - */ - private HMSLogger(final Context context) { - weakContext = new WeakReference<>(context); - hiAnalyticsUtils = HiAnalyticsUtils.getInstance(); - - setupEventMap(singleEventMap); - setupEventMap(periodicEventMap); - initHMSBI(HMSBIInitializer.getInstance(context)); - - Log.d(TAG, "HMS Plugin Dotting is Enabled!"); - } - - /** - * Returns the instance of this class - * - * @param context Application's context - * @return HMSLogger instance - */ - public static synchronized HMSLogger getInstance(final Context context) { - if (instance == null) { - synchronized (HMSLogger.class) { - if (instance == null) { - instance = new HMSLogger(context); - } - } - } - return instance; - } - - /** - * Returns actual context reference - * - * @return Actual context reference - */ - private Context getContext() { - return weakContext.get(); - } - - /** - * Enables HMSLogger - */ - public synchronized void enableLogger() { - isEnabled = true; - Log.d(TAG, "HMS Plugin Dotting is Enabled!"); - } - - /** - * Disables HMSLogger - */ - public synchronized void disableLogger() { - isEnabled = false; - Log.d(TAG, "HMS Plugin Dotting is Disabled!"); - } - - /** - * Sets method start time for given method name - * - * @param methodName Name of the method that will be logged - */ - public synchronized void startMethodExecutionTimer(final String methodName) { - startTimeMap.put(methodName, System.currentTimeMillis()); - } - - /** - * Sends successful single event - * - * @param methodName The name of the method called - */ - public synchronized void sendSingleEvent(final String methodName) { - sendEvent(SINGLE_EVENT_ID, methodName, SUCCESS); - } - - /** - * Sends unsuccessful single event - * - * @param methodName The name of the method called - * @param errorCode API error code - */ - public synchronized void sendSingleEvent(final String methodName, final String errorCode) { - sendEvent(SINGLE_EVENT_ID, methodName, errorCode); - } - - /** - * Sends successful periodic event - * - * @param methodName The name of the method called - */ - public synchronized void sendPeriodicEvent(final String methodName) { - sendEvent(PERIODIC_EVENT_ID, methodName, SUCCESS); - } - - /** - * Sends unsuccessful periodic event - * - * @param methodName The name of the method called - * @param errorCode API error code - */ - public synchronized void sendPeriodicEvent(final String methodName, final String errorCode) { - sendEvent(PERIODIC_EVENT_ID, methodName, errorCode); - } - - /** - * Calls initBI() method from HMSBIInitializer - * - * @param initializer HMSBIInitializer object - */ - private void initHMSBI(final HMSBIInitializer initializer) { - if (!initializer.isInit()) { - initializer.initBI(); - } - } - - /** - * Sends the event based on eventId, methodName, and resultCode - * - * @param eventId Constant id of the event - * @param methodName The name of the method called - * @param resultCode Code of the method's result. "0" for success, others for error - */ - private synchronized void sendEvent(final String eventId, final String methodName, final String resultCode) { - if (isEnabled) { - final long currentTime = System.currentTimeMillis(); - - if (eventId.equals(SINGLE_EVENT_ID)) { - putToSingleEventMap(methodName, resultCode, currentTime); - hiAnalyticsUtils.onNewEvent(getContext(), SINGLE_EVENT_ID, singleEventMap); - - Log.d(TAG, "singleEventMap -> " + singleEventMap); - } else { - putToPeriodicEventMap(methodName, resultCode, currentTime); - hiAnalyticsUtils.onNewEvent(getContext(), PERIODIC_EVENT_ID, periodicEventMap); - - Log.d(TAG, "periodicEventMap -> " + periodicEventMap); - } - } - } - - /** - * Gets "client/app_id" value from agconnect-services.json file - * - * @return app_id value or NOT_AVAILABLE if not found - */ - private String getAppId() { - try { - return AGConnectServicesConfig.fromContext(getContext()).getString("client/app_id"); - } catch (final NullPointerException e) { - Log.d(TAG, "AgConnect is not found. Setting appId value to " + NOT_AVAILABLE); - } - return NOT_AVAILABLE; - } - - /** - * Gets app version name - * - * @param packageName Package name of the app - * @return App version name in String type - */ - private String getAppVersionName(final String packageName) { - try { - return getContext().getPackageManager().getPackageInfo(packageName, 0).versionName; - } catch (final PackageManager.NameNotFoundException e) { - Log.e(TAG, "getAppVersionName -> Could not get appVersionName!"); - return NOT_AVAILABLE; - } - } - - /** - * Detects current network type - * - * @return Human readable network type; such as WIFI, LTE - */ - private String getNetworkType() { - final ConnectivityManager cm = objectCast(getContext().getSystemService(Context.CONNECTIVITY_SERVICE), - ConnectivityManager.class); - if (cm != null) { - if (cm.getActiveNetworkInfo() == null || !cm.getActiveNetworkInfo().isConnected()) { - return NOT_AVAILABLE; - } - - final int networkSubtype = Objects.requireNonNull(cm.getActiveNetworkInfo()).getSubtype(); - final String networkSubtypeString = getOrDefault(networkTypeMap, networkSubtype, UNKNOWN); - - if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { - final NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork()); - if (capabilities != null) { - if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) { - return networkSubtypeString; - } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) { - return NETWORK_TYPE_WIFI; - } else { - return UNKNOWN; - } - } else { - return NOT_AVAILABLE; - } - } else { - final int networkType = Objects.requireNonNull(cm.getActiveNetworkInfo()).getType(); - switch (networkType) { - case ConnectivityManager.TYPE_WIFI: - return NETWORK_TYPE_WIFI; - case ConnectivityManager.TYPE_MOBILE: - return networkSubtypeString; - default: - return UNKNOWN; - } - } - } - return NOT_AVAILABLE; - } - - /** - * Sets default values to given map - * - * @param map HashMap to put default values - */ - private void setupEventMap(final Map map) { - map.put("version", VERSION); - map.put("service", SERVICE); - map.put("appid", getAppId()); - map.put("package", getContext().getPackageName()); - map.put("cpAppVersion", getAppVersionName(getContext().getPackageName())); - map.put("model", DEVICE); - } - - /** - * Prepares sing-event map according to input parameters - * - * @param methodName The name of the method called - * @param resultCode Code of the method's result. "0" for success, others for error - * @param currentTime Current timestamp in millisecond - */ - private void putToSingleEventMap(final String methodName, final String resultCode, final long currentTime) { - final long startTime = getOrDefault(startTimeMap, methodName, currentTime); - final int costTime = (int) (currentTime - startTime); - singleEventMap.put("apiName", methodName); - singleEventMap.put("result", resultCode); - singleEventMap.put("callTime", currentTime); - singleEventMap.put("costTime", costTime); - singleEventMap.put("networkType", getNetworkType()); - } - - /** - * Prepares periodic-event map according to input parameters - * - * @param methodName The name of the method called - * @param resultCode Code of the method's result. "0" for success, others for error - * @param currentTime Current timestamp in millisecond - */ - private void putToPeriodicEventMap(final String methodName, final String resultCode, final long currentTime) { - increaseResultCodeCount(methodName, resultCode); - increaseMapValue(methodName, allCountMap); - - if (!resultCode.equals(SUCCESS)) { - increaseMapValue(methodName, failCountMap); - } - - final long firstReceiveTime = getOrDefault(firstReceiveTimeMap, methodName, currentTime); - periodicEventMap.put("callTime", firstReceiveTime); - - final long lastReceiveTime = getOrDefault(lastReceiveTimeMap, methodName, currentTime); - final int costTime = (int) (currentTime - lastReceiveTime); - periodicEventMap.put("costTime", costTime); - - periodicEventMap.put("apiName", methodName); - periodicEventMap.put("result", resultCodeCountMap.get(methodName)); - - final long allCount = getOrDefault(allCountMap, methodName, 0L); - periodicEventMap.put("allCnt", allCount); - - final long failCount = getOrDefault(failCountMap, methodName, 0L); - periodicEventMap.put("failCnt", failCount); - - periodicEventMap.put("lastCallTime", currentTime); - periodicEventMap.put("networkType", getNetworkType()); - - putIfAbsent(firstReceiveTimeMap, methodName, currentTime); - lastReceiveTimeMap.put(methodName, currentTime); - } - - /** - * Prepares HashMap of network type id and its human-readable string pairs - * - * @return HashMap of human readable network type names - */ - private Map createNetworkTypeMap() { - final Map map = new HashMap<>(); - - map.put(0, UNKNOWN); - map.put(1, "2.5G"); - map.put(2, "2.75G"); - map.put(3, "3G"); - map.put(4, "2G"); - map.put(5, "3G"); - map.put(6, "3G"); - map.put(7, "2G"); - map.put(8, "3G"); - map.put(9, "3G"); - map.put(10, "3G"); - map.put(11, "2G"); - map.put(12, "3G"); - map.put(13, "4G"); - map.put(14, "3G"); - map.put(15, "3G"); - map.put(16, "2G"); - map.put(17, "3G"); - map.put(18, "4G"); - map.put(19, "4G"); - map.put(20, "5G"); - - return Collections.unmodifiableMap(map); - } - - /** - * Increases count of the given result code - * - * @param methodName Name of the calling method - * @param resultCode Code of the method's result. "0" for success, others for error - */ - private void increaseResultCodeCount(final String methodName, final String resultCode) { - final Map map = getOrDefault(resultCodeCountMap, methodName, new HashMap<>()); - - increaseMapValue(resultCode, map); - resultCodeCountMap.put(methodName, map); - } - - /** - * Increases the value of the corresponding key which in the map - * - * @param key Key for map lookup - * @param map The Map that contains the key and its corresponding value - */ - private void increaseMapValue(final String key, final Map map) { - map.put(key, getOrDefault(map, key, 0L) + 1); - } - - /** - * Get the corresponding value of the key. If the key does not exist in the map then the default value is returned. - * - * @param map The Map - * @param key Lookup key - * @param defaultValue The default value will be returned if the key is absent - * @param Generic type of the key - * @param Generic type of the value - * @return Corresponding value or default value - */ - private V getOrDefault(final Map map, final K key, final V defaultValue) { - return map.containsKey(key) ? map.get(key) : defaultValue; - } - - /** - * Put key-value pair to map if the key is absent - * - * @param map The Map - * @param key Lookup key - * @param value The value will be put to the map if the key is absent - * @param Generic type of the key - * @param Generic type of the value - */ - private void putIfAbsent(final Map map, final K key, final V value) { - if (!map.containsKey(key)) { - map.put(key, value); - } - } - - /** - * Utility method that castes given object to given class type - * - * @param source Source object to be casted - * @param clazz Class that object will be casted to its type - * @param Source object's type - * @param Destination type - * @return Object that casted to D type - */ - private D objectCast(final S source, final Class clazz) { - return clazz.cast(source); - } -} diff --git a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/receivers/ActivityConversionBroadcastReceiver.java b/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/receivers/ActivityConversionBroadcastReceiver.java deleted file mode 100644 index 06d8e231..00000000 --- a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/receivers/ActivityConversionBroadcastReceiver.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -package com.huawei.hms.flutter.location.receivers; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; - -import com.huawei.hms.flutter.location.logger.HMSLogger; -import com.huawei.hms.flutter.location.utils.ActivityUtils; -import com.huawei.hms.location.ActivityConversionResponse; - -import io.flutter.plugin.common.EventChannel.EventSink; - -public class ActivityConversionBroadcastReceiver extends BroadcastReceiver { - private final EventSink eventSink; - - public ActivityConversionBroadcastReceiver(final EventSink eventSink) { - this.eventSink = eventSink; - } - - @Override - public void onReceive(final Context context, final Intent intent) { - if (ActivityConversionResponse.containDataFromIntent(intent)) { - final ActivityConversionResponse response = ActivityConversionResponse.getDataFromIntent(intent); - - HMSLogger.getInstance(context).sendPeriodicEvent("ActivityConversionUpdates"); - eventSink.success(ActivityUtils.activityConversionResponseToMap(response)); - } - } -} diff --git a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/receivers/ActivityIdentificationBroadcastReceiver.java b/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/receivers/ActivityIdentificationBroadcastReceiver.java deleted file mode 100644 index bb2c9666..00000000 --- a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/receivers/ActivityIdentificationBroadcastReceiver.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -package com.huawei.hms.flutter.location.receivers; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; - -import com.huawei.hms.flutter.location.logger.HMSLogger; -import com.huawei.hms.flutter.location.utils.ActivityUtils; -import com.huawei.hms.location.ActivityIdentificationResponse; - -import io.flutter.plugin.common.EventChannel.EventSink; - -public class ActivityIdentificationBroadcastReceiver extends BroadcastReceiver { - private final EventSink eventSink; - - public ActivityIdentificationBroadcastReceiver(final EventSink eventSink) { - this.eventSink = eventSink; - } - - @Override - public void onReceive(final Context context, final Intent intent) { - if (ActivityIdentificationResponse.containDataFromIntent(intent)) { - final ActivityIdentificationResponse response = ActivityIdentificationResponse.getDataFromIntent(intent); - - HMSLogger.getInstance(context).sendPeriodicEvent("ActivityIdentificationUpdates"); - eventSink.success(ActivityUtils.activityIdentificationResponseToMap(response)); - } - } -} diff --git a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/receivers/FusedLocationBroadcastReceiver.java b/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/receivers/FusedLocationBroadcastReceiver.java deleted file mode 100644 index dcdfbd49..00000000 --- a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/receivers/FusedLocationBroadcastReceiver.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -package com.huawei.hms.flutter.location.receivers; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.location.Location; - -import com.huawei.hms.flutter.location.logger.HMSLogger; -import com.huawei.hms.flutter.location.utils.LocationUtils; -import com.huawei.hms.location.LocationResult; - -import io.flutter.plugin.common.EventChannel.EventSink; - -public class FusedLocationBroadcastReceiver extends BroadcastReceiver { - private final EventSink eventSink; - - public FusedLocationBroadcastReceiver(final EventSink eventSink) { - this.eventSink = eventSink; - } - - @Override - public void onReceive(final Context context, final Intent intent) { - if (LocationResult.hasResult(intent)) { - HMSLogger.getInstance(context).sendPeriodicEvent("LocationUpdates"); - for (final Location location : LocationResult.extractResult(intent).getLocations()) { - eventSink.success(LocationUtils.fromLocationToMap(location)); - } - } - } -} diff --git a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/receivers/GeofenceBroadcastReceiver.java b/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/receivers/GeofenceBroadcastReceiver.java deleted file mode 100644 index ae9f5451..00000000 --- a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/receivers/GeofenceBroadcastReceiver.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -package com.huawei.hms.flutter.location.receivers; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; - -import com.huawei.hms.flutter.location.logger.HMSLogger; -import com.huawei.hms.flutter.location.utils.GeofenceUtils; -import com.huawei.hms.location.GeofenceData; - -import io.flutter.plugin.common.EventChannel.EventSink; - -public class GeofenceBroadcastReceiver extends BroadcastReceiver { - private final EventSink eventSink; - - public GeofenceBroadcastReceiver(final EventSink eventSink) { - this.eventSink = eventSink; - } - - @Override - public void onReceive(final Context context, final Intent intent) { - if (intent != null) { - final GeofenceData geofenceData = GeofenceData.getDataFromIntent(intent); - HMSLogger.getInstance(context).sendPeriodicEvent("GeofenceUpdates"); - eventSink.success(GeofenceUtils.fromGeofenceDataToMap(geofenceData)); - } - } -} diff --git a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/utils/ActivityUtils.java b/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/utils/ActivityUtils.java deleted file mode 100644 index 6600697a..00000000 --- a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/utils/ActivityUtils.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -package com.huawei.hms.flutter.location.utils; - -import com.huawei.hms.location.ActivityConversionData; -import com.huawei.hms.location.ActivityConversionInfo; -import com.huawei.hms.location.ActivityConversionRequest; -import com.huawei.hms.location.ActivityConversionResponse; -import com.huawei.hms.location.ActivityIdentificationData; -import com.huawei.hms.location.ActivityIdentificationResponse; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public interface ActivityUtils { - /** - * Utility method - * @param list List of the ActivityConversionInfo - * @return ActivityConversionRequest object - */ - static ActivityConversionRequest fromActivityConversionInfoListToActivityConversionRequest( - final List> list) { - final List activityConversionInfos = new ArrayList<>(); - - for (final Map map : list) { - activityConversionInfos.add(fromMapToActivityConversionInfo(map)); - } - - return new ActivityConversionRequest(activityConversionInfos); - } - - /** - * Utility method - * @param map HashMap representation of the ActivityConversionInfo object - * @return ActivityConversionInfo object - */ - static ActivityConversionInfo fromMapToActivityConversionInfo(final Map map) { - return new ActivityConversionInfo(ValueGetter.getInt("activityType", map), - ValueGetter.getInt("conversionType", map)); - } - - /** - * Utility method - * @param data ActivityIdentificationData object - * @return HashMap representation of ActivityIdentificationData object - */ - static Map activityIdentificationDataToMap(final ActivityIdentificationData data) { - final Map map = new HashMap<>(); - - if (data == null) { - return map; - } - - map.put("identificationActivity", data.getIdentificationActivity()); - map.put("possibility", data.getPossibility()); - - return map; - } - - /** - * Utility method - * @param response ActivityIdentificationResponse object - * @return HashMap representation of ActivityIdentificationResponse object - */ - static Map activityIdentificationResponseToMap(final ActivityIdentificationResponse response) { - final Map map = new HashMap<>(); - - if (response == null) { - return map; - } - - map.put("time", response.getTime()); - map.put("elapsedTimeFromReboot", response.getElapsedTimeFromReboot()); - - final List> activityIdentificationDatas = new ArrayList<>(); - for (final ActivityIdentificationData data : response.getActivityIdentificationDatas()) { - activityIdentificationDatas.add(activityIdentificationDataToMap(data)); - } - map.put("activityIdentificationDatas", activityIdentificationDatas); - - return map; - } - - /** - * Utility method - * @param data ActivityConversionData object - * @return HashMap representation of the ActivityConversionData object - */ - static Map activityConversionDataToMap(final ActivityConversionData data) { - final Map map = new HashMap<>(); - - if (data == null) { - return map; - } - - map.put("activityType", data.getActivityType()); - map.put("conversionType", data.getConversionType()); - map.put("elapsedTimeFromReboot", data.getElapsedTimeFromReboot()); - - return map; - } - - /** - * Utility method - * @param response ActivityConversionResponse object - * @return HashMap representation of the ActivityConversionResponse object - */ - static Map activityConversionResponseToMap(final ActivityConversionResponse response) { - final Map map = new HashMap<>(); - - if (response == null) { - return map; - } - - final List> activityConversionDatas = new ArrayList<>(); - - for (final ActivityConversionData data : response.getActivityConversionDatas()) { - activityConversionDatas.add(ActivityUtils.activityConversionDataToMap(data)); - } - - map.put("activityConversionDatas", activityConversionDatas); - return map; - } -} diff --git a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/utils/GeofenceUtils.java b/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/utils/GeofenceUtils.java deleted file mode 100644 index d79cf75d..00000000 --- a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/utils/GeofenceUtils.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -package com.huawei.hms.flutter.location.utils; - -import com.huawei.hms.location.Geofence; -import com.huawei.hms.location.GeofenceData; -import com.huawei.hms.location.GeofenceRequest; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public interface GeofenceUtils { - /** - * Utility method - * @param geofenceData GeofenceData object - * @return HashMap representation of the GeofenceData object - */ - static Map fromGeofenceDataToMap(final GeofenceData geofenceData) { - if (geofenceData == null) { - return Collections.emptyMap(); - } - - final Map map = new HashMap<>(); - final List convertingGeofenceIdList = new ArrayList<>(); - - for (final Geofence geofence : geofenceData.getConvertingGeofenceList()) { - convertingGeofenceIdList.add(geofence.getUniqueId()); - } - - map.put("errorCode", geofenceData.getErrorCode()); - map.put("conversion", geofenceData.getConversion()); - map.put("convertingGeofenceIdList", convertingGeofenceIdList); - map.put("convertingLocation", LocationUtils.fromLocationToMap(geofenceData.getConvertingLocation())); - - return map; - } - - /** - * Utility method - * @param map HashMap representation of the Geofence object - * @return Geofence object - */ - static Geofence fromMapToGeofence(final Map map) { - final Geofence.Builder builder = new Geofence.Builder(); - - final double lat = ValueGetter.getDouble("latitude", map); - final double lng = ValueGetter.getDouble("longitude", map); - final float rad = ValueGetter.getFloat("radius", map); - - builder.setRoundArea(lat, lng, rad); - builder.setUniqueId(ValueGetter.getString("uniqueId", map)); - builder.setConversions(ValueGetter.getInt("conversions", map)); - builder.setDwellDelayTime(ValueGetter.getInt("dwellDelayTime", map)); - builder.setValidContinueTime(ValueGetter.getLong("validDuration", map)); - builder.setNotificationInterval(ValueGetter.getInt("notificationInterval", map)); - - return builder.build(); - } - - /** - * Utility method - * @param map HashMap representation of the GeofenceRequest object - * @return GeofenceRequest object - */ - static GeofenceRequest fromMapToGeofenceRequest(final Map map) { - final GeofenceRequest.Builder builder = new GeofenceRequest.Builder(); - final List geofenceMapList = ObjectUtils.cast(map.get("geofenceList"), List.class); - - if (geofenceMapList != null) { - for (final Object geofence : geofenceMapList) { - final Map geofenceMap = ObjectUtils.cast(geofence, Map.class); - builder.createGeofence(fromMapToGeofence(geofenceMap)); - } - } - - builder.setCoordinateType(ValueGetter.getInt("coordinateType", map)); - builder.setInitConversions(ValueGetter.getInt("initConversions", map)); - - return builder.build(); - } -} diff --git a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/utils/LocationUtils.java b/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/utils/LocationUtils.java deleted file mode 100644 index 36931b67..00000000 --- a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/utils/LocationUtils.java +++ /dev/null @@ -1,309 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -package com.huawei.hms.flutter.location.utils; - -import android.location.Location; -import android.os.Build.VERSION; -import android.os.Build.VERSION_CODES; - -import com.huawei.hms.location.HWLocation; -import com.huawei.hms.location.LocationAvailability; -import com.huawei.hms.location.LocationRequest; -import com.huawei.hms.location.LocationResult; -import com.huawei.hms.location.LocationSettingsRequest; -import com.huawei.hms.location.LocationSettingsStates; -import com.huawei.hms.location.NavigationRequest; -import com.huawei.hms.location.NavigationResult; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -public interface LocationUtils { - /** - * Utility method - * @param location ActivityIdentificationData object - * @return HashMap representation of Location object - */ - static Map fromLocationToMap(final Location location) { - if (location == null) { - return Collections.emptyMap(); - } - - final Map map = new HashMap<>(); - - map.put("provider", location.getProvider()); - map.put("latitude", location.getLatitude()); - map.put("longitude", location.getLongitude()); - map.put("altitude", location.getAltitude()); - map.put("speed", location.getSpeed()); - map.put("bearing", location.getBearing()); - map.put("horizontalAccuracyMeters", location.getAccuracy()); - map.put("time", location.getTime()); - map.put("elapsedRealtimeNanos", location.getElapsedRealtimeNanos()); - map.put("isFromMockProvider", location.isFromMockProvider()); - - if (VERSION.SDK_INT >= VERSION_CODES.O) { - map.put("verticalAccuracyMeters", location.getVerticalAccuracyMeters()); - map.put("speedAccuracyMetersPerSecond", location.getSpeedAccuracyMetersPerSecond()); - map.put("bearingAccuracyDegrees", location.getBearingAccuracyDegrees()); - } else { - map.put("verticalAccuracyMeters", 0.0); - map.put("speedAccuracyMetersPerSecond", 0.0); - map.put("bearingAccuracyDegrees", 0.0); - } - - return map; - } - - /** - * Utility method - * @param hwLocation HWLocation object - * @return HashMap representation of HWLocation object - */ - static Map fromHWLocationToMap(final HWLocation hwLocation) { - if (hwLocation == null) { - return Collections.emptyMap(); - } - - final Map map = new HashMap<>(); - - map.put("provider", hwLocation.getProvider()); - map.put("latitude", hwLocation.getLatitude()); - map.put("longitude", hwLocation.getLongitude()); - map.put("altitude", hwLocation.getAltitude()); - map.put("speed", hwLocation.getSpeed()); - map.put("bearing", hwLocation.getBearing()); - map.put("horizontalAccuracyMeters", hwLocation.getAccuracy()); - map.put("verticalAccuracyMeters", hwLocation.getVerticalAccuracyMeters()); - map.put("speedAccuracyMetersPerSecond", hwLocation.getSpeedAccuracyMetersPerSecond()); - map.put("bearingAccuracyDegrees", hwLocation.getBearingAccuracyDegrees()); - map.put("time", hwLocation.getTime()); - map.put("elapsedRealtimeNanos", hwLocation.getElapsedRealtimeNanos()); - map.put("countryCode", hwLocation.getCountryCode()); - map.put("countryName", hwLocation.getCountryName()); - map.put("state", hwLocation.getState()); - map.put("city", hwLocation.getCity()); - map.put("county", hwLocation.getCounty()); - map.put("street", hwLocation.getStreet()); - map.put("featureName", hwLocation.getFeatureName()); - map.put("postalCode", hwLocation.getPostalCode()); - map.put("phone", hwLocation.getPhone()); - map.put("url", hwLocation.getUrl()); - map.put("extraInfo", hwLocation.getExtraInfo()); - - return map; - } - - /** - * Utility method - * @param locationAvailability LocationAvailability object - * @return HashMap representation of LocationAvailability object - */ - static Map fromLocationAvailabilityToMap(final LocationAvailability locationAvailability) { - if (locationAvailability == null) { - return Collections.emptyMap(); - } - - final Map map = new HashMap<>(); - - map.put("cellStatus", locationAvailability.getCellStatus()); - map.put("wifiStatus", locationAvailability.getWifiStatus()); - map.put("elapsedRealtimeNs", locationAvailability.getElapsedRealtimeNs()); - map.put("locationStatus", locationAvailability.getLocationStatus()); - - return map; - } - - /** - * Utility method - * @param locationResult LocationResult object - * @return HashMap representation of LocationResult object - */ - static Map fromLocationResultToMap(final LocationResult locationResult) { - if (locationResult == null) { - return Collections.emptyMap(); - } - - final Map map = new HashMap<>(); - final List> locationMaps = new ArrayList<>(); - final List> hwLocationMaps = new ArrayList<>(); - - for (final Location location : locationResult.getLocations()) { - locationMaps.add(fromLocationToMap(location)); - } - - for (final HWLocation hwLocation : locationResult.getHWLocationList()) { - hwLocationMaps.add(fromHWLocationToMap(hwLocation)); - } - - map.put("locations", locationMaps); - map.put("hwLocations", hwLocationMaps); - map.put("lastLocation", fromLocationToMap(locationResult.getLastLocation())); - map.put("lastHWLocation", fromHWLocationToMap(locationResult.getLastHWLocation())); - - return map; - } - - /** - * Utility method - * @param states LocationSettingsStates object - * @return HashMap representation of LocationSettingsStates object - */ - static Map fromLocationSettingsStatesToMap(final LocationSettingsStates states) { - if (states == null) { - return Collections.emptyMap(); - } - - final Map map = new HashMap<>(); - - map.put("blePresent", states.isBlePresent()); - map.put("bleUsable", states.isBleUsable()); - map.put("gpsPresent", states.isGpsPresent()); - map.put("gpsUsable", states.isGpsUsable()); - map.put("locationPresent", states.isLocationPresent()); - map.put("locationUsable", states.isLocationUsable()); - map.put("networkLocationPresent", states.isNetworkLocationPresent()); - map.put("networkLocationUsable", states.isNetworkLocationUsable()); - - return map; - } - - /** - * Utility method - * @param result NavigationResult object - * @return HashMap representation of NavigationResult object - */ - static Map fromNavigationResultToMap(final NavigationResult result) { - if (result == null) { - return Collections.emptyMap(); - } - - final Map map = new HashMap<>(); - - map.put("state", result.getState()); - map.put("possibility", result.getPossibility()); - - return map; - } - - /** - * Utility method - * @param map HashMap representation of the LocationRequest object - * @return LocationRequest object - */ - static LocationRequest fromMapToLocationRequest(final Map map) { - final boolean isFastestIntervalExplicitlySet = ValueGetter.getBoolean("isFastestIntervalExplicitlySet", map); - - final LocationRequest result = LocationRequest.create(); - - if (isFastestIntervalExplicitlySet) { - result.setFastestInterval(ValueGetter.getLong("fastestInterval", map)); - } - - result.setPriority(ValueGetter.getInt("priority", map)); - result.setInterval(ValueGetter.getLong("interval", map)); - result.setExpirationTime(ValueGetter.getLong("expirationTime", map)); - result.setNumUpdates(ValueGetter.getInt("numUpdates", map)); - result.setSmallestDisplacement(ValueGetter.getFloat("smallestDisplacement", map)); - result.setMaxWaitTime(ValueGetter.getLong("maxWaitTime", map)); - result.setNeedAddress(ValueGetter.getBoolean("needAddress", map)); - result.setLanguage(ValueGetter.getString("language", map)); - result.setCountryCode(ValueGetter.getString("countryCode", map)); - - final Map extras = ObjectUtils.cast(map.get("extras"), Map.class); - - if (extras != null) { - final Set entries = extras.entrySet(); - for (final Object entry : entries) { - final Map.Entry mapEntry = ObjectUtils.cast(entry, Map.Entry.class); - final String key = ObjectUtils.cast(mapEntry.getKey(), String.class); - final String value = ObjectUtils.cast(mapEntry.getValue(), String.class); - result.putExtras(key, value); - } - } - - return result; - } - - /** - * Utility method - * @param map HashMap representation of the NavigationRequest object - * @return NavigationRequest object - */ - static NavigationRequest fromMapToNavigationRequest(final Map map) { - final int type = ValueGetter.getInt("type", map); - final Map extras = ObjectUtils.cast(map.get("extras"), Map.class); - - final NavigationRequest request = new NavigationRequest(type); - request.setExtras(extras); - - return request; - } - - /** - * Utility method - * @param map HashMap representation of the Location object - * @return Location object - */ - static Location fromMapToLocation(final Map map) { - final String provider = ValueGetter.getString("provider", map); - final Location location = new Location(provider); - - location.setLatitude(ValueGetter.getDouble("latitude", map)); - location.setLongitude(ValueGetter.getDouble("longitude", map)); - location.setAltitude(ValueGetter.getDouble("altitude", map)); - location.setSpeed(ValueGetter.getFloat("speed", map)); - location.setBearing(ValueGetter.getFloat("bearing", map)); - location.setAccuracy(ValueGetter.getFloat("horizontalAccuracyMeters", map)); - location.setTime(ValueGetter.getLong("time", map)); - location.setElapsedRealtimeNanos(ValueGetter.getLong("elapsedRealtimeNanos", map)); - - if (VERSION.SDK_INT >= VERSION_CODES.O) { - location.setVerticalAccuracyMeters(ValueGetter.getFloat("verticalAccuracyMeters", map)); - location.setSpeedAccuracyMetersPerSecond(ValueGetter.getFloat("speedAccuracyMetersPerSecond", map)); - location.setBearingAccuracyDegrees(ValueGetter.getFloat("bearingAccuracyDegrees", map)); - } - - return location; - } - - /** - * Utility method - * @param map HashMap representation of the LocationSettingsRequest object - * @return LocationSettingsRequest object - */ - static LocationSettingsRequest fromMapToLocationSettingsRequest(final Map map) { - final LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder(); - final List requests = ObjectUtils.cast(map.get("requests"), List.class); - - if (requests != null) { - for (final Object request : requests) { - final Map requestMap = ObjectUtils.cast(request, Map.class); - builder.addLocationRequest(fromMapToLocationRequest(requestMap)); - } - } - - builder.setAlwaysShow(ValueGetter.getBoolean("alwaysShow", map)); - builder.setNeedBle(ValueGetter.getBoolean("needBle", map)); - - return builder.build(); - } -} diff --git a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/utils/ObjectUtils.java b/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/utils/ObjectUtils.java deleted file mode 100644 index 395d14a8..00000000 --- a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/utils/ObjectUtils.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -package com.huawei.hms.flutter.location.utils; - -public interface ObjectUtils { - /** - * Utility method that castes given object to given class type - * @param source Source object to be casted - * @param clazz Class that object will be casted to its type - * @param Source object's type - * @param Destination type - * @return Object that casted to D type - */ - static D cast(final S source, final Class clazz) { - return clazz.cast(source); - } -} diff --git a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/utils/ValueGetter.java b/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/utils/ValueGetter.java deleted file mode 100644 index f5d2ba38..00000000 --- a/hms-plugins/flutter-hms-location/android/src/main/java/com/huawei/hms/flutter/location/utils/ValueGetter.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -package com.huawei.hms.flutter.location.utils; - -import java.util.Map; -import java.util.Objects; - -public interface ValueGetter { - /** - * Utility method - * @param key Lookup key for the map - * @param map Map that contains argument keys and values - * @return The "int" value for the corresponding key. - */ - static int getInt(final String key, final Map map) { - final Object value = Objects.requireNonNull(map.get(key)); - if (value instanceof Number) { - return ((Number) value).intValue(); - } else { - throw new IllegalArgumentException(); - } - } - - /** - * Utility method - * @param key Lookup key for the map - * @param map Map that contains argument keys and values - * @return The "long" value for the corresponding key. - */ - static long getLong(final String key, final Map map) { - final Object value = Objects.requireNonNull(map.get(key)); - if (value instanceof Number) { - return ((Number) value).longValue(); - } else { - throw new IllegalArgumentException(); - } - } - - /** - * Utility method - * @param key Lookup key for the map - * @param map Map that contains argument keys and values - * @return The "float" value for the corresponding key. - */ - static float getFloat(final String key, final Map map) { - final Object value = Objects.requireNonNull(map.get(key)); - if (value instanceof Number) { - return ((Number) value).floatValue(); - } else { - throw new IllegalArgumentException(); - } - } - - /** - * Utility method - * @param key Lookup key for the map - * @param map Map that contains argument keys and values - * @return The "double" value for the corresponding key. - */ - static double getDouble(final String key, final Map map) { - final Object value = Objects.requireNonNull(map.get(key)); - if (value instanceof Number) { - return ((Number) value).doubleValue(); - } else { - throw new IllegalArgumentException(); - } - } - - /** - * Utility method - * @param key Lookup key for the map - * @param map Map that contains argument keys and values - * @return The "boolean" value for the corresponding key. - */ - static boolean getBoolean(final String key, final Map map) { - final Object value = Objects.requireNonNull(map.get(key)); - if (value instanceof Boolean) { - return (boolean) value; - } else { - throw new IllegalArgumentException(); - } - } - - /** - * Utility method - * @param key Lookup key for the map - * @param map Map that contains argument keys and values - * @return The "String" value for the corresponding key. - */ - static String getString(final String key, final Map map) { - final Object value = Objects.requireNonNull(map.get(key)); - if (value instanceof String) { - return (String) value; - } else { - throw new IllegalArgumentException(); - } - } -} diff --git a/hms-plugins/flutter-hms-location/ios/Assets/.gitkeep b/hms-plugins/flutter-hms-location/ios/Assets/.gitkeep deleted file mode 100644 index e69de29b..00000000 diff --git a/hms-plugins/flutter-hms-location/ios/Classes/LocationPlugin.h b/hms-plugins/flutter-hms-location/ios/Classes/LocationPlugin.h deleted file mode 100644 index 0676dadb..00000000 --- a/hms-plugins/flutter-hms-location/ios/Classes/LocationPlugin.h +++ /dev/null @@ -1,4 +0,0 @@ -#import - -@interface LocationPlugin : NSObject -@end diff --git a/hms-plugins/flutter-hms-location/ios/Classes/LocationPlugin.m b/hms-plugins/flutter-hms-location/ios/Classes/LocationPlugin.m deleted file mode 100644 index e71b90d2..00000000 --- a/hms-plugins/flutter-hms-location/ios/Classes/LocationPlugin.m +++ /dev/null @@ -1,20 +0,0 @@ -#import "LocationPlugin.h" - -@implementation LocationPlugin -+ (void)registerWithRegistrar:(NSObject*)registrar { - FlutterMethodChannel* channel = [FlutterMethodChannel - methodChannelWithName:@"location" - binaryMessenger:[registrar messenger]]; - LocationPlugin* instance = [[LocationPlugin alloc] init]; - [registrar addMethodCallDelegate:instance channel:channel]; -} - -- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result { - if ([@"getPlatformVersion" isEqualToString:call.method]) { - result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]); - } else { - result(FlutterMethodNotImplemented); - } -} - -@end diff --git a/hms-plugins/flutter-hms-location/ios/Flutter/Generated.xcconfig b/hms-plugins/flutter-hms-location/ios/Flutter/Generated.xcconfig deleted file mode 100644 index 4527e66e..00000000 --- a/hms-plugins/flutter-hms-location/ios/Flutter/Generated.xcconfig +++ /dev/null @@ -1,14 +0,0 @@ -// This is a generated file; do not edit or check into version control. -FLUTTER_ROOT=C:\Program Files\flutter -FLUTTER_APPLICATION_PATH=C:\Projects\DQ\hms-plugins\flutter-hms-location -FLUTTER_TARGET=lib\main.dart -FLUTTER_BUILD_DIR=build -SYMROOT=${SOURCE_ROOT}/../build\ios -OTHER_LDFLAGS=$(inherited) -framework Flutter -FLUTTER_FRAMEWORK_DIR=C:\Program Files\flutter\bin\cache\artifacts\engine\ios -FLUTTER_BUILD_NAME=5.0.0 -FLUTTER_BUILD_NUMBER=301 -DART_OBFUSCATION=false -TRACK_WIDGET_CREATION=false -TREE_SHAKE_ICONS=false -PACKAGE_CONFIG=.packages diff --git a/hms-plugins/flutter-hms-location/ios/Flutter/flutter_export_environment.sh b/hms-plugins/flutter-hms-location/ios/Flutter/flutter_export_environment.sh deleted file mode 100644 index 87c35592..00000000 --- a/hms-plugins/flutter-hms-location/ios/Flutter/flutter_export_environment.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -# This is a generated file; do not edit or check into version control. -export "FLUTTER_ROOT=C:\Program Files\flutter" -export "FLUTTER_APPLICATION_PATH=C:\Projects\DQ\hms-plugins\flutter-hms-location" -export "FLUTTER_TARGET=lib\main.dart" -export "FLUTTER_BUILD_DIR=build" -export "SYMROOT=${SOURCE_ROOT}/../build\ios" -export "OTHER_LDFLAGS=$(inherited) -framework Flutter" -export "FLUTTER_FRAMEWORK_DIR=C:\Program Files\flutter\bin\cache\artifacts\engine\ios" -export "FLUTTER_BUILD_NAME=5.0.0" -export "FLUTTER_BUILD_NUMBER=301" -export "DART_OBFUSCATION=false" -export "TRACK_WIDGET_CREATION=false" -export "TREE_SHAKE_ICONS=false" -export "PACKAGE_CONFIG=.packages" diff --git a/hms-plugins/flutter-hms-location/ios/Runner/GeneratedPluginRegistrant.h b/hms-plugins/flutter-hms-location/ios/Runner/GeneratedPluginRegistrant.h deleted file mode 100644 index ed9a5c61..00000000 --- a/hms-plugins/flutter-hms-location/ios/Runner/GeneratedPluginRegistrant.h +++ /dev/null @@ -1,17 +0,0 @@ -// -// Generated file. Do not edit. -// - -#ifndef GeneratedPluginRegistrant_h -#define GeneratedPluginRegistrant_h - -#import - -NS_ASSUME_NONNULL_BEGIN - -@interface GeneratedPluginRegistrant : NSObject -+ (void)registerWithRegistry:(NSObject*)registry; -@end - -NS_ASSUME_NONNULL_END -#endif /* GeneratedPluginRegistrant_h */ diff --git a/hms-plugins/flutter-hms-location/ios/Runner/GeneratedPluginRegistrant.m b/hms-plugins/flutter-hms-location/ios/Runner/GeneratedPluginRegistrant.m deleted file mode 100644 index 60dfa42b..00000000 --- a/hms-plugins/flutter-hms-location/ios/Runner/GeneratedPluginRegistrant.m +++ /dev/null @@ -1,12 +0,0 @@ -// -// Generated file. Do not edit. -// - -#import "GeneratedPluginRegistrant.h" - -@implementation GeneratedPluginRegistrant - -+ (void)registerWithRegistry:(NSObject*)registry { -} - -@end diff --git a/hms-plugins/flutter-hms-location/ios/huawei_location.podspec b/hms-plugins/flutter-hms-location/ios/huawei_location.podspec deleted file mode 100644 index cd8d7142..00000000 --- a/hms-plugins/flutter-hms-location/ios/huawei_location.podspec +++ /dev/null @@ -1,23 +0,0 @@ -# -# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html. -# Run `pod lib lint location.podspec' to validate before publishing. -# -Pod::Spec.new do |s| - s.name = 'huawei_location' - s.version = '5.0.0+301' - s.summary = 'HUAWEI Flutter Location Kit plugin.' - s.description = <<-DESC - HUAWEI Flutter Location Kit plugin combines the GPS, Wi-Fi and base station locations to help you quickly obtain precise user locations & build up global positioning capabilities. - DESC - s.homepage = 'https://www.huawei.com' - s.license = { :type => 'Apache 2.0', :file => '../LICENSE' } - s.author = { 'Huawei Technologies' => 'huaweideveloper1@gmail.com' } - s.source = { :git => 'https://github.com/HMS-Core/hms-flutter-plugin/tree/master/flutter-hms-location' } - s.source_files = 'Classes/**/*' - s.public_header_files = 'Classes/**/*.h' - s.dependency 'Flutter' - s.platform = :ios, '8.0' - - # Flutter.framework does not contain a i386 slice. Only x86_64 simulators are supported. - s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'VALID_ARCHS[sdk=iphonesimulator*]' => 'x86_64' } -end diff --git a/hms-plugins/flutter-hms-location/lib/activity/activity_conversion_data.dart b/hms-plugins/flutter-hms-location/lib/activity/activity_conversion_data.dart deleted file mode 100644 index 8b5c6444..00000000 --- a/hms-plugins/flutter-hms-location/lib/activity/activity_conversion_data.dart +++ /dev/null @@ -1,76 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -import 'dart:convert'; -import 'dart:ui'; - -class ActivityConversionData { - int activityType; - int conversionType; - int elapsedTimeFromReboot; - - ActivityConversionData({ - this.activityType, - this.conversionType, - this.elapsedTimeFromReboot, - }); - - Map toMap() { - return { - 'activityType': activityType, - 'conversionType': conversionType, - 'elapsedTimeFromReboot': elapsedTimeFromReboot, - }; - } - - factory ActivityConversionData.fromMap(Map map) { - if (map == null) return null; - - return ActivityConversionData( - activityType: map['activityType'], - conversionType: map['conversionType'], - elapsedTimeFromReboot: map['elapsedTimeFromReboot'], - ); - } - - String toJson() => json.encode(toMap()); - - factory ActivityConversionData.fromJson(String source) => - ActivityConversionData.fromMap(json.decode(source)); - - @override - String toString() => - 'ActivityConversionData(activityType: $activityType, conversionType: $conversionType, elapsedTimeFromReboot: $elapsedTimeFromReboot)'; - - @override - bool operator ==(Object o) { - if (identical(this, o)) return true; - - return o is ActivityConversionData && - o.activityType == activityType && - o.conversionType == conversionType && - o.elapsedTimeFromReboot == elapsedTimeFromReboot; - } - - @override - int get hashCode { - return hashList([ - activityType, - conversionType, - elapsedTimeFromReboot, - ]); - } -} diff --git a/hms-plugins/flutter-hms-location/lib/activity/activity_conversion_info.dart b/hms-plugins/flutter-hms-location/lib/activity/activity_conversion_info.dart deleted file mode 100644 index 8eae9a55..00000000 --- a/hms-plugins/flutter-hms-location/lib/activity/activity_conversion_info.dart +++ /dev/null @@ -1,73 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -import 'dart:convert'; -import 'dart:ui'; - -class ActivityConversionInfo { - static const int ENTER_ACTIVITY_CONVERSION = 0; - static const int EXIT_ACTIVITY_CONVERSION = 1; - - int activityType; - int conversionType; - - ActivityConversionInfo({ - this.activityType, - this.conversionType, - }); - - Map toMap() { - return { - 'activityType': activityType, - 'conversionType': conversionType, - }; - } - - factory ActivityConversionInfo.fromMap(Map map) { - if (map == null) return null; - - return ActivityConversionInfo( - activityType: map['activityType'], - conversionType: map['conversionType'], - ); - } - - String toJson() => json.encode(toMap()); - - factory ActivityConversionInfo.fromJson(String source) => - ActivityConversionInfo.fromMap(json.decode(source)); - - @override - String toString() => - 'ActivityConversionInfo(activityType: $activityType, conversionType: $conversionType)'; - - @override - bool operator ==(Object o) { - if (identical(this, o)) return true; - - return o is ActivityConversionInfo && - o.activityType == activityType && - o.conversionType == conversionType; - } - - @override - int get hashCode { - return hashList([ - activityType, - conversionType, - ]); - } -} diff --git a/hms-plugins/flutter-hms-location/lib/activity/activity_conversion_response.dart b/hms-plugins/flutter-hms-location/lib/activity/activity_conversion_response.dart deleted file mode 100644 index 28c44158..00000000 --- a/hms-plugins/flutter-hms-location/lib/activity/activity_conversion_response.dart +++ /dev/null @@ -1,71 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -import 'dart:convert'; -import 'dart:ui'; - -import 'package:flutter/foundation.dart'; - -import 'activity_conversion_data.dart'; - -class ActivityConversionResponse { - List activityConversionDatas; - - ActivityConversionResponse({ - this.activityConversionDatas, - }); - - Map toMap() { - return { - 'activityConversionDatas': - activityConversionDatas?.map((x) => x?.toMap())?.toList(), - }; - } - - factory ActivityConversionResponse.fromMap(Map map) { - if (map == null) return null; - - return ActivityConversionResponse( - activityConversionDatas: List.from( - map['activityConversionDatas'] - ?.map((x) => ActivityConversionData.fromMap(x))), - ); - } - - String toJson() => json.encode(toMap()); - - factory ActivityConversionResponse.fromJson(String source) => - ActivityConversionResponse.fromMap(json.decode(source)); - - @override - String toString() => - 'ActivityConversionResponse(activityConversionDatas: $activityConversionDatas)'; - - @override - bool operator ==(Object o) { - if (identical(this, o)) return true; - - return o is ActivityConversionResponse && - listEquals(o.activityConversionDatas, activityConversionDatas); - } - - @override - int get hashCode { - return hashList([ - activityConversionDatas, - ]); - } -} diff --git a/hms-plugins/flutter-hms-location/lib/activity/activity_identification_data.dart b/hms-plugins/flutter-hms-location/lib/activity/activity_identification_data.dart deleted file mode 100644 index ed171175..00000000 --- a/hms-plugins/flutter-hms-location/lib/activity/activity_identification_data.dart +++ /dev/null @@ -1,94 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -import 'dart:convert'; -import 'dart:ui'; - -class ActivityIdentificationData { - static const int VEHICLE = 100; - static const int BIKE = 101; - static const int FOOT = 102; - static const int STILL = 103; - static const int OTHERS = 104; - static const int TILTING = 105; - static const int WALKING = 107; - static const int RUNNING = 108; - - static const List _validTypes = [ - VEHICLE, - BIKE, - FOOT, - STILL, - OTHERS, - TILTING, - WALKING, - RUNNING - ]; - - int identificationActivity; - int possibility; - - ActivityIdentificationData({ - this.identificationActivity, - this.possibility, - }); - - static bool isValidType(int type) { - return _validTypes.contains(type) ? true : false; - } - - Map toMap() { - return { - 'identificationActivity': identificationActivity, - 'possibility': possibility, - }; - } - - factory ActivityIdentificationData.fromMap(Map map) { - if (map == null) return null; - - return ActivityIdentificationData( - identificationActivity: map['identificationActivity'], - possibility: map['possibility'], - ); - } - - String toJson() => json.encode(toMap()); - - factory ActivityIdentificationData.fromJson(String source) => - ActivityIdentificationData.fromMap(json.decode(source)); - - @override - String toString() => - 'ActivityIdentificationData(identificationActivity: $identificationActivity, possibility: $possibility)'; - - @override - bool operator ==(Object o) { - if (identical(this, o)) return true; - - return o is ActivityIdentificationData && - o.identificationActivity == identificationActivity && - o.possibility == possibility; - } - - @override - int get hashCode { - return hashList([ - identificationActivity, - possibility, - ]); - } -} diff --git a/hms-plugins/flutter-hms-location/lib/activity/activity_identification_response.dart b/hms-plugins/flutter-hms-location/lib/activity/activity_identification_response.dart deleted file mode 100644 index c059ca50..00000000 --- a/hms-plugins/flutter-hms-location/lib/activity/activity_identification_response.dart +++ /dev/null @@ -1,106 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -import 'dart:convert'; -import 'dart:ui'; - -import 'package:flutter/foundation.dart'; - -import 'activity_identification_data.dart'; - -class ActivityIdentificationResponse { - int time; - int elapsedTimeFromReboot; - List activityIdentificationDatas; - - ActivityIdentificationResponse({ - this.activityIdentificationDatas, - this.time, - this.elapsedTimeFromReboot, - }); - - ActivityIdentificationData get mostActivityIdentification { - return activityIdentificationDatas != null && - activityIdentificationDatas.length > 0 - ? activityIdentificationDatas[0] - : null; - } - - int getActivityPossibility(int activityType) { - if (activityIdentificationDatas != null && - activityIdentificationDatas.length > 0) { - Iterator iterator = activityIdentificationDatas.iterator; - - while (iterator.moveNext()) { - ActivityIdentificationData currentData = iterator.current; - if (currentData.identificationActivity == activityType) { - return currentData.possibility; - } - } - } - - return 0; - } - - Map toMap() { - return { - 'time': time, - 'elapsedTimeFromReboot': elapsedTimeFromReboot, - 'activityIdentificationDatas': - activityIdentificationDatas?.map((x) => x?.toMap())?.toList(), - }; - } - - factory ActivityIdentificationResponse.fromMap(Map map) { - if (map == null) return null; - - return ActivityIdentificationResponse( - time: map['time'], - elapsedTimeFromReboot: map['elapsedTimeFromReboot'], - activityIdentificationDatas: List.from( - map['activityIdentificationDatas'] - ?.map((x) => ActivityIdentificationData.fromMap(x))), - ); - } - - String toJson() => json.encode(toMap()); - - factory ActivityIdentificationResponse.fromJson(String source) => - ActivityIdentificationResponse.fromMap(json.decode(source)); - - @override - String toString() => - 'ActivityIdentificationResponse(time: $time, elapsedTimeFromReboot: $elapsedTimeFromReboot, activityIdentificationDatas: $activityIdentificationDatas)'; - - @override - bool operator ==(Object o) { - if (identical(this, o)) return true; - - return o is ActivityIdentificationResponse && - o.time == time && - o.elapsedTimeFromReboot == elapsedTimeFromReboot && - listEquals(o.activityIdentificationDatas, activityIdentificationDatas); - } - - @override - int get hashCode { - return hashList([ - time, - elapsedTimeFromReboot, - activityIdentificationDatas, - ]); - } -} diff --git a/hms-plugins/flutter-hms-location/lib/activity/activity_identification_service.dart b/hms-plugins/flutter-hms-location/lib/activity/activity_identification_service.dart deleted file mode 100644 index c8598871..00000000 --- a/hms-plugins/flutter-hms-location/lib/activity/activity_identification_service.dart +++ /dev/null @@ -1,98 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -import 'package:flutter/services.dart'; - -import 'activity_conversion_info.dart'; -import 'activity_conversion_response.dart'; -import 'activity_identification_response.dart'; - -class ActivityIdentificationService { - static ActivityIdentificationService _instance; - - final MethodChannel _methodChannel; - final EventChannel _activityIdentificationEventChannel; - final EventChannel _activityConversionEventChannel; - - Stream _onActivityIdentification; - Stream _onActivityConversion; - - ActivityIdentificationService._create( - this._methodChannel, - this._activityIdentificationEventChannel, - this._activityConversionEventChannel, - ); - - factory ActivityIdentificationService() { - if (_instance == null) { - final MethodChannel methodChannel = const MethodChannel( - 'com.huawei.flutter.location/activityidentification_methodchannel'); - - final EventChannel activityIdentificationEventChannel = const EventChannel( - 'com.huawei.flutter.location/activityidentification_eventchannel'); - - final EventChannel activityConversionEventChannel = const EventChannel( - 'com.huawei.flutter.location/activityconversion_eventchannel'); - - _instance = ActivityIdentificationService._create( - methodChannel, - activityIdentificationEventChannel, - activityConversionEventChannel, - ); - } - return _instance; - } - - Future createActivityIdentificationUpdates( - int detectionIntervalMillis) async { - return _methodChannel.invokeMethod( - 'createActivityIdentificationUpdates', detectionIntervalMillis); - } - - Future createActivityConversionUpdates( - List activityConversions) async { - return _methodChannel.invokeMethod('createActivityConversionUpdates', - activityConversions?.map((x) => x?.toMap())?.toList()); - } - - Future deleteActivityIdentificationUpdates(int requestCode) async { - return _methodChannel.invokeMethod( - 'deleteActivityIdentificationUpdates', requestCode); - } - - Future deleteActivityConversionUpdates(int requestCode) async { - return _methodChannel.invokeMethod( - 'deleteActivityConversionUpdates', requestCode); - } - - Stream get onActivityIdentification { - if (_onActivityIdentification == null) { - _onActivityIdentification = _activityIdentificationEventChannel - .receiveBroadcastStream() - .map((event) => ActivityIdentificationResponse.fromMap(event)); - } - return _onActivityIdentification; - } - - Stream get onActivityConversion { - if (_onActivityConversion == null) { - _onActivityConversion = _activityConversionEventChannel - .receiveBroadcastStream() - .map((event) => ActivityConversionResponse.fromMap(event)); - } - return _onActivityConversion; - } -} diff --git a/hms-plugins/flutter-hms-location/lib/geofence/geofence.dart b/hms-plugins/flutter-hms-location/lib/geofence/geofence.dart deleted file mode 100644 index fc93cb7b..00000000 --- a/hms-plugins/flutter-hms-location/lib/geofence/geofence.dart +++ /dev/null @@ -1,113 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -import 'dart:convert'; -import 'dart:core'; -import 'dart:ui'; - -class Geofence { - static const int ENTER_GEOFENCE_CONVERSION = 1; - static const int EXIT_GEOFENCE_CONVERSION = 2; - static const int DWELL_GEOFENCE_CONVERSION = 4; - static const int GEOFENCE_NEVER_EXPIRE = -1; - - String uniqueId; - int conversions; - int validDuration; - double latitude; - double longitude; - double radius; - int notificationInterval; - int dwellDelayTime; - - Geofence({ - this.uniqueId, - this.conversions, - this.validDuration, - this.latitude, - this.longitude, - this.radius, - this.notificationInterval = 0, - this.dwellDelayTime = 0, - }); - - Map toMap() { - return { - 'uniqueId': uniqueId, - 'conversions': conversions, - 'validDuration': validDuration, - 'latitude': latitude, - 'longitude': longitude, - 'radius': radius, - 'notificationInterval': notificationInterval, - 'dwellDelayTime': dwellDelayTime, - }; - } - - factory Geofence.fromMap(Map map) { - if (map == null) return null; - - return Geofence( - uniqueId: map['uniqueId'], - conversions: map['conversions'], - validDuration: map['validDuration'], - latitude: map['latitude'], - longitude: map['longitude'], - radius: map['radius'], - notificationInterval: map['notificationInterval'], - dwellDelayTime: map['dwellDelayTime'], - ); - } - - String toJson() => json.encode(toMap()); - - factory Geofence.fromJson(String source) => - Geofence.fromMap(json.decode(source)); - - @override - String toString() { - return 'Geofence(uniqueId: $uniqueId, conversions: $conversions, validDuration: $validDuration, latitude: $latitude, longitude: $longitude, radius: $radius, notificationInterval: $notificationInterval, dwellDelayTime: $dwellDelayTime)'; - } - - @override - bool operator ==(Object o) { - if (identical(this, o)) return true; - - return o is Geofence && - o.uniqueId == uniqueId && - o.conversions == conversions && - o.validDuration == validDuration && - o.latitude == latitude && - o.longitude == longitude && - o.radius == radius && - o.notificationInterval == notificationInterval && - o.dwellDelayTime == dwellDelayTime; - } - - @override - int get hashCode { - return hashList([ - uniqueId, - conversions, - validDuration, - latitude, - longitude, - radius, - notificationInterval, - dwellDelayTime, - ]); - } -} diff --git a/hms-plugins/flutter-hms-location/lib/geofence/geofence_data.dart b/hms-plugins/flutter-hms-location/lib/geofence/geofence_data.dart deleted file mode 100644 index c2aca69e..00000000 --- a/hms-plugins/flutter-hms-location/lib/geofence/geofence_data.dart +++ /dev/null @@ -1,88 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -import 'dart:convert'; -import 'dart:ui'; - -import 'package:flutter/foundation.dart'; - -import '../location/location.dart'; - -class GeofenceData { - int errorCode; - int conversion; - List convertingGeofenceIdList; - Location convertingLocation; - - GeofenceData({ - this.errorCode, - this.conversion, - this.convertingGeofenceIdList, - this.convertingLocation, - }); - - Map toMap() { - return { - 'errorCode': errorCode, - 'conversion': conversion, - 'convertingGeofenceIdList': convertingGeofenceIdList, - 'convertingLocation': convertingLocation?.toMap(), - }; - } - - factory GeofenceData.fromMap(Map map) { - if (map == null) return null; - - return GeofenceData( - errorCode: map['errorCode'], - conversion: map['conversion'], - convertingGeofenceIdList: - List.from(map['convertingGeofenceIdList']), - convertingLocation: Location.fromMap(map['convertingLocation']), - ); - } - - String toJson() => json.encode(toMap()); - - factory GeofenceData.fromJson(String source) => - GeofenceData.fromMap(json.decode(source)); - - @override - String toString() { - return 'GeofenceData(errorCode: $errorCode, conversion: $conversion, convertingGeofenceIdList: $convertingGeofenceIdList, convertingLocation: $convertingLocation)'; - } - - @override - bool operator ==(Object o) { - if (identical(this, o)) return true; - - return o is GeofenceData && - o.errorCode == errorCode && - o.conversion == conversion && - listEquals(o.convertingGeofenceIdList, convertingGeofenceIdList) && - o.convertingLocation == convertingLocation; - } - - @override - int get hashCode { - return hashList([ - errorCode, - conversion, - convertingGeofenceIdList, - convertingLocation, - ]); - } -} diff --git a/hms-plugins/flutter-hms-location/lib/geofence/geofence_request.dart b/hms-plugins/flutter-hms-location/lib/geofence/geofence_request.dart deleted file mode 100644 index bbefb528..00000000 --- a/hms-plugins/flutter-hms-location/lib/geofence/geofence_request.dart +++ /dev/null @@ -1,91 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -import 'dart:convert'; -import 'dart:ui'; - -import 'package:flutter/foundation.dart'; - -import 'geofence.dart'; - -class GeofenceRequest { - static const int ENTER_INIT_CONVERSION = 1; - static const int EXIT_INIT_CONVERSION = 2; - static const int DWELL_INIT_CONVERSION = 4; - static const int COORDINATE_TYPE_WGS_84 = 1; - static const int COORDINATE_TYPE_GCJ_02 = 0; - - List geofenceList; - int initConversions; - int coordinateType; - - GeofenceRequest({ - this.geofenceList, - this.initConversions = ENTER_INIT_CONVERSION | DWELL_INIT_CONVERSION, - this.coordinateType = COORDINATE_TYPE_WGS_84, - }) { - if (this.geofenceList == null) { - this.geofenceList = []; - } - } - - Map toMap() { - return { - 'geofenceList': geofenceList?.map((x) => x?.toMap())?.toList(), - 'initConversions': initConversions, - 'coordinateType': coordinateType, - }; - } - - factory GeofenceRequest.fromMap(Map map) { - if (map == null) return null; - - return GeofenceRequest( - geofenceList: List.from( - map['geofenceList']?.map((x) => Geofence.fromMap(x))), - initConversions: map['initConversions'], - coordinateType: map['coordinateType'], - ); - } - - String toJson() => json.encode(toMap()); - - factory GeofenceRequest.fromJson(String source) => - GeofenceRequest.fromMap(json.decode(source)); - - @override - String toString() => - 'GeofenceRequest(geofenceList: $geofenceList, initConversions: $initConversions, coordinateType: $coordinateType)'; - - @override - bool operator ==(Object o) { - if (identical(this, o)) return true; - - return o is GeofenceRequest && - listEquals(o.geofenceList, geofenceList) && - o.initConversions == initConversions && - o.coordinateType == coordinateType; - } - - @override - int get hashCode { - return hashList([ - geofenceList, - initConversions, - coordinateType, - ]); - } -} diff --git a/hms-plugins/flutter-hms-location/lib/geofence/geofence_service.dart b/hms-plugins/flutter-hms-location/lib/geofence/geofence_service.dart deleted file mode 100644 index 87e9d0a8..00000000 --- a/hms-plugins/flutter-hms-location/lib/geofence/geofence_service.dart +++ /dev/null @@ -1,72 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -import 'package:flutter/services.dart'; - -import 'geofence_data.dart' show GeofenceData; -import 'geofence_request.dart' show GeofenceRequest; - -class GeofenceService { - static GeofenceService _instance; - - final MethodChannel _methodChannel; - final EventChannel _eventChannel; - - Stream _onGeofenceData; - - GeofenceService._create( - this._methodChannel, - this._eventChannel, - ); - - factory GeofenceService() { - if (_instance == null) { - final MethodChannel methodChannel = const MethodChannel( - 'com.huawei.flutter.location/geofence_methodchannel'); - final EventChannel eventChannel = const EventChannel( - 'com.huawei.flutter.location/geofence_eventchannel'); - - _instance = GeofenceService._create( - methodChannel, - eventChannel, - ); - } - return _instance; - } - - Future createGeofenceList(GeofenceRequest geofenceRequest) async { - return _methodChannel.invokeMethod( - 'createGeofenceList', geofenceRequest.toMap()); - } - - Future deleteGeofenceList(int requestCode) async { - return _methodChannel.invokeMethod('deleteGeofenceList', requestCode); - } - - Future deleteGeofenceListWithIds(List geofenceIds) async { - return _methodChannel.invokeMethod( - 'deleteGeofenceListWithIds', geofenceIds); - } - - Stream get onGeofenceData { - if (_onGeofenceData == null) { - _onGeofenceData = _eventChannel - .receiveBroadcastStream() - .map((event) => GeofenceData.fromMap(event)); - } - return _onGeofenceData; - } -} diff --git a/hms-plugins/flutter-hms-location/lib/location/fused_location_provider_client.dart b/hms-plugins/flutter-hms-location/lib/location/fused_location_provider_client.dart deleted file mode 100644 index b67c49af..00000000 --- a/hms-plugins/flutter-hms-location/lib/location/fused_location_provider_client.dart +++ /dev/null @@ -1,158 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -import 'package:flutter/services.dart'; - -import 'hwlocation.dart'; -import 'location.dart'; -import 'location_availability.dart'; -import 'location_callback.dart'; -import 'location_request.dart'; -import 'location_result.dart'; -import 'location_settings_request.dart'; -import 'location_settings_states.dart'; -import 'navigation_request.dart'; -import 'navigation_result.dart'; - -class FusedLocationProviderClient { - static FusedLocationProviderClient _instance; - - final MethodChannel _methodChannel; - final EventChannel _eventChannel; - final Map _callbacks; - - Stream _onLocationData; - - FusedLocationProviderClient._create( - this._methodChannel, - this._eventChannel, - this._callbacks, - ) { - _methodChannel.setMethodCallHandler(_methodCallHandler); - } - - factory FusedLocationProviderClient() { - if (_instance == null) { - _instance = FusedLocationProviderClient._create( - const MethodChannel( - 'com.huawei.flutter.location/fusedlocation_methodchannel'), - const EventChannel( - 'com.huawei.flutter.location/fusedlocation_eventchannel'), - {}, - ); - } - return _instance; - } - - Future _methodCallHandler(MethodCall methodCall) async { - switch (methodCall.method) { - case 'onLocationResult': - _callbacks[methodCall.arguments['callbackId']].onLocationResult( - LocationResult.fromMap(methodCall.arguments['locationResult'])); - break; - case 'onLocationAvailability': - _callbacks[methodCall.arguments['callbackId']].onLocationAvailability( - LocationAvailability.fromMap( - methodCall.arguments['locationAvailability'])); - break; - default: - break; - } - } - - Future checkLocationSettings( - LocationSettingsRequest locationSettingsRequest) async { - return LocationSettingsStates.fromMap( - await _methodChannel.invokeMapMethod( - 'checkLocationSettings', locationSettingsRequest.toMap())); - } - - Future getLastLocation() async { - return Location.fromMap(await _methodChannel - .invokeMapMethod('getLastLocation')); - } - - Future getLastLocationWithAddress( - LocationRequest locationRequest) async { - return HWLocation.fromMap( - await _methodChannel.invokeMapMethod( - 'getLastLocationWithAddress', locationRequest.toMap())); - } - - Future getLocationAvailability() async { - return LocationAvailability.fromMap(await _methodChannel - .invokeMapMethod('getLocationAvailability')); - } - - Future setMockMode(bool mockMode) async { - return _methodChannel.invokeMethod('setMockMode', mockMode); - } - - Future setMockLocation(Location location) async { - return _methodChannel.invokeMethod( - 'setMockLocation', location.toMap()); - } - - Future requestLocationUpdates(LocationRequest locationRequest) async { - return _methodChannel.invokeMethod( - 'requestLocationUpdates', locationRequest.toMap()); - } - - Future requestLocationUpdatesCb(LocationRequest locationRequest, - LocationCallback locationCallback) async { - int callbackId = await _methodChannel.invokeMethod( - 'requestLocationUpdatesCb', locationRequest.toMap()); - _callbacks.putIfAbsent(callbackId, () => locationCallback); - return callbackId; - } - - Future requestLocationUpdatesExCb(LocationRequest locationRequest, - LocationCallback locationCallback) async { - int callbackId = await _methodChannel.invokeMethod( - 'requestLocationUpdatesExCb', - (locationRequest..priority = LocationRequest.PRIORITY_HD_ACCURACY) - .toMap()); - _callbacks.putIfAbsent(callbackId, () => locationCallback); - return callbackId; - } - - Future removeLocationUpdates(int requestCode) async { - return _methodChannel.invokeMethod( - 'removeLocationUpdates', requestCode); - } - - Future removeLocationUpdatesCb(int callbackId) async { - await _methodChannel.invokeMethod( - 'removeLocationUpdatesCb', callbackId); - _callbacks.remove(callbackId); - } - - Future getNavigationContextState( - NavigationRequest navigationRequest) async { - return NavigationResult.fromMap( - await _methodChannel.invokeMapMethod( - 'getNavigationContextState', navigationRequest.toMap())); - } - - Stream get onLocationData { - if (_onLocationData == null) { - _onLocationData = _eventChannel - .receiveBroadcastStream() - .map((event) => Location.fromMap(event)); - } - return _onLocationData; - } -} diff --git a/hms-plugins/flutter-hms-location/lib/location/hwlocation.dart b/hms-plugins/flutter-hms-location/lib/location/hwlocation.dart deleted file mode 100644 index 97c92db5..00000000 --- a/hms-plugins/flutter-hms-location/lib/location/hwlocation.dart +++ /dev/null @@ -1,207 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -import 'dart:convert'; -import 'dart:ui'; - -import 'package:flutter/foundation.dart'; - -class HWLocation { - String provider; - double latitude; - double longitude; - double altitude; - double speed; - double bearing; - double horizontalAccuracyMeters; - double verticalAccuracyMeters; - double speedAccuracyMetersPerSecond; - double bearingAccuracyDegrees; - int time; - int elapsedRealtimeNanos; - String countryCode; - String countryName; - String state; - String city; - String county; - String street; - String featureName; - String postalCode; - String phone; - String url; - Map extraInfo; - - HWLocation({ - this.provider, - this.latitude, - this.longitude, - this.altitude, - this.speed, - this.bearing, - this.horizontalAccuracyMeters, - this.verticalAccuracyMeters, - this.speedAccuracyMetersPerSecond, - this.bearingAccuracyDegrees, - this.time, - this.elapsedRealtimeNanos, - this.countryCode, - this.countryName, - this.state, - this.city, - this.county, - this.street, - this.featureName, - this.postalCode, - this.phone, - this.url, - this.extraInfo, - }); - - Map toMap() { - return { - 'provider': provider, - 'latitude': latitude, - 'longitude': longitude, - 'altitude': altitude, - 'speed': speed, - 'bearing': bearing, - 'horizontalAccuracyMeters': horizontalAccuracyMeters, - 'verticalAccuracyMeters': verticalAccuracyMeters, - 'speedAccuracyMetersPerSecond': speedAccuracyMetersPerSecond, - 'bearingAccuracyDegrees': bearingAccuracyDegrees, - 'time': time, - 'elapsedRealtimeNanos': elapsedRealtimeNanos, - 'countryCode': countryCode, - 'countryName': countryName, - 'state': state, - 'city': city, - 'county': county, - 'street': street, - 'featureName': featureName, - 'postalCode': postalCode, - 'phone': phone, - 'url': url, - 'extraInfo': extraInfo, - }; - } - - factory HWLocation.fromMap(Map map) { - if (map == null) return null; - - return HWLocation( - provider: map["provider"] == null ? null : map["provider"], - latitude: map["latitude"] == null ? null : map["latitude"], - longitude: map["longitude"] == null ? null : map["longitude"], - altitude: map["altitude"] == null ? null : map["altitude"], - speed: map["speed"] == null ? null : map["speed"], - bearing: map["bearing"] == null ? null : map["bearing"], - horizontalAccuracyMeters: map["horizontalAccuracyMeters"], - verticalAccuracyMeters: map["verticalAccuracyMeters"] == null - ? null - : map["verticalAccuracyMeters"], - speedAccuracyMetersPerSecond: - map["speedAccuracyMetersPerSecond"] == null - ? null - : map["speedAccuracyMetersPerSecond"], - bearingAccuracyDegrees: map["bearingAccuracyDegrees"] == null - ? null - : map["bearingAccuracyDegrees"], - time: map["time"] == null ? null : map["time"], - elapsedRealtimeNanos: map["elapsedRealtimeNanos"] == null - ? null - : map["elapsedRealtimeNanos"], - countryCode: map["countryCode"] == null ? null : map["countryCode"], - countryName: map["countryName"] == null ? null : map["countryName"], - state: map["state"] == null ? null : map["state"], - city: map["city"] == null ? null : map["city"], - county: map["county"] == null ? null : map["county"], - street: map["street"] == null ? null : map["street"], - featureName: map["featureName"] == null ? null : map["featureName"], - postalCode: map["postalCode"] == null ? null : map["postalCode"], - phone: map["phone"] == null ? null : map["phone"], - url: map["url"] == null ? null : map["url"], - extraInfo: - map["extraInfo"] == null ? null : Map.from(map["extraInfo"])); - } - - String toJson() => json.encode(toMap()); - - factory HWLocation.fromJson(String source) => - HWLocation.fromMap(json.decode(source)); - - @override - String toString() { - return 'HWLocation(provider: $provider, latitude: $latitude, longitude: $longitude, altitude: $altitude, speed: $speed, bearing: $bearing, horizontalAccuracyMeters: $horizontalAccuracyMeters, verticalAccuracyMeters: $verticalAccuracyMeters, speedAccuracyMetersPerSecond: $speedAccuracyMetersPerSecond, bearingAccuracyDegrees: $bearingAccuracyDegrees, time: $time, elapsedRealtimeNanos: $elapsedRealtimeNanos, countryCode: $countryCode, countryName: $countryName, state: $state, city: $city, county: $county, street: $street, featureName: $featureName, postalCode: $postalCode, phone: $phone, url: $url, extraInfo: $extraInfo)'; - } - - @override - bool operator ==(Object o) { - if (identical(this, o)) return true; - return o is HWLocation && - o.provider == provider && - o.latitude == latitude && - o.longitude == longitude && - o.altitude == altitude && - o.speed == speed && - o.bearing == bearing && - o.horizontalAccuracyMeters == horizontalAccuracyMeters && - o.verticalAccuracyMeters == verticalAccuracyMeters && - o.speedAccuracyMetersPerSecond == speedAccuracyMetersPerSecond && - o.bearingAccuracyDegrees == bearingAccuracyDegrees && - o.time == time && - o.elapsedRealtimeNanos == elapsedRealtimeNanos && - o.countryCode == countryCode && - o.countryName == countryName && - o.state == state && - o.city == city && - o.county == county && - o.street == street && - o.featureName == featureName && - o.postalCode == postalCode && - o.phone == phone && - o.url == url && - mapEquals(o.extraInfo, extraInfo); - } - - @override - int get hashCode { - return hashList([ - provider, - latitude, - longitude, - altitude, - speed, - bearing, - horizontalAccuracyMeters, - verticalAccuracyMeters, - speedAccuracyMetersPerSecond, - bearingAccuracyDegrees, - time, - elapsedRealtimeNanos, - countryCode, - countryName, - state, - city, - county, - street, - featureName, - postalCode, - phone, - url, - extraInfo, - ]); - } -} diff --git a/hms-plugins/flutter-hms-location/lib/location/location.dart b/hms-plugins/flutter-hms-location/lib/location/location.dart deleted file mode 100644 index 5fa17b6a..00000000 --- a/hms-plugins/flutter-hms-location/lib/location/location.dart +++ /dev/null @@ -1,141 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -import 'dart:convert'; -import 'dart:ui'; - -class Location { - String provider; - double latitude; - double longitude; - double altitude; - double speed; - double bearing; - double horizontalAccuracyMeters; - double verticalAccuracyMeters; - double speedAccuracyMetersPerSecond; - double bearingAccuracyDegrees; - int time; - int elapsedRealtimeNanos; - - Location({ - this.provider = 'HMS Mock Location', - this.latitude = 0.0, - this.longitude = 0.0, - this.altitude = 0.0, - this.speed = 0.0, - this.bearing = 0.0, - this.horizontalAccuracyMeters = 0.0, - this.verticalAccuracyMeters = 0.0, - this.speedAccuracyMetersPerSecond = 0.0, - this.bearingAccuracyDegrees = 0.0, - this.time = 0, - this.elapsedRealtimeNanos = 0, - }); - - Map toMap() { - return { - 'provider': provider, - 'latitude': latitude, - 'longitude': longitude, - 'altitude': altitude, - 'speed': speed, - 'bearing': bearing, - 'horizontalAccuracyMeters': horizontalAccuracyMeters, - 'verticalAccuracyMeters': verticalAccuracyMeters, - 'speedAccuracyMetersPerSecond': speedAccuracyMetersPerSecond, - 'bearingAccuracyDegrees': bearingAccuracyDegrees, - 'time': time, - 'elapsedRealtimeNanos': elapsedRealtimeNanos, - }; - } - - factory Location.fromMap(Map map) { - if (map == null) return null; - - return Location( - provider: map["provider"] == null ? null : map["provider"], - latitude: map["latitude"] == null ? null : map["latitude"], - longitude: map["longitude"] == null ? null : map["longitude"], - altitude: map["altitude"] == null ? null : map["altitude"], - speed: map["speed"] == null ? null : map["speed"], - bearing: map["bearing"] == null ? null : map["bearing"], - horizontalAccuracyMeters: map["horizontalAccuracyMeters"] == null - ? null - : map["horizontalAccuracyMeters"], - verticalAccuracyMeters: map["verticalAccuracyMeters"] == null - ? null - : map["verticalAccuracyMeters"], - speedAccuracyMetersPerSecond: map["speedAccuracyMetersPerSecond"] == null - ? null - : map["speedAccuracyMetersPerSecond"], - bearingAccuracyDegrees: map["bearingAccuracyDegrees"] == null - ? null - : map["bearingAccuracyDegrees"], - time: map["time"] == null ? null : map["time"], - elapsedRealtimeNanos: map["elapsedRealtimeNanos"] == null - ? null - : map["elapsedRealtimeNanos"], - ); - } - - String toJson() => json.encode(toMap()); - - factory Location.fromJson(String source) => - Location.fromMap(json.decode(source)); - - @override - String toString() { - return 'Location(provider: $provider, latitude: $latitude, longitude: $longitude, altitude: $altitude, speed: $speed, bearing: $bearing, horizontalAccuracyMeters: $horizontalAccuracyMeters, verticalAccuracyMeters: $verticalAccuracyMeters, speedAccuracyMetersPerSecond: $speedAccuracyMetersPerSecond, bearingAccuracyDegrees: $bearingAccuracyDegrees, time: $time, elapsedRealtimeNanos: $elapsedRealtimeNanos)'; - } - - @override - bool operator ==(Object o) { - if (identical(this, o)) return true; - - return o is Location && - o.provider == provider && - o.latitude == latitude && - o.longitude == longitude && - o.altitude == altitude && - o.speed == speed && - o.bearing == bearing && - o.horizontalAccuracyMeters == horizontalAccuracyMeters && - o.verticalAccuracyMeters == verticalAccuracyMeters && - o.speedAccuracyMetersPerSecond == speedAccuracyMetersPerSecond && - o.bearingAccuracyDegrees == bearingAccuracyDegrees && - o.time == time && - o.elapsedRealtimeNanos == elapsedRealtimeNanos; - } - - @override - int get hashCode { - return hashList([ - provider, - latitude, - longitude, - altitude, - speed, - bearing, - horizontalAccuracyMeters, - verticalAccuracyMeters, - speedAccuracyMetersPerSecond, - bearingAccuracyDegrees, - time, - elapsedRealtimeNanos, - ]); - } -} diff --git a/hms-plugins/flutter-hms-location/lib/location/location_availability.dart b/hms-plugins/flutter-hms-location/lib/location/location_availability.dart deleted file mode 100644 index a93a1061..00000000 --- a/hms-plugins/flutter-hms-location/lib/location/location_availability.dart +++ /dev/null @@ -1,85 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -import 'dart:convert'; -import 'dart:ui'; - -class LocationAvailability { - int cellStatus; - int wifiStatus; - int elapsedRealtimeNs; - int locationStatus; - - LocationAvailability({ - this.cellStatus, - this.wifiStatus, - this.elapsedRealtimeNs, - this.locationStatus, - }); - - bool get isLocationAvailable => locationStatus < 1000; - - Map toMap() { - return { - 'cellStatus': cellStatus, - 'wifiStatus': wifiStatus, - 'elapsedRealtimeNs': elapsedRealtimeNs, - 'locationStatus': locationStatus, - }; - } - - factory LocationAvailability.fromMap(Map map) { - if (map == null) return null; - - return LocationAvailability( - cellStatus: map['cellStatus'], - wifiStatus: map['wifiStatus'], - elapsedRealtimeNs: map['elapsedRealtimeNs'], - locationStatus: map['locationStatus'], - ); - } - - String toJson() => json.encode(toMap()); - - factory LocationAvailability.fromJson(String source) => - LocationAvailability.fromMap(json.decode(source)); - - @override - String toString() { - return 'LocationAvailability(cellStatus: $cellStatus, wifiStatus: $wifiStatus, elapsedRealtimeNs: $elapsedRealtimeNs, locationStatus: $locationStatus)'; - } - - @override - bool operator ==(Object o) { - if (identical(this, o)) return true; - - return o is LocationAvailability && - o.cellStatus == cellStatus && - o.wifiStatus == wifiStatus && - o.elapsedRealtimeNs == elapsedRealtimeNs && - o.locationStatus == locationStatus; - } - - @override - int get hashCode { - return hashList([ - cellStatus, - wifiStatus, - elapsedRealtimeNs, - locationStatus, - ]); - } -} diff --git a/hms-plugins/flutter-hms-location/lib/location/location_callback.dart b/hms-plugins/flutter-hms-location/lib/location/location_callback.dart deleted file mode 100644 index b67068ae..00000000 --- a/hms-plugins/flutter-hms-location/lib/location/location_callback.dart +++ /dev/null @@ -1,31 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -import 'location_availability.dart'; -import 'location_result.dart'; - -typedef void OnLocationResult(LocationResult locationResult); -typedef void OnLocationAvailability(LocationAvailability locationAvailability); - -class LocationCallback { - OnLocationResult onLocationResult; - OnLocationAvailability onLocationAvailability; - - LocationCallback({ - this.onLocationResult, - this.onLocationAvailability, - }); -} diff --git a/hms-plugins/flutter-hms-location/lib/location/location_request.dart b/hms-plugins/flutter-hms-location/lib/location/location_request.dart deleted file mode 100644 index af4ee2ea..00000000 --- a/hms-plugins/flutter-hms-location/lib/location/location_request.dart +++ /dev/null @@ -1,231 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -import 'dart:convert'; -import 'dart:ui'; - -import 'package:flutter/foundation.dart'; - -class LocationRequest { - static const int PRIORITY_HIGH_ACCURACY = 100; - static const int PRIORITY_BALANCED_POWER_ACCURACY = 102; - static const int PRIORITY_LOW_POWER = 104; - static const int PRIORITY_NO_POWER = 105; - static const int PRIORITY_HD_ACCURACY = 200; - static const double _FASTEST_INTERVAL_FACTOR = 6.0; - - int _priority; - int _interval; - int _fastestInterval; - bool _isFastestIntervalExplicitlySet; - int _expirationTime; - int _numUpdates; - double _smallestDisplacement; - int _maxWaitTime; - bool needAddress; - String language; - String countryCode; - Map extras; - - LocationRequest._create( - this._priority, - this._interval, - this._fastestInterval, - this._isFastestIntervalExplicitlySet, - this._expirationTime, - this._numUpdates, - this._smallestDisplacement, - this._maxWaitTime, - this.needAddress, - this.language, - this.countryCode, - this.extras, - ); - - LocationRequest() { - _priority = PRIORITY_BALANCED_POWER_ACCURACY; - _interval = 3600000; - _fastestInterval = (_interval ~/ _FASTEST_INTERVAL_FACTOR); - _isFastestIntervalExplicitlySet = false; - _expirationTime = 9223372036854775807; - _numUpdates = 2147483647; - _smallestDisplacement = 0.0; - _maxWaitTime = 0; - needAddress = false; - language = ''; - countryCode = ''; - } - - int get priority => _priority; - - set priority(int value) { - if (value == PRIORITY_HIGH_ACCURACY || - value == PRIORITY_BALANCED_POWER_ACCURACY || - value == PRIORITY_LOW_POWER || - value == PRIORITY_NO_POWER || - value == PRIORITY_HD_ACCURACY) { - _priority = value; - } else { - throw ArgumentError('Priority is not a known constant'); - } - } - - int get interval => _interval; - - set interval(int value) { - if (value.isNegative) { - throw ArgumentError('Interval is invalid'); - } else { - _interval = value; - _fastestInterval = _isFastestIntervalExplicitlySet - ? _fastestInterval - : (_interval ~/ _FASTEST_INTERVAL_FACTOR); - } - } - - int get fastestInterval => _fastestInterval; - - set fastestInterval(int value) { - if (value.isNegative) { - throw ArgumentError('FastestInterval is invalid'); - } else { - _isFastestIntervalExplicitlySet = true; - _fastestInterval = value; - } - } - - bool get isFastestIntervalExplicitlySet => _isFastestIntervalExplicitlySet; - - int get expirationTime => _expirationTime; - - set expirationTime(int value) { - _expirationTime = value.isNegative ? 0 : value; - } - - int get numUpdates => _numUpdates; - - set numUpdates(int value) { - if (value <= 0) { - throw ArgumentError('numUpdates is invalid'); - } else { - _numUpdates = value; - } - } - - double get smallestDisplacement => _smallestDisplacement; - - set smallestDisplacement(double value) { - if (value.isNegative) { - throw ArgumentError('smallestDisplacement param invalid'); - } else { - _smallestDisplacement = value; - } - } - - int get maxWaitTime => _maxWaitTime < _interval ? _interval : _maxWaitTime; - - set maxWaitTime(int value) => _maxWaitTime = value; - - void putExtras(String key, String value) { - if (extras == null) { - extras = Map(); - } - extras.putIfAbsent(key, () => value); - } - - Map toMap() { - return { - 'priority': _priority, - 'interval': _interval, - 'fastestInterval': _fastestInterval, - 'isFastestIntervalExplicitlySet': _isFastestIntervalExplicitlySet, - 'expirationTime': _expirationTime, - 'numUpdates': _numUpdates, - 'smallestDisplacement': _smallestDisplacement, - 'maxWaitTime': _maxWaitTime, - 'needAddress': needAddress, - 'language': language, - 'countryCode': countryCode, - 'extras': extras, - }; - } - - factory LocationRequest.fromMap(Map map) { - if (map == null) return null; - - return LocationRequest._create( - map['priority'], - map['interval'], - map['fastestInterval'], - map['isFastestIntervalExplicitlySet'], - map['expirationTime'], - map['numUpdates'], - map['smallestDisplacement'], - map['maxWaitTime'], - map['needAddress'], - map['language'], - map['countryCode'], - Map.from(map['extras']), - ); - } - - String toJson() => json.encode(toMap()); - - factory LocationRequest.fromJson(String source) => - LocationRequest.fromMap(json.decode(source)); - - @override - String toString() { - return 'LocationRequest(_priority: $_priority, _interval: $_interval, _fastestInterval: $_fastestInterval, _isFastestIntervalExplicitlySet: $_isFastestIntervalExplicitlySet, _expirationTime: $_expirationTime, _numUpdates: $_numUpdates, _smallestDisplacement: $_smallestDisplacement, _maxWaitTime: $_maxWaitTime, _needAddress: $needAddress, _language: $language, _countryCode: $countryCode, _extras: $extras)'; - } - - @override - bool operator ==(Object o) { - if (identical(this, o)) return true; - - return o is LocationRequest && - o._priority == _priority && - o._interval == _interval && - o._fastestInterval == _fastestInterval && - o._isFastestIntervalExplicitlySet == _isFastestIntervalExplicitlySet && - o._expirationTime == _expirationTime && - o._numUpdates == _numUpdates && - o._smallestDisplacement == _smallestDisplacement && - o._maxWaitTime == _maxWaitTime && - o.needAddress == needAddress && - o.language == language && - o.countryCode == countryCode && - mapEquals(o.extras, extras); - } - - @override - int get hashCode { - return hashList([ - _priority, - _interval, - _fastestInterval, - _isFastestIntervalExplicitlySet, - _expirationTime, - _numUpdates, - _smallestDisplacement, - _maxWaitTime, - needAddress, - language, - countryCode, - extras, - ]); - } -} diff --git a/hms-plugins/flutter-hms-location/lib/location/location_result.dart b/hms-plugins/flutter-hms-location/lib/location/location_result.dart deleted file mode 100644 index 04cac6d5..00000000 --- a/hms-plugins/flutter-hms-location/lib/location/location_result.dart +++ /dev/null @@ -1,98 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -import 'dart:convert'; -import 'dart:ui'; - -import 'package:flutter/foundation.dart'; - -import 'hwlocation.dart' show HWLocation; -import 'location.dart' show Location; - -class LocationResult { - List locations; - List hwLocations; - Location lastLocation; - HWLocation lastHWLocation; - - LocationResult({ - this.locations, - this.hwLocations, - this.lastLocation, - this.lastHWLocation, - }); - - Map toMap() { - return { - 'locations': locations?.map((x) => x?.toMap())?.toList(), - 'hwLocations': hwLocations?.map((x) => x?.toMap())?.toList(), - 'lastLocation': lastLocation?.toMap(), - 'lastHWLocation': lastHWLocation?.toMap(), - }; - } - - factory LocationResult.fromMap(Map map) { - if (map == null) return null; - - return LocationResult( - locations: map["locations"] == null - ? null - : List.from( - map["locations"].map((x) => Location.fromMap(x))), - hwLocations: map["hwLocations"] == null - ? null - : List.from( - map["hwLocations"].map((x) => HWLocation.fromMap(x))), - lastLocation: map["lastLocation"] == null - ? null - : Location.fromMap(map["lastLocation"]), - lastHWLocation: map["lastHWLocation"] == null - ? null - : HWLocation.fromMap(map["lastHWLocation"]), - ); - } - - String toJson() => json.encode(toMap()); - - factory LocationResult.fromJson(String source) => - LocationResult.fromMap(json.decode(source)); - - @override - String toString() { - return 'LocationResult(locations: $locations, hwLocations: $hwLocations, lastLocation: $lastLocation, lastHWLocation: $lastHWLocation)'; - } - - @override - bool operator ==(Object o) { - if (identical(this, o)) return true; - - return o is LocationResult && - listEquals(o.locations, locations) && - listEquals(o.hwLocations, hwLocations) && - o.lastLocation == lastLocation && - o.lastHWLocation == lastHWLocation; - } - - @override - int get hashCode { - return hashList([ - locations, - hwLocations, - lastLocation, - lastHWLocation, - ]); - } -} diff --git a/hms-plugins/flutter-hms-location/lib/location/location_settings_request.dart b/hms-plugins/flutter-hms-location/lib/location/location_settings_request.dart deleted file mode 100644 index f03d7224..00000000 --- a/hms-plugins/flutter-hms-location/lib/location/location_settings_request.dart +++ /dev/null @@ -1,81 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -import 'dart:convert'; -import 'dart:ui'; - -import 'package:flutter/foundation.dart'; - -import 'location_request.dart'; - -class LocationSettingsRequest { - List requests; - bool alwaysShow; - bool needBle; - - LocationSettingsRequest({ - this.requests = const [], - this.alwaysShow = false, - this.needBle = false, - }); - - Map toMap() { - return { - 'requests': requests?.map((x) => x?.toMap())?.toList(), - 'alwaysShow': alwaysShow, - 'needBle': needBle, - }; - } - - factory LocationSettingsRequest.fromMap(Map map) { - if (map == null) return null; - - return LocationSettingsRequest( - requests: List.from( - map['requests']?.map((x) => LocationRequest.fromMap(x))), - alwaysShow: map['alwaysShow'], - needBle: map['needBle'], - ); - } - - String toJson() => json.encode(toMap()); - - factory LocationSettingsRequest.fromJson(String source) => - LocationSettingsRequest.fromMap(json.decode(source)); - - @override - String toString() => - 'LocationSettingsRequest(requests: $requests, alwaysShow: $alwaysShow, needBle: $needBle)'; - - @override - bool operator ==(Object o) { - if (identical(this, o)) return true; - - return o is LocationSettingsRequest && - listEquals(o.requests, requests) && - o.alwaysShow == alwaysShow && - o.needBle == needBle; - } - - @override - int get hashCode { - return hashList([ - requests, - alwaysShow, - needBle, - ]); - } -} diff --git a/hms-plugins/flutter-hms-location/lib/location/location_settings_states.dart b/hms-plugins/flutter-hms-location/lib/location/location_settings_states.dart deleted file mode 100644 index 096374c6..00000000 --- a/hms-plugins/flutter-hms-location/lib/location/location_settings_states.dart +++ /dev/null @@ -1,107 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -import 'dart:convert'; -import 'dart:ui'; - -class LocationSettingsStates { - bool blePresent; - bool bleUsable; - bool gpsPresent; - bool gpsUsable; - bool locationPresent; - bool locationUsable; - bool networkLocationPresent; - bool networkLocationUsable; - - LocationSettingsStates({ - this.blePresent, - this.bleUsable, - this.gpsPresent, - this.gpsUsable, - this.locationPresent, - this.locationUsable, - this.networkLocationPresent, - this.networkLocationUsable, - }); - - Map toMap() { - return { - 'blePresent': blePresent, - 'bleUsable': bleUsable, - 'gpsPresent': gpsPresent, - 'gpsUsable': gpsUsable, - 'locationPresent': locationPresent, - 'locationUsable': locationUsable, - 'networkLocationPresent': networkLocationPresent, - 'networkLocationUsable': networkLocationUsable, - }; - } - - factory LocationSettingsStates.fromMap(Map map) { - if (map == null) return null; - - return LocationSettingsStates( - blePresent: map['blePresent'], - bleUsable: map['bleUsable'], - gpsPresent: map['gpsPresent'], - gpsUsable: map['gpsUsable'], - locationPresent: map['locationPresent'], - locationUsable: map['locationUsable'], - networkLocationPresent: map['networkLocationPresent'], - networkLocationUsable: map['networkLocationUsable'], - ); - } - - String toJson() => json.encode(toMap()); - - factory LocationSettingsStates.fromJson(String source) => - LocationSettingsStates.fromMap(json.decode(source)); - - @override - String toString() { - return 'LocationSettingsStates(blePresent: $blePresent, bleUsable: $bleUsable, gpsPresent: $gpsPresent, gpsUsable: $gpsUsable, locationPresent: $locationPresent, locationUsable: $locationUsable, networkLocationPresent: $networkLocationPresent, networkLocationUsable: $networkLocationUsable)'; - } - - @override - bool operator ==(Object o) { - if (identical(this, o)) return true; - - return o is LocationSettingsStates && - o.blePresent == blePresent && - o.bleUsable == bleUsable && - o.gpsPresent == gpsPresent && - o.gpsUsable == gpsUsable && - o.locationPresent == locationPresent && - o.locationUsable == locationUsable && - o.networkLocationPresent == networkLocationPresent && - o.networkLocationUsable == networkLocationUsable; - } - - @override - int get hashCode { - return hashList([ - blePresent, - bleUsable, - gpsPresent, - gpsUsable, - locationPresent, - locationUsable, - networkLocationPresent, - networkLocationUsable, - ]); - } -} diff --git a/hms-plugins/flutter-hms-location/lib/location/navigation_request.dart b/hms-plugins/flutter-hms-location/lib/location/navigation_request.dart deleted file mode 100644 index d929ec2b..00000000 --- a/hms-plugins/flutter-hms-location/lib/location/navigation_request.dart +++ /dev/null @@ -1,82 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -import 'dart:convert'; -import 'dart:ui'; - -import 'package:flutter/foundation.dart'; - -class NavigationRequest { - static const int OVERPASS = 1; - static const int IS_SUPPORT_EX = 2; - - int type; - Map extras; - - NavigationRequest({ - this.type, - this.extras, - }); - - void putExtras(String key, String value) { - if (extras == null) { - extras = Map(); - } - extras.putIfAbsent(key, () => value); - } - - Map toMap() { - return { - 'type': type, - 'extras': extras, - }; - } - - factory NavigationRequest.fromMap(Map map) { - if (map == null) return null; - - return NavigationRequest( - type: map['type'], - extras: Map.from(map['extras']), - ); - } - - String toJson() => json.encode(toMap()); - - factory NavigationRequest.fromJson(String source) => - NavigationRequest.fromMap(json.decode(source)); - - @override - String toString() { - return 'NavigationRequest(type: $type, extras: $extras)'; - } - - @override - bool operator ==(Object o) { - if (identical(this, o)) return true; - return o is NavigationRequest && - o.type == type && - mapEquals(o.extras, extras); - } - - @override - int get hashCode { - return hashList([ - type, - extras, - ]); - } -} diff --git a/hms-plugins/flutter-hms-location/lib/location/navigation_result.dart b/hms-plugins/flutter-hms-location/lib/location/navigation_result.dart deleted file mode 100644 index 71d3a177..00000000 --- a/hms-plugins/flutter-hms-location/lib/location/navigation_result.dart +++ /dev/null @@ -1,53 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -import 'dart:convert'; - -class NavigationResult { - int possibility; - int state; - - NavigationResult({ - this.possibility, - this.state, - }); - - Map toMap() { - return { - 'state': state, - 'possibility': possibility, - }; - } - - factory NavigationResult.fromMap(Map map) { - if (map == null) return null; - - return NavigationResult( - state: map["state"] == null ? null : map["state"], - possibility: map["possibility"] == null ? null : map["possibility"], - ); - } - - String toJson() => json.encode(toMap()); - - factory NavigationResult.fromJson(String source) => - NavigationResult.fromMap(json.decode(source)); - - @override - String toString() { - return 'State: $state, Possibility: $possibility'; - } -} diff --git a/hms-plugins/flutter-hms-location/lib/logger/hmslogger.dart b/hms-plugins/flutter-hms-location/lib/logger/hmslogger.dart deleted file mode 100644 index f35113e6..00000000 --- a/hms-plugins/flutter-hms-location/lib/logger/hmslogger.dart +++ /dev/null @@ -1,30 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -import 'package:flutter/services.dart'; - -class HMSLogger { - static const MethodChannel _methodChannel = - MethodChannel("com.huawei.flutter.location/hmslogger_methodchannel"); - - static Future enableLogger() async { - return _methodChannel.invokeMethod('enableLogger'); - } - - static Future disableLogger() async { - return _methodChannel.invokeMethod('disableLogger'); - } -} diff --git a/hms-plugins/flutter-hms-location/lib/permission/permission_handler.dart b/hms-plugins/flutter-hms-location/lib/permission/permission_handler.dart deleted file mode 100644 index 865234fb..00000000 --- a/hms-plugins/flutter-hms-location/lib/permission/permission_handler.dart +++ /dev/null @@ -1,63 +0,0 @@ -/* - Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -import 'package:flutter/services.dart'; - -class PermissionHandler { - static PermissionHandler _instance; - - final MethodChannel _methodChannel; - - PermissionHandler._create( - this._methodChannel, - ); - - factory PermissionHandler() { - if (_instance == null) { - final MethodChannel methodChannel = const MethodChannel( - 'com.huawei.flutter.location/permission_methodchannel'); - _instance = PermissionHandler._create(methodChannel); - } - return _instance; - } - - Future hasLocationPermission() async { - return _methodChannel.invokeMethod('hasLocationPermission'); - } - - Future hasBackgroundLocationPermission() async { - return _methodChannel.invokeMethod('hasBackgroundLocationPermission'); - } - - Future hasActivityRecognitionPermission() async { - return _methodChannel - .invokeMethod('hasActivityRecognitionPermission'); - } - - Future requestLocationPermission() async { - return _methodChannel.invokeMethod('requestLocationPermission'); - } - - Future requestBackgroundLocationPermission() async { - return _methodChannel - .invokeMethod('requestBackgroundLocationPermission'); - } - - Future requestActivityRecognitionPermission() async { - return _methodChannel - .invokeMethod('requestActivityRecognitionPermission'); - } -} diff --git a/hms-plugins/flutter-hms-location/pubspec.yaml b/hms-plugins/flutter-hms-location/pubspec.yaml deleted file mode 100644 index 74c68492..00000000 --- a/hms-plugins/flutter-hms-location/pubspec.yaml +++ /dev/null @@ -1,24 +0,0 @@ -name: huawei_location -description: HUAWEI Flutter Location Kit plugin combines the GPS, Wi-Fi and base station locations to help you quickly obtain precise user locations & build up global positioning capabilities. -version: 5.0.0+301 -homepage: https://www.huawei.com -repository: https://github.com/HMS-Core/hms-flutter-plugin/tree/master/flutter-hms-location - -environment: - sdk: ">=2.1.0 <3.0.0" - flutter: ">=1.12.13+hotfix.6 <2.0.0" - -dependencies: - flutter: - sdk: flutter - -dev_dependencies: - flutter_test: - sdk: flutter - -flutter: - plugin: - platforms: - android: - package: com.huawei.hms.flutter.location - pluginClass: LocationPlugin diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj index 240eb6e4..61f83109 100644 --- a/ios/Runner.xcodeproj/project.pbxproj +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -3,7 +3,7 @@ archiveVersion = 1; classes = { }; - objectVersion = 51; + objectVersion = 54; objects = { /* Begin PBXBuildFile section */ @@ -271,7 +271,7 @@ 97C146E61CF9000F007C117D /* Project object */ = { isa = PBXProject; attributes = { - LastUpgradeCheck = 1300; + LastUpgradeCheck = 1430; ORGANIZATIONNAME = ""; TargetAttributes = { 97C146ED1CF9000F007C117D = { @@ -322,10 +322,12 @@ /* Begin PBXShellScriptBuildPhase section */ 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; buildActionMask = 2147483647; files = ( ); inputPaths = ( + "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", ); name = "Thin Binary"; outputPaths = ( @@ -392,6 +394,7 @@ }; 9740EEB61CF901F6004384FC /* Run Script */ = { isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; buildActionMask = 2147483647; files = ( ); diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index 533f04ef..65a0bf75 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -114,5 +114,7 @@ io.flutter.embedded_views_preview + UIApplicationSupportsIndirectInputEvents + diff --git a/lib/core/viewModels/AlHabibMedicalService/H2O_view_model.dart b/lib/core/viewModels/AlHabibMedicalService/H2O_view_model.dart index 26f1bf0f..d7df4773 100644 --- a/lib/core/viewModels/AlHabibMedicalService/H2O_view_model.dart +++ b/lib/core/viewModels/AlHabibMedicalService/H2O_view_model.dart @@ -94,30 +94,30 @@ class H2OViewModel extends BaseViewModel { } } - List> createUserProgressForWeekDataSeries() { - List globalData = []; - _h2OService.userProgressForWeekDataList.forEach((UserProgressForWeekDataModel data) { - globalData.add(new ChartSeries(data.dayName!, data.percentageConsumed!)); - }); - Iterable minMaxList = globalData.map((e) => e.x).toList(); - int maxValue = minMaxList.isEmpty ? 0 : minMaxList.reduce(math.max); - int minValue = minMaxList.isEmpty ? 0 : minMaxList.reduce(math.min); - - if (maxValue == 0 && minValue == 0) { - maxValue = 1; - minValue = -1; - } - return [ - Charts.series( - id: 'Global Revenue', - domainFn: (ChartSeries sales, _) => sales.y, - measureFn: (ChartSeries sales, _) => sales.x, - measureLowerBoundFn: (ChartSeries sales, _) => minValue, - measureUpperBoundFn: (ChartSeries sales, _) => maxValue, - data: globalData, - ), - ]; - } + // List> createUserProgressForWeekDataSeries() { + // List globalData = []; + // _h2OService.userProgressForWeekDataList.forEach((UserProgressForWeekDataModel data) { + // globalData.add(new ChartSeries(data.dayName!, data.percentageConsumed!)); + // }); + // Iterable minMaxList = globalData.map((e) => e.x).toList(); + // int maxValue = minMaxList.isEmpty ? 0 : minMaxList.reduce(math.max); + // int minValue = minMaxList.isEmpty ? 0 : minMaxList.reduce(math.min); + // + // if (maxValue == 0 && minValue == 0) { + // maxValue = 1; + // minValue = -1; + // } + // return [ + // Charts.series( + // id: 'Global Revenue', + // domainFn: (ChartSeries sales, _) => sales.y, + // measureFn: (ChartSeries sales, _) => sales.x, + // measureLowerBoundFn: (ChartSeries sales, _) => minValue, + // measureUpperBoundFn: (ChartSeries sales, _) => maxValue, + // data: globalData, + // ), + // ]; + // } List createUserProgressForWeekDataSeriesNew() { List list = []; @@ -136,20 +136,20 @@ class H2OViewModel extends BaseViewModel { return list; } - List> createUserProgressForMonthDataSeries() { - List globalData = []; - _h2OService.userProgressForMonthDataList.forEach((UserProgressForMonthDataModel data) { - globalData.add(new ChartSeries(data.monthName!, data.percentageConsumed!)); - }); - return [ - new charts.Series( - id: 'Global Revenue', - domainFn: (ChartSeries sales, _) => sales.y, - measureFn: (ChartSeries sales, _) => sales.x, - data: globalData, - ), - ]; - } + // List> createUserProgressForMonthDataSeries() { + // List globalData = []; + // _h2OService.userProgressForMonthDataList.forEach((UserProgressForMonthDataModel data) { + // globalData.add(new ChartSeries(data.monthName!, data.percentageConsumed!)); + // }); + // return [ + // new charts.Series( + // id: 'Global Revenue', + // domainFn: (ChartSeries sales, _) => sales.y, + // measureFn: (ChartSeries sales, _) => sales.x, + // data: globalData, + // ), + // ]; + // } Future insertUserActivity(InsertUserActivityRequestModel insertUserActivityRequestModel) async { setState(ViewState.BusyLocal); diff --git a/lib/core/viewModels/medical/reports_monthly_view_model.dart b/lib/core/viewModels/medical/reports_monthly_view_model.dart index 7f12e002..bbd6916e 100644 --- a/lib/core/viewModels/medical/reports_monthly_view_model.dart +++ b/lib/core/viewModels/medical/reports_monthly_view_model.dart @@ -37,7 +37,7 @@ class ReportsMonthlyViewModel extends BaseViewModel { setState(ViewState.ErrorLocal); } else { if (isUpdateEmail) { - await _reportsService.updateEmail(email: email); + await _reportsService.updateEmail(email: email!); if (_reportsService.hasError) { error = _reportsService.error!; AppToast.showErrorToast(message: error); diff --git a/lib/core/viewModels/pharmacyModule/PharmacyAddressesViewModel.dart b/lib/core/viewModels/pharmacyModule/PharmacyAddressesViewModel.dart index 1183cfd5..d920f1e3 100644 --- a/lib/core/viewModels/pharmacyModule/PharmacyAddressesViewModel.dart +++ b/lib/core/viewModels/pharmacyModule/PharmacyAddressesViewModel.dart @@ -17,7 +17,7 @@ class PharmacyAddressesViewModel extends BaseViewModel { int get selectedAddressIndex => _pharmacyAddressService.selectedAddressIndex; - CountryData get country => _pharmacyAddressService.country; + CountryData get country => _pharmacyAddressService.country!; setSelectedAddressIndex(int index) { _pharmacyAddressService.selectedAddressIndex = index; diff --git a/lib/core/viewModels/pharmacyModule/product_detail_view_model.dart b/lib/core/viewModels/pharmacyModule/product_detail_view_model.dart index 193e6ee6..de48afd5 100644 --- a/lib/core/viewModels/pharmacyModule/product_detail_view_model.dart +++ b/lib/core/viewModels/pharmacyModule/product_detail_view_model.dart @@ -27,13 +27,13 @@ class ProductDetailViewModel extends BaseViewModel { bool hasError = false; - num get stockQuantity => _productDetailService.stockQuantity; + num get stockQuantity => _productDetailService.stockQuantity!; - String get stockAvailability => _productDetailService.stockAvailability; + String get stockAvailability => _productDetailService.stockAvailability!; - String get stockAvailabilityn => _productDetailService.stockAvailabilityn; + String get stockAvailabilityn => _productDetailService.stockAvailabilityn!; - bool get isStockAvailable => _productDetailService.isStockAvailable; + bool get isStockAvailable => _productDetailService.isStockAvailable!; Future getProductReviewsData(productID) async { hasError = false; diff --git a/lib/core/viewModels/project_view_model.dart b/lib/core/viewModels/project_view_model.dart index 0feaaaeb..a66a0752 100644 --- a/lib/core/viewModels/project_view_model.dart +++ b/lib/core/viewModels/project_view_model.dart @@ -13,7 +13,7 @@ import 'package:diplomaticquarterapp/models/Authentication/register_info_respons import 'package:diplomaticquarterapp/uitl/PlatformBridge.dart'; import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart'; import 'package:flutter/cupertino.dart'; -import 'package:flutter_datetime_picker/flutter_datetime_picker.dart'; +import 'package:flutter_datetime_picker_plus/flutter_datetime_picker_plus.dart'; var isAppArabic = false; diff --git a/lib/pages/AlHabibMedicalService/health_calculator/delivery_due/delivery_due.dart b/lib/pages/AlHabibMedicalService/health_calculator/delivery_due/delivery_due.dart index b8528ea6..d6d5ab8a 100644 --- a/lib/pages/AlHabibMedicalService/health_calculator/delivery_due/delivery_due.dart +++ b/lib/pages/AlHabibMedicalService/health_calculator/delivery_due/delivery_due.dart @@ -7,7 +7,7 @@ import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_datetime_picker/flutter_datetime_picker.dart'; +import 'package:flutter_datetime_picker_plus/flutter_datetime_picker_plus.dart'; import 'package:intl/intl.dart'; import 'delivery_due_result_page.dart'; diff --git a/lib/pages/AlHabibMedicalService/health_calculator/ovulation_period/ovulation_period.dart b/lib/pages/AlHabibMedicalService/health_calculator/ovulation_period/ovulation_period.dart index a92b7e06..c1fc6097 100644 --- a/lib/pages/AlHabibMedicalService/health_calculator/ovulation_period/ovulation_period.dart +++ b/lib/pages/AlHabibMedicalService/health_calculator/ovulation_period/ovulation_period.dart @@ -6,7 +6,7 @@ import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_datetime_picker/flutter_datetime_picker.dart'; +import 'package:flutter_datetime_picker_plus/flutter_datetime_picker_plus.dart'; import 'package:intl/intl.dart'; import 'package:jiffy/jiffy.dart'; diff --git a/lib/pages/AlHabibMedicalService/my_web_view.dart b/lib/pages/AlHabibMedicalService/my_web_view.dart index fe116bfa..1779b127 100644 --- a/lib/pages/AlHabibMedicalService/my_web_view.dart +++ b/lib/pages/AlHabibMedicalService/my_web_view.dart @@ -8,8 +8,7 @@ class MyWebView extends StatelessWidget { final String title; final String selectedUrl; - final Completer _controller = - Completer(); + final Completer _controller = Completer(); MyWebView({ required this.title, diff --git a/lib/pages/ChildVaccines/add_newchild_page.dart b/lib/pages/ChildVaccines/add_newchild_page.dart index bbd292fb..b03a6db2 100644 --- a/lib/pages/ChildVaccines/add_newchild_page.dart +++ b/lib/pages/ChildVaccines/add_newchild_page.dart @@ -13,7 +13,7 @@ import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_datetime_picker/flutter_datetime_picker.dart'; +import 'package:flutter_datetime_picker_plus/flutter_datetime_picker_plus.dart'; enum Gender { Male, Female, NON } enum BeneficiaryType { MyAccount, MyFamilyFiles, OtherAccount, NON } diff --git a/lib/pages/ErService/EdOnline/EdOnlineNotesPage.dart b/lib/pages/ErService/EdOnline/EdOnlineNotesPage.dart index a31e5205..2ed77c2e 100644 --- a/lib/pages/ErService/EdOnline/EdOnlineNotesPage.dart +++ b/lib/pages/ErService/EdOnline/EdOnlineNotesPage.dart @@ -13,7 +13,7 @@ import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_datetime_picker/flutter_datetime_picker.dart'; +import 'package:flutter_datetime_picker_plus/flutter_datetime_picker_plus.dart'; import 'package:provider/provider.dart'; class EdOnlineNotesPage extends StatefulWidget { diff --git a/lib/pages/ToDoList/ToDo.dart b/lib/pages/ToDoList/ToDo.dart index c01611b1..f5de01e6 100644 --- a/lib/pages/ToDoList/ToDo.dart +++ b/lib/pages/ToDoList/ToDo.dart @@ -54,7 +54,7 @@ class ToDo extends StatefulWidget { late MyInAppBrowser browser; bool isShowAppBar = true; - VoidCallbackAction? onBackClick; + Function()? onBackClick; ToDo({required this.isShowAppBar, this.onBackClick}); diff --git a/lib/pages/login/register.dart b/lib/pages/login/register.dart index eecb1a94..0abb3093 100644 --- a/lib/pages/login/register.dart +++ b/lib/pages/login/register.dart @@ -23,7 +23,7 @@ import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_datetime_picker/flutter_datetime_picker.dart'; +import 'package:flutter_datetime_picker_plus/flutter_datetime_picker_plus.dart'; import 'package:intl/intl.dart' as intl; class Register extends StatefulWidget { diff --git a/lib/pages/medical/active_medications/reminder_page.dart b/lib/pages/medical/active_medications/reminder_page.dart index b6d96f90..3c775bdc 100644 --- a/lib/pages/medical/active_medications/reminder_page.dart +++ b/lib/pages/medical/active_medications/reminder_page.dart @@ -11,7 +11,7 @@ import 'package:diplomaticquarterapp/widgets/data_display/text.dart'; import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_datetime_picker/flutter_datetime_picker.dart'; +import 'package:flutter_datetime_picker_plus/flutter_datetime_picker_plus.dart'; import 'package:provider/provider.dart'; import 'DayCheckBoxDialog.dart'; diff --git a/lib/pages/medical/medical_profile_page_new.dart b/lib/pages/medical/medical_profile_page_new.dart index e3094877..b89afe70 100644 --- a/lib/pages/medical/medical_profile_page_new.dart +++ b/lib/pages/medical/medical_profile_page_new.dart @@ -13,7 +13,7 @@ import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; class MedicalProfilePageNew extends StatefulWidget { - VoidCallbackAction? onTap; + Function()? onTap; String? a; MedicalProfilePageNew({this.onTap}); @override diff --git a/lib/pages/medical/my_trackers/Weight/AddWeightPage.dart b/lib/pages/medical/my_trackers/Weight/AddWeightPage.dart index 8748ebe9..fbe60a75 100644 --- a/lib/pages/medical/my_trackers/Weight/AddWeightPage.dart +++ b/lib/pages/medical/my_trackers/Weight/AddWeightPage.dart @@ -13,7 +13,7 @@ import 'package:diplomaticquarterapp/widgets/dialogs/radio_selection_dialog.dart import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_datetime_picker/flutter_datetime_picker.dart'; +import 'package:flutter_datetime_picker_plus/flutter_datetime_picker_plus.dart'; import 'package:provider/provider.dart'; class AddWeightPage extends StatefulWidget { diff --git a/lib/pages/medical/my_trackers/blood_pressure/AddBloodPressurePage.dart b/lib/pages/medical/my_trackers/blood_pressure/AddBloodPressurePage.dart index fa86e247..780f94f5 100644 --- a/lib/pages/medical/my_trackers/blood_pressure/AddBloodPressurePage.dart +++ b/lib/pages/medical/my_trackers/blood_pressure/AddBloodPressurePage.dart @@ -13,7 +13,7 @@ import 'package:diplomaticquarterapp/widgets/dialogs/radio_selection_dialog.dart import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_datetime_picker/flutter_datetime_picker.dart'; +import 'package:flutter_datetime_picker_plus/flutter_datetime_picker_plus.dart'; import 'package:provider/provider.dart'; class AddBloodPressurePage extends StatefulWidget { diff --git a/lib/pages/medical/my_trackers/blood_suger/AddBloodSugarPage.dart b/lib/pages/medical/my_trackers/blood_suger/AddBloodSugarPage.dart index 6b27fd8e..1077fd05 100644 --- a/lib/pages/medical/my_trackers/blood_suger/AddBloodSugarPage.dart +++ b/lib/pages/medical/my_trackers/blood_suger/AddBloodSugarPage.dart @@ -13,7 +13,7 @@ import 'package:diplomaticquarterapp/widgets/dialogs/radio_selection_dialog.dart import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_datetime_picker/flutter_datetime_picker.dart'; +import 'package:flutter_datetime_picker_plus/flutter_datetime_picker_plus.dart'; import 'package:provider/provider.dart'; class AddBloodSugarPage extends StatefulWidget { diff --git a/lib/pages/medical/my_trackers/widget/CurvedChartBloodPressure.dart b/lib/pages/medical/my_trackers/widget/CurvedChartBloodPressure.dart index a658ab5e..5f093eb7 100644 --- a/lib/pages/medical/my_trackers/widget/CurvedChartBloodPressure.dart +++ b/lib/pages/medical/my_trackers/widget/CurvedChartBloodPressure.dart @@ -15,8 +15,8 @@ class CurvedChartBloodPressure extends StatelessWidget { CurvedChartBloodPressure({this.title, this.timeSeries1, this.indexes, this.timeSeries2, this.horizontalInterval = 20.0}); - List xAxixs =[]; - List yAxixs =[]; + List xAxixs = []; + List yAxixs = []; @override Widget build(BuildContext context) { @@ -49,7 +49,7 @@ class CurvedChartBloodPressure extends StatelessWidget { padding: const EdgeInsets.only(right: 18.0, left: 16.0, top: 15), child: LineChart( sampleData1(context), - swapAnimationDuration: const Duration(milliseconds: 250), + duration: const Duration(milliseconds: 250), ), ), ), @@ -119,42 +119,66 @@ class CurvedChartBloodPressure extends StatelessWidget { ), gridData: FlGridData(show: true, drawVerticalLine: true, drawHorizontalLine: true), titlesData: FlTitlesData( - bottomTitles: SideTitles( - showTitles: true, - getTextStyles: (cxt, value) => const TextStyle( - color: Colors.black, - fontSize: 10, - ), - margin: 22, - getTitles: (value) { - if (timeSeries1!.length < 15) { - if (timeSeries1!.length > value.toInt()) { - return '${timeSeries1![value.toInt()].time.month}/ ${timeSeries1![value.toInt()].time.year}'; - } else - return ''; - } else { - if (value.toInt() == 0) return '${timeSeries1![value.toInt()].time.month}/ ${timeSeries1![value.toInt()].time.year}'; - if (value.toInt() == timeSeries1!.length - 1) return '${timeSeries1![value.toInt()].time.month}/ ${timeSeries1![value.toInt()].time.year}'; - if (xAxixs.contains(value.toInt())) { - return '${timeSeries1![value.toInt()].time.month}/ ${timeSeries1![value.toInt()].time.year}'; + bottomTitles: AxisTitles( + sideTitles: SideTitles( + showTitles: true, + getTitlesWidget: (value, TitleMeta) { + TextStyle style = TextStyle( + color: Colors.black, + fontSize: 10, + ); + if (timeSeries1!.length < 15) { + if (timeSeries1!.length > value.toInt()) { + return Text( + '${timeSeries1![value.toInt()].time.month}/ ${timeSeries1![value.toInt()].time.year}', + style: style, + ); + } else + //return Text(""); + return SizedBox(); + } else { + if (value.toInt() == 0) + return Text( + '${timeSeries1![value.toInt()].time.month}/ ${timeSeries1![value.toInt()].time.year}', + style: style, + ); + if (value.toInt() == timeSeries1!.length - 1) + return Text( + '${timeSeries1![value.toInt()].time.month}/ ${timeSeries1![value.toInt()].time.year}', + style: style, + ); + if (xAxixs.contains(value.toInt())) { + return Text( + '${timeSeries1![value.toInt()].time.month}/ ${timeSeries1![value.toInt()].time.year}', + style: style, + ); + } } - } - return ''; - }, - ), - leftTitles: SideTitles( - showTitles: true, - interval: getMaxY() - getMinY() <= 500 - ? 50 - : getMaxY() - getMinY() <= 1000 - ? 100 - : 200, - getTextStyles: (cxt, value) => const TextStyle( - color: Colors.black, - fontWeight: FontWeight.bold, - fontSize: 10, + return SizedBox(); + }, + + // margin: 22, ), - margin: 12, + ), + leftTitles: AxisTitles( + sideTitles: SideTitles( + showTitles: true, + interval: getMaxY() - getMinY() <= 500 + ? 50 + : getMaxY() - getMinY() <= 1000 + ? 100 + : 200, + getTitlesWidget: (value, TitleMeta) { + TextStyle style = TextStyle( + color: Colors.black, + fontWeight: FontWeight.bold, + fontSize: 10, + ); + return SizedBox(); + } + + // margin: 12, + ), ), ), borderData: FlBorderData( @@ -214,12 +238,12 @@ class CurvedChartBloodPressure extends StatelessWidget { } List getData(context) { - List spots =[]; + List spots = []; for (int index = 0; index < timeSeries1!.length; index++) { spots.add(FlSpot(index.toDouble(), timeSeries1![index].sales)); } - List spots2 =[]; + List spots2 = []; for (int index = 0; index < timeSeries2!.length; index++) { spots2.add(FlSpot(index.toDouble(), timeSeries2![index].sales)); } @@ -227,7 +251,7 @@ class CurvedChartBloodPressure extends StatelessWidget { final LineChartBarData lineChartBarData1 = LineChartBarData( spots: spots, isCurved: true, - colors: [Colors.red], + color: Colors.red, barWidth: 5, isStrokeCapRound: true, dotData: FlDotData( @@ -240,7 +264,7 @@ class CurvedChartBloodPressure extends StatelessWidget { final LineChartBarData lineChartBarData2 = LineChartBarData( spots: spots2, isCurved: true, - colors: [Theme.of(context).primaryColor], + color: Theme.of(context).primaryColor, barWidth: 5, isStrokeCapRound: true, dotData: FlDotData( diff --git a/lib/pages/medical/my_trackers/widget/LineChartCurved.dart b/lib/pages/medical/my_trackers/widget/LineChartCurved.dart index 01ee6bed..882cf034 100644 --- a/lib/pages/medical/my_trackers/widget/LineChartCurved.dart +++ b/lib/pages/medical/my_trackers/widget/LineChartCurved.dart @@ -12,8 +12,8 @@ class LineChartCurved extends StatelessWidget { LineChartCurved({this.title, this.timeSeries, this.indexes, this.horizontalInterval = 20.0}); - List xAxixs =[]; - List yAxixs =[]; + List xAxixs = []; + List yAxixs = []; @override Widget build(BuildContext context) { @@ -47,7 +47,7 @@ class LineChartCurved extends StatelessWidget { padding: const EdgeInsets.only(right: 18.0, left: 16.0), child: LineChart( sampleData1(context), - swapAnimationDuration: const Duration(milliseconds: 250), + duration: const Duration(milliseconds: 250), ), ), ), @@ -168,50 +168,67 @@ class LineChartCurved extends StatelessWidget { ), gridData: FlGridData(show: true, drawVerticalLine: true, drawHorizontalLine: true, horizontalInterval: 14, verticalInterval: 14), titlesData: FlTitlesData( - bottomTitles: SideTitles( - showTitles: true, - getTextStyles: (cxt, value) => const TextStyle( - color: Colors.black, - fontSize: 10, - ), - rotateAngle: -65, - margin: 22, - getTitles: (value) { - if (timeSeries!.length < 15) { - if (timeSeries!.length > value.toInt()) { - return '${timeSeries![value.toInt()].time.month}/ ${timeSeries![value.toInt()].time.year}'; - } else - return ''; - } else { - if (value.toInt() == 0) return '${timeSeries![value.toInt()].time.month}/ ${timeSeries![value.toInt()].time.year}'; - if (value.toInt() == timeSeries!.length - 1) return '${timeSeries![value.toInt()].time.month}/ ${timeSeries![value.toInt()].time.year}'; - if (xAxixs.contains(value.toInt())) { - return '${timeSeries![value.toInt()].time.month}/ ${timeSeries![value.toInt()].time.year}'; - } - } - return ''; - }, - ), - leftTitles: SideTitles( - showTitles: true, - getTextStyles: (cxt, value) => const TextStyle( - color: Colors.black, - fontWeight: FontWeight.bold, - fontSize: 10, + bottomTitles: AxisTitles( + axisNameSize: 22, + sideTitles: SideTitles( + showTitles: true, +//Changed By Aamir + // rotateAngle: -65, + // margin: 22, + getTitlesWidget: (value, title) { + TextStyle style = TextStyle( + color: Colors.black, + fontSize: 10, + ); + if (timeSeries!.length < 15) { + if (timeSeries!.length > value.toInt()) { + return Text( + '${timeSeries![value.toInt()].time.month}/ ${timeSeries![value.toInt()].time.year}', + style: style, + ); + } else + return SizedBox(); + } else { + if (value.toInt() == 0) return Text('${timeSeries![value.toInt()].time.month}/ ${timeSeries![value.toInt()].time.year}', style: style); + if (value.toInt() == timeSeries!.length - 1) return Text('${timeSeries![value.toInt()].time.month}/ ${timeSeries![value.toInt()].time.year}', style: style); + if (xAxixs.contains(value.toInt())) { + return Text( + '${timeSeries![value.toInt()].time.month}/ ${timeSeries![value.toInt()].time.year}', + style: style, + ); + } + } + return SizedBox(); + }, + ), ), - interval: 3.0, - // interval: getMaxY() - getMinY() <= 500 - // ? getMaxY() - getMinY() <= 50 - // ? 10 - // : 10 - // : getMaxY() - getMinY() <= 1000 - // ? 100 - // : getMaxY() - getMinY() >= 10000 - // ? 5000 - // : 200, - margin: 12, - ), - ), + leftTitles: AxisTitles( + sideTitles: SideTitles( + showTitles: true, + interval: 3.0, + getTitlesWidget: (val, title) { + TextStyle styl = const TextStyle( + color: Colors.black, + fontWeight: FontWeight.bold, + fontSize: 10, + ); + return Text( + "", + style: styl, + ); + } + // interval: getMaxY() - getMinY() <= 500 + // ? getMaxY() - getMinY() <= 50 + // ? 10 + // : 10 + // : getMaxY() - getMinY() <= 1000 + // ? 100 + // : getMaxY() - getMinY() >= 10000 + // ? 5000 + // : 200, + //margin: 12, + ), + )), borderData: FlBorderData( show: true, border: const Border( @@ -230,14 +247,15 @@ class LineChartCurved extends StatelessWidget { ), ), ), - minX: 0, - maxX: (timeSeries!.length - 1).toDouble(), - maxY: getMaxY() + 0.3, - minY: 0, - //getMinY(), + minX: 0, + maxX: (timeSeries!.length - 1).toDouble(), + maxY: getMaxY() + 0.3, + minY: 0, + //getMinY(), lineBarsData: getData(context), ); } + double getMaxY() { double max = 0; timeSeries!.forEach((element) { @@ -260,7 +278,7 @@ class LineChartCurved extends StatelessWidget { } List getData(context) { - List spots =[]; + List spots = []; for (int index = 0; index < timeSeries!.length; index++) { spots.add(FlSpot(index.toDouble(), timeSeries![index].sales)); } @@ -268,7 +286,7 @@ class LineChartCurved extends StatelessWidget { final LineChartBarData lineChartBarData1 = LineChartBarData( spots: spots, isCurved: true, - colors: [secondaryColor!], + color: secondaryColor, barWidth: 1.5, isStrokeCapRound: true, dotData: FlDotData( diff --git a/lib/pages/medical/my_trackers/widget/MonthCurvedChartBloodPressure.dart b/lib/pages/medical/my_trackers/widget/MonthCurvedChartBloodPressure.dart index e3bbc8c2..dfa882f6 100644 --- a/lib/pages/medical/my_trackers/widget/MonthCurvedChartBloodPressure.dart +++ b/lib/pages/medical/my_trackers/widget/MonthCurvedChartBloodPressure.dart @@ -48,7 +48,7 @@ class MonthCurvedChartBloodPressure extends StatelessWidget { padding: const EdgeInsets.only(right: 18.0, left: 16.0, top: 15), child: LineChart( sampleData1(context), - swapAnimationDuration: const Duration(milliseconds: 250), + duration: const Duration(milliseconds: 250), ), ), ), @@ -118,40 +118,50 @@ class MonthCurvedChartBloodPressure extends StatelessWidget { ), gridData: FlGridData(show: true, drawVerticalLine: true, drawHorizontalLine: true, horizontalInterval: 14, verticalInterval: 14), titlesData: FlTitlesData( - bottomTitles: SideTitles( - showTitles: true, - getTextStyles: (cxt, value) => const TextStyle( - color: Colors.black, - fontSize: 10, - ), - margin: 22, - getTitles: (value) { - return timeSeries1![value.toInt()].time; - // return ''; - }, + bottomTitles: AxisTitles( + sideTitles: SideTitles( + showTitles: true, + getTitlesWidget: (value, title) { + TextStyle styl = const TextStyle( + color: Colors.black, + fontWeight: FontWeight.bold, + fontSize: 10, + ); + return Text( + timeSeries1![value.toInt()].time, + style: styl, + ); + }), ), - leftTitles: SideTitles( - showTitles: true, - interval: getMaxY() - getMinY() <= 500 - ? 10 - : getMaxY() - getMinY() <= 1000 - ? 30 - : 40, - - getTextStyles: (cxt, value) => const TextStyle( - color: Colors.black, - fontWeight: FontWeight.bold, - fontSize: 10, - ), - // getTitles: (value) { - // // if (value.toInt() == 0) - // // return '${value.toInt()}'; - // // else if (value.toInt() % horizontalInterval == 0) - // // return '${value.toInt()}'; - // // else - // return '${value.toInt()}'; - // }, - margin: 12, + leftTitles: AxisTitles( + sideTitles: SideTitles( + showTitles: true, + interval: getMaxY() - getMinY() <= 500 + ? 10 + : getMaxY() - getMinY() <= 1000 + ? 30 + : 40, + getTitlesWidget: (value, title) { + TextStyle styl = const TextStyle( + color: Colors.black, + fontWeight: FontWeight.bold, + fontSize: 10, + ); + return Text( + timeSeries1![value.toInt()].time, + style: styl, + ); + } + // getTitles: (value) { + // // if (value.toInt() == 0) + // // return '${value.toInt()}'; + // // else if (value.toInt() % horizontalInterval == 0) + // // return '${value.toInt()}'; + // // else + // return '${value.toInt()}'; + // }, + // margin: 12, + ), ), ), borderData: FlBorderData( @@ -224,7 +234,7 @@ class MonthCurvedChartBloodPressure extends StatelessWidget { final LineChartBarData lineChartBarData1 = LineChartBarData( spots: spots, isCurved: true, - colors: [Colors.red], + color: Colors.red, barWidth: 1.5, isStrokeCapRound: true, dotData: FlDotData( @@ -237,7 +247,7 @@ class MonthCurvedChartBloodPressure extends StatelessWidget { final LineChartBarData lineChartBarData2 = LineChartBarData( spots: spots2, isCurved: true, - colors: [Theme.of(context).primaryColor], + color: Theme.of(context).primaryColor, barWidth: 1.5, isStrokeCapRound: true, dotData: FlDotData( diff --git a/lib/pages/medical/my_trackers/widget/MonthLineChartCurved.dart b/lib/pages/medical/my_trackers/widget/MonthLineChartCurved.dart index 2b891ef5..9a6616f9 100644 --- a/lib/pages/medical/my_trackers/widget/MonthLineChartCurved.dart +++ b/lib/pages/medical/my_trackers/widget/MonthLineChartCurved.dart @@ -12,8 +12,8 @@ class MonthLineChartCurved extends StatelessWidget { MonthLineChartCurved({this.title, this.timeSeries, this.indexes, this.horizontalInterval = 15.0}); - List xAxixs =[]; - List yAxixs =[]; + List xAxixs = []; + List yAxixs = []; @override Widget build(BuildContext context) { @@ -47,7 +47,7 @@ class MonthLineChartCurved extends StatelessWidget { padding: const EdgeInsets.only(right: 18.0, left: 16.0, top: 15, bottom: 15), child: LineChart( sampleData1(context), - swapAnimationDuration: const Duration(milliseconds: 250), + duration: const Duration(milliseconds: 250), ), ), ), @@ -98,39 +98,52 @@ class MonthLineChartCurved extends StatelessWidget { verticalInterval: 12, ), titlesData: FlTitlesData( - bottomTitles: SideTitles( - showTitles: true, - getTextStyles: (cxt, value) => const TextStyle( - color: Colors.black, - fontSize: 10, - ), - margin: 22, - getTitles: (value) { - return '${value.toInt()}'; - }, + bottomTitles: AxisTitles( + sideTitles: SideTitles( + showTitles: true, + getTitlesWidget: (value, title) { + TextStyle styl = const TextStyle( + color: Colors.black, + fontSize: 10, + ); + return Text( + '${value.toInt()}', + style: styl, + ); + } + // margin: 22, + ), ), - leftTitles: SideTitles( - showTitles: true, - getTextStyles: (cxt, value) => const TextStyle( - color: Colors.black, - fontWeight: FontWeight.bold, - fontSize: 10, + leftTitles: AxisTitles( + sideTitles: SideTitles( + showTitles: true, + getTitlesWidget: (value, title) { + TextStyle styl = const TextStyle( + color: Colors.black, + fontWeight: FontWeight.bold, + fontSize: 10, + ); + return Text( + '', + style: styl, + ); + }, + interval: getMaxY() - getMinY() <= 500 + ? 50 + : getMaxY() - getMinY() <= 1000 + ? 100 + : 200, + + // getTitles: (value) { + // if (value.toInt() == 0) + // return '${value.toInt()}'; + // else if (value.toInt() % horizontalInterval == 0) + // return '${value.toInt()}'; + // else + // return ''; + // }, + // margin: 12, ), - interval: getMaxY() - getMinY() <= 500 - ? 50 - : getMaxY() - getMinY() <= 1000 - ? 100 - : 200, - - // getTitles: (value) { - // if (value.toInt() == 0) - // return '${value.toInt()}'; - // else if (value.toInt() % horizontalInterval == 0) - // return '${value.toInt()}'; - // else - // return ''; - // }, - margin: 12, ), ), borderData: FlBorderData( @@ -181,7 +194,7 @@ class MonthLineChartCurved extends StatelessWidget { } List getData(context) { - List spots =[]; + List spots = []; if (timeSeries!.length == 0) { spots.add(FlSpot(0, 0)); } @@ -192,7 +205,7 @@ class MonthLineChartCurved extends StatelessWidget { final LineChartBarData lineChartBarData1 = LineChartBarData( spots: spots, isCurved: true, - colors: [secondaryColor!], + color: secondaryColor, barWidth: 1.5, isStrokeCapRound: true, curveSmoothness: 0.0, diff --git a/lib/pages/medical/vital_sign/LineChartCurved.dart b/lib/pages/medical/vital_sign/LineChartCurved.dart index aadcaeef..e86f31bf 100644 --- a/lib/pages/medical/vital_sign/LineChartCurved.dart +++ b/lib/pages/medical/vital_sign/LineChartCurved.dart @@ -62,7 +62,7 @@ class LineChartCurved extends StatelessWidget { padding: const EdgeInsets.only(right: 18.0, left: 16.0), child: LineChart( sampleData1(context), - swapAnimationDuration: const Duration(milliseconds: 250), + duration: const Duration(milliseconds: 250), ), ), ), @@ -106,39 +106,63 @@ class LineChartCurved extends StatelessWidget { ), gridData: FlGridData(show: true, drawVerticalLine: true, drawHorizontalLine: true, horizontalInterval: 14, verticalInterval: 14), titlesData: FlTitlesData( - bottomTitles: SideTitles( - showTitles: true, - getTextStyles: (cxt, value) => const TextStyle( - color: Colors.black, - fontSize: 10, - ), - rotateAngle: -65, - margin: 22, - getTitles: (value) { - if (timeSeries.length < 15) { - if (timeSeries.length > value.toInt()) { - return '${timeSeries[value.toInt()].time.month}/ ${timeSeries[value.toInt()].time.year}'; - } else - return ''; - } else { - if (value.toInt() == 0) return '${timeSeries[value.toInt()].time.month}/ ${timeSeries[value.toInt()].time.year}'; - if (value.toInt() == timeSeries.length - 1) return '${timeSeries[value.toInt()].time.month}/ ${timeSeries[value.toInt()].time.year}'; - if (xAxixs.contains(value.toInt())) { - return '${timeSeries[value.toInt()].time.month}/ ${timeSeries[value.toInt()].time.year}'; + bottomTitles: AxisTitles( + sideTitles: SideTitles( + showTitles: true, + // getTextStyles: (cxt, value) => const TextStyle( + // color: Colors.black, + // fontSize: 10, + // ), + + getTitlesWidget: (value, title) { + TextStyle style = TextStyle( + color: Colors.black, + fontSize: 10, + ); + + if (timeSeries.length < 15) { + if (timeSeries.length > value.toInt()) { + return Text( + '${timeSeries[value.toInt()].time.month}/ ${timeSeries[value.toInt()].time.year}', + style: style, + ); + } else + return SizedBox(); + } else { + if (value.toInt() == 0) + return Text( + '${timeSeries[value.toInt()].time.month}/ ${timeSeries[value.toInt()].time.year}', + style: style, + ); + if (value.toInt() == timeSeries.length - 1) + return Text( + '${timeSeries[value.toInt()].time.month}/ ${timeSeries[value.toInt()].time.year}', + style: style, + ); + if (xAxixs.contains(value.toInt())) { + return Text( + '${timeSeries[value.toInt()].time.month}/ ${timeSeries[value.toInt()].time.year}', + style: style, + ); + } } - } - return ''; - }, + return SizedBox(); + }, + // rotateAngle: -65, + // margin: 22, + ), ), - leftTitles: SideTitles( - showTitles: true, - getTextStyles: (cxt, value) => const TextStyle( - color: Colors.black, - fontWeight: FontWeight.bold, - fontSize: 10, + leftTitles: AxisTitles( + sideTitles: SideTitles( + showTitles: true, + /* getTextStyles: (cxt, value) => const TextStyle( + color: Colors.black, + fontWeight: FontWeight.bold, + fontSize: 10, + ),*/ + interval: 3.0, + // margin: 12, ), - interval: 3.0, - margin: 12, ), ), borderData: FlBorderData( @@ -239,7 +263,7 @@ class LineChartCurved extends StatelessWidget { final LineChartBarData lineChartBarData1 = LineChartBarData( spots: spots, isCurved: true, - colors: [secondaryColor!], + color: secondaryColor, barWidth: 1.5, isStrokeCapRound: true, dotData: FlDotData( diff --git a/lib/pages/medical/vital_sign/LineChartCurvedBloodPressure.dart b/lib/pages/medical/vital_sign/LineChartCurvedBloodPressure.dart index ec76a391..7bcf8977 100644 --- a/lib/pages/medical/vital_sign/LineChartCurvedBloodPressure.dart +++ b/lib/pages/medical/vital_sign/LineChartCurvedBloodPressure.dart @@ -13,8 +13,8 @@ class LineChartCurvedBloodPressure extends StatelessWidget { LineChartCurvedBloodPressure({required this.title, required this.timeSeries1, required this.indexes, required this.timeSeries2}); - List xAxixs =[]; - List yAxixs =[]; + List xAxixs = []; + List yAxixs = []; @override Widget build(BuildContext context) { @@ -58,7 +58,7 @@ class LineChartCurvedBloodPressure extends StatelessWidget { padding: const EdgeInsets.only(right: 18.0, left: 16.0, top: 15), child: LineChart( sampleData1(context), - swapAnimationDuration: const Duration(milliseconds: 250), + duration: const Duration(milliseconds: 250), ), ), ), @@ -147,43 +147,63 @@ class LineChartCurvedBloodPressure extends StatelessWidget { ), gridData: FlGridData(show: true, drawVerticalLine: true, drawHorizontalLine: true, horizontalInterval: 14, verticalInterval: 14), titlesData: FlTitlesData( - bottomTitles: SideTitles( - showTitles: true, - getTextStyles: (cxt, value) => const TextStyle( - color: Colors.black, - fontSize: 10, - ), - rotateAngle: -65, - margin: 22, - getTitles: (value) { - if (timeSeries1.length < 15) { - if (timeSeries1.length > value.toInt()) { - return '${timeSeries1[value.toInt()].time.month}/ ${timeSeries1[value.toInt()].time.year}'; - } else - return ''; - } else { - if (value.toInt() == 0) return '${timeSeries1[value.toInt()].time.month}/ ${timeSeries1[value.toInt()].time.year}'; - if (value.toInt() == timeSeries1.length - 1) return '${timeSeries1[value.toInt()].time.month}/ ${timeSeries1[value.toInt()].time.year}'; - if (xAxixs.contains(value.toInt())) { - return '${timeSeries1[value.toInt()].time.month}/ ${timeSeries1[value.toInt()].time.year}'; + bottomTitles: AxisTitles( + sideTitles: SideTitles( + showTitles: true, + getTitlesWidget: (value, title) { + TextStyle style = TextStyle( + color: Colors.black, + fontSize: 10, + ); + + if (timeSeries1.length < 15) { + if (timeSeries1.length > value.toInt()) { + return Text( + '${timeSeries1[value.toInt()].time.month}/ ${timeSeries1[value.toInt()].time.year}', + style: style, + ); + } else + return SizedBox(); + } else { + if (value.toInt() == 0) + return Text( + '${timeSeries1[value.toInt()].time.month}/ ${timeSeries1[value.toInt()].time.year}', + style: style, + ); + if (value.toInt() == timeSeries1.length - 1) + return Text( + '${timeSeries1[value.toInt()].time.month}/ ${timeSeries1[value.toInt()].time.year}', + style: style, + ); + if (xAxixs.contains(value.toInt())) { + return Text( + '${timeSeries1[value.toInt()].time.month}/ ${timeSeries1[value.toInt()].time.year}', + style: style, + ); + } } - } - return ''; - }, + return SizedBox(); + }, + + // rotateAngle: -65, + // margin: 22, + ), ), - leftTitles: SideTitles( - showTitles: true, - getTextStyles: (cxt, value) => const TextStyle( - color: Colors.black, - fontWeight: FontWeight.bold, - fontSize: 10, + leftTitles: AxisTitles( + sideTitles: SideTitles( + showTitles: true, + // getTextStyles: (cxt, value) => const TextStyle( + // color: Colors.black, + // fontWeight: FontWeight.bold, + // fontSize: 10, + // ), + interval: getMaxY() - getMinY() <= 500 + ? 50 + : getMaxY() - getMinY() <= 1000 + ? 100 + : 200, + // margin: 12, ), - interval: getMaxY() - getMinY() <= 500 - ? 50 - : getMaxY() - getMinY() <= 1000 - ? 100 - : 200, - margin: 12, ), ), borderData: FlBorderData( @@ -243,12 +263,12 @@ class LineChartCurvedBloodPressure extends StatelessWidget { } List getData(context) { - List spots =[]; + List spots = []; for (int index = 0; index < timeSeries1.length; index++) { spots.add(FlSpot(index.toDouble(), timeSeries1[index].sales)); } - List spots2 =[]; + List spots2 = []; for (int index = 0; index < timeSeries2.length; index++) { spots2.add(FlSpot(index.toDouble(), timeSeries2[index].sales)); } @@ -256,7 +276,7 @@ class LineChartCurvedBloodPressure extends StatelessWidget { final LineChartBarData lineChartBarData1 = LineChartBarData( spots: spots, isCurved: true, - colors: [Colors.red], + color: Colors.red, barWidth: 1.5, isStrokeCapRound: true, dotData: FlDotData( @@ -269,7 +289,7 @@ class LineChartCurvedBloodPressure extends StatelessWidget { final LineChartBarData lineChartBarData2 = LineChartBarData( spots: spots2, isCurved: true, - colors: [Theme.of(context).primaryColor], + color: Theme.of(context).primaryColor, barWidth: 1.5, isStrokeCapRound: true, dotData: FlDotData( diff --git a/lib/widgets/charts/custom_line_chart.dart b/lib/widgets/charts/custom_line_chart.dart index 7176846d..8eaa415d 100644 --- a/lib/widgets/charts/custom_line_chart.dart +++ b/lib/widgets/charts/custom_line_chart.dart @@ -71,24 +71,33 @@ class _CustomLineChartState extends State { LineChartData mainData() { SideTitles right = SideTitles( showTitles: true, - margin: 0, + //margin: 0, reservedSize: 8, - getTitles: (value) { - return ''; + + getTitlesWidget: (value, titile) { + TextStyle style = TextStyle(color: Color(0xff2E303A), fontWeight: FontWeight.w600, fontSize: 12, letterSpacing: 0); + return Text(''); }, ); SideTitles left = SideTitles( showTitles: true, interval: 1, - getTextStyles: (cxt, value) => const TextStyle(color: Color(0xff2E303A), fontWeight: FontWeight.w600, fontSize: 12, letterSpacing: 0), - getTitles: (value) { + getTitlesWidget: (value, titile) { + TextStyle style = TextStyle(color: Color(0xff2E303A), fontWeight: FontWeight.w600, fontSize: 12, letterSpacing: 0); if (widget.list.isEmpty) { - return (value).toInt().toString(); + return Text( + (value).toInt().toString(), + style: style, + ); } - return (value * 20).toInt().toString(); + return Text( + (value * 20).toInt().toString(), + style: style, + ); }, + reservedSize: 22, - margin: 12, + // margin: 12, ); return LineChartData( lineTouchData: LineTouchData(enabled: false), @@ -103,21 +112,34 @@ class _CustomLineChartState extends State { }, ), titlesData: FlTitlesData( - show: true, - topTitles: SideTitles(showTitles: false), - bottomTitles: SideTitles( + show: true, + topTitles: AxisTitles( + sideTitles: SideTitles(showTitles: false), + ), + bottomTitles: AxisTitles( + sideTitles: SideTitles( showTitles: true, reservedSize: 22, interval: 1, - getTextStyles: (cxt, value) => const TextStyle(color: Color(0xff2E303A), fontWeight: FontWeight.w600, fontSize: 12, letterSpacing: 0), - getTitles: (value) { + getTitlesWidget: (value, title) { + TextStyle style = TextStyle(color: Color(0xff2E303A), fontWeight: FontWeight.w600, fontSize: 12, letterSpacing: 0); String _title = list[value.toInt()].title; - return (_title.length > 3 ? (widget.isArabic ? _title : _title.substring(0, 3)) : _title).toUpperCase(); + return Text( + (_title.length > 3 ? (widget.isArabic ? _title : _title.substring(0, 3)) : _title).toUpperCase(), + style: style, + ); }, - margin: 12, + + // margin: 12, ), - rightTitles: widget.isArabic ? left : right, - leftTitles: widget.isArabic ? right : left), + ), + rightTitles: AxisTitles( + sideTitles: widget.isArabic ? left : right, + ), + leftTitles: AxisTitles( + sideTitles: widget.isArabic ? right : left, + ), + ), borderData: FlBorderData( show: true, border: Border.symmetric( diff --git a/lib/widgets/charts/show_chart.dart b/lib/widgets/charts/show_chart.dart index 4390401a..3128734f 100644 --- a/lib/widgets/charts/show_chart.dart +++ b/lib/widgets/charts/show_chart.dart @@ -64,7 +64,7 @@ class ShowChart extends StatelessWidget { padding: const EdgeInsets.only(right: 18.0, left: 16.0), child: LineChart( sampleData1(context), - swapAnimationDuration: const Duration(milliseconds: 250), + duration: const Duration(milliseconds: 250), ), ), ), @@ -108,49 +108,78 @@ class ShowChart extends StatelessWidget { ), gridData: FlGridData(show: true, drawVerticalLine: true, drawHorizontalLine: true), titlesData: FlTitlesData( - bottomTitles: SideTitles( - showTitles: true, - getTextStyles: (cxt, value) => const TextStyle( - color: Colors.black, - fontSize: 10, - ), - rotateAngle: -65, - margin: 22, - getTitles: (value) { - if (isWeeklyOrMonthly) { - return '${timeSeries![value.toInt()].time.day}/ ${timeSeries![value.toInt()].time.month}'; - } else { - if (timeSeries!.length < 15) { - if (timeSeries!.length > value.toInt()) { - return '${timeSeries![value.toInt()].time.month}/ ${timeSeries![value.toInt()].time.year}'; - } else - return ''; + bottomTitles: AxisTitles( + sideTitles: SideTitles( + showTitles: true, + getTitlesWidget: (value, title) { + TextStyle style = TextStyle( + color: Colors.black, + fontSize: 10, + ); + + if (isWeeklyOrMonthly) { + return Text( + '${timeSeries![value.toInt()].time.day}/ ${timeSeries![value.toInt()].time.month}', + style: style, + ); } else { - if (value.toInt() == 0) return '${timeSeries![value.toInt()].time.month}/ ${timeSeries![value.toInt()].time.year}'; - if (value.toInt() == timeSeries!.length - 1) return '${timeSeries![value.toInt()].time.month}/ ${timeSeries![value.toInt()].time.year}'; - if (xAxixs.contains(value.toInt())) { - return '${timeSeries![value.toInt()].time.month}/ ${timeSeries![value.toInt()].time.year}'; + if (timeSeries!.length < 15) { + if (timeSeries!.length > value.toInt()) { + return Text( + '${timeSeries![value.toInt()].time.month}/ ${timeSeries![value.toInt()].time.year}', + style: style, + ); + } else + return SizedBox(); + } else { + if (value.toInt() == 0) + return Text( + '${timeSeries![value.toInt()].time.month}/ ${timeSeries![value.toInt()].time.year}', + style: style, + ); + if (value.toInt() == timeSeries!.length - 1) + return Text( + '${timeSeries![value.toInt()].time.month}/ ${timeSeries![value.toInt()].time.year}', + style: style, + ); + if (xAxixs.contains(value.toInt())) { + return Text( + '${timeSeries![value.toInt()].time.month}/ ${timeSeries![value.toInt()].time.year}', + style: style, + ); + } } + return SizedBox(); } - return ''; - } - }, + }, + + // rotateAngle: -65, + // margin: 22, + ), ), - leftTitles: SideTitles( - showTitles: true, - getTextStyles: (cxt, value) => const TextStyle( - color: Colors.black, - fontWeight: FontWeight.bold, - fontSize: 10, + leftTitles: AxisTitles( + sideTitles: SideTitles( + showTitles: true, + getTitlesWidget: (cxt, value) { + var style = TextStyle( + color: Colors.black, + fontWeight: FontWeight.bold, + fontSize: 10, + ); + return Text( + "", + style: style, + ); + }, + interval: _fetchLeftTileInterval(), + //margin: 12, ), - interval: _fetchLeftTileInterval(), - margin: 12, ), - topTitles: SideTitles( - showTitles: false + topTitles: AxisTitles( + sideTitles: SideTitles(showTitles: false), ), - rightTitles: SideTitles( - showTitles: false + rightTitles: AxisTitles( + sideTitles: SideTitles(showTitles: false), ), ), borderData: FlBorderData( @@ -188,7 +217,7 @@ class ShowChart extends StatelessWidget { increasingY = ((maxY - minY) / timeSeries!.length - 1) * 15; maxY += increasingY.abs(); minY -= increasingY.abs(); - } catch(ex) { + } catch (ex) { print(ex); } } @@ -252,7 +281,7 @@ class ShowChart extends StatelessWidget { } List getData(context) { - List spots =[]; + List spots = []; for (int index = 0; index < timeSeries!.length; index++) { spots.add(FlSpot(index.toDouble(), timeSeries![index].sales)); } @@ -260,7 +289,7 @@ class ShowChart extends StatelessWidget { final LineChartBarData lineChartBarData1 = LineChartBarData( spots: spots, isCurved: true, - colors: [secondaryColor!], + color: secondaryColor, barWidth: 1.5, isStrokeCapRound: true, dotData: FlDotData( diff --git a/lib/widgets/data_display/medical/LabResult/LineChartCurved.dart b/lib/widgets/data_display/medical/LabResult/LineChartCurved.dart index f939e2ae..8d7ebda5 100644 --- a/lib/widgets/data_display/medical/LabResult/LineChartCurved.dart +++ b/lib/widgets/data_display/medical/LabResult/LineChartCurved.dart @@ -59,7 +59,7 @@ class LineChartCurvedState extends State { padding: EdgeInsets.only(right: 16.0, left: 6.0), child: LineChart( sampleData1(), - swapAnimationDuration: const Duration(milliseconds: 250), + duration: const Duration(milliseconds: 250), ), ), ), @@ -81,40 +81,60 @@ class LineChartCurvedState extends State { ), gridData: FlGridData(show: true, drawVerticalLine: false, drawHorizontalLine: true), titlesData: FlTitlesData( - bottomTitles: SideTitles( - showTitles: true, - getTextStyles: (cxt, value) => TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Color(0xff2E303A), letterSpacing: 0, height: 18 / 12), - margin: 8, - rotateAngle: -0, - getTitles: (value) { - print(value); - DateTime date = DateUtil.convertStringToDate(widget.labResult![value.toInt()]!.verifiedOnDateTime!); - if (widget.labResult!.length < 8) { - if (widget.labResult!.length > value.toInt()) { - return '${date.day}/ ${date.year}'; - } else - return ''; - } else { - if (value.toInt() == 0) return '${date.day}/ ${date.year}'; - if (value.toInt() == widget.labResult!.length - 1) return '${date.day}/ ${date.year}'; - if (xAxixs.contains(value.toInt())) { - return '${date.day}/ ${date.year}'; + bottomTitles: AxisTitles( + sideTitles: SideTitles( + showTitles: true, + getTitlesWidget: (value, titile) { + TextStyle style = TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Color(0xff2E303A), letterSpacing: 0, height: 18 / 12); + print(value); + DateTime date = DateUtil.convertStringToDate(widget.labResult![value.toInt()].verifiedOnDateTime!); + if (widget.labResult!.length < 8) { + if (widget.labResult!.length > value.toInt()) { + return Text( + '${date.day}/ ${date.year}', + style: style, + ); + } else + return SizedBox(); + } else { + if (value.toInt() == 0) + return Text( + '${date.day}/ ${date.year}', + style: style, + ); + if (value.toInt() == widget.labResult!.length - 1) + return Text( + '${date.day}/ ${date.year}', + style: style, + ); + if (xAxixs.contains(value.toInt())) { + return Text( + '${date.day}/ ${date.year}', + style: style, + ); + } } - } - return ''; - }, + return SizedBox(); + }, + // margin: 8, + // rotateAngle: -0, + ), ), - leftTitles: SideTitles( - showTitles: true, - getTextStyles: (cxt, value) => TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Color(0xff2E303A), letterSpacing: 0, height: 18 / 12), - - getTitles: (value) { - return '${value}'; - }, - margin: 8, - interval: getInterval(), - //reservedSize: 30, + leftTitles: AxisTitles( + sideTitles: SideTitles( + showTitles: true, + getTitlesWidget: (value, title) { + TextStyle style = TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Color(0xff2E303A), letterSpacing: 0, height: 18 / 12); + return Text( + '${value}', + style: style, + ); + }, + // margin: 8, + interval: getInterval(), + //reservedSize: 30, + ), ), ), borderData: FlBorderData( @@ -183,7 +203,7 @@ class LineChartCurvedState extends State { } List getData() { - List spots =[]; + List spots = []; for (int index = 0; index < widget.labResult!.length; index++) { try { var resultValueDouble = double.parse(widget.labResult![index].resultValue!); @@ -199,7 +219,7 @@ class LineChartCurvedState extends State { spots: spots, isCurved: true, //preventCurveOverShooting : true, - colors: [Color(0xffD02127)], + color: Color(0xffD02127), barWidth: 1.5, isStrokeCapRound: true, dotData: FlDotData( diff --git a/lib/widgets/others/app_scaffold_widget.dart b/lib/widgets/others/app_scaffold_widget.dart index 97d302b2..0d12774f 100644 --- a/lib/widgets/others/app_scaffold_widget.dart +++ b/lib/widgets/others/app_scaffold_widget.dart @@ -76,7 +76,7 @@ class AppScaffold extends StatefulWidget { final int? dropdownIndexValue; List? dropDownList; final void Function(int?)? dropDownIndexChange; - final VoidCallbackAction? onTap; + final Function? onTap; final bool isMainPharmacyPages; final bool extendBody; final ValueChanged? changeCurrentTab; @@ -242,7 +242,9 @@ class _AppScaffoldState extends State { dropDownList: widget.dropDownList! ?? [], dropDownIndexChange: widget.dropDownIndexChange, appBarIcons: widget.appBarIcons!, - onTap:widget.onTap, + onTap: () { + widget.onTap; + }, )) : (widget.isShowAppBar! ? widget.customAppBar != null @@ -256,7 +258,9 @@ class _AppScaffoldState extends State { isOfferPackages: widget.isOfferPackages!, showOfferPackagesCart: widget.showOfferPackagesCart!, isShowDecPage: widget.isShowDecPage!, - backButtonTab: widget.backButtonTab!, + backButtonTab: () { + widget.backButtonTab; + }, ) : null)), bottomSheet: widget.bottomSheet, @@ -338,8 +342,8 @@ class NewAppBarWidget extends StatelessWidget implements PreferredSizeWidget { List? dropDownList; final void Function(int?)? dropDownIndexChange; final List? appBarIcons; - - VoidCallbackAction? onTap; + + Function? onTap; NewAppBarWidget({Key? key, this.showTitle = false, this.showDropDown = false, this.title = "", this.dropDownList, this.appBarIcons, this.dropdownIndexValue, this.dropDownIndexChange, this.onTap}) : super(key: key); @@ -354,7 +358,9 @@ class NewAppBarWidget extends StatelessWidget implements PreferredSizeWidget { // backgroundColor: Colors.red, // automaticallyImplyLeading: false, leading: ArrowBack( - onTap: onTap!, + onTap: () { + onTap; + }, ), titleSpacing: -8, // centerTitle: false, @@ -443,7 +449,7 @@ class AppBarWidget extends StatefulWidget implements PreferredSizeWidget { final bool showOfferPackagesCart; final bool isShowDecPage; - final VoidCallbackAction? backButtonTab; + final Function()? backButtonTab; Function(String)? badgeUpdater; AppBarWidget( diff --git a/lib/widgets/others/arrow_back.dart b/lib/widgets/others/arrow_back.dart index ac0258a5..adf1bda3 100644 --- a/lib/widgets/others/arrow_back.dart +++ b/lib/widgets/others/arrow_back.dart @@ -3,7 +3,7 @@ import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; class ArrowBack extends StatelessWidget { - final VoidCallbackAction? onTap; + final Function? onTap; ArrowBack({Key? key, this.onTap,}) : super(key: key); diff --git a/pubspec.yaml b/pubspec.yaml index 75b516fd..86841913 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -14,8 +14,8 @@ dependencies: flutter_localizations: sdk: flutter intl: ^0.18.1 - # web view - # webview_flutter: ^2.3.1 + + webview_flutter: ^2.0.4 # http client http: ^0.13.4 @@ -25,7 +25,7 @@ dependencies: audio_wave: ^0.1.4 # audio_session: ^0.1.13 # State Management - provider: ^6.0.1 + provider: ^6.0.5 #Dependency Injection get_it: ^7.2.0 @@ -34,7 +34,7 @@ dependencies: health: ^3.0.3 #chart - fl_chart: 0.45.0 + fl_chart: ^0.64.0 #Camera Preview @@ -44,7 +44,7 @@ dependencies: permission_handler: ^11.0.1 # Flutter Html View - flutter_html: ^2.2.1 + flutter_html: ^3.0.0-beta.2 # Pagnation pull_to_refresh: ^2.0.0 @@ -109,7 +109,7 @@ dependencies: syncfusion_flutter_calendar: ^23.1.42 # SVG Images - # flutter_svg: ^0.23.0+1 + flutter_svg: ^2.0.8 #Calendar Events manage_calendar_events: ^2.0.1 @@ -127,7 +127,8 @@ dependencies: hijri: ^3.0.0 #datetime_picker - flutter_datetime_picker: ^1.5.1 + #flutter_datetime_picker: ^1.5.1 + flutter_datetime_picker_plus: ^2.1.0 # Carousel # carousel_pro: ^1.0.0 //8/oct carousel_pro_nullsafety: ^2.0.0 @@ -218,9 +219,9 @@ dependencies: # crypto: dependency_overrides: - provider: ^5.0.0 + #provider: ^5.0.0 # permission_handler : ^10.2.0 - flutter_svg: ^1.1.6 + #flutter_svg: ^1.1.6 # firebase_messaging_platform_interface: any # flutter_inappwebview: 5.7.2+3 # git: diff --git a/speech_to_text/.github/workflows/master.yml b/speech_to_text/.github/workflows/master.yml deleted file mode 100644 index 4d4cff1c..00000000 --- a/speech_to_text/.github/workflows/master.yml +++ /dev/null @@ -1,19 +0,0 @@ -name: build - -on: - push: - branches: - - master - -jobs: - test: - name: Test on Ubuntu - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v1 - - uses: subosito/flutter-action@v1.3.2 - with: - flutter-version: '1.17.1' - channel: 'stable' - - run: flutter pub get - - run: flutter test diff --git a/speech_to_text/.gitignore b/speech_to_text/.gitignore deleted file mode 100644 index 8969cbcd..00000000 --- a/speech_to_text/.gitignore +++ /dev/null @@ -1,11 +0,0 @@ -.DS_Store -.dart_tool/ - -.packages -.pub/ - -build/ -coverage/ -example/.flutter-plugins-dependencies -**/ios/Flutter/flutter_export_environment.sh -android/.idea/ diff --git a/speech_to_text/.metadata b/speech_to_text/.metadata deleted file mode 100644 index 1940d996..00000000 --- a/speech_to_text/.metadata +++ /dev/null @@ -1,10 +0,0 @@ -# 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: 2d2a1ffec95cc70a3218872a2cd3f8de4933c42f - channel: stable - -project_type: plugin diff --git a/speech_to_text/CHANGELOG.md b/speech_to_text/CHANGELOG.md deleted file mode 100644 index 477e110c..00000000 --- a/speech_to_text/CHANGELOG.md +++ /dev/null @@ -1,166 +0,0 @@ -# Changelog - -## 2.3.0 - -### New - * new parameter `onDevice` on the `listen` method enforces on device recognition for sensitive content - * onSoundLevelChange now supported on iOS - * added compile troubleshooting help to README.md - * `SpeechToTextProvider` is an alternate and simpler way to interact with the `SpeechToText` plugin. - * new `provider_example.dart` example for usage of `SpeechToTextProvider`. -### Fix - * on iOS handles some conflicts with other applications better to keep speech working after calls for example - - -## 2.2.0 - -### New - * improved error handling and logging in the iOS implementation - * added general guides for iOS to the README - * moved stress testing out of the main example - * iOS now defaults to using the speaker rather than the receiver for start /stop sounds when no headphones -### Fix - * iOS now properly deactivates the audio session when no longer listening - * start and stop sounds on iOS should be more reliable when available - -## 2.1.0 -### Breaking - * `listenFor` now calls `stop` rather than `cancel` as this seems like more useful behaviour - -### Fix - * Android no longer stops or cancels the speech recognizer if it has already been shutdown by a - timeout or other platform behaviour. - * Android no longer tries to restart the listener when it is already active - * Now properly notifies errors that happen after listening stops due to platform callback rather than - client request. See https://github.com/csdcorp/speech_to_text/issues/51 - -## 2.0.1 -### Fix - * Resolves an issue with the Android implementation not handling permission requests properly on apps - that didn't use the 1.12.x plugin APIs for registration. The permission dialog would not appear and - permission was denied. - - -## 2.0.0 - -### Breaking - - * Upgraded to New Swift 1.12 plugin structure, may work with older Flutter version but not guaranteed - -### New - - * the plugin now requests both speech and microphone permission on initialize on iOS - * added `debugLogging` parameter to the `initialize` method to control native logging - -### Fix - - * The Android implementation now blocks duplicate results notifications. It appears that at least on some - Android versions the final results notification onResults is notified twice when Android automatically - terminates the session due to a pause time. The de-duplication looks for successive notifications - with < 100 ms between them and blocks the second. If you miss any onResult notifications please post - an issue. - -## 1.1.0 - -### New - - * error_timeout has been separated into error_network_timeout and error_speech_timeout - -## 1.0.0 - -### New - * hasPermission to check for the current permission without bringing up the system dialog - * `listen` has a new optional `cancelOnError` parameter to support automatically canceling - a listening session on a permanent error. - * `listen` has a new optional `partialResults` parameter that controls whether the callback - receives partial or only final results. - -## 0.8.0 - -### New - - * speech recognizer now exposes multiple possible transcriptions for each recognized speech - * alternates list on SpeechRecognitionResult exposes alternate transcriptions of voice - * confidence on SpeechRecognitionResult gives an estimate of confidence in the transcription - * isConfident on SpeechRecognitionResult supports testing confidence - * hasConfidenceRating on SpeechRecognitionResult indicates if confidence was provided from the device - * new SpeechRecognitionWords class gives details on per transcription words and confidence - -### Fix - - * speechRecognizer availabilityDidChange was crashing if invoked due to an invalid parameter type - * Added iOS platform 10 to example Podfile to resolve compilation warnings - -## 0.7.2 - -### Breaking - - * Upgrade Swift to version 5 to match Flutter. Projects using this plugin must now switch to 5. - -## 0.7.1 - -### Fix - - * Upgrade Kotlin to 1.3.5 to match the Flutter 1.12 version - * Upgrade Gradle build to 3.5.0 to match the Flutter 1.12 version - * Android version of the plugin was repeating the system default locale in the `locales` list - -## 0.7.0 - -### New - - * locales method returns the list of available languages for speech - * new optional localeId parameter on listen method supports choosing the comprehension language separately from the current system locale. - -### Breaking - - * `cancel` and `stop` are now async - -## 0.6.3 - -### Fix - - * request permission fix on Android to ensure it doesn't conflict with other requests - -## 0.6.2 - -### Fix - - * channel invoke wasn't being done on the main thread in iOS - -## 0.6.1 - -### Fix - - * listening sound was failing due to timing, now uses play and record mode on iOS. - - ## 0.6.0 -### Breaking - - * The filenames for the optional sounds for iOS have changed. - -### New - - * Added an optional listenFor parameter to set a max duration to listen for speech and then automatically cancel. - -### Fix - - * Was failing to play sounds because of record mode. Now plays sounds before going into record mode and after coming out. - * Status listener was being ignored, now properly notifies on status changes. - -## 0.5.1 - * Fixes a problem where the recognizer left the AVAudioSession in record mode which meant that subsequent sounds couldn't be played. - -## 0.5.0 -Initial draft with limited functionality, supports: - * initializing speech recognition - * asking the user for permission if required - * listening for recognized speech - * canceling the current recognition session - * stopping the current recognition session -* Android and iOS 10+ support - -Missing: - * some error handling - * testing across multiple OS versions - * and more, to be discovered... diff --git a/speech_to_text/LICENSE b/speech_to_text/LICENSE deleted file mode 100644 index 7c3991c8..00000000 --- a/speech_to_text/LICENSE +++ /dev/null @@ -1,29 +0,0 @@ -BSD 3-Clause License - -Copyright (c) 2019, Corner Software Development Corp. -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/speech_to_text/README.md b/speech_to_text/README.md deleted file mode 100644 index af726f0e..00000000 --- a/speech_to_text/README.md +++ /dev/null @@ -1,150 +0,0 @@ -# speech_to_text - -[![pub package](https://img.shields.io/badge/pub-v2.3.0-blue)](https://pub.dartlang.org/packages/speech_to_text) [![build status](https://github.com/csdcorp/speech_to_text/workflows/build/badge.svg)](https://github.com/csdcorp/speech_to_text/actions?query=workflow%3Abuild) - -A library that exposes device specific speech recognition capability. - -This plugin contains a set of classes that make it easy to use the speech recognition -capabilities of the mobile device in Flutter. It supports both Android and iOS. The -target use cases for this library are commands and short phrases, not continuous spoken -conversion or always on listening. - -## Recent Updates - -The 2.3.0 version adds `SpeechToTextProvider` as a simpler way to interact with the plugin. Checkout -the new `provider_example.dart` for intended usage. - -The 2.2.0 version improves audio session handling and start / stop sound playback on iOS. - -*Note*: Feedback from any test devices is welcome. - -## Using - -To recognize text from the microphone import the package and call the plugin, like so: - -```dart -import 'package:speech_to_text/speech_to_text.dart' as stt; - - stt.SpeechToText speech = stt.SpeechToText(); - bool available = await speech.initialize( onStatus: statusListener, onError: errorListener ); - if ( available ) { - speech.listen( onResult: resultListener ); - } - else { - print("The user has denied the use of speech recognition."); - } - // some time later... - speech.stop() -``` - -### Initialize once -The `initialize` method only needs to be called once per application session. After that `listen`, -`start`, `stop`, and `cancel` can be used to interact with the plugin. Subsequent calls to `initialize` -are ignored which is safe but does mean that the `onStatus` and `onError` callbacks cannot be reset after -the first call to `initialize`. For that reason there should be only one instance of the plugin per -application. The `SpeechToTextProvider` is one way to create a single instance and easily reuse it in -multiple widgets. - -## Permissions - -Applications using this plugin require user permissions. -### iOS - -Add the following keys to your _Info.plist_ file, located in `/ios/Runner/Info.plist`: - -* `NSSpeechRecognitionUsageDescription` - describe why your app uses speech recognition. This is called _Privacy - Speech Recognition Usage Description_ in the visual editor. -* `NSMicrophoneUsageDescription` - describe why your app needs access to the microphone. This is called _Privacy - Microphone Usage Description_ in the visual editor. - -### Android - -Add the record audio permission to your _AndroidManifest.xml_ file, located in `/android/app/src/main/AndroidManifest.xml`. - -* `android.permission.RECORD_AUDIO` - this permission is required for microphone access. -* `android.permission.INTERNET` - this permission is required because speech recognition may use remote services. - -## Adding Sounds for iOS (optional) - -Android automatically plays system sounds when speech listening starts or stops but iOS does not. This plugin supports playing sounds to indicate listening status on iOS if sound files are available as assets in the application. To enable sounds in an application using this plugin add the sound files to the project and reference them in the assets section of the application `pubspec.yaml`. The location and filenames of the sound files must exactly match what -is shown below or they will not be found. The example application for the plugin shows the usage. *Note* These files should be very short as they delay -the start / end of the speech recognizer until the sound playback is complete. -```yaml - assets: - - assets/sounds/speech_to_text_listening.m4r - - assets/sounds/speech_to_text_cancel.m4r - - assets/sounds/speech_to_text_stop.m4r -``` -* `speech_to_text_listening.m4r` - played when the listen method is called. -* `speech_to_text_cancel.m4r` - played when the cancel method is called. -* `speech_to_text_stop.m4r` - played when the stop method is called. - -## Troubleshooting - -### SDK version error trying to compile for Android -``` -Manifest merger failed : uses-sdk:minSdkVersion 16 cannot be smaller than version 21 declared in library [:speech_to_text] -``` -The speech_to_text plugin requires at least Android SDK 21 because some of the speech functions in Android -were only introduced in that version. To fix this error you need to change the `build.gradle` entry to reflect -this version. Here's what the relevant part of that file looked like as of this writing: -``` - defaultConfig { - applicationId "com.example.app" - minSdkVersion 21 - targetSdkVersion 28 - versionCode flutterVersionCode.toInteger() - versionName flutterVersionName - testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" - } -``` - -### Incorrect Swift version trying to compile for iOS -``` -/Users/markvandergon/flutter/.pub-cache/hosted/pub.dartlang.org/speech_to_text-1.1.0/ios/Classes/SwiftSpeechToTextPlugin.swift:224:44: error: value of type 'SwiftSpeechToTextPlugin' has no member 'AVAudioSession' - rememberedAudioCategory = self.AVAudioSession.Category - ~~~~ ^~~~~~~~~~~~~~ - /Users/markvandergon/flutter/.pub-cache/hosted/pub.dartlang.org/speech_to_text-1.1.0/ios/Classes/SwiftSpeechToTextPlugin.swift:227:63: error: type 'Int' has no member 'notifyOthersOnDeactivation' - try self.audioSession.setActive(true, withFlags: .notifyOthersOnDeactivation) -``` -This happens when the Swift language version is not set correctly. See this thread for help https://github.com/csdcorp/speech_to_text/issues/45. - -### Swift not supported trying to compile for iOS -``` -`speech_to_text` does not specify a Swift version and none of the targets (`Runner`) integrating it have the `SWIFT_VERSION` attribute set. -``` -This usually happens for older projects that only support Objective-C. See this thread for help https://github.com/csdcorp/speech_to_text/issues/88. - -### Not working on a particular Android device -The symptom for this issue is that the `initialize` method will always fail. If you turn on debug logging -using the `debugLogging: true` flag on the `initialize` method you'll see `'Speech recognition unavailable'` -in the Android log. There's a lengthy issue discussion here https://github.com/csdcorp/speech_to_text/issues/36 -about this. The issue seems to be that the recognizer is not always automatically enabled on the device. Two -key things helped resolve the issue in this case at least. - -#### First -1. Go to Google Play -2. Search for 'Google' -3. You should find this app: https://play.google.com/store/apps/details?id=com.google.android.googlequicksearchbox -If 'Disabled' enable it - -This is the SO post that helped: https://stackoverflow.com/questions/28769320/how-to-check-wether-speech-recognition-is-available-or-not - -#### Second -Ensure the app has the required permissions. The symptom for this that you get a permanent error notification - 'error_audio_error` when starting a listen session. Here's a Stack Overflow post that addresses that - https://stackoverflow.com/questions/46376193/android-speechrecognizer-audio-recording-error - Here's the important excerpt: - >You should go to system setting, Apps, Google app, then enable its permission of microphone. - -### iOS recognition guidelines -Apple has quite a good guide on the user experience for using speech, the original is here -https://developer.apple.com/documentation/speech/sfspeechrecognizer This is the section that I think is particularly relevant: - ->#### Create a Great User Experience for Speech Recognition ->Here are some tips to consider when adding speech recognition support to your app. - ->**Be prepared to handle failures caused by speech recognition limits.** Because speech recognition is a network-based service, limits are enforced so that the service can remain freely available to all apps. Individual devices may be limited in the number of recognitions that can be performed per day, and each app may be throttled globally based on the number of requests it makes per day. If a recognition request fails quickly (within a second or two of starting), check to see if the recognition service became unavailable. If it is, you may want to ask users to try again later. - ->**Plan for a one-minute limit on audio duration.** Speech recognition places a relatively high burden on battery life and network usage. To minimize this burden, the framework stops speech recognition tasks that last longer than one minute. This limit is similar to the one for keyboard-related dictation. -Remind the user when your app is recording. For example, display a visual indicator and play sounds at the beginning and end of speech recognition to help users understand that they're being actively recorded. You can also display speech as it is being recognized so that users understand what your app is doing and see any mistakes made during the recognition process. - ->**Do not perform speech recognition on private or sensitive information.** Some speech is not appropriate for recognition. Don't send passwords, health or financial data, and other sensitive speech for recognition. diff --git a/speech_to_text/android/.classpath b/speech_to_text/android/.classpath deleted file mode 100644 index eb19361b..00000000 --- a/speech_to_text/android/.classpath +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/speech_to_text/android/.gitignore b/speech_to_text/android/.gitignore deleted file mode 100644 index c6cbe562..00000000 --- a/speech_to_text/android/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -*.iml -.gradle -/local.properties -/.idea/workspace.xml -/.idea/libraries -.DS_Store -/build -/captures diff --git a/speech_to_text/android/.project b/speech_to_text/android/.project deleted file mode 100644 index 3050653c..00000000 --- a/speech_to_text/android/.project +++ /dev/null @@ -1,23 +0,0 @@ - - - speech_to_text - Project android_____ created by Buildship. - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.buildship.core.gradleprojectbuilder - - - - - - org.eclipse.jdt.core.javanature - org.eclipse.buildship.core.gradleprojectnature - - diff --git a/speech_to_text/android/.settings/org.eclipse.buildship.core.prefs b/speech_to_text/android/.settings/org.eclipse.buildship.core.prefs deleted file mode 100644 index 7a23d112..00000000 --- a/speech_to_text/android/.settings/org.eclipse.buildship.core.prefs +++ /dev/null @@ -1,13 +0,0 @@ -arguments= -auto.sync=false -build.scans.enabled=false -connection.gradle.distribution=GRADLE_DISTRIBUTION(VERSION(5.6.1)) -connection.project.dir= -eclipse.preferences.version=1 -gradle.user.home= -java.home= -jvm.arguments= -offline.mode=false -override.workspace.settings=true -show.console.view=true -show.executions.view=true diff --git a/speech_to_text/android/build.gradle b/speech_to_text/android/build.gradle deleted file mode 100644 index cc06ea57..00000000 --- a/speech_to_text/android/build.gradle +++ /dev/null @@ -1,44 +0,0 @@ -group 'com.csdcorp.speech_to_text' -version '1.0-SNAPSHOT' - -buildscript { - ext.kotlin_version = '1.3.50' - repositories { - google() - jcenter() - } - - dependencies { - classpath 'com.android.tools.build:gradle:3.5.0' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - } -} - -rootProject.allprojects { - repositories { - google() - jcenter() - } -} - -apply plugin: 'com.android.library' -apply plugin: 'kotlin-android' - -android { - compileSdkVersion 28 - - sourceSets { - main.java.srcDirs += 'src/main/kotlin' - } - defaultConfig { - minSdkVersion 18 - testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" - } - lintOptions { - disable 'InvalidPackage' - } -} - -dependencies { - implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" -} diff --git a/speech_to_text/android/gradle/gradle.properties b/speech_to_text/android/gradle/gradle.properties deleted file mode 100644 index 94adc3a3..00000000 --- a/speech_to_text/android/gradle/gradle.properties +++ /dev/null @@ -1,3 +0,0 @@ -org.gradle.jvmargs=-Xmx1536M -android.useAndroidX=true -android.enableJetifier=true diff --git a/speech_to_text/android/gradle/local.properties b/speech_to_text/android/gradle/local.properties deleted file mode 100644 index b85628e7..00000000 --- a/speech_to_text/android/gradle/local.properties +++ /dev/null @@ -1,2 +0,0 @@ -sdk.dir=/Users/stephen.owens/Library/Android/sdk -flutter.sdk=/Users/stephen.owens/Documents/dev/flutter/sdk/flutter \ No newline at end of file diff --git a/speech_to_text/android/gradle/settings.gradle b/speech_to_text/android/gradle/settings.gradle deleted file mode 100644 index cdfc1c4b..00000000 --- a/speech_to_text/android/gradle/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = 'speech_to_text' diff --git a/speech_to_text/android/gradle/wrapper/gradle-wrapper.properties b/speech_to_text/android/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 674bdda0..00000000 --- a/speech_to_text/android/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,5 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip diff --git a/speech_to_text/android/src/main/AndroidManifest.xml b/speech_to_text/android/src/main/AndroidManifest.xml deleted file mode 100644 index 61a73f32..00000000 --- a/speech_to_text/android/src/main/AndroidManifest.xml +++ /dev/null @@ -1,3 +0,0 @@ - - diff --git a/speech_to_text/android/src/main/kotlin/com/csdcorp/speech_to_text/SpeechToTextPlugin.kt b/speech_to_text/android/src/main/kotlin/com/csdcorp/speech_to_text/SpeechToTextPlugin.kt deleted file mode 100644 index 34562cdb..00000000 --- a/speech_to_text/android/src/main/kotlin/com/csdcorp/speech_to_text/SpeechToTextPlugin.kt +++ /dev/null @@ -1,605 +0,0 @@ -package com.csdcorp.speech_to_text - -import androidx.annotation.NonNull; -import io.flutter.embedding.engine.plugins.FlutterPlugin -import android.Manifest -import android.annotation.TargetApi -import android.app.Activity -import android.content.Intent -import android.content.pm.PackageManager -import android.os.Build -import android.os.Bundle -import android.speech.RecognitionListener -import android.speech.SpeechRecognizer.createSpeechRecognizer -import android.speech.RecognizerIntent -import android.speech.SpeechRecognizer -import androidx.core.app.ActivityCompat -import androidx.core.content.ContextCompat -import io.flutter.plugin.common.MethodCall -import io.flutter.plugin.common.MethodChannel -import io.flutter.plugin.common.MethodChannel.MethodCallHandler -import io.flutter.plugin.common.MethodChannel.Result -import io.flutter.plugin.common.PluginRegistry -import io.flutter.plugin.common.PluginRegistry.Registrar -import org.json.JSONObject -import android.content.Context -import android.content.BroadcastReceiver -import android.os.Handler -import android.os.Looper -import android.util.Log -import androidx.annotation.RequiresApi -import io.flutter.embedding.engine.plugins.activity.ActivityAware -import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding -import io.flutter.plugin.common.BinaryMessenger -import org.json.JSONArray -import java.util.* - - -enum class SpeechToTextErrors { - multipleRequests, - unimplemented, - noLanguageIntent, - recognizerNotAvailable, - missingOrInvalidArg, - unknown -} - -enum class SpeechToTextCallbackMethods { - textRecognition, - notifyStatus, - notifyError, - soundLevelChange, -} - -enum class SpeechToTextStatus { - listening, - notListening, - unavailable, - available, -} - -enum class ListenMode { - deviceDefault, - dictation, - search, - confirmation, -} - -const val pluginChannelName = "plugin.csdcorp.com/speech_to_text" - -@TargetApi(8) -/** SpeechToTextPlugin */ -public class SpeechToTextPlugin : - MethodCallHandler, RecognitionListener, - PluginRegistry.RequestPermissionsResultListener, FlutterPlugin, - ActivityAware { - private var pluginContext: Context? = null - private var channel: MethodChannel? = null - private val minSdkForSpeechSupport = 21 - private val speechToTextPermissionCode = 28521 - private val missingConfidence: Double = -1.0 - private val logTag = "SpeechToTextPlugin" - private var currentActivity: Activity? = null - private var activeResult: Result? = null - private var initializedSuccessfully: Boolean = false - private var permissionToRecordAudio: Boolean = false - private var listening = false - private var debugLogging: Boolean = false - private var speechRecognizer: SpeechRecognizer? = null - private var recognizerIntent: Intent? = null - private var previousRecognizerLang: String? = null - private var previousPartialResults: Boolean = true - private var previousListenMode: ListenMode = ListenMode.deviceDefault - private var lastFinalTime: Long = 0 - private val handler: Handler = Handler(Looper.getMainLooper()) - @RequiresApi(Build.VERSION_CODES.LOLLIPOP) - private val defaultLanguageTag: String = Locale.getDefault().toLanguageTag() - - override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { - - onAttachedToEngine(flutterPluginBinding.getApplicationContext(), flutterPluginBinding.getBinaryMessenger()); - } - - // This static function is optional and equivalent to onAttachedToEngine. It supports the old - // pre-Flutter-1.12 Android projects. You are encouraged to continue supporting - // plugin registration via this function while apps migrate to use the new Android APIs - // post-flutter-1.12 via https://flutter.dev/go/android-project-migration. - // - // It is encouraged to share logic between onAttachedToEngine and registerWith to keep - // them functionally equivalent. Only one of onAttachedToEngine or registerWith will be called - // depending on the user's project. onAttachedToEngine or registerWith must both be defined - // in the same class. - companion object { - @JvmStatic - fun registerWith(registrar: Registrar) { - val speechPlugin = SpeechToTextPlugin() - speechPlugin.currentActivity = registrar.activity() - registrar.addRequestPermissionsResultListener(speechPlugin) - speechPlugin.onAttachedToEngine(registrar.context(), registrar.messenger()) - } - } - - private fun onAttachedToEngine(applicationContext: Context, messenger: BinaryMessenger) { - this.pluginContext = applicationContext; - channel = MethodChannel(messenger, pluginChannelName) - channel?.setMethodCallHandler(this) - } - - override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) { - this.pluginContext = null; - channel?.setMethodCallHandler(null) - channel = null - } - - override fun onDetachedFromActivity() { - currentActivity = null - } - - override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) { - currentActivity = binding.activity - binding.addRequestPermissionsResultListener(this) - } - - override fun onAttachedToActivity(binding: ActivityPluginBinding) { - currentActivity = binding.activity - binding.addRequestPermissionsResultListener(this) - } - - override fun onDetachedFromActivityForConfigChanges() { - currentActivity = null - } - - @RequiresApi(Build.VERSION_CODES.LOLLIPOP) - override fun onMethodCall(@NonNull call: MethodCall, @NonNull rawrResult: Result) { - val result = ChannelResultWrapper(rawrResult) - try { - when (call.method) { - "has_permission" -> hasPermission(result) - "initialize" -> { - var dlog = call.argument("debugLogging") - if (null != dlog) { - debugLogging = dlog - } - initialize(result) - } - "listen" -> { - var localeId = call.argument("localeId") - if (null == localeId) { - localeId = defaultLanguageTag - } - var partialResults = call.argument("partialResults") - if (null == partialResults) { - partialResults = true - } - val listenModeIndex = call.argument("listenMode") - if ( null == listenModeIndex ) { - result.error(SpeechToTextErrors.missingOrInvalidArg.name, - "listenMode is required", null) - return - } - startListening(result, localeId, partialResults, listenModeIndex ) - } - "stop" -> stopListening(result) - "cancel" -> cancelListening(result) - "locales" -> locales(result) - else -> result.notImplemented() - } - } catch (exc: Exception) { - Log.e(logTag, "Unexpected exception", exc) - result.error(SpeechToTextErrors.unknown.name, - "Unexpected exception", exc.localizedMessage) - } - } - - private fun hasPermission(result: Result) { - if (sdkVersionTooLow(result)) { - return - } - debugLog("Start has_permission") - val localContext = pluginContext - if (localContext != null) { - val hasPerm = ContextCompat.checkSelfPermission(localContext, - Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED - result.success(hasPerm) - } - } - - @RequiresApi(Build.VERSION_CODES.LOLLIPOP) - private fun initialize(result: Result) { - if (sdkVersionTooLow(result)) { - return - } - debugLog("Start initialize") - if (null != activeResult) { - result.error(SpeechToTextErrors.multipleRequests.name, - "Only one initialize at a time", null) - return - } - activeResult = result - val localContext = pluginContext - initializeIfPermitted(pluginContext) - } - - private fun sdkVersionTooLow(result: Result): Boolean { - if (Build.VERSION.SDK_INT < minSdkForSpeechSupport) { - result.success(false) - return true; - } - return false; - } - - private fun isNotInitialized(result: Result): Boolean { - if (!initializedSuccessfully || null == pluginContext) { - result.success(false) - } - return !initializedSuccessfully - } - - private fun isListening(): Boolean { - return listening - } - - private fun isNotListening(): Boolean { - return !listening - } - - @RequiresApi(Build.VERSION_CODES.LOLLIPOP) - private fun startListening(result: Result, languageTag: String, partialResults: Boolean, - listenModeIndex: Int) { - if (sdkVersionTooLow(result) || isNotInitialized(result) || isListening()) { - return - } - debugLog("Start listening") - var listenMode = ListenMode.deviceDefault - if ( listenModeIndex == ListenMode.dictation.ordinal) { - listenMode = ListenMode.dictation - } - setupRecognizerIntent(languageTag, partialResults, listenMode) - handler.post { - run { - speechRecognizer?.startListening(recognizerIntent) - } - } - notifyListening(isRecording = true) - result.success(true) - debugLog("Start listening done") - } - - private fun stopListening(result: Result) { - if (sdkVersionTooLow(result) || isNotInitialized(result) || isNotListening()) { - return - } - debugLog("Stop listening") - handler.post { - run { - speechRecognizer?.stopListening() - } - } - notifyListening(isRecording = false) - result.success(true) - debugLog("Stop listening done") - } - - private fun cancelListening(result: Result) { - if (sdkVersionTooLow(result) || isNotInitialized(result) || isNotListening()) { - return - } - debugLog("Cancel listening") - handler.post { - run { - speechRecognizer?.cancel() - } - } - notifyListening(isRecording = false) - result.success(true) - debugLog("Cancel listening done") - } - - private fun locales(result: Result) { - if (sdkVersionTooLow(result) || isNotInitialized(result)) { - return - } - var detailsIntent = RecognizerIntent.getVoiceDetailsIntent(pluginContext) - if (null == detailsIntent) { - detailsIntent = Intent(RecognizerIntent.ACTION_GET_LANGUAGE_DETAILS) - } - if (null == detailsIntent) { - result.error(SpeechToTextErrors.noLanguageIntent.name, - "Could not get voice details", null) - return - } - pluginContext?.sendOrderedBroadcast( - detailsIntent, null, LanguageDetailsChecker(result), - null, Activity.RESULT_OK, null, null) - } - - private fun notifyListening(isRecording: Boolean) { - debugLog("Notify listening") - listening = isRecording - val status = when (isRecording) { - true -> SpeechToTextStatus.listening.name - false -> SpeechToTextStatus.notListening.name - } - channel?.invokeMethod(SpeechToTextCallbackMethods.notifyStatus.name, status) - debugLog("Notify listening done") - } - - private fun updateResults(speechBundle: Bundle?, isFinal: Boolean) { - if (isDuplicateFinal( isFinal )) { - debugLog("Discarding duplicate final") - return - } - val userSaid = speechBundle?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION) - if (null != userSaid && userSaid.isNotEmpty()) { - val speechResult = JSONObject() - speechResult.put("finalResult", isFinal) - val confidence = speechBundle?.getFloatArray(SpeechRecognizer.CONFIDENCE_SCORES) - val alternates = JSONArray() - for (resultIndex in 0..userSaid.size - 1) { - val speechWords = JSONObject() - speechWords.put("recognizedWords", userSaid[resultIndex]) - if (null != confidence && confidence.size >= userSaid.size) { - speechWords.put("confidence", confidence[resultIndex]) - } else { - speechWords.put("confidence", missingConfidence) - } - alternates.put(speechWords) - } - speechResult.put("alternates", alternates) - val jsonResult = speechResult.toString() - debugLog("Calling results callback") - channel?.invokeMethod(SpeechToTextCallbackMethods.textRecognition.name, - jsonResult) - } - } - - private fun isDuplicateFinal( isFinal: Boolean ) : Boolean { - if ( !isFinal ) { - return false - } - val delta = System.currentTimeMillis() - lastFinalTime - lastFinalTime = System.currentTimeMillis() - return delta >= 0 && delta < 100 - } - - @RequiresApi(Build.VERSION_CODES.LOLLIPOP) - private fun initializeIfPermitted(context: Context?) { - val localContext = context - if (null == localContext) { - completeInitialize() - return - } - permissionToRecordAudio = ContextCompat.checkSelfPermission(localContext, - Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED - debugLog("Checked permission") - if (!permissionToRecordAudio) { - val localActivity = currentActivity - if (null != localActivity) { - debugLog("Requesting permission") - ActivityCompat.requestPermissions(localActivity, - arrayOf(Manifest.permission.RECORD_AUDIO), speechToTextPermissionCode) - } else { - debugLog("no permission, no activity, completing") - completeInitialize() - } - } else { - debugLog("has permission, completing") - completeInitialize() - } - debugLog("leaving initializeIfPermitted") - } - - @RequiresApi(Build.VERSION_CODES.LOLLIPOP) - private fun completeInitialize() { - - debugLog("completeInitialize") - if (permissionToRecordAudio) { - debugLog("Testing recognition availability") - if (!SpeechRecognizer.isRecognitionAvailable(pluginContext)) { - Log.e(logTag, "Speech recognition not available on this device") - activeResult?.error(SpeechToTextErrors.recognizerNotAvailable.name, - "Speech recognition not available on this device", "") - activeResult = null - return - } - - debugLog("Creating recognizer") - speechRecognizer = createSpeechRecognizer(pluginContext).apply { - debugLog("Setting listener") - setRecognitionListener(this@SpeechToTextPlugin) - } - if (null == speechRecognizer) { - Log.e(logTag, "Speech recognizer null") - activeResult?.error( - SpeechToTextErrors.recognizerNotAvailable.name, - "Speech recognizer null", "") - activeResult = null - } - - debugLog("before setup intent") - setupRecognizerIntent(defaultLanguageTag, true, ListenMode.deviceDefault) - debugLog("after setup intent") - } - - initializedSuccessfully = permissionToRecordAudio - debugLog("sending result") - activeResult?.success(permissionToRecordAudio) - debugLog("leaving complete") - activeResult = null - } - - @RequiresApi(Build.VERSION_CODES.LOLLIPOP) - private fun setupRecognizerIntent(languageTag: String, partialResults: Boolean, listenMode: ListenMode) { - debugLog("setupRecognizerIntent") - if (previousRecognizerLang == null || - previousRecognizerLang != languageTag || - partialResults != previousPartialResults || previousListenMode != listenMode ) { - previousRecognizerLang = languageTag; - previousPartialResults = partialResults - previousListenMode = listenMode - handler.post { - run { - recognizerIntent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply { - debugLog("In RecognizerIntent apply") - putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM) - debugLog("put model") - val localContext = pluginContext - if (null != localContext) { - putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, - localContext.applicationInfo.packageName) - } - debugLog("put package") - putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, partialResults) - debugLog("put partial") - if (languageTag != Locale.getDefault().toLanguageTag()) { - putExtra(RecognizerIntent.EXTRA_LANGUAGE, languageTag); - debugLog("put languageTag") - } - } - } - } - } - } - - @RequiresApi(Build.VERSION_CODES.LOLLIPOP) - override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray): Boolean { - when (requestCode) { - speechToTextPermissionCode -> { - if (null != grantResults) { - permissionToRecordAudio = grantResults.isNotEmpty() && - grantResults.get(0) == PackageManager.PERMISSION_GRANTED - } - completeInitialize() - return true - } - } - return false - } - - - override fun onPartialResults(results: Bundle?) = updateResults(results, false) - override fun onResults(results: Bundle?) = updateResults(results, true) - override fun onEndOfSpeech() = notifyListening(isRecording = false) - - override fun onError(errorCode: Int) { - val errorMsg = when (errorCode) { - SpeechRecognizer.ERROR_AUDIO -> "error_audio_error" - SpeechRecognizer.ERROR_CLIENT -> "error_client" - SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS -> "error_permission" - SpeechRecognizer.ERROR_NETWORK -> "error_network" - SpeechRecognizer.ERROR_NETWORK_TIMEOUT -> "error_network_timeout" - SpeechRecognizer.ERROR_NO_MATCH -> "error_no_match" - SpeechRecognizer.ERROR_RECOGNIZER_BUSY -> "error_busy" - SpeechRecognizer.ERROR_SERVER -> "error_server" - SpeechRecognizer.ERROR_SPEECH_TIMEOUT -> "error_speech_timeout" - else -> "error_unknown" - } - sendError(errorMsg) - } - - private fun debugLog( msg: String ) { - if ( debugLogging ) { - Log.d( logTag, msg ) - } - } - - private fun sendError(errorMsg: String) { - val speechError = JSONObject() - speechError.put("errorMsg", errorMsg) - speechError.put("permanent", true) - handler.post { - run { - channel?.invokeMethod(SpeechToTextCallbackMethods.notifyError.name, speechError.toString()) - } - } - } - - override fun onRmsChanged(rmsdB: Float) { - handler.post { - run { - channel?.invokeMethod(SpeechToTextCallbackMethods.soundLevelChange.name, rmsdB) - } - } - } - - override fun onReadyForSpeech(p0: Bundle?) {} - override fun onBufferReceived(p0: ByteArray?) {} - override fun onEvent(p0: Int, p1: Bundle?) {} - override fun onBeginningOfSpeech() {} -} - -// See https://stackoverflow.com/questions/10538791/how-to-set-the-language-in-speech-recognition-on-android/10548680#10548680 -class LanguageDetailsChecker(flutterResult: Result) : BroadcastReceiver() { - private val result: Result = flutterResult - private var supportedLanguages: List? = null - - private var languagePreference: String? = null - - @RequiresApi(Build.VERSION_CODES.LOLLIPOP) - override fun onReceive(context: Context, intent: Intent) { - val results = getResultExtras(true) - if (results.containsKey(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE)) { - languagePreference = results.getString(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE) - } - if (results.containsKey(RecognizerIntent.EXTRA_SUPPORTED_LANGUAGES)) { - supportedLanguages = results.getStringArrayList( - RecognizerIntent.EXTRA_SUPPORTED_LANGUAGES) - createResponse(supportedLanguages) - } - } - - @RequiresApi(Build.VERSION_CODES.LOLLIPOP) - private fun createResponse(supportedLanguages: List?) { - val currentLocale = Locale.getDefault() - val localeNames = ArrayList() - localeNames.add(buildIdNameForLocale(currentLocale)) - if (null != supportedLanguages) { - for (lang in supportedLanguages) { - if (currentLocale.toLanguageTag() == lang) { - continue - } - val locale = Locale.forLanguageTag(lang) - localeNames.add(buildIdNameForLocale(locale)) - } - } - result.success(localeNames) - - } - - private fun buildIdNameForLocale(locale: Locale): String { - val name = locale.displayName.replace(':', ' ') - return "${locale.language}_${locale.country}:$name" - } -} - -private class ChannelResultWrapper(result: Result) : Result { - // Caller handler - val handler: Handler = Handler(Looper.getMainLooper()) - val result: Result = result - - // make sure to respond in the caller thread - override fun success(results: Any?) { - - handler.post { - run { - result.success(results); - } - } - } - - override fun error(errorCode: String, errorMessage: String?, data: Any?) { - handler.post { - run { - result.error(errorCode, errorMessage, data); - } - } - } - - override fun notImplemented() { - handler.post { - run { - result.notImplemented(); - } - } - } -} diff --git a/speech_to_text/example/.gitignore b/speech_to_text/example/.gitignore deleted file mode 100644 index 2ddde2a5..00000000 --- a/speech_to_text/example/.gitignore +++ /dev/null @@ -1,73 +0,0 @@ -# Miscellaneous -*.class -*.log -*.pyc -*.swp -.DS_Store -.atom/ -.buildlog/ -.history -.svn/ - -# 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/ -.dart_tool/ -.flutter-plugins -.packages -.pub-cache/ -.pub/ -/build/ - -# Android related -**/android/**/gradle-wrapper.jar -**/android/.gradle -**/android/captures/ -**/android/gradlew -**/android/gradlew.bat -**/android/local.properties -**/android/**/GeneratedPluginRegistrant.java - -# iOS/XCode related -**/ios/**/*.mode1v3 -**/ios/**/*.mode2v3 -**/ios/**/*.moved-aside -**/ios/**/*.pbxuser -**/ios/**/*.perspectivev3 -**/ios/**/*sync/ -**/ios/**/.sconsign.dblite -**/ios/**/.tags* -**/ios/**/.vagrant/ -**/ios/**/DerivedData/ -**/ios/**/Icon? -**/ios/**/Pods/ -**/ios/**/.symlinks/ -**/ios/**/profile -**/ios/**/xcuserdata -**/ios/.generated/ -**/ios/Flutter/App.framework -**/ios/Flutter/Flutter.framework -**/ios/Flutter/Generated.xcconfig -**/ios/Flutter/app.flx -**/ios/Flutter/app.zip -**/ios/Flutter/flutter_assets/ -**/ios/Flutter/flutter_export_environment.sh -**/ios/ServiceDefinitions.json -**/ios/Runner/GeneratedPluginRegistrant.* - -# Exceptions to above rules. -!**/ios/**/default.mode1v3 -!**/ios/**/default.mode2v3 -!**/ios/**/default.pbxuser -!**/ios/**/default.perspectivev3 -!/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages diff --git a/speech_to_text/example/.metadata b/speech_to_text/example/.metadata deleted file mode 100644 index aeb01ee2..00000000 --- a/speech_to_text/example/.metadata +++ /dev/null @@ -1,10 +0,0 @@ -# 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: 2d2a1ffec95cc70a3218872a2cd3f8de4933c42f - channel: stable - -project_type: app diff --git a/speech_to_text/example/README.md b/speech_to_text/example/README.md deleted file mode 100644 index 92252821..00000000 --- a/speech_to_text/example/README.md +++ /dev/null @@ -1,155 +0,0 @@ -# speech_to_text_example - -Demonstrates how to use the speech_to_text plugin. This example requires -that the plugin has been installed. It initializes speech recognition, -listens for words and prints them. - - -## Source - -```dart -import 'package:flutter/material.dart'; -import 'dart:async'; - -import 'package:speech_to_text/speech_to_text.dart'; -import 'package:speech_to_text/speech_recognition_result.dart'; -import 'package:speech_to_text/speech_recognition_error.dart'; - -void main() => runApp(MyApp()); - -class MyApp extends StatefulWidget { - @override - _MyAppState createState() => _MyAppState(); -} - -class _MyAppState extends State { - bool _hasSpeech = false; - String lastWords = ""; - String lastError = ""; - String lastStatus = ""; - final SpeechToText speech = SpeechToText(); - - @override - void initState() { - super.initState(); - initSpeechState(); - } - - Future initSpeechState() async { - bool hasSpeech = await speech.initialize(onError: errorListener, onStatus: statusListener ); - - if (!mounted) return; - setState(() { - _hasSpeech = hasSpeech; - }); - } - - @override - Widget build(BuildContext context) { - return MaterialApp( - home: Scaffold( - appBar: AppBar( - title: const Text('Speech to Text Example'), - ), - body: _hasSpeech - ? Column(children: [ - Expanded( - child: Center( - child: Text('Speech recognition available'), - ), - ), - Expanded( - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - FlatButton( - child: Text('Start'), - onPressed: startListening, - ), - FlatButton( - child: Text('Stop'), - onPressed: stopListening, - ), - FlatButton( - child: Text('Cancel'), - onPressed:cancelListening, - ), - ], - ), - ), - Expanded( - child: Column( - children: [ - Center( - child: Text('Recognized Words'), - ), - Center( - child: Text(lastWords), - ), - ], - ), - ), - Expanded( - child: Column( - children: [ - Center( - child: Text('Error'), - ), - Center( - child: Text(lastError), - ), - ], - ), - ), - Expanded( - child: Center( - child: speech.isListening ? Text("I'm listening...") : Text( 'Not listening' ), - ), - ), - ]) - : Center( child: Text('Speech recognition unavailable', style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold))), - ), - ); - } - - void startListening() { - lastWords = ""; - lastError = ""; - speech.listen(onResult: resultListener ); - setState(() { - - }); - } - - void stopListening() { - speech.stop( ); - setState(() { - - }); - } - - void cancelListening() { - speech.cancel( ); - setState(() { - - }); - } - - void resultListener(SpeechRecognitionResult result) { - setState(() { - lastWords = "${result.recognizedWords} - ${result.finalResult}"; - }); - } - - void errorListener(SpeechRecognitionError error ) { - setState(() { - lastError = "${error.errorMsg} - ${error.permanent}"; - }); - } - void statusListener(String status ) { - setState(() { - lastStatus = "$status"; - }); - } -} -``` \ No newline at end of file diff --git a/speech_to_text/example/android/.project b/speech_to_text/example/android/.project deleted file mode 100644 index d7d48141..00000000 --- a/speech_to_text/example/android/.project +++ /dev/null @@ -1,17 +0,0 @@ - - - android___ - Project android___ created by Buildship. - - - - - org.eclipse.buildship.core.gradleprojectbuilder - - - - - - org.eclipse.buildship.core.gradleprojectnature - - diff --git a/speech_to_text/example/android/.settings/org.eclipse.buildship.core.prefs b/speech_to_text/example/android/.settings/org.eclipse.buildship.core.prefs deleted file mode 100644 index e8895216..00000000 --- a/speech_to_text/example/android/.settings/org.eclipse.buildship.core.prefs +++ /dev/null @@ -1,2 +0,0 @@ -connection.project.dir= -eclipse.preferences.version=1 diff --git a/speech_to_text/example/android/app/build.gradle b/speech_to_text/example/android/app/build.gradle deleted file mode 100644 index 104069d3..00000000 --- a/speech_to_text/example/android/app/build.gradle +++ /dev/null @@ -1,67 +0,0 @@ -def localProperties = new Properties() -def localPropertiesFile = rootProject.file('local.properties') -if (localPropertiesFile.exists()) { - localPropertiesFile.withReader('UTF-8') { reader -> - localProperties.load(reader) - } -} - -def flutterRoot = localProperties.getProperty('flutter.sdk') -if (flutterRoot == null) { - throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") -} - -def flutterVersionCode = localProperties.getProperty('flutter.versionCode') -if (flutterVersionCode == null) { - flutterVersionCode = '1' -} - -def flutterVersionName = localProperties.getProperty('flutter.versionName') -if (flutterVersionName == null) { - flutterVersionName = '1.0' -} - -apply plugin: 'com.android.application' -apply plugin: 'kotlin-android' -apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" - -android { - compileSdkVersion 28 - - sourceSets { - main.java.srcDirs += 'src/main/kotlin' - } - - lintOptions { - disable 'InvalidPackage' - } - - defaultConfig { - // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). - applicationId "com.csdcorp.speech_to_text_example" - minSdkVersion 18 - targetSdkVersion 28 - versionCode flutterVersionCode.toInteger() - versionName flutterVersionName - testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" - } - - 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 { - implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" - testImplementation 'junit:junit:4.12' - androidTestImplementation 'androidx.test:runner:1.1.1' - androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' -} diff --git a/speech_to_text/example/android/app/src/debug/AndroidManifest.xml b/speech_to_text/example/android/app/src/debug/AndroidManifest.xml deleted file mode 100644 index 36edf838..00000000 --- a/speech_to_text/example/android/app/src/debug/AndroidManifest.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - diff --git a/speech_to_text/example/android/app/src/main/AndroidManifest.xml b/speech_to_text/example/android/app/src/main/AndroidManifest.xml deleted file mode 100644 index b0912061..00000000 --- a/speech_to_text/example/android/app/src/main/AndroidManifest.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/speech_to_text/example/android/app/src/main/kotlin/com/csdcorp/speech_to_text_example/MainActivity.kt b/speech_to_text/example/android/app/src/main/kotlin/com/csdcorp/speech_to_text_example/MainActivity.kt deleted file mode 100644 index f44e470e..00000000 --- a/speech_to_text/example/android/app/src/main/kotlin/com/csdcorp/speech_to_text_example/MainActivity.kt +++ /dev/null @@ -1,12 +0,0 @@ -package com.csdcorp.speech_to_text_example - -import androidx.annotation.NonNull; -import io.flutter.embedding.android.FlutterActivity -import io.flutter.embedding.engine.FlutterEngine -import io.flutter.plugins.GeneratedPluginRegistrant - -class MainActivity: FlutterActivity() { - override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) { - GeneratedPluginRegistrant.registerWith(flutterEngine); - } -} diff --git a/speech_to_text/example/android/app/src/main/res/drawable/launch_background.xml b/speech_to_text/example/android/app/src/main/res/drawable/launch_background.xml deleted file mode 100644 index 304732f8..00000000 --- a/speech_to_text/example/android/app/src/main/res/drawable/launch_background.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - diff --git a/speech_to_text/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/speech_to_text/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png deleted file mode 100644 index db77bb4b..00000000 Binary files a/speech_to_text/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png and /dev/null differ diff --git a/speech_to_text/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/speech_to_text/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png deleted file mode 100644 index 17987b79..00000000 Binary files a/speech_to_text/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png and /dev/null differ diff --git a/speech_to_text/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/speech_to_text/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png deleted file mode 100644 index 09d43914..00000000 Binary files a/speech_to_text/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png and /dev/null differ diff --git a/speech_to_text/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/speech_to_text/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png deleted file mode 100644 index d5f1c8d3..00000000 Binary files a/speech_to_text/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png and /dev/null differ diff --git a/speech_to_text/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/speech_to_text/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png deleted file mode 100644 index 4d6372ee..00000000 Binary files a/speech_to_text/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png and /dev/null differ diff --git a/speech_to_text/example/android/app/src/main/res/values/styles.xml b/speech_to_text/example/android/app/src/main/res/values/styles.xml deleted file mode 100644 index 00fa4417..00000000 --- a/speech_to_text/example/android/app/src/main/res/values/styles.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - diff --git a/speech_to_text/example/android/app/src/profile/AndroidManifest.xml b/speech_to_text/example/android/app/src/profile/AndroidManifest.xml deleted file mode 100644 index 36edf838..00000000 --- a/speech_to_text/example/android/app/src/profile/AndroidManifest.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - diff --git a/speech_to_text/example/android/build.gradle b/speech_to_text/example/android/build.gradle deleted file mode 100644 index 13546311..00000000 --- a/speech_to_text/example/android/build.gradle +++ /dev/null @@ -1,31 +0,0 @@ -buildscript { - ext.kotlin_version = '1.3.50' - repositories { - google() - jcenter() - } - - dependencies { - classpath 'com.android.tools.build:gradle:3.6.1' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - } -} - -allprojects { - repositories { - google() - jcenter() - } -} - -rootProject.buildDir = '../build' -subprojects { - project.buildDir = "${rootProject.buildDir}/${project.name}" -} -subprojects { - project.evaluationDependsOn(':app') -} - -task clean(type: Delete) { - delete rootProject.buildDir -} diff --git a/speech_to_text/example/android/gradle.properties b/speech_to_text/example/android/gradle.properties deleted file mode 100644 index a6738207..00000000 --- a/speech_to_text/example/android/gradle.properties +++ /dev/null @@ -1,4 +0,0 @@ -org.gradle.jvmargs=-Xmx1536M -android.useAndroidX=true -android.enableJetifier=true -android.enableR8=true diff --git a/speech_to_text/example/android/gradle/wrapper/gradle-wrapper.properties b/speech_to_text/example/android/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 052e7951..00000000 --- a/speech_to_text/example/android/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,6 +0,0 @@ -#Mon Mar 16 08:57:32 EDT 2020 -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip diff --git a/speech_to_text/example/android/settings.gradle b/speech_to_text/example/android/settings.gradle deleted file mode 100644 index 5a2f14fb..00000000 --- a/speech_to_text/example/android/settings.gradle +++ /dev/null @@ -1,15 +0,0 @@ -include ':app' - -def flutterProjectRoot = rootProject.projectDir.parentFile.toPath() - -def plugins = new Properties() -def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins') -if (pluginsFile.exists()) { - pluginsFile.withReader('UTF-8') { reader -> plugins.load(reader) } -} - -plugins.each { name, path -> - def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile() - include ":$name" - project(":$name").projectDir = pluginDirectory -} diff --git a/speech_to_text/example/assets/sounds/speech_to_text_cancel.m4r b/speech_to_text/example/assets/sounds/speech_to_text_cancel.m4r deleted file mode 100644 index ccb3afe3..00000000 Binary files a/speech_to_text/example/assets/sounds/speech_to_text_cancel.m4r and /dev/null differ diff --git a/speech_to_text/example/assets/sounds/speech_to_text_listening.m4r b/speech_to_text/example/assets/sounds/speech_to_text_listening.m4r deleted file mode 100644 index 3131d60f..00000000 Binary files a/speech_to_text/example/assets/sounds/speech_to_text_listening.m4r and /dev/null differ diff --git a/speech_to_text/example/assets/sounds/speech_to_text_stop.m4r b/speech_to_text/example/assets/sounds/speech_to_text_stop.m4r deleted file mode 100644 index 8817f01b..00000000 Binary files a/speech_to_text/example/assets/sounds/speech_to_text_stop.m4r and /dev/null differ diff --git a/speech_to_text/example/ios/Flutter/AppFrameworkInfo.plist b/speech_to_text/example/ios/Flutter/AppFrameworkInfo.plist deleted file mode 100644 index 6b4c0f78..00000000 --- a/speech_to_text/example/ios/Flutter/AppFrameworkInfo.plist +++ /dev/null @@ -1,26 +0,0 @@ - - - - - CFBundleDevelopmentRegion - $(DEVELOPMENT_LANGUAGE) - CFBundleExecutable - App - CFBundleIdentifier - io.flutter.flutter.app - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - App - CFBundlePackageType - FMWK - CFBundleShortVersionString - 1.0 - CFBundleSignature - ???? - CFBundleVersion - 1.0 - MinimumOSVersion - 8.0 - - diff --git a/speech_to_text/example/ios/Flutter/Debug.xcconfig b/speech_to_text/example/ios/Flutter/Debug.xcconfig deleted file mode 100644 index e8efba11..00000000 --- a/speech_to_text/example/ios/Flutter/Debug.xcconfig +++ /dev/null @@ -1,2 +0,0 @@ -#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" -#include "Generated.xcconfig" diff --git a/speech_to_text/example/ios/Flutter/Flutter.podspec b/speech_to_text/example/ios/Flutter/Flutter.podspec deleted file mode 100644 index 5ca30416..00000000 --- a/speech_to_text/example/ios/Flutter/Flutter.podspec +++ /dev/null @@ -1,18 +0,0 @@ -# -# NOTE: This podspec is NOT to be published. It is only used as a local source! -# - -Pod::Spec.new do |s| - s.name = 'Flutter' - s.version = '1.0.0' - s.summary = 'High-performance, high-fidelity mobile apps.' - s.description = <<-DESC -Flutter provides an easy and productive way to build and deploy high-performance mobile apps for Android and iOS. - DESC - s.homepage = 'https://flutter.io' - s.license = { :type => 'MIT' } - s.author = { 'Flutter Dev Team' => 'flutter-dev@googlegroups.com' } - s.source = { :git => 'https://github.com/flutter/engine', :tag => s.version.to_s } - s.ios.deployment_target = '8.0' - s.vendored_frameworks = 'Flutter.framework' -end diff --git a/speech_to_text/example/ios/Flutter/Release.xcconfig b/speech_to_text/example/ios/Flutter/Release.xcconfig deleted file mode 100644 index 399e9340..00000000 --- a/speech_to_text/example/ios/Flutter/Release.xcconfig +++ /dev/null @@ -1,2 +0,0 @@ -#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" -#include "Generated.xcconfig" diff --git a/speech_to_text/example/ios/Podfile b/speech_to_text/example/ios/Podfile deleted file mode 100644 index ab7d5b46..00000000 --- a/speech_to_text/example/ios/Podfile +++ /dev/null @@ -1,90 +0,0 @@ -# Uncomment this line to define a global platform for your project -platform :ios, '10.0' - -# CocoaPods analytics sends network stats synchronously affecting flutter build latency. -ENV['COCOAPODS_DISABLE_STATS'] = 'true' - -project 'Runner', { - 'Debug' => :debug, - 'Profile' => :release, - 'Release' => :release, -} - -def parse_KV_file(file, separator='=') - file_abs_path = File.expand_path(file) - if !File.exists? file_abs_path - return []; - end - generated_key_values = {} - skip_line_start_symbols = ["#", "/"] - File.foreach(file_abs_path) do |line| - next if skip_line_start_symbols.any? { |symbol| line =~ /^\s*#{symbol}/ } - plugin = line.split(pattern=separator) - if plugin.length == 2 - podname = plugin[0].strip() - path = plugin[1].strip() - podpath = File.expand_path("#{path}", file_abs_path) - generated_key_values[podname] = podpath - else - puts "Invalid plugin specification: #{line}" - end - end - generated_key_values -end - -target 'Runner' do - use_frameworks! - use_modular_headers! - - # Flutter Pod - - copied_flutter_dir = File.join(__dir__, 'Flutter') - copied_framework_path = File.join(copied_flutter_dir, 'Flutter.framework') - copied_podspec_path = File.join(copied_flutter_dir, 'Flutter.podspec') - unless File.exist?(copied_framework_path) && File.exist?(copied_podspec_path) - # Copy Flutter.framework and Flutter.podspec to Flutter/ to have something to link against if the xcode backend script has not run yet. - # That script will copy the correct debug/profile/release version of the framework based on the currently selected Xcode configuration. - # CocoaPods will not embed the framework on pod install (before any build phases can generate) if the dylib does not exist. - - generated_xcode_build_settings_path = File.join(copied_flutter_dir, 'Generated.xcconfig') - unless File.exist?(generated_xcode_build_settings_path) - raise "Generated.xcconfig must exist. If you're running pod install manually, make sure flutter pub get is executed first" - end - generated_xcode_build_settings = parse_KV_file(generated_xcode_build_settings_path) - cached_framework_dir = generated_xcode_build_settings['FLUTTER_FRAMEWORK_DIR']; - - unless File.exist?(copied_framework_path) - FileUtils.cp_r(File.join(cached_framework_dir, 'Flutter.framework'), copied_flutter_dir) - end - unless File.exist?(copied_podspec_path) - FileUtils.cp(File.join(cached_framework_dir, 'Flutter.podspec'), copied_flutter_dir) - end - end - - # Keep pod path relative so it can be checked into Podfile.lock. - pod 'Flutter', :path => 'Flutter' - - # Plugin Pods - - # Prepare symlinks folder. We use symlinks to avoid having Podfile.lock - # referring to absolute paths on developers' machines. - system('rm -rf .symlinks') - system('mkdir -p .symlinks/plugins') - plugin_pods = parse_KV_file('../.flutter-plugins') - plugin_pods.each do |name, path| - symlink = File.join('.symlinks', 'plugins', name) - File.symlink(path, symlink) - pod name, :path => File.join(symlink, 'ios') - end -end - -# Prevent Cocoapods from embedding a second Flutter framework and causing an error with the new Xcode build system. -install! 'cocoapods', :disable_input_output_paths => true - -post_install do |installer| - installer.pods_project.targets.each do |target| - target.build_configurations.each do |config| - config.build_settings['ENABLE_BITCODE'] = 'NO' - end - end -end diff --git a/speech_to_text/example/ios/Podfile.lock b/speech_to_text/example/ios/Podfile.lock deleted file mode 100644 index 60c8b57d..00000000 --- a/speech_to_text/example/ios/Podfile.lock +++ /dev/null @@ -1,29 +0,0 @@ -PODS: - - Flutter (1.0.0) - - speech_to_text (0.0.1): - - Flutter - - Try - - Try (2.1.1) - -DEPENDENCIES: - - Flutter (from `Flutter`) - - speech_to_text (from `.symlinks/plugins/speech_to_text/ios`) - -SPEC REPOS: - trunk: - - Try - -EXTERNAL SOURCES: - Flutter: - :path: Flutter - speech_to_text: - :path: ".symlinks/plugins/speech_to_text/ios" - -SPEC CHECKSUMS: - Flutter: 0e3d915762c693b495b44d77113d4970485de6ec - speech_to_text: b43a7d99aef037bd758ed8e45d79bbac035d2dfe - Try: 5ef669ae832617b3cee58cb2c6f99fb767a4ff96 - -PODFILE CHECKSUM: 0ba44ad07df4ab62269dc769727cf0f12b1e453d - -COCOAPODS: 1.9.3 diff --git a/speech_to_text/example/ios/Runner.xcodeproj/project.pbxproj b/speech_to_text/example/ios/Runner.xcodeproj/project.pbxproj deleted file mode 100644 index c40af650..00000000 --- a/speech_to_text/example/ios/Runner.xcodeproj/project.pbxproj +++ /dev/null @@ -1,578 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 46; - objects = { - -/* Begin PBXBuildFile section */ - 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; - 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; - 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; - 9740EEB41CF90195004384FC /* Debug.xcconfig in Resources */ = {isa = PBXBuildFile; fileRef = 9740EEB21CF90195004384FC /* Debug.xcconfig */; }; - 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; - 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; - 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; - C446300A034BF27D9F1ACEF9 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E76E9615C6B4FABD88067D55 /* Pods_Runner.framework */; }; -/* End PBXBuildFile section */ - -/* Begin PBXCopyFilesBuildPhase section */ - 9705A1C41CF9048500538489 /* Embed Frameworks */ = { - isa = PBXCopyFilesBuildPhase; - buildActionMask = 2147483647; - dstPath = ""; - dstSubfolderSpec = 10; - files = ( - ); - name = "Embed Frameworks"; - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXCopyFilesBuildPhase section */ - -/* Begin PBXFileReference section */ - 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; - 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; - 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; - 59AFE6BB0B596A0E0811BDFF /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; - 6280E2A777726D2043BF80B7 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; - 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; - 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; - 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; - 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; - 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; - 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; - 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; - 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; - 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; - 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - C3909A4B7EC98A20255210E3 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; - E76E9615C6B4FABD88067D55 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 97C146EB1CF9000F007C117D /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - C446300A034BF27D9F1ACEF9 /* Pods_Runner.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 7937AF765430D66F28F7FEEF /* Frameworks */ = { - isa = PBXGroup; - children = ( - E76E9615C6B4FABD88067D55 /* Pods_Runner.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; - 9740EEB11CF90186004384FC /* Flutter */ = { - isa = PBXGroup; - children = ( - 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, - 9740EEB21CF90195004384FC /* Debug.xcconfig */, - 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, - 9740EEB31CF90195004384FC /* Generated.xcconfig */, - ); - name = Flutter; - sourceTree = ""; - }; - 97C146E51CF9000F007C117D = { - isa = PBXGroup; - children = ( - 9740EEB11CF90186004384FC /* Flutter */, - 97C146F01CF9000F007C117D /* Runner */, - 97C146EF1CF9000F007C117D /* Products */, - A68CCF1640763A551D35BD31 /* Pods */, - 7937AF765430D66F28F7FEEF /* Frameworks */, - ); - sourceTree = ""; - }; - 97C146EF1CF9000F007C117D /* Products */ = { - isa = PBXGroup; - children = ( - 97C146EE1CF9000F007C117D /* Runner.app */, - ); - name = Products; - sourceTree = ""; - }; - 97C146F01CF9000F007C117D /* Runner */ = { - isa = PBXGroup; - children = ( - 97C146FA1CF9000F007C117D /* Main.storyboard */, - 97C146FD1CF9000F007C117D /* Assets.xcassets */, - 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, - 97C147021CF9000F007C117D /* Info.plist */, - 97C146F11CF9000F007C117D /* Supporting Files */, - 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, - 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, - 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, - 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, - ); - path = Runner; - sourceTree = ""; - }; - 97C146F11CF9000F007C117D /* Supporting Files */ = { - isa = PBXGroup; - children = ( - ); - name = "Supporting Files"; - sourceTree = ""; - }; - A68CCF1640763A551D35BD31 /* Pods */ = { - isa = PBXGroup; - children = ( - 59AFE6BB0B596A0E0811BDFF /* Pods-Runner.debug.xcconfig */, - 6280E2A777726D2043BF80B7 /* Pods-Runner.release.xcconfig */, - C3909A4B7EC98A20255210E3 /* Pods-Runner.profile.xcconfig */, - ); - path = Pods; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - 97C146ED1CF9000F007C117D /* Runner */ = { - isa = PBXNativeTarget; - buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; - buildPhases = ( - 949FCB95217187F2C022D6A9 /* [CP] Check Pods Manifest.lock */, - 9740EEB61CF901F6004384FC /* Run Script */, - 97C146EA1CF9000F007C117D /* Sources */, - 97C146EB1CF9000F007C117D /* Frameworks */, - 97C146EC1CF9000F007C117D /* Resources */, - 9705A1C41CF9048500538489 /* Embed Frameworks */, - 3B06AD1E1E4923F5004D2608 /* Thin Binary */, - 8B0988F04B6AE44AA0304FEF /* [CP] Embed Pods Frameworks */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = Runner; - productName = Runner; - productReference = 97C146EE1CF9000F007C117D /* Runner.app */; - productType = "com.apple.product-type.application"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 97C146E61CF9000F007C117D /* Project object */ = { - isa = PBXProject; - attributes = { - LastUpgradeCheck = 1020; - ORGANIZATIONNAME = "The Chromium Authors"; - TargetAttributes = { - 97C146ED1CF9000F007C117D = { - CreatedOnToolsVersion = 7.3.1; - DevelopmentTeam = 3X949YE9K2; - LastSwiftMigration = 0910; - }; - }; - }; - buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; - compatibilityVersion = "Xcode 3.2"; - developmentRegion = en; - hasScannedForEncodings = 0; - knownRegions = ( - en, - Base, - ); - mainGroup = 97C146E51CF9000F007C117D; - productRefGroup = 97C146EF1CF9000F007C117D /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 97C146ED1CF9000F007C117D /* Runner */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 97C146EC1CF9000F007C117D /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, - 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, - 9740EEB41CF90195004384FC /* Debug.xcconfig in Resources */, - 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, - 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXShellScriptBuildPhase section */ - 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - ); - name = "Thin Binary"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; - }; - 8B0988F04B6AE44AA0304FEF /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - ); - name = "[CP] Embed Pods Frameworks"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; - 949FCB95217187F2C022D6A9 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - 9740EEB61CF901F6004384FC /* Run Script */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - ); - name = "Run Script"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; - }; -/* End PBXShellScriptBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 97C146EA1CF9000F007C117D /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, - 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXVariantGroup section */ - 97C146FA1CF9000F007C117D /* Main.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 97C146FB1CF9000F007C117D /* Base */, - ); - name = Main.storyboard; - sourceTree = ""; - }; - 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 97C147001CF9000F007C117D /* Base */, - ); - name = LaunchScreen.storyboard; - sourceTree = ""; - }; -/* End PBXVariantGroup section */ - -/* Begin XCBuildConfiguration section */ - 249021D3217E4FDB00AE95B9 /* Profile */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - MTL_ENABLE_DEBUG_INFO = NO; - SDKROOT = iphoneos; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - }; - name = Profile; - }; - 249021D4217E4FDB00AE95B9 /* Profile */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CLANG_ENABLE_MODULES = YES; - CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; - DEVELOPMENT_TEAM = 3X949YE9K2; - ENABLE_BITCODE = NO; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); - INFOPLIST_FILE = Runner/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 10.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.csdcorp.speechToTextExample; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; - SWIFT_VERSION = 5.0; - VERSIONING_SYSTEM = "apple-generic"; - }; - name = Profile; - }; - 97C147031CF9000F007C117D /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = dwarf; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_DYNAMIC_NO_PIC = NO; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - MTL_ENABLE_DEBUG_INFO = YES; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = iphoneos; - TARGETED_DEVICE_FAMILY = "1,2"; - }; - name = Debug; - }; - 97C147041CF9000F007C117D /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - MTL_ENABLE_DEBUG_INFO = NO; - SDKROOT = iphoneos; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - }; - name = Release; - }; - 97C147061CF9000F007C117D /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CLANG_ENABLE_MODULES = YES; - CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; - DEVELOPMENT_TEAM = 3X949YE9K2; - ENABLE_BITCODE = NO; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); - INFOPLIST_FILE = Runner/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 10.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.csdcorp.speechToTextExample; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 5.0; - VERSIONING_SYSTEM = "apple-generic"; - }; - name = Debug; - }; - 97C147071CF9000F007C117D /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CLANG_ENABLE_MODULES = YES; - CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; - DEVELOPMENT_TEAM = 3X949YE9K2; - ENABLE_BITCODE = NO; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); - INFOPLIST_FILE = Runner/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 10.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.csdcorp.speechToTextExample; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; - SWIFT_VERSION = 5.0; - VERSIONING_SYSTEM = "apple-generic"; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 97C147031CF9000F007C117D /* Debug */, - 97C147041CF9000F007C117D /* Release */, - 249021D3217E4FDB00AE95B9 /* Profile */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 97C147061CF9000F007C117D /* Debug */, - 97C147071CF9000F007C117D /* Release */, - 249021D4217E4FDB00AE95B9 /* Profile */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 97C146E61CF9000F007C117D /* Project object */; -} diff --git a/speech_to_text/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/speech_to_text/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index 1d526a16..00000000 --- a/speech_to_text/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,7 +0,0 @@ - - - - - diff --git a/speech_to_text/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/speech_to_text/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme deleted file mode 100644 index a28140cf..00000000 --- a/speech_to_text/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ /dev/null @@ -1,91 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/speech_to_text/example/ios/Runner.xcworkspace/contents.xcworkspacedata b/speech_to_text/example/ios/Runner.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index 21a3cc14..00000000 --- a/speech_to_text/example/ios/Runner.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - diff --git a/speech_to_text/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/speech_to_text/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist deleted file mode 100644 index 18d98100..00000000 --- a/speech_to_text/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +++ /dev/null @@ -1,8 +0,0 @@ - - - - - IDEDidComputeMac32BitWarning - - - diff --git a/speech_to_text/example/ios/Runner/AppDelegate.swift b/speech_to_text/example/ios/Runner/AppDelegate.swift deleted file mode 100644 index 70693e4a..00000000 --- a/speech_to_text/example/ios/Runner/AppDelegate.swift +++ /dev/null @@ -1,13 +0,0 @@ -import UIKit -import Flutter - -@UIApplicationMain -@objc class AppDelegate: FlutterAppDelegate { - override func application( - _ application: UIApplication, - didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? - ) -> Bool { - GeneratedPluginRegistrant.register(with: self) - return super.application(application, didFinishLaunchingWithOptions: launchOptions) - } -} diff --git a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json deleted file mode 100644 index d36b1fab..00000000 --- a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json +++ /dev/null @@ -1,122 +0,0 @@ -{ - "images" : [ - { - "size" : "20x20", - "idiom" : "iphone", - "filename" : "Icon-App-20x20@2x.png", - "scale" : "2x" - }, - { - "size" : "20x20", - "idiom" : "iphone", - "filename" : "Icon-App-20x20@3x.png", - "scale" : "3x" - }, - { - "size" : "29x29", - "idiom" : "iphone", - "filename" : "Icon-App-29x29@1x.png", - "scale" : "1x" - }, - { - "size" : "29x29", - "idiom" : "iphone", - "filename" : "Icon-App-29x29@2x.png", - "scale" : "2x" - }, - { - "size" : "29x29", - "idiom" : "iphone", - "filename" : "Icon-App-29x29@3x.png", - "scale" : "3x" - }, - { - "size" : "40x40", - "idiom" : "iphone", - "filename" : "Icon-App-40x40@2x.png", - "scale" : "2x" - }, - { - "size" : "40x40", - "idiom" : "iphone", - "filename" : "Icon-App-40x40@3x.png", - "scale" : "3x" - }, - { - "size" : "60x60", - "idiom" : "iphone", - "filename" : "Icon-App-60x60@2x.png", - "scale" : "2x" - }, - { - "size" : "60x60", - "idiom" : "iphone", - "filename" : "Icon-App-60x60@3x.png", - "scale" : "3x" - }, - { - "size" : "20x20", - "idiom" : "ipad", - "filename" : "Icon-App-20x20@1x.png", - "scale" : "1x" - }, - { - "size" : "20x20", - "idiom" : "ipad", - "filename" : "Icon-App-20x20@2x.png", - "scale" : "2x" - }, - { - "size" : "29x29", - "idiom" : "ipad", - "filename" : "Icon-App-29x29@1x.png", - "scale" : "1x" - }, - { - "size" : "29x29", - "idiom" : "ipad", - "filename" : "Icon-App-29x29@2x.png", - "scale" : "2x" - }, - { - "size" : "40x40", - "idiom" : "ipad", - "filename" : "Icon-App-40x40@1x.png", - "scale" : "1x" - }, - { - "size" : "40x40", - "idiom" : "ipad", - "filename" : "Icon-App-40x40@2x.png", - "scale" : "2x" - }, - { - "size" : "76x76", - "idiom" : "ipad", - "filename" : "Icon-App-76x76@1x.png", - "scale" : "1x" - }, - { - "size" : "76x76", - "idiom" : "ipad", - "filename" : "Icon-App-76x76@2x.png", - "scale" : "2x" - }, - { - "size" : "83.5x83.5", - "idiom" : "ipad", - "filename" : "Icon-App-83.5x83.5@2x.png", - "scale" : "2x" - }, - { - "size" : "1024x1024", - "idiom" : "ios-marketing", - "filename" : "Icon-App-1024x1024@1x.png", - "scale" : "1x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} diff --git a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png deleted file mode 100644 index dc9ada47..00000000 Binary files a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png and /dev/null differ diff --git a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png deleted file mode 100644 index 28c6bf03..00000000 Binary files a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png and /dev/null differ diff --git a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png deleted file mode 100644 index 2ccbfd96..00000000 Binary files a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png and /dev/null differ diff --git a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png deleted file mode 100644 index f091b6b0..00000000 Binary files a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png and /dev/null differ diff --git a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png deleted file mode 100644 index 4cde1211..00000000 Binary files a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png and /dev/null differ diff --git a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png deleted file mode 100644 index d0ef06e7..00000000 Binary files a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png and /dev/null differ diff --git a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png deleted file mode 100644 index dcdc2306..00000000 Binary files a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png and /dev/null differ diff --git a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png deleted file mode 100644 index 2ccbfd96..00000000 Binary files a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png and /dev/null differ diff --git a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png deleted file mode 100644 index c8f9ed8f..00000000 Binary files a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png and /dev/null differ diff --git a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png deleted file mode 100644 index a6d6b860..00000000 Binary files a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png and /dev/null differ diff --git a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png deleted file mode 100644 index a6d6b860..00000000 Binary files a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png and /dev/null differ diff --git a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png deleted file mode 100644 index 75b2d164..00000000 Binary files a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png and /dev/null differ diff --git a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png deleted file mode 100644 index c4df70d3..00000000 Binary files a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png and /dev/null differ diff --git a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png deleted file mode 100644 index 6a84f41e..00000000 Binary files a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png and /dev/null differ diff --git a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png deleted file mode 100644 index d0e1f585..00000000 Binary files a/speech_to_text/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png and /dev/null differ diff --git a/speech_to_text/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/speech_to_text/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json deleted file mode 100644 index 0bedcf2f..00000000 --- a/speech_to_text/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "LaunchImage.png", - "scale" : "1x" - }, - { - "idiom" : "universal", - "filename" : "LaunchImage@2x.png", - "scale" : "2x" - }, - { - "idiom" : "universal", - "filename" : "LaunchImage@3x.png", - "scale" : "3x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} diff --git a/speech_to_text/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/speech_to_text/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png deleted file mode 100644 index 9da19eac..00000000 Binary files a/speech_to_text/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png and /dev/null differ diff --git a/speech_to_text/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/speech_to_text/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png deleted file mode 100644 index 9da19eac..00000000 Binary files a/speech_to_text/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png and /dev/null differ diff --git a/speech_to_text/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/speech_to_text/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png deleted file mode 100644 index 9da19eac..00000000 Binary files a/speech_to_text/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png and /dev/null differ diff --git a/speech_to_text/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/speech_to_text/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md deleted file mode 100644 index 89c2725b..00000000 --- a/speech_to_text/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# Launch Screen Assets - -You can customize the launch screen with your own desired assets by replacing the image files in this directory. - -You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/speech_to_text/example/ios/Runner/Base.lproj/LaunchScreen.storyboard b/speech_to_text/example/ios/Runner/Base.lproj/LaunchScreen.storyboard deleted file mode 100644 index f2e259c7..00000000 --- a/speech_to_text/example/ios/Runner/Base.lproj/LaunchScreen.storyboard +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/speech_to_text/example/ios/Runner/Base.lproj/Main.storyboard b/speech_to_text/example/ios/Runner/Base.lproj/Main.storyboard deleted file mode 100644 index f3c28516..00000000 --- a/speech_to_text/example/ios/Runner/Base.lproj/Main.storyboard +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/speech_to_text/example/ios/Runner/Info.plist b/speech_to_text/example/ios/Runner/Info.plist deleted file mode 100644 index a69c0fce..00000000 --- a/speech_to_text/example/ios/Runner/Info.plist +++ /dev/null @@ -1,49 +0,0 @@ - - - - - NSMicrophoneUsageDescription - This example listens for speech on the device microphone on your request. - NSSpeechRecognitionUsageDescription - This example recognizes words as you speak them and displays them. - CFBundleDevelopmentRegion - $(DEVELOPMENT_LANGUAGE) - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - speech_to_text_example - CFBundlePackageType - APPL - CFBundleShortVersionString - $(FLUTTER_BUILD_NAME) - CFBundleSignature - ???? - CFBundleVersion - $(FLUTTER_BUILD_NUMBER) - LSRequiresIPhoneOS - - UILaunchStoryboardName - LaunchScreen - UIMainStoryboardFile - Main - UISupportedInterfaceOrientations - - UIInterfaceOrientationPortrait - UIInterfaceOrientationLandscapeLeft - UIInterfaceOrientationLandscapeRight - - UISupportedInterfaceOrientations~ipad - - UIInterfaceOrientationPortrait - UIInterfaceOrientationPortraitUpsideDown - UIInterfaceOrientationLandscapeLeft - UIInterfaceOrientationLandscapeRight - - UIViewControllerBasedStatusBarAppearance - - - diff --git a/speech_to_text/example/ios/Runner/Runner-Bridging-Header.h b/speech_to_text/example/ios/Runner/Runner-Bridging-Header.h deleted file mode 100644 index 7335fdf9..00000000 --- a/speech_to_text/example/ios/Runner/Runner-Bridging-Header.h +++ /dev/null @@ -1 +0,0 @@ -#import "GeneratedPluginRegistrant.h" \ No newline at end of file diff --git a/speech_to_text/example/lib/main.dart b/speech_to_text/example/lib/main.dart deleted file mode 100644 index c7471184..00000000 --- a/speech_to_text/example/lib/main.dart +++ /dev/null @@ -1,275 +0,0 @@ -import 'dart:async'; -import 'dart:math'; - -import 'package:flutter/material.dart'; -import 'package:permission_handler/permission_handler.dart'; -import 'package:speech_to_text/speech_recognition_error.dart'; -import 'package:speech_to_text/speech_recognition_result.dart'; -import 'package:speech_to_text/speech_to_text.dart'; - -void main() => runApp(MyApp()); - -class MyApp extends StatefulWidget { - @override - _MyAppState createState() => _MyAppState(); -} - -class _MyAppState extends State { - bool _hasSpeech = false; - double level = 0.0; - double minSoundLevel = 50000; - double maxSoundLevel = -50000; - String lastWords = ""; - String lastError = ""; - String lastStatus = ""; - String _currentLocaleId = ""; - List _localeNames = []; - final SpeechToText speech = SpeechToText(); - - @override - void initState() { - requestPermissions(); - super.initState(); - } - - Future initSpeechState() async { - bool hasSpeech = await speech.initialize( - onError: errorListener, onStatus: statusListener); - if (hasSpeech) { - _localeNames = await speech.locales(); - - var systemLocale = await speech.systemLocale(); - _currentLocaleId = systemLocale.localeId; - } - - if (!mounted) return; - - setState(() { - _hasSpeech = hasSpeech; - }); - } - - void requestPermissions() async{ - Map statuses = await [ - Permission.microphone, - ].request(); - } - - @override - Widget build(BuildContext context) { - return MaterialApp( - home: Scaffold( - appBar: AppBar( - title: const Text('Speech to Text CloudSolution'), - ), - body: Column(children: [ - Center( - child: Text( - 'Speech recognition available', - style: TextStyle(fontSize: 22.0), - ), - ), - Container( - child: Column( - children: [ - Row( - mainAxisAlignment: MainAxisAlignment.spaceAround, - children: [ - TextButton( - child: Text('Initialize'), - onPressed: _hasSpeech ? null : initSpeechState, - ), - ], - ), - Row( - mainAxisAlignment: MainAxisAlignment.spaceAround, - children: [ - TextButton( - child: Text('Start'), - onPressed: !_hasSpeech || speech.isListening - ? null - : startListening, - ), - TextButton( - child: Text('Stop'), - onPressed: speech.isListening ? stopListening : null, - ), - TextButton( - child: Text('Cancel'), - onPressed: speech.isListening ? cancelListening : null, - ), - ], - ), - Row( - mainAxisAlignment: MainAxisAlignment.spaceAround, - children: [ - DropdownButton( - onChanged: (selectedVal) => _switchLang(selectedVal), - value: _currentLocaleId, - items: _localeNames - .map( - (localeName) => DropdownMenuItem( - value: localeName.localeId, - child: Text(localeName.name), - ), - ) - .toList(), - ), - ], - ) - ], - ), - ), - Expanded( - flex: 4, - child: Column( - children: [ - Center( - child: Text( - 'Recognized Words', - style: TextStyle(fontSize: 22.0), - ), - ), - Expanded( - child: Stack( - children: [ - Container( - color: Theme.of(context).selectedRowColor, - child: Center( - child: Text( - lastWords, - textAlign: TextAlign.center, - ), - ), - ), - Positioned.fill( - bottom: 10, - child: Align( - alignment: Alignment.bottomCenter, - child: Container( - width: 40, - height: 40, - alignment: Alignment.center, - decoration: BoxDecoration( - boxShadow: [ - BoxShadow( - blurRadius: .26, - spreadRadius: level * 1.5, - color: Colors.black.withOpacity(.05)) - ], - color: Colors.white, - borderRadius: - BorderRadius.all(Radius.circular(50)), - ), - child: IconButton(icon: Icon(Icons.mic)), - ), - ), - ), - ], - ), - ), - ], - ), - ), - Expanded( - flex: 1, - child: Column( - children: [ - Center( - child: Text( - 'Error Status', - style: TextStyle(fontSize: 22.0), - ), - ), - Center( - child: Text(lastError), - ), - ], - ), - ), - Container( - padding: EdgeInsets.symmetric(vertical: 20), - color: Theme.of(context).backgroundColor, - child: Center( - child: speech.isListening - ? Text( - "I'm listening...", - style: TextStyle(fontWeight: FontWeight.bold), - ) - : Text( - 'Not listening', - style: TextStyle(fontWeight: FontWeight.bold), - ), - ), - ), - ]), - ), - ); - } - - void startListening() { - lastWords = ""; - lastError = ""; - speech.listen( - onResult: resultListener, - listenFor: Duration(seconds: 10), - localeId: _currentLocaleId, - onSoundLevelChange: soundLevelListener, - cancelOnError: true, - partialResults: true, - onDevice: true, - listenMode: ListenMode.confirmation); - setState(() {}); - } - - void stopListening() { - speech.stop(); - setState(() { - level = 0.0; - }); - } - - void cancelListening() { - speech.cancel(); - setState(() { - level = 0.0; - }); - } - - void resultListener(SpeechRecognitionResult result) { - setState(() { - lastWords = "${result.recognizedWords} - ${result.finalResult}"; - }); - } - - void soundLevelListener(double level) { - minSoundLevel = min(minSoundLevel, level); - maxSoundLevel = max(maxSoundLevel, level); - // print("sound level $level: $minSoundLevel - $maxSoundLevel "); - setState(() { - this.level = level; - }); - } - - void errorListener(SpeechRecognitionError error) { - // print("Received error status: $error, listening: ${speech.isListening}"); - setState(() { - lastError = "${error.errorMsg} - ${error.permanent}"; - }); - } - - void statusListener(String status) { - // print( - // "Received listener status: $status, listening: ${speech.isListening}"); - setState(() { - lastStatus = "$status"; - }); - } - - _switchLang(selectedVal) { - setState(() { - _currentLocaleId = selectedVal; - }); - print(selectedVal); - } -} diff --git a/speech_to_text/example/pubspec.yaml b/speech_to_text/example/pubspec.yaml deleted file mode 100644 index d2bfcff7..00000000 --- a/speech_to_text/example/pubspec.yaml +++ /dev/null @@ -1,33 +0,0 @@ -name: speech_to_text_example -description: Demonstrates how to use the speech_to_text plugin. -version: 1.1.0 -publish_to: 'none' - -environment: - sdk: ">=2.1.0 <3.0.0" - -dependencies: - flutter: - sdk: flutter - - cupertino_icons: ^0.1.2 - permission_handler: ^5.0.1+1 - - provider: - -dev_dependencies: - flutter_test: - sdk: flutter - - speech_to_text: - path: ../ - -# The following section is specific to Flutter. -flutter: - - uses-material-design: true - - assets: - - assets/sounds/speech_to_text_listening.m4r - - assets/sounds/speech_to_text_cancel.m4r - - assets/sounds/speech_to_text_stop.m4r diff --git a/speech_to_text/example/test/widget_test.dart b/speech_to_text/example/test/widget_test.dart deleted file mode 100644 index 639a52fb..00000000 --- a/speech_to_text/example/test/widget_test.dart +++ /dev/null @@ -1,27 +0,0 @@ -// This is a basic Flutter widget test. -// -// To perform an interaction with a widget in your test, use the WidgetTester -// utility that Flutter provides. For example, you can send tap and scroll -// gestures. You can also use WidgetTester to find child widgets in the widget -// tree, read text, and verify that the values of widget properties are correct. - -import 'package:flutter/material.dart'; -import 'package:flutter_test/flutter_test.dart'; - -import '../lib/main.dart'; - -void main() { - testWidgets('Verify Platform version', (WidgetTester tester) async { - // Build our app and trigger a frame. - await tester.pumpWidget(MyApp()); - - // Verify that platform version is retrieved. - expect( - find.byWidgetPredicate( - (Widget widget) => - widget is Text && widget.data.startsWith('Running on:'), - ), - findsOneWidget, - ); - }); -} diff --git a/speech_to_text/ios/.gitignore b/speech_to_text/ios/.gitignore deleted file mode 100644 index aa479fd3..00000000 --- a/speech_to_text/ios/.gitignore +++ /dev/null @@ -1,37 +0,0 @@ -.idea/ -.vagrant/ -.sconsign.dblite -.svn/ - -.DS_Store -*.swp -profile - -DerivedData/ -build/ -GeneratedPluginRegistrant.h -GeneratedPluginRegistrant.m - -.generated/ - -*.pbxuser -*.mode1v3 -*.mode2v3 -*.perspectivev3 - -!default.pbxuser -!default.mode1v3 -!default.mode2v3 -!default.perspectivev3 - -xcuserdata - -*.moved-aside - -*.pyc -*sync/ -Icon? -.tags* - -/Flutter/Generated.xcconfig -/Flutter/flutter_export_environment.sh \ No newline at end of file diff --git a/speech_to_text/ios/Assets/.gitkeep b/speech_to_text/ios/Assets/.gitkeep deleted file mode 100644 index e69de29b..00000000 diff --git a/speech_to_text/ios/Classes/SpeechToTextPlugin.h b/speech_to_text/ios/Classes/SpeechToTextPlugin.h deleted file mode 100644 index 1785eb8f..00000000 --- a/speech_to_text/ios/Classes/SpeechToTextPlugin.h +++ /dev/null @@ -1,4 +0,0 @@ -#import - -@interface SpeechToTextPlugin : NSObject -@end diff --git a/speech_to_text/ios/Classes/SpeechToTextPlugin.m b/speech_to_text/ios/Classes/SpeechToTextPlugin.m deleted file mode 100644 index 20d0327d..00000000 --- a/speech_to_text/ios/Classes/SpeechToTextPlugin.m +++ /dev/null @@ -1,8 +0,0 @@ -#import "SpeechToTextPlugin.h" -#import - -@implementation SpeechToTextPlugin -+ (void)registerWithRegistrar:(NSObject*)registrar { - [SwiftSpeechToTextPlugin registerWithRegistrar:registrar]; -} -@end diff --git a/speech_to_text/ios/Classes/SwiftSpeechToTextPlugin.swift b/speech_to_text/ios/Classes/SwiftSpeechToTextPlugin.swift deleted file mode 100644 index 68687967..00000000 --- a/speech_to_text/ios/Classes/SwiftSpeechToTextPlugin.swift +++ /dev/null @@ -1,580 +0,0 @@ -import Flutter -import UIKit -import Speech -import os.log -import Try - -public enum SwiftSpeechToTextMethods: String { - case has_permission - case initialize - case listen - case stop - case cancel - case locales - case unknown // just for testing -} - -public enum SwiftSpeechToTextCallbackMethods: String { - case textRecognition - case notifyStatus - case notifyError - case soundLevelChange -} - -public enum SpeechToTextStatus: String { - case listening - case notListening - case unavailable - case available -} - -public enum SpeechToTextErrors: String { - case onDeviceError - case noRecognizerError - case listenFailedError - case missingOrInvalidArg -} - -public enum ListenMode: Int { - case deviceDefault = 0 - case dictation = 1 - case search = 2 - case confirmation = 3 -} - -struct SpeechRecognitionWords : Codable { - let recognizedWords: String - let confidence: Decimal -} - -struct SpeechRecognitionResult : Codable { - let alternates: [SpeechRecognitionWords] - let finalResult: Bool -} - -struct SpeechRecognitionError : Codable { - let errorMsg: String - let permanent: Bool -} - -enum SpeechToTextError: Error { - case runtimeError(String) -} - - -@available(iOS 10.0, *) -public class SwiftSpeechToTextPlugin: NSObject, FlutterPlugin { - private var channel: FlutterMethodChannel - private var registrar: FlutterPluginRegistrar - private var recognizer: SFSpeechRecognizer? - private var currentRequest: SFSpeechAudioBufferRecognitionRequest? - private var currentTask: SFSpeechRecognitionTask? - private var listeningSound: AVAudioPlayer? - private var successSound: AVAudioPlayer? - private var cancelSound: AVAudioPlayer? - private var rememberedAudioCategory: AVAudioSession.Category? - private var previousLocale: Locale? - private var onPlayEnd: (() -> Void)? - private var returnPartialResults: Bool = true - private var failedListen: Bool = false - private var listening = false - private let audioSession = AVAudioSession.sharedInstance() - private let audioEngine = AVAudioEngine() - private let jsonEncoder = JSONEncoder() - private let busForNodeTap = 0 - private let speechBufferSize: AVAudioFrameCount = 1024 - private static var subsystem = Bundle.main.bundleIdentifier! - private let pluginLog = OSLog(subsystem: "com.csdcorp.speechToText", category: "plugin") - - public static func register(with registrar: FlutterPluginRegistrar) { - let channel = FlutterMethodChannel(name: "plugin.csdcorp.com/speech_to_text", binaryMessenger: registrar.messenger()) - let instance = SwiftSpeechToTextPlugin( channel, registrar: registrar ) - registrar.addMethodCallDelegate(instance, channel: channel ) - } - - init( _ channel: FlutterMethodChannel, registrar: FlutterPluginRegistrar ) { - self.channel = channel - self.registrar = registrar - } - - public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { - switch call.method { - case SwiftSpeechToTextMethods.has_permission.rawValue: - hasPermission( result ) - case SwiftSpeechToTextMethods.initialize.rawValue: - initialize( result ) - case SwiftSpeechToTextMethods.listen.rawValue: - guard let argsArr = call.arguments as? Dictionary, - let partialResults = argsArr["partialResults"] as? Bool, let onDevice = argsArr["onDevice"] as? Bool, let listenModeIndex = argsArr["listenMode"] as? Int - else { - DispatchQueue.main.async { - result(FlutterError( code: SpeechToTextErrors.missingOrInvalidArg.rawValue, - message:"Missing arg partialResults, onDevice, and listenMode are required", - details: nil )) - } - return - } - var localeStr: String? = nil - if let localeParam = argsArr["localeId"] as? String { - localeStr = localeParam - } - guard let listenMode = ListenMode(rawValue: listenModeIndex) else { - DispatchQueue.main.async { - result(FlutterError( code: SpeechToTextErrors.missingOrInvalidArg.rawValue, - message:"invalid value for listenMode, must be 0-2, was \(listenModeIndex)", - details: nil )) - } - return - } - - listenForSpeech( result, localeStr: localeStr, partialResults: partialResults, onDevice: onDevice, listenMode: listenMode ) - case SwiftSpeechToTextMethods.stop.rawValue: - stopSpeech( result ) - case SwiftSpeechToTextMethods.cancel.rawValue: - cancelSpeech( result ) - case SwiftSpeechToTextMethods.locales.rawValue: - locales( result ) - default: - os_log("Unrecognized method: %{PUBLIC}@", log: pluginLog, type: .error, call.method) - DispatchQueue.main.async { - result( FlutterMethodNotImplemented) - } - } - } - - private func hasPermission( _ result: @escaping FlutterResult) { - let has = SFSpeechRecognizer.authorizationStatus() == SFSpeechRecognizerAuthorizationStatus.authorized && - AVAudioSession.sharedInstance().recordPermission == AVAudioSession.RecordPermission.granted - DispatchQueue.main.async { - result( has ) - } - } - - private func initialize( _ result: @escaping FlutterResult) { - var success = false - let status = SFSpeechRecognizer.authorizationStatus() - switch status { - case SFSpeechRecognizerAuthorizationStatus.notDetermined: - SFSpeechRecognizer.requestAuthorization({(status)->Void in - success = status == SFSpeechRecognizerAuthorizationStatus.authorized - if ( success ) { - AVAudioSession.sharedInstance().requestRecordPermission({(granted: Bool)-> Void in - if granted { - self.setupSpeechRecognition(result) - } else{ - self.sendBoolResult( false, result ); - os_log("User denied permission", log: self.pluginLog, type: .info) - } - }) - } - else { - self.sendBoolResult( false, result ); - } - }); - case SFSpeechRecognizerAuthorizationStatus.denied: - os_log("Permission permanently denied", log: self.pluginLog, type: .info) - sendBoolResult( false, result ); - case SFSpeechRecognizerAuthorizationStatus.restricted: - os_log("Device restriction prevented initialize", log: self.pluginLog, type: .info) - sendBoolResult( false, result ); - default: - os_log("Has permissions continuing with setup", log: self.pluginLog, type: .debug) - setupSpeechRecognition(result) - } - } - - fileprivate func sendBoolResult( _ value: Bool, _ result: @escaping FlutterResult) { - DispatchQueue.main.async { - result( value ) - } - } - - fileprivate func setupListeningSound() { - listeningSound = loadSound("assets/sounds/speech_to_text_listening.m4r") - successSound = loadSound("assets/sounds/speech_to_text_stop.m4r") - cancelSound = loadSound("assets/sounds/speech_to_text_cancel.m4r") - } - - fileprivate func loadSound( _ assetPath: String ) -> AVAudioPlayer? { - var player: AVAudioPlayer? = nil - let soundKey = registrar.lookupKey(forAsset: assetPath ) - guard !soundKey.isEmpty else { - return player - } - if let soundPath = Bundle.main.path(forResource: soundKey, ofType:nil) { - let soundUrl = URL(fileURLWithPath: soundPath ) - do { - player = try AVAudioPlayer(contentsOf: soundUrl ) - player?.delegate = self - } catch { - // no audio - } - } - return player - } - - private func setupSpeechRecognition( _ result: @escaping FlutterResult) { - setupRecognizerForLocale( locale: Locale.current ) - guard recognizer != nil else { - sendBoolResult( false, result ); - return - } - recognizer?.delegate = self - setupListeningSound() - - sendBoolResult( true, result ); - } - - private func setupRecognizerForLocale( locale: Locale ) { - if ( previousLocale == locale ) { - return - } - previousLocale = locale - recognizer = SFSpeechRecognizer( locale: locale ) - } - - private func getLocale( _ localeStr: String? ) -> Locale { - guard let aLocaleStr = localeStr else { - return Locale.current - } - let locale = Locale(identifier: aLocaleStr) - return locale - } - - private func stopSpeech( _ result: @escaping FlutterResult) { - if ( !listening ) { - sendBoolResult( false, result ); - return - } - stopAllPlayers() - if let sound = successSound { - onPlayEnd = {() -> Void in - self.currentTask?.finish() - self.stopCurrentListen( ) - self.sendBoolResult( true, result ) - return - } - sound.play() - } - else { - stopCurrentListen( ) - sendBoolResult( true, result ); - } - } - - private func cancelSpeech( _ result: @escaping FlutterResult) { - if ( !listening ) { - sendBoolResult( false, result ); - return - } - stopAllPlayers() - if let sound = cancelSound { - onPlayEnd = {() -> Void in - self.currentTask?.cancel() - self.stopCurrentListen( ) - self.sendBoolResult( true, result ) - return - } - sound.play() - } - else { - self.currentTask?.cancel() - stopCurrentListen( ) - sendBoolResult( true, result ); - } - } - - private func stopAllPlayers() { - cancelSound?.stop() - successSound?.stop() - listeningSound?.stop() - } - - private func stopCurrentListen( ) { - stopAllPlayers() - currentRequest?.endAudio() - - do { - try trap { - self.audioEngine.stop() - } - } - catch { - os_log("Error stopping engine: %{PUBLIC}@", log: pluginLog, type: .error, error.localizedDescription) - } - do { - try trap { - let inputNode = self.audioEngine.inputNode - inputNode.removeTap(onBus: self.busForNodeTap); - } - } - catch { - os_log("Error removing trap: %{PUBLIC}@", log: pluginLog, type: .error, error.localizedDescription) - } - do { - if let rememberedAudioCategory = rememberedAudioCategory { - try self.audioSession.setCategory(rememberedAudioCategory) - } - } - catch { - os_log("Error stopping listen: %{PUBLIC}@", log: pluginLog, type: .error, error.localizedDescription) - } - do { - try self.audioSession.setActive(false, options: .notifyOthersOnDeactivation) - } - catch { - os_log("Error deactivation: %{PUBLIC}@", log: pluginLog, type: .info, error.localizedDescription) - } - currentRequest = nil - currentTask = nil - onPlayEnd = nil - listening = false - } - - private func listenForSpeech( _ result: @escaping FlutterResult, localeStr: String?, partialResults: Bool, onDevice: Bool, listenMode: ListenMode ) { - if ( nil != currentTask || listening ) { - sendBoolResult( false, result ); - return - } - do { - // let inErrorTest = true - failedListen = false - returnPartialResults = partialResults - setupRecognizerForLocale(locale: getLocale(localeStr)) - guard let localRecognizer = recognizer else { - result(FlutterError( code: SpeechToTextErrors.noRecognizerError.rawValue, - message:"Failed to create speech recognizer", - details: nil )) - return - } - if ( onDevice ) { - if #available(iOS 13.0, *), !localRecognizer.supportsOnDeviceRecognition { - result(FlutterError( code: SpeechToTextErrors.onDeviceError.rawValue, - message:"on device recognition is not supported on this device", - details: nil )) - } - } - rememberedAudioCategory = self.audioSession.category - try self.audioSession.setCategory(AVAudioSession.Category.playAndRecord, options: .defaultToSpeaker) - // try self.audioSession.setMode(AVAudioSession.Mode.measurement) - try self.audioSession.setMode(AVAudioSession.Mode.default) - try self.audioSession.setActive(true, options: .notifyOthersOnDeactivation) - if let sound = listeningSound { - self.onPlayEnd = {()->Void in - if ( !self.failedListen ) { - self.listening = true - self.invokeFlutter( SwiftSpeechToTextCallbackMethods.notifyStatus, arguments: SpeechToTextStatus.listening.rawValue ) - - } - } - sound.play() - } - self.audioEngine.reset(); - let inputNode = self.audioEngine.inputNode - if(inputNode.inputFormat(forBus: 0).channelCount == 0){ - throw SpeechToTextError.runtimeError("Not enough available inputs.") - } - self.currentRequest = SFSpeechAudioBufferRecognitionRequest() - guard let currentRequest = self.currentRequest else { - sendBoolResult( false, result ); - return - } - currentRequest.shouldReportPartialResults = true - if #available(iOS 13.0, *), onDevice { - currentRequest.requiresOnDeviceRecognition = true - } - switch listenMode { - case ListenMode.dictation: - currentRequest.taskHint = SFSpeechRecognitionTaskHint.dictation - break - case ListenMode.search: - currentRequest.taskHint = SFSpeechRecognitionTaskHint.search - break - case ListenMode.confirmation: - currentRequest.taskHint = SFSpeechRecognitionTaskHint.confirmation - break - default: - break - } - self.currentTask = self.recognizer?.recognitionTask(with: currentRequest, delegate: self ) - let recordingFormat = inputNode.outputFormat(forBus: self.busForNodeTap) - try trap { - inputNode.installTap(onBus: self.busForNodeTap, bufferSize: self.speechBufferSize, format: recordingFormat) { (buffer: AVAudioPCMBuffer, when: AVAudioTime) in - currentRequest.append(buffer) - self.updateSoundLevel( buffer: buffer ) - } - } - // if ( inErrorTest ){ - // throw SpeechToTextError.runtimeError("for testing only") - // } - self.audioEngine.prepare() - try self.audioEngine.start() - if nil == listeningSound { - listening = true - self.invokeFlutter( SwiftSpeechToTextCallbackMethods.notifyStatus, arguments: SpeechToTextStatus.listening.rawValue ) - } - sendBoolResult( true, result ); - } - catch { - failedListen = true - os_log("Error starting listen: %{PUBLIC}@", log: pluginLog, type: .error, error.localizedDescription) - stopCurrentListen() - sendBoolResult( false, result ); - invokeFlutter( SwiftSpeechToTextCallbackMethods.notifyStatus, arguments: SpeechToTextStatus.notListening.rawValue ) - let speechError = SpeechRecognitionError(errorMsg: "error_listen_failed", permanent: true ) - do { - let errorResult = try jsonEncoder.encode(speechError) - invokeFlutter( SwiftSpeechToTextCallbackMethods.notifyError, arguments: String( data:errorResult, encoding: .utf8) ) - } catch { - os_log("Could not encode JSON", log: pluginLog, type: .error) - } - } - } - - private func updateSoundLevel( buffer: AVAudioPCMBuffer) { - guard - let channelData = buffer.floatChannelData - else { - return - } - - let channelDataValue = channelData.pointee - let channelDataValueArray = stride(from: 0, - to: Int(buffer.frameLength), - by: buffer.stride).map{ channelDataValue[$0] } - let frameLength = Float(buffer.frameLength) - let rms = sqrt(channelDataValueArray.map{ $0 * $0 }.reduce(0, +) / frameLength ) - let avgPower = 20 * log10(rms) - self.invokeFlutter( SwiftSpeechToTextCallbackMethods.soundLevelChange, arguments: avgPower ) - } - - /// Build a list of localId:name with the current locale first - private func locales( _ result: @escaping FlutterResult ) { - var localeNames = [String](); - let locales = SFSpeechRecognizer.supportedLocales(); - let currentLocale = Locale.current - if let idName = buildIdNameForLocale(forIdentifier: currentLocale.identifier ) { - localeNames.append(idName) - } - for locale in locales { - if ( locale.identifier == currentLocale.identifier) { - continue - } - if let idName = buildIdNameForLocale(forIdentifier: locale.identifier ) { - localeNames.append(idName) - } - } - DispatchQueue.main.async { - result(localeNames) - } - } - - private func buildIdNameForLocale( forIdentifier: String ) -> String? { - var idName: String? - if let name = Locale.current.localizedString(forIdentifier: forIdentifier ) { - let sanitizedName = name.replacingOccurrences(of: ":", with: " ") - idName = "\(forIdentifier):\(sanitizedName)" - } - return idName - } - - private func handleResult( _ transcriptions: [SFTranscription], isFinal: Bool ) { - if ( !isFinal && !returnPartialResults ) { - return - } - var speechWords: [SpeechRecognitionWords] = [] - for transcription in transcriptions { - let words: SpeechRecognitionWords = SpeechRecognitionWords(recognizedWords: transcription.formattedString, confidence: confidenceIn( transcription)) - speechWords.append( words ) - } - let speechInfo = SpeechRecognitionResult(alternates: speechWords, finalResult: isFinal ) - do { - let speechMsg = try jsonEncoder.encode(speechInfo) - if let speechStr = String( data:speechMsg, encoding: .utf8) { - os_log("Encoded JSON result: %{PUBLIC}@", log: pluginLog, type: .debug, speechStr ) - invokeFlutter( SwiftSpeechToTextCallbackMethods.textRecognition, arguments: speechStr ) - } - } catch { - os_log("Could not encode JSON", log: pluginLog, type: .error) - } - } - - private func confidenceIn( _ transcription: SFTranscription ) -> Decimal { - guard ( transcription.segments.count > 0 ) else { - return 0; - } - var totalConfidence: Float = 0.0; - for segment in transcription.segments { - totalConfidence += segment.confidence - } - let avgConfidence: Float = totalConfidence / Float(transcription.segments.count ) - let confidence: Float = (avgConfidence * 1000).rounded() / 1000 - return Decimal( string: String( describing: confidence ) )! - } - - private func invokeFlutter( _ method: SwiftSpeechToTextCallbackMethods, arguments: Any? ) { - DispatchQueue.main.async { - self.channel.invokeMethod( method.rawValue, arguments: arguments ) - } - } - -} - -@available(iOS 10.0, *) -extension SwiftSpeechToTextPlugin : SFSpeechRecognizerDelegate { - public func speechRecognizer(_ speechRecognizer: SFSpeechRecognizer, availabilityDidChange available: Bool) { - let availability = available ? SpeechToTextStatus.available.rawValue : SpeechToTextStatus.unavailable.rawValue - os_log("Availability changed: %{PUBLIC}@", log: pluginLog, type: .debug, availability) - invokeFlutter( SwiftSpeechToTextCallbackMethods.notifyStatus, arguments: availability ) - } -} - -@available(iOS 10.0, *) -extension SwiftSpeechToTextPlugin : SFSpeechRecognitionTaskDelegate { - public func speechRecognitionDidDetectSpeech(_ task: SFSpeechRecognitionTask) { - // Do nothing for now - } - - public func speechRecognitionTaskFinishedReadingAudio(_ task: SFSpeechRecognitionTask) { - reportError(source: "FinishedReadingAudio", error: task.error) - invokeFlutter( SwiftSpeechToTextCallbackMethods.notifyStatus, arguments: SpeechToTextStatus.notListening.rawValue ) - } - - public func speechRecognitionTaskWasCancelled(_ task: SFSpeechRecognitionTask) { - reportError(source: "TaskWasCancelled", error: task.error) - invokeFlutter( SwiftSpeechToTextCallbackMethods.notifyStatus, arguments: SpeechToTextStatus.notListening.rawValue ) - } - - public func speechRecognitionTask(_ task: SFSpeechRecognitionTask, didFinishSuccessfully successfully: Bool) { - reportError(source: "FinishSuccessfully", error: task.error) - stopCurrentListen( ) - } - - public func speechRecognitionTask(_ task: SFSpeechRecognitionTask, didHypothesizeTranscription transcription: SFTranscription) { - reportError(source: "HypothesizeTranscription", error: task.error) - handleResult( [transcription], isFinal: false ) - } - - public func speechRecognitionTask(_ task: SFSpeechRecognitionTask, didFinishRecognition recognitionResult: SFSpeechRecognitionResult) { - reportError(source: "FinishRecognition", error: task.error) - let isFinal = recognitionResult.isFinal - handleResult( recognitionResult.transcriptions, isFinal: isFinal ) - } - - private func reportError( source: String, error: Error?) { - if ( nil != error) { - os_log("%{PUBLIC}@ with error: %{PUBLIC}@", log: pluginLog, type: .debug, source, error.debugDescription) - } - } -} - -@available(iOS 10.0, *) -extension SwiftSpeechToTextPlugin : AVAudioPlayerDelegate { - - public func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, - successfully flag: Bool) { - if let playEnd = self.onPlayEnd { - playEnd() - } - } -} diff --git a/speech_to_text/ios/speech_to_text.podspec b/speech_to_text/ios/speech_to_text.podspec deleted file mode 100644 index 1db79aa0..00000000 --- a/speech_to_text/ios/speech_to_text.podspec +++ /dev/null @@ -1,22 +0,0 @@ -# -# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html -# -Pod::Spec.new do |s| - s.name = 'speech_to_text' - s.version = '0.0.1' - s.summary = 'A new flutter plugin project.' - s.description = <<-DESC -A new flutter plugin project. - DESC - s.homepage = 'http://example.com' - s.license = { :file => '../LICENSE' } - s.author = { 'Your Company' => 'email@example.com' } - s.source = { :path => '.' } - s.source_files = 'Classes/**/*' - s.public_header_files = 'Classes/**/*.h' - s.dependency 'Flutter' - s.dependency 'Try' - - s.ios.deployment_target = '8.0' -end - diff --git a/speech_to_text/lib/speech_recognition_error.dart b/speech_to_text/lib/speech_recognition_error.dart deleted file mode 100644 index 1b47b0c9..00000000 --- a/speech_to_text/lib/speech_recognition_error.dart +++ /dev/null @@ -1,45 +0,0 @@ -import 'package:json_annotation/json_annotation.dart'; - - -part 'speech_recognition_error.g.dart'; - -/// A single error returned from the underlying speech services. -/// -/// Errors are either transient or permanent. Permanent errors -/// block speech recognition from continuing and must be -/// addressed before recogntion will work. Transient errors -/// cause individual recognition sessions to fail but subsequent -/// attempts may well succeed. -@JsonSerializable() -class SpeechRecognitionError { - /// Use this to differentiate the various error conditions. - /// - /// Not meant for display to the user. - final String errorMsg; - - /// True means that recognition cannot continue until - /// the error is resolved. - final bool permanent; - - SpeechRecognitionError(this.errorMsg, this.permanent); - - factory SpeechRecognitionError.fromJson(Map json) => - _$SpeechRecognitionErrorFromJson(json); - Map toJson() => _$SpeechRecognitionErrorToJson(this); - - @override - String toString() { - return "SpeechRecognitionError msg: $errorMsg, permanent: $permanent"; - } - - @override - bool operator ==(Object other) { - return identical(this, other) || - other is SpeechRecognitionError && - errorMsg == other.errorMsg && - permanent == other.permanent; - } - - @override - int get hashCode => errorMsg.hashCode; -} diff --git a/speech_to_text/lib/speech_recognition_error.g.dart b/speech_to_text/lib/speech_recognition_error.g.dart deleted file mode 100644 index 65299f6d..00000000 --- a/speech_to_text/lib/speech_recognition_error.g.dart +++ /dev/null @@ -1,22 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of 'speech_recognition_error.dart'; - -// ************************************************************************** -// JsonSerializableGenerator -// ************************************************************************** - -SpeechRecognitionError _$SpeechRecognitionErrorFromJson( - Map json) { - return SpeechRecognitionError( - json['errorMsg'] as String, - json['permanent'] as bool, - ); -} - -Map _$SpeechRecognitionErrorToJson( - SpeechRecognitionError instance) => - { - 'errorMsg': instance.errorMsg, - 'permanent': instance.permanent, - }; diff --git a/speech_to_text/lib/speech_recognition_event.dart b/speech_to_text/lib/speech_recognition_event.dart deleted file mode 100644 index 71729365..00000000 --- a/speech_to_text/lib/speech_recognition_event.dart +++ /dev/null @@ -1,30 +0,0 @@ -import 'package:speech_to_text/speech_recognition_error.dart'; -import 'package:speech_to_text/speech_recognition_result.dart'; - -enum SpeechRecognitionEventType { - finalRecognitionEvent, - partialRecognitionEvent, - errorEvent, - statusChangeEvent, - soundLevelChangeEvent, -} - -/// A single event in a stream of speech recognition events. -/// -/// Use [eventType] to determine what type of event it is and depending on that -/// use the other properties to get information about it. -class SpeechRecognitionEvent { - final SpeechRecognitionEventType eventType; - final SpeechRecognitionError _error; - final SpeechRecognitionResult _result; - final bool _listening; - final double _level; - - SpeechRecognitionEvent( - this.eventType, this._result, this._error, this._listening, this._level); - - bool get isListening => _listening; - double get level => _level; - SpeechRecognitionResult get recognitionResult => _result; - SpeechRecognitionError get error => _error; -} diff --git a/speech_to_text/lib/speech_recognition_result.dart b/speech_to_text/lib/speech_recognition_result.dart deleted file mode 100644 index 38509f65..00000000 --- a/speech_to_text/lib/speech_recognition_result.dart +++ /dev/null @@ -1,140 +0,0 @@ -import 'dart:collection'; - -import 'package:json_annotation/json_annotation.dart'; - -part 'speech_recognition_result.g.dart'; - -/// A sequence of recognized words from the speech recognition -/// service. -/// -/// Depending on the platform behaviour the words may come in all -/// at once at the end or as partial results as each word is -/// recognized. Use the [finalResult] flag to determine if the -/// result is considered final by the platform. -@JsonSerializable(explicitToJson: true) -class SpeechRecognitionResult { - List _alternates; - - /// Returns a list of possible transcriptions of the speech. - /// - /// The first value is always the same as the [recognizedWords] - /// value. Use the confidence for each alternate transcription - /// to determine how likely it is. Note that not all platforms - /// do a good job with confidence, there are convenience methods - /// on [SpeechRecogntionWords] to work with possibly missing - /// confidence values. - List get alternates => - UnmodifiableListView(_alternates); - - /// The sequence of words that is the best transcription of - /// what was said. - /// - /// This is the same as the first value of [alternates]. - String get recognizedWords => - _alternates.isNotEmpty ? _alternates.first.recognizedWords : ""; - - /// False means the words are an interim result, true means - /// they are the final recognition. - final bool finalResult; - - /// The confidence that the [recognizedWords] are correct. - /// - /// Confidence is expressed as a value between 0 and 1. -1 - /// means that the confidence value was not available. - double get confidence => - _alternates.isNotEmpty ? _alternates.first.confidence : 0; - - /// true if there is confidence in this recognition, false otherwise. - /// - /// There are two separate ways for there to be confidence, the first - /// is if the confidence is missing, which is indicated by a value of - /// -1. The second is if the confidence is greater than or equal - /// [threshold]. If [threshold] is not provided it defaults to 0.8. - bool isConfident( - {double threshold = SpeechRecognitionWords.confidenceThreshold}) => - _alternates.isNotEmpty - ? _alternates.first.isConfident(threshold: threshold) - : false; - - /// true if [confidence] is not the [missingConfidence] value, false - /// otherwise. - bool get hasConfidenceRating => - _alternates.isNotEmpty ? _alternates.first.hasConfidenceRating : false; - - SpeechRecognitionResult(this._alternates, this.finalResult); - - @override - String toString() { - return "SpeechRecognitionResult words: $_alternates, final: $finalResult"; - } - - @override - bool operator ==(Object other) { - return identical(this, other) || - other is SpeechRecognitionResult && - recognizedWords == other.recognizedWords && - finalResult == other.finalResult; - } - - @override - int get hashCode => recognizedWords.hashCode; - - factory SpeechRecognitionResult.fromJson(Map json) => - _$SpeechRecognitionResultFromJson(json); - Map toJson() => _$SpeechRecognitionResultToJson(this); -} - -/// A set of words recognized in a [SpeechRecognitionResult]. -/// -/// Each result will have one or more [SpeechRecognitionWords] -/// with a varying degree of confidence about each set of words. -@JsonSerializable() -class SpeechRecognitionWords { - /// The sequence of words recognized - final String recognizedWords; - - /// The confidence that the [recognizedWords] are correct. - /// - /// Confidence is expressed as a value between 0 and 1. 0 - /// means that the confidence value was not available. Use - /// [isConfident] which will ignore 0 values automatically. - final double confidence; - - static const double confidenceThreshold = 0.8; - static const double missingConfidence = -1; - - const SpeechRecognitionWords(this.recognizedWords, this.confidence); - - /// true if there is confidence in this recognition, false otherwise. - /// - /// There are two separate ways for there to be confidence, the first - /// is if the confidence is missing, which is indicated by a value of - /// -1. The second is if the confidence is greater than or equal - /// [threshold]. If [threshold] is not provided it defaults to 0.8. - bool isConfident({double threshold = confidenceThreshold}) => - confidence == missingConfidence || confidence >= threshold; - - /// true if [confidence] is not the [missingConfidence] value, false - /// otherwise. - bool get hasConfidenceRating => confidence != missingConfidence; - - @override - String toString() { - return "SpeechRecognitionWords words: $recognizedWords, confidence: $confidence"; - } - - @override - bool operator ==(Object other) { - return identical(this, other) || - other is SpeechRecognitionWords && - recognizedWords == other.recognizedWords && - confidence == other.confidence; - } - - @override - int get hashCode => recognizedWords.hashCode; - - factory SpeechRecognitionWords.fromJson(Map json) => - _$SpeechRecognitionWordsFromJson(json); - Map toJson() => _$SpeechRecognitionWordsToJson(this); -} diff --git a/speech_to_text/lib/speech_recognition_result.g.dart b/speech_to_text/lib/speech_recognition_result.g.dart deleted file mode 100644 index 023e5485..00000000 --- a/speech_to_text/lib/speech_recognition_result.g.dart +++ /dev/null @@ -1,41 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of 'speech_recognition_result.dart'; - -// ************************************************************************** -// JsonSerializableGenerator -// ************************************************************************** - -SpeechRecognitionResult _$SpeechRecognitionResultFromJson( - Map json) { - return SpeechRecognitionResult( - (json['alternates'] as List) - ?.map((e) => e == null - ? null - : SpeechRecognitionWords.fromJson(e as Map)) - ?.toList(), - json['finalResult'] as bool, - ); -} - -Map _$SpeechRecognitionResultToJson( - SpeechRecognitionResult instance) => - { - 'alternates': instance.alternates?.map((e) => e?.toJson())?.toList(), - 'finalResult': instance.finalResult, - }; - -SpeechRecognitionWords _$SpeechRecognitionWordsFromJson( - Map json) { - return SpeechRecognitionWords( - json['recognizedWords'] as String, - (json['confidence'] as num)?.toDouble(), - ); -} - -Map _$SpeechRecognitionWordsToJson( - SpeechRecognitionWords instance) => - { - 'recognizedWords': instance.recognizedWords, - 'confidence': instance.confidence, - }; diff --git a/speech_to_text/lib/speech_to_text.dart b/speech_to_text/lib/speech_to_text.dart deleted file mode 100644 index 343706e6..00000000 --- a/speech_to_text/lib/speech_to_text.dart +++ /dev/null @@ -1,511 +0,0 @@ -import 'dart:async'; -import 'dart:convert'; -import 'dart:math'; - -import 'package:clock/clock.dart'; -import 'package:flutter/foundation.dart'; -import 'package:flutter/services.dart'; -import 'package:speech_to_text/speech_recognition_error.dart'; -import 'package:speech_to_text/speech_recognition_result.dart'; - -enum ListenMode { - deviceDefault, - dictation, - search, - confirmation, -} - -/// Notified as words are recognized with the current set of recognized words. -/// -/// See the [onResult] argument on the [listen] method for use. -typedef SpeechResultListener = void Function(SpeechRecognitionResult result); - -/// Notified if errors occur during recognition or intialization. -/// -/// Possible errors per the Android docs are described here: -/// https://developer.android.com/reference/android/speech/SpeechRecognizer -/// "error_audio_error" -/// "error_client" -/// "error_permission" -/// "error_network" -/// "error_network_timeout" -/// "error_no_match" -/// "error_busy" -/// "error_server" -/// "error_speech_timeout" -/// See the [onError] argument on the [initialize] method for use. -typedef SpeechErrorListener = void Function( - SpeechRecognitionError errorNotification); - -/// Notified when recognition status changes. -/// -/// See the [onStatus] argument on the [initialize] method for use. -typedef SpeechStatusListener = void Function(String status); - -/// Notified when the sound level changes during a listen method. -/// -/// [level] is a measure of the decibels of the current sound on -/// the recognition input. See the [onSoundLevelChange] argument on -/// the [listen] method for use. -typedef SpeechSoundLevelChange = Function(double level); - -/// An interface to device specific speech recognition services. -/// -/// The general flow of a speech recognition session is as follows: -/// ```Dart -/// SpeechToText speech = SpeechToText(); -/// bool isReady = await speech.initialize(); -/// if ( isReady ) { -/// await speech.listen( resultListener: resultListener ); -/// } -/// ... -/// // At some point later -/// speech.stop(); -/// ``` -class SpeechToText { - static const String listenMethod = 'listen'; - static const String textRecognitionMethod = 'textRecognition'; - static const String notifyErrorMethod = 'notifyError'; - static const String notifyStatusMethod = 'notifyStatus'; - static const String soundLevelChangeMethod = "soundLevelChange"; - static const String notListeningStatus = "notListening"; - static const String listeningStatus = "listening"; - - static const MethodChannel speechChannel = - const MethodChannel('plugin.csdcorp.com/speech_to_text'); - static final SpeechToText _instance = - SpeechToText.withMethodChannel(speechChannel); - bool _initWorked = false; - bool _recognized = false; - bool _listening = false; - bool _cancelOnError = false; - bool _partialResults = false; - int _listenStartedAt = 0; - int _lastSpeechEventAt = 0; - Duration _pauseFor; - Duration _listenFor; - - /// True if not listening or the user called cancel / stop, false - /// if cancel/stop were invoked by timeout or error condition. - bool _userEnded = false; - String _lastRecognized = ""; - String _lastStatus = ""; - double _lastSoundLevel = 0; - Timer _listenTimer; - LocaleName _systemLocale; - SpeechRecognitionError _lastError; - SpeechResultListener _resultListener; - SpeechErrorListener errorListener; - SpeechStatusListener statusListener; - SpeechSoundLevelChange _soundLevelChange; - - final MethodChannel channel; - factory SpeechToText() => _instance; - - @visibleForTesting - SpeechToText.withMethodChannel(this.channel); - - /// True if words have been recognized during the current [listen] call. - /// - /// Goes false as soon as [cancel] is called. - bool get hasRecognized => _recognized; - - /// The last set of recognized words received. - /// - /// This is maintained across [cancel] calls but cleared on the next - /// [listen]. - String get lastRecognizedWords => _lastRecognized; - - /// The last status update received, see [initialize] to register - /// an optional listener to be notified when this changes. - String get lastStatus => _lastStatus; - - /// The last sound level received during a listen event. - /// - /// The sound level is a measure of how loud the current - /// input is during listening. Use the [onSoundLevelChange] - /// argument in the [listen] method to get notified of - /// changes. - double get lastSoundLevel => _lastSoundLevel; - - /// True if [initialize] succeeded - bool get isAvailable => _initWorked; - - /// True if [listen] succeeded and [stop] or [cancel] has not been called. - /// - /// Also goes false when listening times out if listenFor was set. - bool get isListening => _listening; - bool get isNotListening => !isListening; - - /// The last error received or null if none, see [initialize] to - /// register an optional listener to be notified of errors. - SpeechRecognitionError get lastError => _lastError; - - /// True if an error has been received, see [lastError] for details - bool get hasError => null != lastError; - - /// Returns true if the user has already granted permission to access the - /// microphone, does not prompt the user. - /// - /// This method can be called before [initialize] to check if permission - /// has already been granted. If this returns false then the [initialize] - /// call will prompt the user for permission if it is allowed to do so. - /// Note that applications cannot ask for permission again if the user has - /// denied them permission in the past. - Future get hasPermission async { - bool hasPermission = await channel.invokeMethod('has_permission'); - return hasPermission; - } - - /// Initialize speech recognition services, returns true if - /// successful, false if failed. - /// - /// This method must be called before any other speech functions. - /// If this method returns false no further [SpeechToText] methods - /// should be used. Should only be called once if successful but does protect - /// itself if called repeatedly. False usually means that the user has denied - /// permission to use speech. The usual option in that case is to give them - /// instructions on how to open system settings and grant permission. - /// - /// [onError] is an optional listener for errors like - /// timeout, or failure of the device speech recognition. - /// [onStatus] is an optional listener for status changes from - /// listening to not listening. - /// [debugLogging] controls whether there is detailed logging from the underlying - /// plugins. It is off by default, usually only useful for troubleshooting issues - /// with a paritcular OS version or device, fairly verbose - Future initialize( - {SpeechErrorListener onError, - SpeechStatusListener onStatus, - debugLogging = false}) async { - if (_initWorked) { - return Future.value(_initWorked); - } - errorListener = onError; - statusListener = onStatus; - channel.setMethodCallHandler(_handleCallbacks); - _initWorked = await channel - .invokeMethod('initialize', {"debugLogging": debugLogging}); - return _initWorked; - } - - /// Stops the current listen for speech if active, does nothing if not. - /// - /// Stopping a listen session will cause a final result to be sent. Each - /// listen session should be ended with either [stop] or [cancel], for - /// example in the dispose method of a Widget. [cancel] is automatically - /// invoked by a permanent error if [cancelOnError] is set to true in the - /// [listen] call. - /// - /// *Note:* Cannot be used until a successful [initialize] call. Should - /// only be used after a successful [listen] call. - Future stop() async { - _userEnded = true; - return _stop(); - } - - Future _stop() async { - if (!_initWorked) { - return; - } - _shutdownListener(); - await channel.invokeMethod('stop'); - } - - /// Cancels the current listen for speech if active, does nothing if not. - /// - /// Canceling means that there will be no final result returned from the - /// recognizer. Each listen session should be ended with either [stop] or - /// [cancel], for example in the dispose method of a Widget. [cancel] is - /// automatically invoked by a permanent error if [cancelOnError] is set - /// to true in the [listen] call. - /// - /// *Note* Cannot be used until a successful [initialize] call. Should only - /// be used after a successful [listen] call. - Future cancel() async { - _userEnded = true; - return _cancel(); - } - - Future _cancel() async { - if (!_initWorked) { - return; - } - _shutdownListener(); - await channel.invokeMethod('cancel'); - } - - /// Starts a listening session for speech and converts it to text, - /// invoking the provided [onResult] method as words are recognized. - /// - /// Cannot be used until a successful [initialize] call. There is a - /// time limit on listening imposed by both Android and iOS. The time - /// depends on the device, network, etc. Android is usually quite short, - /// especially if there is no active speech event detected, on the order - /// of ten seconds or so. - /// - /// When listening is done always invoke either [cancel] or [stop] to - /// end the session, even if it times out. [cancelOnError] provides an - /// automatic way to ensure this happens. - /// - /// [onResult] is an optional listener that is notified when words - /// are recognized. - /// - /// [listenFor] sets the maximum duration that it will listen for, after - /// that it automatically stops the listen for you. - /// - /// [pauseFor] sets the maximum duration of a pause in speech with no words - /// detected, after that it automatically stops the listen for you. - /// - /// [localeId] is an optional locale that can be used to listen in a language - /// other than the current system default. See [locales] to find the list of - /// supported languages for listening. - /// - /// [onSoundLevelChange] is an optional listener that is notified when the - /// sound level of the input changes. Use this to update the UI in response to - /// more or less input. The values currently differ between Ancroid and iOS, - /// haven't yet been able to determine from the Android documentation what the - /// value means. On iOS the value returned is in decibels. - /// - /// [cancelOnError] if true then listening is automatically canceled on a - /// permanent error. This defaults to false. When false cancel should be - /// called from the error handler. - /// - /// [partialResults] if true the listen reports results as they are recognized, - /// when false only final results are reported. Defaults to true. - /// - /// [onDevice] if true the listen attempts to recognize locally with speech never - /// leaving the device. If it cannot do this the listen attempt will fail. This is - /// usually only needed for sensitive content where privacy or security is a concern. - Future listen( - {SpeechResultListener onResult, - Duration listenFor, - Duration pauseFor, - String localeId, - SpeechSoundLevelChange onSoundLevelChange, - cancelOnError = false, - partialResults = true, - onDevice = false, - ListenMode listenMode = ListenMode.confirmation}) async { - if (!_initWorked) { - throw SpeechToTextNotInitializedException(); - } - _userEnded = false; - _cancelOnError = cancelOnError; - _recognized = false; - _resultListener = onResult; - _soundLevelChange = onSoundLevelChange; - _partialResults = partialResults; - Map listenParams = { - "partialResults": partialResults || null != pauseFor, - "onDevice": onDevice, - "listenMode": listenMode.index, - }; - if (null != localeId) { - listenParams["localeId"] = localeId; - } - try { - bool started = await channel.invokeMethod(listenMethod, listenParams); - if (started) { - _listenStartedAt = clock.now().millisecondsSinceEpoch; - _setupListenAndPause(pauseFor, listenFor); - } - } on PlatformException catch (e) { - throw ListenFailedException(e.details); - } - } - - void _setupListenAndPause(Duration pauseFor, Duration listenFor) { - _pauseFor = null; - _listenFor = null; - if (null == pauseFor && null == listenFor) { - return; - } - var minDuration; - if (null == pauseFor) { - _listenFor = Duration(milliseconds: listenFor.inMilliseconds); - minDuration = listenFor; - } else if (null == listenFor) { - _pauseFor = Duration(milliseconds: pauseFor.inMilliseconds); - minDuration = pauseFor; - } else { - _listenFor = Duration(milliseconds: listenFor.inMilliseconds); - _pauseFor = Duration(milliseconds: pauseFor.inMilliseconds); - var minMillis = min(listenFor.inMilliseconds - _elapsedListenMillis, - pauseFor.inMilliseconds); - minDuration = Duration(milliseconds: minMillis); - } - _listenTimer = Timer(minDuration, _stopOnPauseOrListen); - } - - int get _elapsedListenMillis => - clock.now().millisecondsSinceEpoch - _listenStartedAt; - int get _elapsedSinceSpeechEvent => - clock.now().millisecondsSinceEpoch - _lastSpeechEventAt; - - void _stopOnPauseOrListen() { - if (null != _listenFor && - _elapsedListenMillis >= _listenFor.inMilliseconds) { - _stop(); - } else if (null != _pauseFor && - _elapsedSinceSpeechEvent >= _pauseFor.inMilliseconds) { - _stop(); - } else { - _setupListenAndPause(_pauseFor, _listenFor); - } - } - - /// returns the list of speech locales available on the device. - /// - /// This method is useful to find the identifier to use - /// for the [listen] method, it is the [localeId] member of the - /// [LocaleName]. - /// - /// Each [LocaleName] in the returned list has the - /// identifier for the locale as well as a name for - /// display. The name is localized for the system locale on - /// the device. - Future> locales() async { - if (!_initWorked) { - throw SpeechToTextNotInitializedException(); - } - final List locales = await channel.invokeMethod('locales'); - List filteredLocales = locales - .map((locale) { - var components = locale.split(":"); - if (components.length != 2) { - return null; - } - return LocaleName(components[0], components[1]); - }) - .where((item) => item != null) - .toList(); - if (filteredLocales.isNotEmpty) { - _systemLocale = filteredLocales.first; - } else { - _systemLocale = null; - } - filteredLocales.sort((ln1, ln2) => ln1.name.compareTo(ln2.name)); - return filteredLocales; - } - - /// returns the locale that will be used if no localeId is passed - /// to the [listen] method. - Future systemLocale() async { - if (null == _systemLocale) { - await locales(); - } - return Future.value(_systemLocale); - } - - Future _handleCallbacks(MethodCall call) async { - // print("SpeechToText call: ${call.method} ${call.arguments}"); - switch (call.method) { - case textRecognitionMethod: - if (call.arguments is String) { - _onTextRecognition(call.arguments); - } - break; - case notifyErrorMethod: - if (call.arguments is String) { - await _onNotifyError(call.arguments); - } - break; - case notifyStatusMethod: - if (call.arguments is String) { - _onNotifyStatus(call.arguments); - } - break; - case soundLevelChangeMethod: - if (call.arguments is double) { - _onSoundLevelChange(call.arguments); - } - break; - default: - } - } - - void _onTextRecognition(String resultJson) { - _lastSpeechEventAt = clock.now().millisecondsSinceEpoch; - Map resultMap = jsonDecode(resultJson); - SpeechRecognitionResult speechResult = - SpeechRecognitionResult.fromJson(resultMap); - if (!_partialResults && !speechResult.finalResult) { - return; - } - _recognized = true; - // print("Recognized text $resultJson"); - - _lastRecognized = speechResult.recognizedWords; - if (null != _resultListener) { - _resultListener(speechResult); - } - } - - Future _onNotifyError(String errorJson) async { - if (isNotListening && _userEnded) { - return; - } - Map errorMap = jsonDecode(errorJson); - SpeechRecognitionError speechError = - SpeechRecognitionError.fromJson(errorMap); - _lastError = speechError; - if (null != errorListener) { - errorListener(speechError); - } - if (_cancelOnError && speechError.permanent) { - await _cancel(); - } - } - - void _onNotifyStatus(String status) { - _lastStatus = status; - _listening = status == listeningStatus; - // print(status); - if (null != statusListener) { - statusListener(status); - } - } - - void _onSoundLevelChange(double level) { - if (isNotListening) { - return; - } - _lastSoundLevel = level; - if (null != _soundLevelChange) { - _soundLevelChange(level); - } - } - - _shutdownListener() { - _listening = false; - _recognized = false; - _listenTimer?.cancel(); - _listenTimer = null; - } - - @visibleForTesting - Future processMethodCall(MethodCall call) async { - return await _handleCallbacks(call); - } -} - -/// A single locale with a [name], localized to the current system locale, -/// and a [localeId] which can be used in the [listen] method to choose a -/// locale for speech recognition. -class LocaleName { - final String localeId; - final String name; - LocaleName(this.localeId, this.name); -} - -/// Thrown when a method is called that requires successful -/// initialization first. -class SpeechToTextNotInitializedException implements Exception {} - -/// Thrown when listen fails to properly start a speech listening session -/// on the device -class ListenFailedException implements Exception { - final String details; - ListenFailedException(this.details); -} diff --git a/speech_to_text/lib/speech_to_text_provider.dart b/speech_to_text/lib/speech_to_text_provider.dart deleted file mode 100644 index 91adf3b4..00000000 --- a/speech_to_text/lib/speech_to_text_provider.dart +++ /dev/null @@ -1,201 +0,0 @@ -import 'dart:async'; - -import 'package:flutter/material.dart'; -import 'package:speech_to_text/speech_recognition_error.dart'; -import 'package:speech_to_text/speech_recognition_event.dart'; -import 'package:speech_to_text/speech_recognition_result.dart'; -import 'package:speech_to_text/speech_to_text.dart'; - -/// Simplifies interaction with [SpeechToText] by handling all the callbacks and notifying -/// listeners as events happen. -/// -/// Here's an example of using the [SpeechToTextProvider] -/// ``` -/// var speechProvider = SpeechToTextProvider( SpeechToText()); -/// var available = await speechProvider.initialize(); -/// StreamSubscription _subscription; -/// _subscription = speechProvider.recognitionController.stream.listen((recognitionEvent) { -/// if (recognitionEvent.eventType == SpeechRecognitionEventType.finalRecognitionEvent ) { -/// print("I heard: ${recognitionEvent.recognitionResult.recognizedWords}"); -/// } -/// }); -/// speechProvider.addListener(() { -/// var words = speechProvider.lastWords; -/// }); -class SpeechToTextProvider extends ChangeNotifier { - final StreamController _recognitionController = - StreamController.broadcast(); - final SpeechToText _speechToText; - SpeechRecognitionResult _lastResult; - double _lastLevel = 0; - List _locales = []; - LocaleName _systemLocale; - - /// Only construct one instance in an application. - /// - /// Do not call `initialize` on the [SpeechToText] that is passed as a parameter, instead - /// call the [initialize] method on this class. - SpeechToTextProvider(this._speechToText); - - Stream get stream => _recognitionController.stream; - - /// Returns the last result received, may be null. - SpeechRecognitionResult get lastResult => _lastResult; - - /// Returns the last error received, may be null. - SpeechRecognitionError get lastError => _speechToText.lastError; - - /// Returns the last sound level received. - /// - /// Note this is only available when the `soundLevel` is set to true on - /// a call to [listen], will be 0 at all other times. - double get lastLevel => _lastLevel; - - /// Initializes the provider and the contained [SpeechToText] instance. - /// - /// Returns true if [SpeechToText] was initialized successful and can now - /// be used, false otherwse. - Future initialize() async { - if (isAvailable) { - return isAvailable; - } - bool availableBefore = _speechToText.isAvailable; - bool available = - await _speechToText.initialize(onStatus: _onStatus, onError: _onError); - if (available) { - _locales = []; - _locales.addAll(await _speechToText.locales()); - _systemLocale = await _speechToText.systemLocale(); - } - if (availableBefore != available) { - notifyListeners(); - } - return available; - } - - /// Returns true if the provider has been initialized and can be used to recognize speech. - bool get isAvailable => _speechToText.isAvailable; - - /// Returns true if the provider cannot be used to recognize speech, either because it has not - /// yet been initialized or because initialization failed. - bool get isNotAvailable => !_speechToText.isAvailable; - - /// Returns true if [SpeechToText] is listening for new speech. - bool get isListening => _speechToText.isListening; - - /// Returns true if [SpeechToText] is not listening for new speech. - bool get isNotListening => _speechToText.isNotListening; - - /// Returns true if [SpeechToText] has a previous error. - bool get hasError => _speechToText.hasError; - - /// Returns true if [lastResult] has a last result. - bool get hasResults => null != _lastResult; - - /// Returns the list of locales that are available on the device for speech recognition. - List get locales => _locales; - - /// Returns the locale that is currently set as active on the device. - LocaleName get systemLocale => _systemLocale; - - /// Start listening for new events, set [partialResults] to true to receive interim - /// recognition results. - /// - /// [soundLevel] set to true to be notified on changes to the input sound level - /// on the microphone. - /// - /// [listenFor] sets the maximum duration that it will listen for, after - /// that it automatically stops the listen for you. - /// - /// [pauseFor] sets the maximum duration of a pause in speech with no words - /// detected, after that it automatically stops the listen for you. - /// - /// Call this only after a successful [initialize] call - void listen( - {bool partialResults = false, - bool soundLevel = false, - Duration listenFor, - Duration pauseFor}) { - _lastLevel = 0; - _lastResult = null; - if (soundLevel) { - _speechToText.listen( - partialResults: partialResults, - listenFor: listenFor, - pauseFor: pauseFor, - cancelOnError: true, - onResult: _onListenResult, - // onSoundLevelChange: _onSoundLevelChange); - ); - } else { - _speechToText.listen( - partialResults: partialResults, - listenFor: listenFor, - pauseFor: pauseFor, - cancelOnError: true, - onResult: _onListenResult); - } - } - - /// Stops a current active listening session. - /// - /// Call this after calling [listen] to stop the recognizer from listening further - /// and return the current result as final. - void stop() { - _speechToText.stop(); - notifyListeners(); - } - - /// Cancel a current active listening session. - /// - /// Call this after calling [listen] to stop the recognizer from listening further - /// and ignore any results recognized so far. - void cancel() { - _speechToText.cancel(); - notifyListeners(); - } - - void _onError(SpeechRecognitionError errorNotification) { - _recognitionController.add(SpeechRecognitionEvent( - SpeechRecognitionEventType.errorEvent, - null, - errorNotification, - isListening, - null)); - notifyListeners(); - } - - void _onStatus(String status) { - _recognitionController.add(SpeechRecognitionEvent( - SpeechRecognitionEventType.statusChangeEvent, - null, - null, - isListening, - null)); - notifyListeners(); - } - - void _onListenResult(SpeechRecognitionResult result) { - _lastResult = result; - _recognitionController.add(SpeechRecognitionEvent( - result.finalResult - ? SpeechRecognitionEventType.finalRecognitionEvent - : SpeechRecognitionEventType.partialRecognitionEvent, - result, - null, - isListening, - null)); - notifyListeners(); - } - - // void _onSoundLevelChange(double level) { - // _lastLevel = level; - // _recognitionController.add(SpeechRecognitionEvent( - // SpeechRecognitionEventType.soundLevelChangeEvent, - // null, - // null, - // null, - // level)); - // notifyListeners(); - // } -} diff --git a/speech_to_text/pubspec.yaml b/speech_to_text/pubspec.yaml deleted file mode 100644 index 831c9181..00000000 --- a/speech_to_text/pubspec.yaml +++ /dev/null @@ -1,31 +0,0 @@ -name: speech_to_text -description: A Flutter plugin that exposes device specific speech to text recognition capability. - - - -environment: - sdk: ">=2.1.0 <3.0.0" - flutter: ">=1.10.0" - -dependencies: - flutter: - sdk: flutter - json_annotation: ^4.3.0 - clock: ^1.1.0 - -dev_dependencies: - flutter_test: - sdk: flutter - build_runner: ^2.1.5 - json_serializable: ^6.0.1 - fake_async: ^1.2.0 - -flutter: - plugin: - platforms: - android: - package: com.csdcorp.speech_to_text - pluginClass: SpeechToTextPlugin - ios: - pluginClass: SpeechToTextPlugin - diff --git a/speech_to_text/test/speech_recognition_error_test.dart b/speech_to_text/test/speech_recognition_error_test.dart deleted file mode 100644 index 202ae4cd..00000000 --- a/speech_to_text/test/speech_recognition_error_test.dart +++ /dev/null @@ -1,65 +0,0 @@ -import 'dart:convert'; - -import 'package:flutter_test/flutter_test.dart'; -import 'package:speech_to_text/speech_recognition_error.dart'; - -void main() { - const String msg1 = "msg1"; - - setUp(() {}); - - group('properties', () { - test('equals true for same object', () { - SpeechRecognitionError error = SpeechRecognitionError(msg1, false); - expect(error, error); - }); - test('equals true for different object same values', () { - SpeechRecognitionError error1 = SpeechRecognitionError(msg1, false); - SpeechRecognitionError error2 = SpeechRecognitionError(msg1, false); - expect(error1, error2); - }); - test('equals false for different object', () { - SpeechRecognitionError error1 = SpeechRecognitionError(msg1, false); - SpeechRecognitionError error2 = SpeechRecognitionError("msg2", false); - expect(error1, isNot(error2)); - }); - test('hash same for same object', () { - SpeechRecognitionError error = SpeechRecognitionError(msg1, false); - expect(error.hashCode, error.hashCode); - }); - test('hash same for different object same values', () { - SpeechRecognitionError error1 = SpeechRecognitionError(msg1, false); - SpeechRecognitionError error2 = SpeechRecognitionError(msg1, false); - expect(error1.hashCode, error2.hashCode); - }); - test('hash different for different object', () { - SpeechRecognitionError error1 = SpeechRecognitionError(msg1, false); - SpeechRecognitionError error2 = SpeechRecognitionError("msg2", false); - expect(error1.hashCode, isNot(error2.hashCode)); - }); - test('toString as expected', () { - SpeechRecognitionError error1 = SpeechRecognitionError(msg1, false); - expect(error1.toString(), - "SpeechRecognitionError msg: $msg1, permanent: false"); - }); - }); - group('json', () { - test('loads properly', () { - var json = jsonDecode('{"errorMsg":"$msg1","permanent":true}'); - SpeechRecognitionError error = SpeechRecognitionError.fromJson(json); - expect(error.errorMsg, msg1); - expect(error.permanent, isTrue); - json = jsonDecode('{"errorMsg":"$msg1","permanent":false}'); - error = SpeechRecognitionError.fromJson(json); - expect(error.permanent, isFalse); - }); - test('roundtrips properly', () { - var json = jsonDecode('{"errorMsg":"$msg1","permanent":true}'); - SpeechRecognitionError error = SpeechRecognitionError.fromJson(json); - var roundtripJson = error.toJson(); - SpeechRecognitionError roundtripError = - SpeechRecognitionError.fromJson(roundtripJson); - expect(error, roundtripError); - }); - }); -} diff --git a/speech_to_text/test/speech_recognition_event_test.dart b/speech_to_text/test/speech_recognition_event_test.dart deleted file mode 100644 index ceaaab8a..00000000 --- a/speech_to_text/test/speech_recognition_event_test.dart +++ /dev/null @@ -1,42 +0,0 @@ -import 'package:flutter_test/flutter_test.dart'; -import 'package:speech_to_text/speech_recognition_event.dart'; - -import 'test_speech_channel_handler.dart'; - -void main() { - group('properties', () { - test('status listening matches', () { - var event = SpeechRecognitionEvent( - SpeechRecognitionEventType.statusChangeEvent, null, null, true, null); - expect(event.eventType, SpeechRecognitionEventType.statusChangeEvent); - expect(event.isListening, isTrue); - }); - test('result matches', () { - var event = SpeechRecognitionEvent( - SpeechRecognitionEventType.finalRecognitionEvent, - TestSpeechChannelHandler.firstRecognizedResult, - null, - null, - null); - expect(event.eventType, SpeechRecognitionEventType.finalRecognitionEvent); - expect(event.recognitionResult, - TestSpeechChannelHandler.firstRecognizedResult); - }); - test('error matches', () { - var event = SpeechRecognitionEvent(SpeechRecognitionEventType.errorEvent, - null, TestSpeechChannelHandler.firstError, null, null); - expect(event.eventType, SpeechRecognitionEventType.errorEvent); - expect(event.error, TestSpeechChannelHandler.firstError); - }); - test('sound level matches', () { - var event = SpeechRecognitionEvent( - SpeechRecognitionEventType.soundLevelChangeEvent, - null, - null, - null, - TestSpeechChannelHandler.level1); - expect(event.eventType, SpeechRecognitionEventType.soundLevelChangeEvent); - expect(event.level, TestSpeechChannelHandler.level1); - }); - }); -} diff --git a/speech_to_text/test/speech_recognition_result_test.dart b/speech_to_text/test/speech_recognition_result_test.dart deleted file mode 100644 index 1516779a..00000000 --- a/speech_to_text/test/speech_recognition_result_test.dart +++ /dev/null @@ -1,134 +0,0 @@ -import 'dart:convert'; - -import 'package:flutter_test/flutter_test.dart'; -import 'package:speech_to_text/speech_recognition_result.dart'; - -void main() { - final String firstRecognizedWords = 'hello'; - final String secondRecognizedWords = 'hello there'; - final double firstConfidence = 0.85; - final double secondConfidence = 0.62; - final String firstRecognizedJson = - '{"alternates":[{"recognizedWords":"$firstRecognizedWords","confidence":$firstConfidence}],"finalResult":false}'; - final String secondRecognizedJson = - '{"alternates":[{"recognizedWords":"$secondRecognizedWords","confidence":$secondConfidence}],"finalResult":false}'; - final SpeechRecognitionWords firstWords = - SpeechRecognitionWords(firstRecognizedWords, firstConfidence); - final SpeechRecognitionWords secondWords = - SpeechRecognitionWords(secondRecognizedWords, secondConfidence); - - setUp(() {}); - - group('recognizedWords', () { - test('empty if no alternates', () { - SpeechRecognitionResult result = SpeechRecognitionResult([], true); - expect(result.recognizedWords, isEmpty); - }); - test('matches first alternate', () { - SpeechRecognitionResult result = - SpeechRecognitionResult([firstWords, secondWords], true); - expect(result.recognizedWords, firstRecognizedWords); - }); - }); - group('alternates', () { - test('empty if no alternates', () { - SpeechRecognitionResult result = SpeechRecognitionResult([], true); - expect(result.alternates, isEmpty); - }); - test('expected contents', () { - SpeechRecognitionResult result = - SpeechRecognitionResult([firstWords, secondWords], true); - expect(result.alternates, contains(firstWords)); - expect(result.alternates, contains(secondWords)); - }); - test('in order', () { - SpeechRecognitionResult result = - SpeechRecognitionResult([firstWords, secondWords], true); - expect(result.alternates.first, firstWords); - }); - }); - group('confidence', () { - test('0 if no alternates', () { - SpeechRecognitionResult result = SpeechRecognitionResult([], true); - expect(result.confidence, 0); - }); - test('isConfident false if no alternates', () { - SpeechRecognitionResult result = SpeechRecognitionResult([], true); - expect(result.isConfident(), isFalse); - }); - test('isConfident matches first alternate', () { - SpeechRecognitionResult result = - SpeechRecognitionResult([firstWords, secondWords], true); - expect(result.isConfident(), firstWords.isConfident()); - }); - test('hasConfidenceRating false if no alternates', () { - SpeechRecognitionResult result = SpeechRecognitionResult([], true); - expect(result.hasConfidenceRating, isFalse); - }); - test('hasConfidenceRating matches first alternate', () { - SpeechRecognitionResult result = - SpeechRecognitionResult([firstWords, secondWords], true); - expect(result.hasConfidenceRating, firstWords.hasConfidenceRating); - }); - }); - group('json', () { - test('loads correctly', () { - var json = jsonDecode(firstRecognizedJson); - SpeechRecognitionResult result = SpeechRecognitionResult.fromJson(json); - expect(result.recognizedWords, firstRecognizedWords); - expect(result.confidence, firstConfidence); - }); - test('roundtrips correctly', () { - var json = jsonDecode(firstRecognizedJson); - SpeechRecognitionResult result = SpeechRecognitionResult.fromJson(json); - var roundTripJson = result.toJson(); - SpeechRecognitionResult roundtripResult = - SpeechRecognitionResult.fromJson(roundTripJson); - expect(result, roundtripResult); - }); - }); - group('overrides', () { - test('toString works with no alternates', () { - SpeechRecognitionResult result = SpeechRecognitionResult([], true); - expect( - result.toString(), "SpeechRecognitionResult words: [], final: true"); - }); - test('toString works with alternates', () { - SpeechRecognitionResult result = - SpeechRecognitionResult([firstWords], true); - expect(result.toString(), - "SpeechRecognitionResult words: [SpeechRecognitionWords words: hello, confidence: 0.85], final: true"); - }); - test('hash same for same object', () { - SpeechRecognitionResult result = - SpeechRecognitionResult([firstWords], true); - expect(result.hashCode, result.hashCode); - }); - test('hash differs for different objects', () { - SpeechRecognitionResult result1 = - SpeechRecognitionResult([firstWords], true); - SpeechRecognitionResult result2 = - SpeechRecognitionResult([secondWords], true); - expect(result1.hashCode, isNot(result2.hashCode)); - }); - test('equals same for same object', () { - SpeechRecognitionResult result = - SpeechRecognitionResult([firstWords], true); - expect(result, result); - }); - test('equals same for different object same values', () { - SpeechRecognitionResult result1 = - SpeechRecognitionResult([firstWords], true); - SpeechRecognitionResult result1a = - SpeechRecognitionResult([firstWords], true); - expect(result1, result1a); - }); - test('equals differs for different objects', () { - SpeechRecognitionResult result1 = - SpeechRecognitionResult([firstWords], true); - SpeechRecognitionResult result2 = - SpeechRecognitionResult([secondWords], true); - expect(result1, isNot(result2)); - }); - }); -} diff --git a/speech_to_text/test/speech_recognitions_words_test.dart b/speech_to_text/test/speech_recognitions_words_test.dart deleted file mode 100644 index 36a9ef0e..00000000 --- a/speech_to_text/test/speech_recognitions_words_test.dart +++ /dev/null @@ -1,86 +0,0 @@ -import 'dart:convert'; - -import 'package:flutter_test/flutter_test.dart'; -import 'package:speech_to_text/speech_recognition_result.dart'; - -void main() { - final String firstRecognizedWords = 'hello'; - final String secondRecognizedWords = 'hello there'; - final double firstConfidence = 0.85; - final double secondConfidence = 0.62; - final String firstRecognizedJson = - '{"recognizedWords":"$firstRecognizedWords","confidence":$firstConfidence}'; - final SpeechRecognitionWords firstWords = - SpeechRecognitionWords(firstRecognizedWords, firstConfidence); - final SpeechRecognitionWords secondWords = - SpeechRecognitionWords(secondRecognizedWords, secondConfidence); - - setUp(() {}); - - group('properties', () { - test('words', () { - expect(firstWords.recognizedWords, firstRecognizedWords); - expect(secondWords.recognizedWords, secondRecognizedWords); - }); - test('confidence', () { - expect(firstWords.confidence, firstConfidence); - expect(secondWords.confidence, secondConfidence); - expect(firstWords.hasConfidenceRating, isTrue); - }); - test('equals true for same object', () { - expect(firstWords, firstWords); - }); - test('equals true for different object with same values', () { - SpeechRecognitionWords firstWordsA = - SpeechRecognitionWords(firstRecognizedWords, firstConfidence); - expect(firstWords, firstWordsA); - }); - test('equals false for different results', () { - expect(firstWords, isNot(secondWords)); - }); - test('hash same for same object', () { - expect(firstWords.hashCode, firstWords.hashCode); - }); - test('hash same for different object with same values', () { - SpeechRecognitionWords firstWordsA = - SpeechRecognitionWords(firstRecognizedWords, firstConfidence); - expect(firstWords.hashCode, firstWordsA.hashCode); - }); - test('hash different for different results', () { - expect(firstWords.hashCode, isNot(secondWords.hashCode)); - }); - }); - group('isConfident', () { - test('true when >= 0.8', () { - expect(firstWords.isConfident(), isTrue); - }); - test('false when < 0.8', () { - expect(secondWords.isConfident(), isFalse); - }); - test('respects threshold', () { - expect(secondWords.isConfident(threshold: 0.5), isTrue); - }); - test('true when missing', () { - SpeechRecognitionWords words = SpeechRecognitionWords( - firstRecognizedWords, SpeechRecognitionWords.missingConfidence); - expect(words.isConfident(), isTrue); - expect(words.hasConfidenceRating, isFalse); - }); - }); - group('json', () { - test('loads correctly', () { - var json = jsonDecode(firstRecognizedJson); - SpeechRecognitionWords words = SpeechRecognitionWords.fromJson(json); - expect(words.recognizedWords, firstRecognizedWords); - expect(words.confidence, firstConfidence); - }); - test('roundtrips correctly', () { - var json = jsonDecode(firstRecognizedJson); - SpeechRecognitionWords words = SpeechRecognitionWords.fromJson(json); - var roundTripJson = words.toJson(); - SpeechRecognitionWords roundtripWords = - SpeechRecognitionWords.fromJson(roundTripJson); - expect(words, roundtripWords); - }); - }); -} diff --git a/speech_to_text/test/speech_to_text_provider_test.dart b/speech_to_text/test/speech_to_text_provider_test.dart deleted file mode 100644 index 25366b6f..00000000 --- a/speech_to_text/test/speech_to_text_provider_test.dart +++ /dev/null @@ -1,196 +0,0 @@ -import 'package:fake_async/fake_async.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:speech_to_text/speech_to_text.dart'; -import 'package:speech_to_text/speech_to_text_provider.dart'; - -import 'test_speech_channel_handler.dart'; -import 'test_speech_listener.dart'; - -void main() { - SpeechToTextProvider provider; - SpeechToText speechToText; - TestSpeechChannelHandler speechHandler; - TestSpeechListener speechListener; - - TestWidgetsFlutterBinding.ensureInitialized(); - - setUp(() { - speechToText = SpeechToText.withMethodChannel(SpeechToText.speechChannel); - speechHandler = TestSpeechChannelHandler(speechToText); - speechToText.channel - .setMockMethodCallHandler(speechHandler.methodCallHandler); - provider = SpeechToTextProvider(speechToText); - speechListener = TestSpeechListener(provider); - provider.addListener(speechListener.onNotify); - }); - - tearDown(() { - speechToText.channel.setMockMethodCallHandler(null); - }); - - group('delegates', () { - test('isListening matches delegate defaults', () { - expect(provider.isListening, speechToText.isListening); - expect(provider.isNotListening, speechToText.isNotListening); - }); - test('isAvailable matches delegate defaults', () { - expect(provider.isAvailable, speechToText.isAvailable); - expect(provider.isNotAvailable, !speechToText.isAvailable); - }); - test('isAvailable matches delegate after init', () async { - expect(await provider.initialize(), isTrue); - expect(provider.isAvailable, speechToText.isAvailable); - expect(provider.isNotAvailable, !speechToText.isAvailable); - }); - test('hasError matches delegate after error', () async { - expect(await provider.initialize(), isTrue); - expect(provider.hasError, speechToText.hasError); - }); - }); - group('listening', () { - test('notifies on initialize', () async { - fakeAsync((fa) { - provider.initialize(); - fa.flushMicrotasks(); - expect(speechListener.notified, isTrue); - expect(speechListener.isAvailable, isTrue); - }); - }); - test('notifies on listening', () async { - fakeAsync((fa) { - setupForListen(provider, fa, speechListener); - expect(speechListener.notified, isTrue); - expect(speechListener.isListening, isTrue); - expect(provider.hasResults, isFalse); - }); - }); - test('notifies on final words', () async { - fakeAsync((fa) { - setupForListen(provider, fa, speechListener); - speechListener.reset(); - speechHandler.notifyFinalWords(); - fa.flushMicrotasks(); - expect(speechListener.notified, isTrue); - expect(provider.hasResults, isTrue); - var result = speechListener.recognitionResult; - expect(result.recognizedWords, - TestSpeechChannelHandler.secondRecognizedWords); - expect(result.finalResult, isTrue); - }); - }); - test('hasResult false after listening before new results', () async { - fakeAsync((fa) { - setupForListen(provider, fa, speechListener); - speechHandler.notifyFinalWords(); - provider.stop(); - setupForListen(provider, fa, speechListener); - fa.flushMicrotasks(); - expect(provider.hasResults, isFalse); - }); - }); - test('notifies on partial words', () async { - fakeAsync((fa) { - setupForListen(provider, fa, speechListener, partialResults: true); - speechListener.reset(); - speechHandler.notifyPartialWords(); - fa.flushMicrotasks(); - expect(speechListener.notified, isTrue); - expect(provider.hasResults, isTrue); - var result = speechListener.recognitionResult; - expect(result.recognizedWords, - TestSpeechChannelHandler.firstRecognizedWords); - expect(result.finalResult, isFalse); - }); - }); - }); - group('soundLevel', () { - test('notifies when requested', () async { - fakeAsync((fa) { - setupForListen(provider, fa, speechListener, - partialResults: true, soundLevel: true); - speechListener.reset(); - speechHandler.notifySoundLevel(); - fa.flushMicrotasks(); - expect(speechListener.notified, isTrue); - expect(speechListener.soundLevel, TestSpeechChannelHandler.level2); - }); - }); - test('no notification by default', () async { - fakeAsync((fa) { - setupForListen(provider, fa, speechListener, - partialResults: true, soundLevel: false); - speechListener.reset(); - speechHandler.notifySoundLevel(); - fa.flushMicrotasks(); - expect(speechListener.notified, isFalse); - expect(speechListener.soundLevel, 0); - }); - }); - }); - group('stop/cancel', () { - test('notifies on stop', () async { - fakeAsync((fa) { - provider.initialize(); - setupForListen(provider, fa, speechListener); - speechListener.reset(); - provider.stop(); - fa.flushMicrotasks(); - expect(speechListener.notified, isTrue); - expect(speechListener.isListening, isFalse); - }); - }); - test('notifies on cancel', () async { - fakeAsync((fa) { - provider.initialize(); - setupForListen(provider, fa, speechListener); - speechListener.reset(); - provider.cancel(); - fa.flushMicrotasks(); - expect(speechListener.notified, isTrue); - expect(speechListener.isListening, isFalse); - }); - }); - }); - group('error handling', () { - test('hasError matches delegate default', () async { - expect(await provider.initialize(), isTrue); - expect(provider.hasError, speechToText.hasError); - }); - test('notifies on error', () async { - fakeAsync((fa) { - provider.initialize(); - setupForListen(provider, fa, speechListener); - speechListener.reset(); - speechHandler.notifyPermanentError(); - expect(speechListener.notified, isTrue); - expect(speechListener.hasError, isTrue); - }); - }); - }); - group('locale', () { - test('locales empty before init', () async { - expect(provider.systemLocale, isNull); - expect(provider.locales, isEmpty); - }); - test('set from SpeechToText after init', () async { - fakeAsync((fa) { - speechHandler.setupLocales(); - provider.initialize(); - fa.flushMicrotasks(); - expect( - provider.systemLocale.localeId, TestSpeechChannelHandler.localeId1); - expect(provider.locales, hasLength(speechHandler.locales.length)); - }); - }); - }); -} - -void setupForListen(SpeechToTextProvider provider, FakeAsync fa, - TestSpeechListener speechListener, - {bool partialResults = false, bool soundLevel = false}) { - provider.initialize(); - fa.flushMicrotasks(); - speechListener.reset(); - provider.listen(partialResults: partialResults, soundLevel: soundLevel); - fa.flushMicrotasks(); -} diff --git a/speech_to_text/test/speech_to_text_test.dart b/speech_to_text/test/speech_to_text_test.dart deleted file mode 100644 index 7b4701ff..00000000 --- a/speech_to_text/test/speech_to_text_test.dart +++ /dev/null @@ -1,425 +0,0 @@ -import 'package:fake_async/fake_async.dart'; -import 'package:flutter/services.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:speech_to_text/speech_recognition_error.dart'; -import 'package:speech_to_text/speech_recognition_result.dart'; -import 'package:speech_to_text/speech_to_text.dart'; - -import 'test_speech_channel_handler.dart'; - -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - TestSpeechListener listener; - TestSpeechChannelHandler speechHandler; - SpeechToText speech; - - setUp(() { - listener = TestSpeechListener(); - speech = SpeechToText.withMethodChannel(SpeechToText.speechChannel); - speechHandler = TestSpeechChannelHandler(speech); - speech.channel.setMockMethodCallHandler(speechHandler.methodCallHandler); - }); - - tearDown(() { - speech.channel.setMockMethodCallHandler(null); - }); - - group('hasPermission', () { - test('true if platform reports true', () async { - expect(await speech.hasPermission, true); - }); - test('false if platform reports false', () async { - speechHandler.hasPermissionResult = false; - expect(await speech.hasPermission, false); - }); - }); - group('init', () { - test('succeeds on platform success', () async { - expect(await speech.initialize(), true); - expect(speechHandler.initInvoked, true); - expect(speech.isAvailable, true); - }); - test('only invokes once', () async { - expect(await speech.initialize(), true); - speechHandler.initInvoked = false; - expect(await speech.initialize(), true); - expect(speechHandler.initInvoked, false); - }); - test('fails on platform failure', () async { - speechHandler.initResult = false; - expect(await speech.initialize(), false); - expect(speech.isAvailable, false); - }); - }); - - group('listen', () { - test('fails with exception if not initialized', () async { - try { - await speech.listen(); - fail("Expected an exception."); - } on SpeechToTextNotInitializedException { - // This is a good result - } - }); - test('fails with exception if init fails', () async { - try { - speechHandler.initResult = false; - await speech.initialize(); - await speech.listen(); - fail("Expected an exception."); - } on SpeechToTextNotInitializedException { - // This is a good result - } - }); - test('invokes listen after successful init', () async { - await speech.initialize(); - await speech.listen(); - expect(speechHandler.listenLocale, isNull); - expect(speechHandler.listenInvoked, true); - }); - test('converts platformException to listenFailed', () async { - await speech.initialize(); - speechHandler.listenException = true; - try { - await speech.listen(); - fail("Should have thrown"); - } on ListenFailedException catch (e) { - expect(e.details, TestSpeechChannelHandler.listenExceptionDetails); - } catch (wrongE) { - fail("Should have been ListenFailedException"); - } - }); - test('stops listen after listenFor duration', () async { - fakeAsync((fa) { - speech.initialize(); - fa.flushMicrotasks(); - speech.listen(listenFor: Duration(seconds: 2)); - fa.flushMicrotasks(); - expect(speech.isListening, isTrue); - fa.elapse(Duration(seconds: 2)); - expect(speech.isListening, isFalse); - }); - }); - test('stops listen after listenFor duration even with speech event', - () async { - fakeAsync((fa) { - speech.initialize(); - fa.flushMicrotasks(); - speech.listen(listenFor: Duration(seconds: 1)); - speech.processMethodCall(MethodCall(SpeechToText.textRecognitionMethod, - TestSpeechChannelHandler.firstRecognizedJson)); - fa.flushMicrotasks(); - expect(speech.isListening, isTrue); - fa.elapse(Duration(seconds: 1)); - expect(speech.isListening, isFalse); - }); - }); - test('stops listen after pauseFor duration with no speech', () async { - fakeAsync((fa) { - speech.initialize(); - fa.flushMicrotasks(); - speech.listen(pauseFor: Duration(seconds: 2)); - fa.flushMicrotasks(); - expect(speech.isListening, isTrue); - fa.elapse(Duration(seconds: 2)); - expect(speech.isListening, isFalse); - }); - }); - test('stops listen after pauseFor with longer listenFor duration', - () async { - fakeAsync((fa) { - speech.initialize(); - fa.flushMicrotasks(); - speech.listen( - pauseFor: Duration(seconds: 1), listenFor: Duration(seconds: 5)); - fa.flushMicrotasks(); - expect(speech.isListening, isTrue); - fa.elapse(Duration(seconds: 1)); - expect(speech.isListening, isFalse); - }); - }); - test('stops listen after listenFor with longer pauseFor duration', - () async { - fakeAsync((fa) { - speech.initialize(); - fa.flushMicrotasks(); - speech.listen( - listenFor: Duration(seconds: 1), pauseFor: Duration(seconds: 5)); - fa.flushMicrotasks(); - expect(speech.isListening, isTrue); - fa.elapse(Duration(seconds: 1)); - expect(speech.isListening, isFalse); - }); - }); - test('keeps listening after pauseFor with speech event', () async { - fakeAsync((fa) { - speech.initialize(); - fa.flushMicrotasks(); - speech.listen(pauseFor: Duration(seconds: 2)); - fa.flushMicrotasks(); - fa.elapse(Duration(seconds: 1)); - speech.processMethodCall(MethodCall(SpeechToText.textRecognitionMethod, - TestSpeechChannelHandler.firstRecognizedJson)); - fa.flushMicrotasks(); - fa.elapse(Duration(seconds: 1)); - expect(speech.isListening, isTrue); - }); - }); - test('uses localeId if provided', () async { - await speech.initialize(); - await speech.listen(localeId: TestSpeechChannelHandler.localeId1); - expect(speechHandler.listenInvoked, true); - expect(speechHandler.listenLocale, TestSpeechChannelHandler.localeId1); - }); - test('calls speech listener', () async { - await speech.initialize(); - await speech.listen(onResult: listener.onSpeechResult); - await speech.processMethodCall(MethodCall( - SpeechToText.textRecognitionMethod, - TestSpeechChannelHandler.firstRecognizedJson)); - expect(listener.speechResults, 1); - expect( - listener.results, [TestSpeechChannelHandler.firstRecognizedResult]); - expect(speech.lastRecognizedWords, - TestSpeechChannelHandler.firstRecognizedWords); - }); - test('calls speech listener with multiple', () async { - await speech.initialize(); - await speech.listen(onResult: listener.onSpeechResult); - await speech.processMethodCall(MethodCall( - SpeechToText.textRecognitionMethod, - TestSpeechChannelHandler.firstRecognizedJson)); - await speech.processMethodCall(MethodCall( - SpeechToText.textRecognitionMethod, - TestSpeechChannelHandler.secondRecognizedJson)); - expect(listener.speechResults, 2); - expect(listener.results, [ - TestSpeechChannelHandler.firstRecognizedResult, - TestSpeechChannelHandler.secondRecognizedResult - ]); - expect(speech.lastRecognizedWords, - TestSpeechChannelHandler.secondRecognizedWords); - }); - }); - - group('status callback', () { - test('invoked on listen', () async { - await speech.initialize( - onError: listener.onSpeechError, onStatus: listener.onSpeechStatus); - await speech.processMethodCall(MethodCall( - SpeechToText.notifyStatusMethod, SpeechToText.listeningStatus)); - expect(listener.speechStatus, 1); - expect(listener.statuses.contains(SpeechToText.listeningStatus), true); - }); - }); - - group('soundLevel callback', () { - test('invoked on listen', () async { - await speech.initialize(); - await speech.listen(onSoundLevelChange: listener.onSoundLevel); - await speech.processMethodCall(MethodCall( - SpeechToText.soundLevelChangeMethod, - TestSpeechChannelHandler.level1)); - expect(listener.soundLevel, 1); - expect(listener.soundLevels, contains(TestSpeechChannelHandler.level1)); - }); - test('sets lastLevel', () async { - await speech.initialize(); - await speech.listen(onSoundLevelChange: listener.onSoundLevel); - await speech.processMethodCall(MethodCall( - SpeechToText.soundLevelChangeMethod, - TestSpeechChannelHandler.level1)); - expect(speech.lastSoundLevel, TestSpeechChannelHandler.level1); - }); - }); - - group('cancel', () { - test('does nothing if not initialized', () async { - speech.cancel(); - expect(speechHandler.cancelInvoked, false); - }); - test('cancels an active listen', () async { - await speech.initialize(); - await speech.listen(); - await speech.cancel(); - expect(speechHandler.cancelInvoked, true); - expect(speech.isListening, isFalse); - }); - }); - group('stop', () { - test('does nothing if not initialized', () async { - speech.stop(); - expect(speechHandler.cancelInvoked, false); - }); - test('stops an active listen', () async { - await speech.initialize(); - speech.listen(); - speech.stop(); - expect(speechHandler.stopInvoked, true); - }); - }); - group('error', () { - test('notifies handler with transient', () async { - await speech.initialize(onError: listener.onSpeechError); - await speech.listen(); - await speech.processMethodCall(MethodCall(SpeechToText.notifyErrorMethod, - TestSpeechChannelHandler.transientErrorJson)); - expect(listener.speechErrors, 1); - expect(listener.errors.first.permanent, isFalse); - }); - test('notifies handler with permanent', () async { - await speech.initialize(onError: listener.onSpeechError); - await speech.listen(); - await speech.processMethodCall(MethodCall(SpeechToText.notifyErrorMethod, - TestSpeechChannelHandler.permanentErrorJson)); - expect(listener.speechErrors, 1); - expect(listener.errors.first.permanent, isTrue); - }); - test('continues listening on transient', () async { - await speech.initialize(onError: listener.onSpeechError); - await speech.listen(); - await speech.processMethodCall(MethodCall(SpeechToText.notifyErrorMethod, - TestSpeechChannelHandler.transientErrorJson)); - expect(speech.isListening, isTrue); - }); - test('continues listening on permanent if cancel not explicitly requested', - () async { - await speech.initialize(onError: listener.onSpeechError); - await speech.listen(); - await speech.processMethodCall(MethodCall(SpeechToText.notifyErrorMethod, - TestSpeechChannelHandler.permanentErrorJson)); - expect(speech.isListening, isTrue); - }); - test('stops listening on permanent if cancel explicitly requested', - () async { - await speech.initialize(onError: listener.onSpeechError); - await speech.listen(cancelOnError: true); - await speech.processMethodCall(MethodCall(SpeechToText.notifyErrorMethod, - TestSpeechChannelHandler.permanentErrorJson)); - expect(speech.isListening, isFalse); - }); - test('Error not sent after cancel', () async { - await speech.initialize(onError: listener.onSpeechError); - await speech.listen(); - await speech.cancel(); - await speech.processMethodCall(MethodCall(SpeechToText.notifyErrorMethod, - TestSpeechChannelHandler.permanentErrorJson)); - expect(speech.isListening, isFalse); - expect(listener.speechErrors, 0); - }); - test('Error still sent after implicit cancel', () async { - await speech.initialize(onError: listener.onSpeechError); - await speech.listen(cancelOnError: true); - await speech.processMethodCall(MethodCall(SpeechToText.notifyErrorMethod, - TestSpeechChannelHandler.permanentErrorJson)); - await speech.processMethodCall(MethodCall(SpeechToText.notifyErrorMethod, - TestSpeechChannelHandler.permanentErrorJson)); - expect(speech.isListening, isFalse); - expect(listener.speechErrors, 2); - }); - }); - group('locales', () { - test('fails with exception if not initialized', () async { - try { - await speech.locales(); - fail("Expected an exception."); - } on SpeechToTextNotInitializedException { - // This is a good result - } - }); - test('system locale null if not initialized', () async { - LocaleName current; - try { - current = await speech.systemLocale(); - fail("Expected an exception."); - } on SpeechToTextNotInitializedException { - expect(current, isNull); - } - }); - test('handles an empty list', () async { - await speech.initialize(onError: listener.onSpeechError); - List localeNames = await speech.locales(); - expect(speechHandler.localesInvoked, isTrue); - expect(localeNames, isEmpty); - }); - test('returns expected locales', () async { - await speech.initialize(onError: listener.onSpeechError); - speechHandler.locales.add(TestSpeechChannelHandler.locale1); - speechHandler.locales.add(TestSpeechChannelHandler.locale2); - List localeNames = await speech.locales(); - expect(localeNames, hasLength(speechHandler.locales.length)); - expect(localeNames[0].localeId, TestSpeechChannelHandler.localeId1); - expect(localeNames[0].name, TestSpeechChannelHandler.name1); - expect(localeNames[1].localeId, TestSpeechChannelHandler.localeId2); - expect(localeNames[1].name, TestSpeechChannelHandler.name2); - }); - test('skips incorrect locales', () async { - await speech.initialize(onError: listener.onSpeechError); - speechHandler.locales.add("InvalidJunk"); - speechHandler.locales.add(TestSpeechChannelHandler.locale1); - List localeNames = await speech.locales(); - expect(localeNames, hasLength(1)); - expect(localeNames[0].localeId, TestSpeechChannelHandler.localeId1); - expect(localeNames[0].name, TestSpeechChannelHandler.name1); - }); - test('system locale matches first returned locale', () async { - await speech.initialize(onError: listener.onSpeechError); - speechHandler.locales.add(TestSpeechChannelHandler.locale1); - speechHandler.locales.add(TestSpeechChannelHandler.locale2); - LocaleName current = await speech.systemLocale(); - expect(current.localeId, TestSpeechChannelHandler.localeId1); - }); - }); - group('status', () { - test('recognized false at start', () async { - expect(speech.hasRecognized, isFalse); - }); - test('listening false at start', () async { - expect(speech.isListening, isFalse); - }); - }); - test('available false at start', () async { - expect(speech.isAvailable, isFalse); - }); - test('hasError false at start', () async { - expect(speech.hasError, isFalse); - }); - test('lastError null at start', () async { - expect(speech.lastError, isNull); - }); - test('status empty at start', () async { - expect(speech.lastStatus, isEmpty); - }); -} - -class TestSpeechListener { - int speechResults = 0; - List results = []; - int speechErrors = 0; - List errors = []; - int speechStatus = 0; - List statuses = []; - int soundLevel = 0; - List soundLevels = []; - - void onSpeechResult(SpeechRecognitionResult result) { - ++speechResults; - results.add(result); - } - - void onSpeechError(SpeechRecognitionError errorResult) { - ++speechErrors; - errors.add(errorResult); - } - - void onSpeechStatus(String status) { - ++speechStatus; - statuses.add(status); - } - - void onSoundLevel(double level) { - ++soundLevel; - soundLevels.add(level); - } -} diff --git a/speech_to_text/test/test_speech_channel_handler.dart b/speech_to_text/test/test_speech_channel_handler.dart deleted file mode 100644 index a55f0670..00000000 --- a/speech_to_text/test/test_speech_channel_handler.dart +++ /dev/null @@ -1,134 +0,0 @@ -import 'package:flutter/services.dart'; -import 'package:speech_to_text/speech_recognition_error.dart'; -import 'package:speech_to_text/speech_recognition_result.dart'; -import 'package:speech_to_text/speech_to_text.dart'; - -/// Holds a set of responses and acts as a mock for the platform specific -/// implementations allowing test cases to determine what the result of -/// a call should be. -class TestSpeechChannelHandler { - final SpeechToText _speech; - - bool listenException = false; - - static const String listenExceptionCode = "listenFailedError"; - static const String listenExceptionMessage = "Failed"; - static const String listenExceptionDetails = "Device Listen Failure"; - - TestSpeechChannelHandler(this._speech); - - bool initResult = true; - bool initInvoked = false; - bool listenInvoked = false; - bool cancelInvoked = false; - bool stopInvoked = false; - bool localesInvoked = false; - bool hasPermissionResult = true; - String listeningStatusResponse = SpeechToText.listeningStatus; - String listenLocale; - List locales = []; - static const String localeId1 = "en_US"; - static const String localeId2 = "fr_CA"; - static const String name1 = "English US"; - static const String name2 = "French Canada"; - static const String locale1 = "$localeId1:$name1"; - static const String locale2 = "$localeId2:$name2"; - static const String firstRecognizedWords = 'hello'; - static const String secondRecognizedWords = 'hello there'; - static const double firstConfidence = 0.85; - static const double secondConfidence = 0.62; - static const String firstRecognizedJson = - '{"alternates":[{"recognizedWords":"$firstRecognizedWords","confidence":$firstConfidence}],"finalResult":false}'; - static const String secondRecognizedJson = - '{"alternates":[{"recognizedWords":"$secondRecognizedWords","confidence":$secondConfidence}],"finalResult":false}'; - static const String finalRecognizedJson = - '{"alternates":[{"recognizedWords":"$secondRecognizedWords","confidence":$secondConfidence}],"finalResult":true}'; - static const SpeechRecognitionWords firstWords = - SpeechRecognitionWords(firstRecognizedWords, firstConfidence); - static const SpeechRecognitionWords secondWords = - SpeechRecognitionWords(secondRecognizedWords, secondConfidence); - static final SpeechRecognitionResult firstRecognizedResult = - SpeechRecognitionResult([firstWords], false); - static final SpeechRecognitionResult secondRecognizedResult = - SpeechRecognitionResult([secondWords], false); - static final SpeechRecognitionResult finalRecognizedResult = - SpeechRecognitionResult([secondWords], true); - static const String transientErrorJson = - '{"errorMsg":"network","permanent":false}'; - static const String permanentErrorJson = - '{"errorMsg":"network","permanent":true}'; - static final SpeechRecognitionError firstError = - SpeechRecognitionError("network", true); - static const double level1 = 0.5; - static const double level2 = 10; - - Future methodCallHandler(MethodCall methodCall) async { - switch (methodCall.method) { - case "has_permission": - return hasPermissionResult; - break; - case "initialize": - initInvoked = true; - return initResult; - break; - case "cancel": - cancelInvoked = true; - return true; - break; - case "stop": - stopInvoked = true; - return true; - break; - case SpeechToText.listenMethod: - listenInvoked = true; - if (listenException) { - throw PlatformException( - code: listenExceptionCode, - message: listenExceptionMessage, - details: listenExceptionDetails); - } - listenLocale = methodCall.arguments["localeId"]; - await _speech.processMethodCall(MethodCall( - SpeechToText.notifyStatusMethod, listeningStatusResponse)); - return initResult; - break; - case "locales": - localesInvoked = true; - return locales; - break; - default: - } - return initResult; - } - - void notifyFinalWords() { - _speech.processMethodCall( - MethodCall(SpeechToText.textRecognitionMethod, finalRecognizedJson)); - } - - void notifyPartialWords() { - _speech.processMethodCall( - MethodCall(SpeechToText.textRecognitionMethod, firstRecognizedJson)); - } - - void notifyPermanentError() { - _speech.processMethodCall( - MethodCall(SpeechToText.notifyErrorMethod, permanentErrorJson)); - } - - void notifyTransientError() { - _speech.processMethodCall( - MethodCall(SpeechToText.notifyErrorMethod, transientErrorJson)); - } - - void notifySoundLevel() { - _speech.processMethodCall( - MethodCall(SpeechToText.soundLevelChangeMethod, level2)); - } - - void setupLocales() { - locales.clear(); - locales.add(locale1); - locales.add(locale2); - } -} diff --git a/speech_to_text/test/test_speech_listener.dart b/speech_to_text/test/test_speech_listener.dart deleted file mode 100644 index 1efcd81c..00000000 --- a/speech_to_text/test/test_speech_listener.dart +++ /dev/null @@ -1,36 +0,0 @@ -import 'package:speech_to_text/speech_recognition_error.dart'; -import 'package:speech_to_text/speech_recognition_result.dart'; -import 'package:speech_to_text/speech_to_text_provider.dart'; - -/// Holds the results of notification by the [SpeechToTextProvider] -class TestSpeechListener { - final SpeechToTextProvider _speechProvider; - - bool isListening = false; - bool isFinal = false; - bool isAvailable = false; - bool notified = false; - bool hasError = false; - SpeechRecognitionResult recognitionResult; - SpeechRecognitionError lastError; - double soundLevel; - - TestSpeechListener(this._speechProvider); - - void reset() { - isListening = false; - isFinal = false; - isAvailable = false; - notified = false; - } - - void onNotify() { - notified = true; - isAvailable = _speechProvider.isAvailable; - isListening = _speechProvider.isListening; - recognitionResult = _speechProvider.lastResult; - hasError = _speechProvider.hasError; - lastError = _speechProvider.lastError; - soundLevel = _speechProvider.lastLevel; - } -}