diff --git a/.circleci/config.yml b/.circleci/config.yml index 8809e70..574b500 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -1,28 +1,28 @@ -version: 2 -jobs: - build: - docker: - - image: cirrusci/flutter:stable - - branches: - only: master - - steps: - - checkout - - run: - name: Run Flutter doctor - command: flutter doctor - - run: - name: Update package - command: flutter pub upgrade - - run: echo $ENCODED_KEYSTORE | base64 -di > ${HOME}/keystore.jks - - run: echo 'export KEYSTORE=${HOME}/keystore.jks' >> $BASH_ENV - - run: dart tool/env.dart - - run: - name: Build the Android apk - command: flutter build apk --split-per-abi --obfuscate --split-debug-info=debug/ - - run: - name: Build the Android version - command: flutter build appbundle --obfuscate --split-debug-info=debug/ - - store_artifacts: - path: build/app/outputs/ +version: 2 +jobs: + build: + docker: + - image: cirrusci/flutter:stable + + branches: + only: master + + steps: + - checkout + - run: + name: Run Flutter doctor + command: flutter doctor + - run: + name: Update package + command: flutter pub upgrade + - run: echo $ENCODED_KEYSTORE | base64 -di > ${HOME}/keystore.jks + - run: echo 'export KEYSTORE=${HOME}/keystore.jks' >> $BASH_ENV + - run: dart tool/env.dart + - run: + name: Build the Android apk + command: flutter build apk --split-per-abi --obfuscate --split-debug-info=debug/ + - run: + name: Build the Android version + command: flutter build appbundle --obfuscate --split-debug-info=debug/ + - store_artifacts: + path: build/app/outputs/ diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index 305c91c..b67802d 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1,12 +1,12 @@ -# These are supported funding model platforms - -github: # Replace with up to 4buy-enabled usernames e.g., [user1, user2] -patreon: # Replace with a single Patreon username -open_collective: # Replace with a single Open Collective username -ko_fi: # Replace with a single Ko-fi username -tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel -community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry -liberapay: stonegate # Replace with a single Liberapay username -issuehunt: # Replace with a single IssueHunt username -otechie: # Replace with a single Otechie username -custom: ["https://www.buymeacoffee.com/stonegate"] # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] +# These are supported funding model platforms + +github: # Replace with up to 4buy-enabled usernames e.g., [user1, user2] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: stonegate # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: ["https://www.buymeacoffee.com/stonegate"] # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/.github/workflows/flutter_build.yml b/.github/workflows/flutter_build.yml index a573d44..b5db384 100644 --- a/.github/workflows/flutter_build.yml +++ b/.github/workflows/flutter_build.yml @@ -1,43 +1,40 @@ -name: Flutter Build -on: - push: - branches: - - master -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v1 - - uses: actions/setup-java@v1 - with: - java-version: "12.x" - - uses: subosito/flutter-action@v1 - with: - channel: "stable" # 'dev', 'alpha', default to: 'stable' - - run: flutter pub get - - run: echo $ENCODED_KEYSTORE | base64 -di > android/app/keystore.jks - env: - ENCODED_KEYSTORE: ${{ secrets.ENCODED_KEYSTORE }} - - run: dart tool/env.dart - env: - API_KEY: ${{ secrets.API_KEY }} - PI_API_SECRET: ${{ secrets.PI_API_SECRET}} - PI_API_KEY: ${{ secrets.PI_API_KEY}} - - run: flutter build apk --split-per-abi --obfuscate --split-debug-info=debug/ - env: - KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }} - KEY_ALIAS: ${{ secrets.KEY_ALIAS }} - KEY_PASSWORD: ${{ secrets.KEY_PASSWORD}} - - - run: flutter build appbundle --obfuscate --split-debug-info=debug/ - env: - API_KEY: ${{ secrets.API_KEY }} - KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }} - KEY_ALIAS: ${{ secrets.KEY_ALIAS }} - KEY_PASSWORD: ${{ secrets.KEY_PASSWORD}} - PI_API_SECRET: ${{ secrets.PI_API_SECRET}} - PI_API_KEY: ${{ secrets.PI_API_KEY}} - - uses: actions/upload-artifact@v2 - with: - name: release-apk - path: build/app/outputs/**/release/* +name: Flutter Build +on: + push: + branches: + - master +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v1 + - uses: actions/setup-java@v1 + with: + java-version: "12.x" + - uses: subosito/flutter-action@v1 + with: + channel: "stable" # 'dev', 'alpha', default to: 'stable' + - run: flutter pub get + - run: echo $ENCODED_KEYSTORE | base64 -di > android/app/keystore.jks + env: + ENCODED_KEYSTORE: ${{ secrets.ENCODED_KEYSTORE }} + - run: dart tool/env.dart + env: + API_KEY: ${{ secrets.API_KEY }} + PI_API_SECRET: ${{ secrets.PI_API_SECRET}} + PI_API_KEY: ${{ secrets.PI_API_KEY}} + - run: flutter build apk --split-per-abi --obfuscate --split-debug-info=debug/ + env: + KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }} + KEY_ALIAS: ${{ secrets.KEY_ALIAS }} + KEY_PASSWORD: ${{ secrets.KEY_PASSWORD}} + + - run: flutter build appbundle --obfuscate --split-debug-info=debug/ + env: + KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }} + KEY_ALIAS: ${{ secrets.KEY_ALIAS }} + KEY_PASSWORD: ${{ secrets.KEY_PASSWORD}} + - uses: actions/upload-artifact@v2 + with: + name: release-file + path: build/app/outputs/**/release/* diff --git a/.gitignore b/.gitignore index bdb020c..26adfd1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,41 +1,41 @@ -# 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 -.flutter-plugins-dependencies -.packages -.pub-cache/ -.pub/ -/lib/.env.dart -/build/ -pubspec.lock -.vscode -analysis_options.yaml - -# Web related -lib/generated_plugin_registrant.dart - -# Exceptions to above rules. -!/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages +# 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 +.flutter-plugins-dependencies +.packages +.pub-cache/ +.pub/ +/lib/.env.dart +/build/ +pubspec.lock +.vscode +analysis_options.yaml + +# Web related +lib/generated_plugin_registrant.dart + +# Exceptions to above rules. +!/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages diff --git a/.metadata b/.metadata index 7ec1395..5a59dd8 100644 --- a/.metadata +++ b/.metadata @@ -1,10 +1,10 @@ -# 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: 659dc8129d4edb9166e9a0d600439d135740933f - channel: beta - -project_type: app +# 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: 659dc8129d4edb9166e9a0d600439d135740933f + channel: beta + +project_type: app diff --git a/CHANGELOG.md b/CHANGELOG.md index 9853b7e..1cd4392 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,331 +1,331 @@ -# Tsacdop Changelog - -## 0.5.0 - -Release date 2020/10/13 - -### New fewtures - -* Support multi select on recent and favorite tab. -* Select all/ select before/ select after. -* Option to delete episode download file when played. -* OPtion to mark as listened after skipped. - -### Bug fixed - -* Feed pubdate parse error. -* Episodes load with initial position failed. - -### Minor changes - -* Single colume layout update. -* About page UI update. -* More smooth animation when open podcast detail page. -* Change sort by button style in podcast detail page. -* Auto rewind 3 seconds when resuming from paused state. - -## 0.4.20 - -Release date 2020/10/3 - -### Bug fixed - -* Rss feed parse error. - -## 0.4.19 - -Release date 2020/10/1 - -### New features - -* Set podcastindex as default search engine. -* Option to hide podcast discovery in search page. -* Italian translation support, thanks Edoardo. - -### Bug fixed - -* Mark all listened error. - -## 0.4.18 - -Release date 2020/9/27 - -### New features - -* Support gpodder.net sync. -* Portuguese translation, thanks Bruno. -* Turn off auto update for podcast. -* Pull to refresh in recent tab, supports group update. - -### Minor changes - -* Longpress 'see all' to open full podcast list. - -## 0.4.17 - -Release date 2020/9/16 - -### Bug fixed - -* Remove notification after app removed from recent. - -## 0.4.16 - -Release date 2020/9/15 - -### New features - -* Discovery feature in search page. -* Multi select in podcast page. -* Customize the speed options available. - -### Bugs fixed - -* Fix download error when podcast name includes /. -* Make the group name editable directly. -* Fixed shownote timestamp click error. - -### Minor changes - -* Update donate button UI. - -## 0.4.15 - -Release date 2020/8/30 - -### New features - -* Option to change notification panel layout. -* Option to change show notes font style. -* Option to hide listened default. -* Change skip next/previous to fastForward/rewind on headset click. - -### Bugs fixed - -* Download error when filename too long. - -### Minor change - -* Update download button style and downloaded indicator style. -* Add 1.1 to speed setting. -* Add 5s to skip seconds setting. - -## 0.4.14 - -Release date 2020/8/20 -Only for izzyonandroid. - -## 0.4.13 - -Release date 2020/8/19 - -### Bugs fixed - -* Downloaded episode play error, you might need to redownload the episode. - -## 0.4.12 - -Release date 2020/8/15 - -### Bugs fixed - -* Crash when reorder episodes or podcasts. -* Popup menu setting import bug. -* Default language failed to load. - -### Minor changes - -* Change language|feedback|podcast settings to button sheet. -* Add history in home playlist button. -* History page UI improved. - -## 0.4.11 - -Release date 2020/8/12 - -### New features - -* Boost volume. You can change boost level in settings. -* You can tap time stamp to skip instantly in shownote when the episode is playing. -* Add history list in playlist page. -* You can also mark not listened now. - -### Minor change - -* Improved time picker UI. -* Add episode setting page. - -### Bugs fix - -* Play record didn't saved after stop playing. -* Network error message didn't disapear after skip to next. -* Fireside avatar load error. - -## 0.4.10 - -Release date 2020/8/6 - -### Bugs fixed - -* Episdoe date parse error. -* Play from start after interrupt. -* Playlist in player unstable. -* Language setting not saved after restart app. - -### Minor change - -* Fast forward and rewind buttons UI changed. - -## v0.4.9 - -Release date 2020/8/1 - -### New features - -* Player UI redesign. -* Added player height setting. -* Added skip silence feature. - -### Bugs fixed - -* Language fixs. (Thanks to Atrate) -* Make app movable to SD card. (Thanks to Atrate) - -### Minor change - -* Episode page open animation improved. -* Podcast page load faster than before. -* Removed unnecessary scroll overlay effect. -* Episode page bottom menu hide when scroll down. - -## v0.4.8 - -Release date 2020/7/25 - -### New features - -* Filter in podcast detail page, you can also hide listened episodes. -* Search result ui improved, you can see more info for result. -* Update audio service to latest version. -* Support fast forward seconds and rewind seconds customize. -* Add Franch language support(beta). -* Add translators in about page. - -### Bugs fixed - -* Icon issue on below android 8 devices. - -### Minor change - -* Download button ui improved. -* Title changed to scrollable in episode detail page. -* Real dark theme improved. -* Add dot indicator in popup menu. -* Tap logo in homepage to toggle theme. - -## v0.4.7 - -Release date 2020/7/18 - -### Bugs fixed - -* Ompl files form other platform import error. -* Audio cache did't work. - -## v0.4.6 - -Release date 2020/7/17 - -### Bugs fixed - -* Mark listened not work. -* Recover subscribe wrong group. - -## v0.4.5 - -Release date 2020/7/16 - -## New features - -* OPML backup file supports group. -* Add settings backup and restore. -* Enable R8 and dart obfuscate. - -## Bugs fixed - -* OPML import not shown in group. - -## Minor UI change - -* Tap logo in homepage to toggle theme mode. -* Change subscribe button style. -* Improve history chart style. - -## v0.4.0 - -Release date 2020/7/9 - -### New features - -* Localization, changed all UI strings in app to support locale, support languages include en & zh right now. -* Changed episode popup menu UI, add a switch to tap to open popup men. - -### Minor UI change - -* Improve dropdown menu UI. -* Change icons color in setting page. -* Improve player panel animation. -* Add scroll bar in libraries page. - -## v0.3.6 - -Release date 2020/6/30 - -### New feature - -* Add sleep timer settings. include default time, auto start sleep timer, etc. - -### Bug fixed - -* Crash on stop player. -* Some download file didn't auto deleted. - -## v0.3.5 - -Release date 2020/6/20 -This is a energency release. - -### Bugs fixed - -* Crashed in download page or button after remove a podcast. Add episode check when load tasks from flutterdownloader. - -### Minor UI change - -* Add buy me a coffee in about page. -* Remove progress number in download list in failed task, change refresh icon color to red. - -## v0.3.4 - -Release date 2020/6/16 - -### New Feature - -* Support auto download new episodes, you can choose which podcast you want to auto download, you can also set if download using cellular data. -* Support auto delete downloaded episode, you can set days before delete. -* Support customize episode popup menu, you can add options you most want, **Like** | **Mark Listened** | **Download** newly added. -* Improved downloaded file manager, you can now sort downloads by date or size, you can also only view listened downloads. - -### Minor UI Change - -* Removed the listened indicator, increased the color difference for listened episodes. -* Add text in podcast manage page menu. -* Change episode shownote font to Martel. - -### Bugs Fixed - -* Auto play when receive notification. -* Lose podcast when import OMPL file. - -### Other - -* Add privacy policy. +# Tsacdop Changelog + +## 0.5.0 + +Release date 2020/10/13 + +### New fewtures + +* Support multi select on recent and favorite tab. +* Select all/ select before/ select after. +* Option to delete episode download file when played. +* OPtion to mark as listened after skipped. + +### Bug fixed + +* Feed pubdate parse error. +* Episodes load with initial position failed. + +### Minor changes + +* Single colume layout update. +* About page UI update. +* More smooth animation when open podcast detail page. +* Change sort by button style in podcast detail page. +* Auto rewind 3 seconds when resuming from paused state. + +## 0.4.20 + +Release date 2020/10/3 + +### Bug fixed + +* Rss feed parse error. + +## 0.4.19 + +Release date 2020/10/1 + +### New features + +* Set podcastindex as default search engine. +* Option to hide podcast discovery in search page. +* Italian translation support, thanks Edoardo. + +### Bug fixed + +* Mark all listened error. + +## 0.4.18 + +Release date 2020/9/27 + +### New features + +* Support gpodder.net sync. +* Portuguese translation, thanks Bruno. +* Turn off auto update for podcast. +* Pull to refresh in recent tab, supports group update. + +### Minor changes + +* Longpress 'see all' to open full podcast list. + +## 0.4.17 + +Release date 2020/9/16 + +### Bug fixed + +* Remove notification after app removed from recent. + +## 0.4.16 + +Release date 2020/9/15 + +### New features + +* Discovery feature in search page. +* Multi select in podcast page. +* Customize the speed options available. + +### Bugs fixed + +* Fix download error when podcast name includes /. +* Make the group name editable directly. +* Fixed shownote timestamp click error. + +### Minor changes + +* Update donate button UI. + +## 0.4.15 + +Release date 2020/8/30 + +### New features + +* Option to change notification panel layout. +* Option to change show notes font style. +* Option to hide listened default. +* Change skip next/previous to fastForward/rewind on headset click. + +### Bugs fixed + +* Download error when filename too long. + +### Minor change + +* Update download button style and downloaded indicator style. +* Add 1.1 to speed setting. +* Add 5s to skip seconds setting. + +## 0.4.14 + +Release date 2020/8/20 +Only for izzyonandroid. + +## 0.4.13 + +Release date 2020/8/19 + +### Bugs fixed + +* Downloaded episode play error, you might need to redownload the episode. + +## 0.4.12 + +Release date 2020/8/15 + +### Bugs fixed + +* Crash when reorder episodes or podcasts. +* Popup menu setting import bug. +* Default language failed to load. + +### Minor changes + +* Change language|feedback|podcast settings to button sheet. +* Add history in home playlist button. +* History page UI improved. + +## 0.4.11 + +Release date 2020/8/12 + +### New features + +* Boost volume. You can change boost level in settings. +* You can tap time stamp to skip instantly in shownote when the episode is playing. +* Add history list in playlist page. +* You can also mark not listened now. + +### Minor change + +* Improved time picker UI. +* Add episode setting page. + +### Bugs fix + +* Play record didn't saved after stop playing. +* Network error message didn't disapear after skip to next. +* Fireside avatar load error. + +## 0.4.10 + +Release date 2020/8/6 + +### Bugs fixed + +* Episdoe date parse error. +* Play from start after interrupt. +* Playlist in player unstable. +* Language setting not saved after restart app. + +### Minor change + +* Fast forward and rewind buttons UI changed. + +## v0.4.9 + +Release date 2020/8/1 + +### New features + +* Player UI redesign. +* Added player height setting. +* Added skip silence feature. + +### Bugs fixed + +* Language fixs. (Thanks to Atrate) +* Make app movable to SD card. (Thanks to Atrate) + +### Minor change + +* Episode page open animation improved. +* Podcast page load faster than before. +* Removed unnecessary scroll overlay effect. +* Episode page bottom menu hide when scroll down. + +## v0.4.8 + +Release date 2020/7/25 + +### New features + +* Filter in podcast detail page, you can also hide listened episodes. +* Search result ui improved, you can see more info for result. +* Update audio service to latest version. +* Support fast forward seconds and rewind seconds customize. +* Add Franch language support(beta). +* Add translators in about page. + +### Bugs fixed + +* Icon issue on below android 8 devices. + +### Minor change + +* Download button ui improved. +* Title changed to scrollable in episode detail page. +* Real dark theme improved. +* Add dot indicator in popup menu. +* Tap logo in homepage to toggle theme. + +## v0.4.7 + +Release date 2020/7/18 + +### Bugs fixed + +* Ompl files form other platform import error. +* Audio cache did't work. + +## v0.4.6 + +Release date 2020/7/17 + +### Bugs fixed + +* Mark listened not work. +* Recover subscribe wrong group. + +## v0.4.5 + +Release date 2020/7/16 + +## New features + +* OPML backup file supports group. +* Add settings backup and restore. +* Enable R8 and dart obfuscate. + +## Bugs fixed + +* OPML import not shown in group. + +## Minor UI change + +* Tap logo in homepage to toggle theme mode. +* Change subscribe button style. +* Improve history chart style. + +## v0.4.0 + +Release date 2020/7/9 + +### New features + +* Localization, changed all UI strings in app to support locale, support languages include en & zh right now. +* Changed episode popup menu UI, add a switch to tap to open popup men. + +### Minor UI change + +* Improve dropdown menu UI. +* Change icons color in setting page. +* Improve player panel animation. +* Add scroll bar in libraries page. + +## v0.3.6 + +Release date 2020/6/30 + +### New feature + +* Add sleep timer settings. include default time, auto start sleep timer, etc. + +### Bug fixed + +* Crash on stop player. +* Some download file didn't auto deleted. + +## v0.3.5 + +Release date 2020/6/20 +This is a energency release. + +### Bugs fixed + +* Crashed in download page or button after remove a podcast. Add episode check when load tasks from flutterdownloader. + +### Minor UI change + +* Add buy me a coffee in about page. +* Remove progress number in download list in failed task, change refresh icon color to red. + +## v0.3.4 + +Release date 2020/6/16 + +### New Feature + +* Support auto download new episodes, you can choose which podcast you want to auto download, you can also set if download using cellular data. +* Support auto delete downloaded episode, you can set days before delete. +* Support customize episode popup menu, you can add options you most want, **Like** | **Mark Listened** | **Download** newly added. +* Improved downloaded file manager, you can now sort downloads by date or size, you can also only view listened downloads. + +### Minor UI Change + +* Removed the listened indicator, increased the color difference for listened episodes. +* Add text in podcast manage page menu. +* Change episode shownote font to Martel. + +### Bugs Fixed + +* Auto play when receive notification. +* Lose podcast when import OMPL file. + +### Other + +* Add privacy policy. diff --git a/LICENSE b/LICENSE index f288702..3877ae0 100644 --- a/LICENSE +++ b/LICENSE @@ -1,674 +1,674 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md index 6a98d77..6e8c5cd 100644 --- a/README.md +++ b/README.md @@ -1,192 +1,192 @@ -[![Tsacdop Banner][]][google play] - -[![github action][]][github action link] -[![Build Status - Cirrus][]][build status] -[![GitHub Release][]][github release - recent] -[![Github Downloads][]][github release - recent] -[![Localizely][]][localizely - website] -[![style: effective dart][]][effective dart pub] -[![License badge][]][license] - -## About - -Enjoy podcasts with Tsacdop. - -Tsacdop is a podcast player developed with Flutter, a clean, simply beautiful and friendly app, which is also free and open source. - -Credit to Flutter team and all involved plugins, especially [webfeed](https://github.com/witochandra/webfeed) and [Just_Audio](https://pub.dev/packages/just_audio). - -The podcast search engine is powered by [ListenNotes](https://listennotes.com). - -## Features - -* Podcast group management -* Playlist support -* Sleep timer / speed setting -* OPML file export and import -* Auto syncing in background -* Listening and subscription history record -* Dark mode / accent color -* Download for offline play -* Auto download new episodes / auto delete outdated downloads -* Settings backup -* Skip silence -* Boost volume - -More to come... - -## Preview - -| Home Page | Group | Podcast | Episode| Dark Mode | -| ----- | ----- | ----- | ------ | ----- | -|![][Homepage ScreenShot]|![][Group Screenshot] | ![][Podcast Screenshot] | ![][Episode Screenshot]| ![][Darkmode Screenshot] | - -## Localization - -Please [Email](mailto:) me you'd like to contribute to support more languages! - -Credit to [Localizely](https://localizely.com/) for kind support to open source projects. - -### ![English] - -### ![Chinese Simplified] - -### ![French] - -### ![Spanish] - -### ![Portuguese] - -## License - -Tsacdop is licensed under the [GPL v3.0](https://github.com/stonega/tsacdop/blob/master/LICENSE) license. - -## Build - -1. If you don't have Flutter SDK installed, please visit offcial [Flutter][Flutter Install] site. -2. Fetch latest sorce code from master branch. - -``` -git clone https://github.com/stonega/tsacdop.git -``` - -3. Add api search api configure file. - -Tsacdop uses ListenNotes API 1.0 pro to search for podcasts, which is not free, so I can not expose the API key in the repo. -If you want to build the app, you need to create a new file named `.env.dart` in lib folder. Add the following code to `.env.dart` . -You can get your own API key on [ListenNotes](https://www.listennotes.com/api/), remember that you need to get pro plan API, because basic plan dosen't provide rss link for serach result. If no api key is added, the search function in the app won't work. But you can still add podcasts by using an RSS link or importing an OMPL file. - -``` dart -final environment = {"apiKey":"APIKEY"}; -``` - -4. Run the app with Android Studio or Visual Studio. Or the command line. - -``` -flutter pub get -flutter run -``` - -## Contribute - -If you have an issue or found a bug, please raise a GitHub issue. Pull requests are also welcome. - -## Archetecture - -### Plugins - -* Local storage - + sqflite - + shared_preferences -* Audio - + just_audio - + audio_service -* State management - + provider -* Download - + flutter_downloader -* Background task - + workmanager - -### Directory Structure - -``` -UI -src -├──home - ├──home.dart [Homepage] - ├──searc_podcast.dart [Search Page] - └──playlist.dart [Playlist Page] -├──podcasts - ├──podcast_manage.dart [Group Page] - └──podcast_detail.dart [Podcast Page] -├──episodes - └──episode_detail.dart [Episode Page] -├──settings - └──setting.dart [Setting Page] - -STATE -src -├──state - ├──audio_state.dart [Audio State] - ├──download_state.dart [Episode Download] - ├──podcast_group.dart [Podcast Groups] - ├──refresh_podcast.dart [Episode Refresh] - └──setting_state.dart [Setting] - -Service -src -├──service - ├──api_service.dart [Podcast Search] - └──ompl_builde.dart [OMPL export] -``` - -## Known Issue - -* Playlist is unstable - -## Contact - -You can reach out to me directly at [tsacdop.app@gmail.com](mailto:). - -Or you can join our [Telegram Group](https://t.me/joinchat/Bk3LkRpTHy40QYC78PK7Qg). - -## Getting Started with Flutter - -This project is a starting point for a Flutter application. - -Here are 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. - -[Flutter Install]: https://flutter.dev/docs/get-started/install -[tsacdop banner]: https://raw.githubusercontent.com/stonega/tsacdop/master/preview/banner.png -[build status - cirrus]: https://circleci.com/gh/stonega/tsacdop/tree/master.svg?style=shield -[github action]: https://github.com/stonega/tsacdop/workflows/Flutter%20Build/badge.svg -[github action link]: https://github.com/stonega/tsacdop/actions -[build status ]: https://circleci.com/gh/stonega/tsacdop/tree/master -[github release]: https://img.shields.io/github/v/release/stonega/tsacdop -[github release - recent]: https://github.com/stonega/tsacdop/releases -[github downloads]: https://img.shields.io/github/downloads/stonega/tsacdop/total?color=%230000d&label=downloads -[localizely]: https://img.shields.io/badge/dynamic/json?color=%2326c6da&label=localizely&query=%24.languages.length&url=https%3A%2F%2Fapi.localizely.com%2Fv1%2Fprojects%2Fbde4e9bd-4cb2-449b-9de2-18f231ddb47d%2Fstatus -[English]: https://img.shields.io/badge/dynamic/json?style=for-the-badge&color=%2323CCC6&label=English&query=%24.languages%5B3%5D.reviewedProgress&url=https%3A%2F%2Fapi.localizely.com%2Fv1%2Fprojects%2Fbde4e9bd-4cb2-449b-9de2-18f231ddb47d%2Fstatus&suffix=% -[Chinese Simplified]: https://img.shields.io/badge/dynamic/json?style=for-the-badge&color=%2323CCC6&label=Chinese%20Simplified&query=%24.languages%5B2%5D.reviewedProgress&url=https%3A%2F%2Fapi.localizely.com%2Fv1%2Fprojects%2Fbde4e9bd-4cb2-449b-9de2-18f231ddb47d%2Fstatus&suffix=% -[French]: https://img.shields.io/badge/dynamic/json?style=for-the-badge&color=%2323CCC6&label=French(ppp)&query=%24.languages%5B5%5D.reviewedProgress&url=https%3A%2F%2Fapi.localizely.com%2Fv1%2Fprojects%2Fbde4e9bd-4cb2-449b-9de2-18f231ddb47d%2Fstatus&suffix=% -[Spanish]: https://img.shields.io/badge/dynamic/json?style=for-the-badge&color=%2323CCC6&label=Spanish(Joel)&query=%24.languages%5B7%5D.reviewedProgress&url=https%3A%2F%2Fapi.localizely.com%2Fv1%2Fprojects%2Fbde4e9bd-4cb2-449b-9de2-18f231ddb47d%2Fstatus&suffix=% -[Portuguese]: https://img.shields.io/badge/dynamic/json?style=for-the-badge&color=%2323CCC6&label=portuguese(Bruno)&query=%24.languages%5B9%5D.reviewedProgress&url=https%3A%2F%2Fapi.localizely.com%2Fv1%2Fprojects%2Fbde4e9bd-4cb2-449b-9de2-18f231ddb47d%2Fstatus&suffix=% -[localizely - website]: https://localizely.com/ -[google play - icon]: https://img.shields.io/badge/google-playStore-%2323CCC6 -[google play]: https://play.google.com/store/apps/details?id=com.stonegate.tsacdop -[Homepage ScreenShot]: https://raw.githubusercontent.com/stonega/tsacdop/master/preview/1585893838840.png -[Group Screenshot]: https://raw.githubusercontent.com/stonega/tsacdop/master/preview/1585894051734.png -[Podcast Screenshot]: https://raw.githubusercontent.com/stonega/tsacdop/master/preview/1585893877702.png -[Episode Screenshot]: https://raw.githubusercontent.com/stonega/tsacdop/master/preview/1585896237809.png -[Darkmode Screenshot]: https://raw.githubusercontent.com/stonega/tsacdop/master/preview/1585893920721.png -[style: effective dart]: https://img.shields.io/badge/style-effective_dart-40c4ff.svg -[effective dart pub]: https://pub.dev/packages/effective_dart -[license]: https://github.com/stonega/tsacdop/blob/master/LICENSE -[License badge]: https://img.shields.io/badge/license-GPLv3-yellow.svg +[![Tsacdop Banner][]][google play] + +[![github action][]][github action link] +[![Build Status - Cirrus][]][build status] +[![GitHub Release][]][github release - recent] +[![Github Downloads][]][github release - recent] +[![Localizely][]][localizely - website] +[![style: effective dart][]][effective dart pub] +[![License badge][]][license] + +## About + +Enjoy podcasts with Tsacdop. + +Tsacdop is a podcast player developed with Flutter, a clean, simply beautiful and friendly app, which is also free and open source. + +Credit to Flutter team and all involved plugins, especially [webfeed](https://github.com/witochandra/webfeed) and [Just_Audio](https://pub.dev/packages/just_audio). + +The podcast search engine is powered by [ListenNotes](https://listennotes.com). + +## Features + +* Podcast group management +* Playlist support +* Sleep timer / speed setting +* OPML file export and import +* Auto syncing in background +* Listening and subscription history record +* Dark mode / accent color +* Download for offline play +* Auto download new episodes / auto delete outdated downloads +* Settings backup +* Skip silence +* Boost volume + +More to come... + +## Preview + +| Home Page | Group | Podcast | Episode| Dark Mode | +| ----- | ----- | ----- | ------ | ----- | +|![][Homepage ScreenShot]|![][Group Screenshot] | ![][Podcast Screenshot] | ![][Episode Screenshot]| ![][Darkmode Screenshot] | + +## Localization + +Please [Email](mailto:) me you'd like to contribute to support more languages! + +Credit to [Localizely](https://localizely.com/) for kind support to open source projects. + +### ![English] + +### ![Chinese Simplified] + +### ![French] + +### ![Spanish] + +### ![Portuguese] + +## License + +Tsacdop is licensed under the [GPL v3.0](https://github.com/stonega/tsacdop/blob/master/LICENSE) license. + +## Build + +1. If you don't have Flutter SDK installed, please visit offcial [Flutter][Flutter Install] site. +2. Fetch latest sorce code from master branch. + +``` +git clone https://github.com/stonega/tsacdop.git +``` + +3. Add api search api configure file. + +Tsacdop uses ListenNotes API 1.0 pro to search for podcasts, which is not free, so I can not expose the API key in the repo. +If you want to build the app, you need to create a new file named `.env.dart` in lib folder. Add the following code to `.env.dart` . +You can get your own API key on [ListenNotes](https://www.listennotes.com/api/), remember that you need to get pro plan API, because basic plan dosen't provide rss link for serach result. If no api key is added, the search function in the app won't work. But you can still add podcasts by using an RSS link or importing an OMPL file. + +``` dart +final environment = {"apiKey":"APIKEY"}; +``` + +4. Run the app with Android Studio or Visual Studio. Or the command line. + +``` +flutter pub get +flutter run +``` + +## Contribute + +If you have an issue or found a bug, please raise a GitHub issue. Pull requests are also welcome. + +## Archetecture + +### Plugins + +* Local storage + + sqflite + + shared_preferences +* Audio + + just_audio + + audio_service +* State management + + provider +* Download + + flutter_downloader +* Background task + + workmanager + +### Directory Structure + +``` +UI +src +├──home + ├──home.dart [Homepage] + ├──searc_podcast.dart [Search Page] + └──playlist.dart [Playlist Page] +├──podcasts + ├──podcast_manage.dart [Group Page] + └──podcast_detail.dart [Podcast Page] +├──episodes + └──episode_detail.dart [Episode Page] +├──settings + └──setting.dart [Setting Page] + +STATE +src +├──state + ├──audio_state.dart [Audio State] + ├──download_state.dart [Episode Download] + ├──podcast_group.dart [Podcast Groups] + ├──refresh_podcast.dart [Episode Refresh] + └──setting_state.dart [Setting] + +Service +src +├──service + ├──api_service.dart [Podcast Search] + └──ompl_builde.dart [OMPL export] +``` + +## Known Issue + +* Playlist is unstable + +## Contact + +You can reach out to me directly at [tsacdop.app@gmail.com](mailto:). + +Or you can join our [Telegram Group](https://t.me/joinchat/Bk3LkRpTHy40QYC78PK7Qg). + +## Getting Started with Flutter + +This project is a starting point for a Flutter application. + +Here are 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. + +[Flutter Install]: https://flutter.dev/docs/get-started/install +[tsacdop banner]: https://raw.githubusercontent.com/stonega/tsacdop/master/preview/banner.png +[build status - cirrus]: https://circleci.com/gh/stonega/tsacdop/tree/master.svg?style=shield +[github action]: https://github.com/stonega/tsacdop/workflows/Flutter%20Build/badge.svg +[github action link]: https://github.com/stonega/tsacdop/actions +[build status ]: https://circleci.com/gh/stonega/tsacdop/tree/master +[github release]: https://img.shields.io/github/v/release/stonega/tsacdop +[github release - recent]: https://github.com/stonega/tsacdop/releases +[github downloads]: https://img.shields.io/github/downloads/stonega/tsacdop/total?color=%230000d&label=downloads +[localizely]: https://img.shields.io/badge/dynamic/json?color=%2326c6da&label=localizely&query=%24.languages.length&url=https%3A%2F%2Fapi.localizely.com%2Fv1%2Fprojects%2Fbde4e9bd-4cb2-449b-9de2-18f231ddb47d%2Fstatus +[English]: https://img.shields.io/badge/dynamic/json?style=for-the-badge&color=%2323CCC6&label=English&query=%24.languages%5B3%5D.reviewedProgress&url=https%3A%2F%2Fapi.localizely.com%2Fv1%2Fprojects%2Fbde4e9bd-4cb2-449b-9de2-18f231ddb47d%2Fstatus&suffix=% +[Chinese Simplified]: https://img.shields.io/badge/dynamic/json?style=for-the-badge&color=%2323CCC6&label=Chinese%20Simplified&query=%24.languages%5B2%5D.reviewedProgress&url=https%3A%2F%2Fapi.localizely.com%2Fv1%2Fprojects%2Fbde4e9bd-4cb2-449b-9de2-18f231ddb47d%2Fstatus&suffix=% +[French]: https://img.shields.io/badge/dynamic/json?style=for-the-badge&color=%2323CCC6&label=French(ppp)&query=%24.languages%5B5%5D.reviewedProgress&url=https%3A%2F%2Fapi.localizely.com%2Fv1%2Fprojects%2Fbde4e9bd-4cb2-449b-9de2-18f231ddb47d%2Fstatus&suffix=% +[Spanish]: https://img.shields.io/badge/dynamic/json?style=for-the-badge&color=%2323CCC6&label=Spanish(Joel)&query=%24.languages%5B7%5D.reviewedProgress&url=https%3A%2F%2Fapi.localizely.com%2Fv1%2Fprojects%2Fbde4e9bd-4cb2-449b-9de2-18f231ddb47d%2Fstatus&suffix=% +[Portuguese]: https://img.shields.io/badge/dynamic/json?style=for-the-badge&color=%2323CCC6&label=portuguese(Bruno)&query=%24.languages%5B9%5D.reviewedProgress&url=https%3A%2F%2Fapi.localizely.com%2Fv1%2Fprojects%2Fbde4e9bd-4cb2-449b-9de2-18f231ddb47d%2Fstatus&suffix=% +[localizely - website]: https://localizely.com/ +[google play - icon]: https://img.shields.io/badge/google-playStore-%2323CCC6 +[google play]: https://play.google.com/store/apps/details?id=com.stonegate.tsacdop +[Homepage ScreenShot]: https://raw.githubusercontent.com/stonega/tsacdop/master/preview/1585893838840.png +[Group Screenshot]: https://raw.githubusercontent.com/stonega/tsacdop/master/preview/1585894051734.png +[Podcast Screenshot]: https://raw.githubusercontent.com/stonega/tsacdop/master/preview/1585893877702.png +[Episode Screenshot]: https://raw.githubusercontent.com/stonega/tsacdop/master/preview/1585896237809.png +[Darkmode Screenshot]: https://raw.githubusercontent.com/stonega/tsacdop/master/preview/1585893920721.png +[style: effective dart]: https://img.shields.io/badge/style-effective_dart-40c4ff.svg +[effective dart pub]: https://pub.dev/packages/effective_dart +[license]: https://github.com/stonega/tsacdop/blob/master/LICENSE +[License badge]: https://img.shields.io/badge/license-GPLv3-yellow.svg diff --git a/android/.gitignore b/android/.gitignore index bc2100d..0b9e049 100644 --- a/android/.gitignore +++ b/android/.gitignore @@ -1,7 +1,7 @@ -gradle-wrapper.jar -/.gradle -/captures/ -/gradlew -/gradlew.bat -/local.properties -GeneratedPluginRegistrant.java +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java diff --git a/android/.project b/android/.project index 3964dd3..549de72 100644 --- a/android/.project +++ b/android/.project @@ -1,17 +1,17 @@ - - - android - Project android created by Buildship. - - - - - org.eclipse.buildship.core.gradleprojectbuilder - - - - - - org.eclipse.buildship.core.gradleprojectnature - - + + + android + Project android created by Buildship. + + + + + org.eclipse.buildship.core.gradleprojectbuilder + + + + + + org.eclipse.buildship.core.gradleprojectnature + + diff --git a/android/.settings/org.eclipse.buildship.core.prefs b/android/.settings/org.eclipse.buildship.core.prefs index 0f7dc43..6f65e63 100644 --- a/android/.settings/org.eclipse.buildship.core.prefs +++ b/android/.settings/org.eclipse.buildship.core.prefs @@ -1,13 +1,13 @@ -arguments= -auto.sync=false -build.scans.enabled=false -connection.gradle.distribution=GRADLE_DISTRIBUTION(WRAPPER) -connection.project.dir=app -eclipse.preferences.version=1 -gradle.user.home= -java.home=C\:/Program Files/Java/jdk1.8.0_171 -jvm.arguments= -offline.mode=false -override.workspace.settings=true -show.console.view=true -show.executions.view=true +arguments= +auto.sync=false +build.scans.enabled=false +connection.gradle.distribution=GRADLE_DISTRIBUTION(WRAPPER) +connection.project.dir=app +eclipse.preferences.version=1 +gradle.user.home= +java.home=C\:/Program Files/Java/jdk1.8.0_171 +jvm.arguments= +offline.mode=false +override.workspace.settings=true +show.console.view=true +show.executions.view=true diff --git a/android/app/.classpath b/android/app/.classpath index eb19361..4f3f504 100644 --- a/android/app/.classpath +++ b/android/app/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/android/app/.project b/android/app/.project index ac485d7..d1eb8cb 100644 --- a/android/app/.project +++ b/android/app/.project @@ -1,23 +1,23 @@ - - - app - Project app created by Buildship. - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.buildship.core.gradleprojectbuilder - - - - - - org.eclipse.jdt.core.javanature - org.eclipse.buildship.core.gradleprojectnature - - + + + app + Project app 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/android/app/.settings/org.eclipse.buildship.core.prefs b/android/app/.settings/org.eclipse.buildship.core.prefs index d54f9e4..aa059e5 100644 --- a/android/app/.settings/org.eclipse.buildship.core.prefs +++ b/android/app/.settings/org.eclipse.buildship.core.prefs @@ -1,13 +1,13 @@ -arguments= -auto.sync=false -build.scans.enabled=false -connection.gradle.distribution=GRADLE_DISTRIBUTION(VERSION(6.3)) -connection.project.dir= -eclipse.preferences.version=1 -gradle.user.home= -java.home=C\:/Program Files/Java/jdk1.8.0_171 -jvm.arguments= -offline.mode=false -override.workspace.settings=true -show.console.view=true -show.executions.view=true +arguments= +auto.sync=false +build.scans.enabled=false +connection.gradle.distribution=GRADLE_DISTRIBUTION(VERSION(6.3)) +connection.project.dir= +eclipse.preferences.version=1 +gradle.user.home= +java.home=C\:/Program Files/Java/jdk1.8.0_171 +jvm.arguments= +offline.mode=false +override.workspace.settings=true +show.console.view=true +show.executions.view=true diff --git a/android/app/.settings/org.eclipse.jdt.core.prefs b/android/app/.settings/org.eclipse.jdt.core.prefs index 35068d9..7eeabf5 100644 --- a/android/app/.settings/org.eclipse.jdt.core.prefs +++ b/android/app/.settings/org.eclipse.jdt.core.prefs @@ -1,4 +1,4 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.source=1.8 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/android/app/build.gradle b/android/app/build.gradle index 1e14732..9278c0d 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -1,90 +1,90 @@ -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" - - def keystoreProperties = new Properties() - def keystorePropertiesFile = rootProject.file('key.properties') - if (keystorePropertiesFile.exists()) { - keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) - } - -android { - compileSdkVersion 29 - - ndkVersion "21.3.6528147" - - 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.stonegate.tsacdop" - minSdkVersion 19 - targetSdkVersion 29 - versionCode flutterVersionCode.toInteger() - versionName flutterVersionName - testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" - } - - signingConfigs { - release { - storeFile file(System.getenv("KEYSTORE") ?:"keystore.jks") - storePassword System.getenv("KEYSTORE_PASSWORD") - keyAlias System.getenv("KEY_ALIAS") - keyPassword System.getenv("KEY_PASSWORD") - // keyAlias keystoreProperties['keyAlias'] - // keyPassword keystoreProperties['keyPassword'] - // storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null - // storePassword keystoreProperties['storePassword'] - } - } - buildTypes { - release { - signingConfig signingConfigs.release - shrinkResources false - } - } - -} - -flutter { - source '../..' -} - -dependencies { - implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" - testImplementation 'junit:junit:4.13' - androidTestImplementation 'androidx.test:runner:1.2.0' - androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' - def appcompat_version = "1.1.0" - implementation "androidx.appcompat:appcompat:$appcompat_version" - implementation "androidx.appcompat:appcompat-resources:$appcompat_version" -} +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" + + def keystoreProperties = new Properties() + def keystorePropertiesFile = rootProject.file('key.properties') + if (keystorePropertiesFile.exists()) { + keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) + } + +android { + compileSdkVersion 29 + + ndkVersion "21.3.6528147" + + 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.stonegate.tsacdop" + minSdkVersion 19 + targetSdkVersion 29 + versionCode flutterVersionCode.toInteger() + versionName flutterVersionName + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + } + + signingConfigs { + release { + storeFile file(System.getenv("KEYSTORE") ?:"keystore.jks") + storePassword System.getenv("KEYSTORE_PASSWORD") + keyAlias System.getenv("KEY_ALIAS") + keyPassword System.getenv("KEY_PASSWORD") + // keyAlias keystoreProperties['keyAlias'] + // keyPassword keystoreProperties['keyPassword'] + // storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null + // storePassword keystoreProperties['storePassword'] + } + } + buildTypes { + release { + signingConfig signingConfigs.release + shrinkResources false + } + } + +} + +flutter { + source '../..' +} + +dependencies { + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" + testImplementation 'junit:junit:4.13' + androidTestImplementation 'androidx.test:runner:1.2.0' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' + def appcompat_version = "1.1.0" + implementation "androidx.appcompat:appcompat:$appcompat_version" + implementation "androidx.appcompat:appcompat-resources:$appcompat_version" +} diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml index 35c9116..64c8d13 100644 --- a/android/app/src/debug/AndroidManifest.xml +++ b/android/app/src/debug/AndroidManifest.xml @@ -1,7 +1,7 @@ - - - - + + + + diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 49b308a..bfa7fe2 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -1,34 +1,34 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/java/io/flutter/plugins/IsolatePluginRegistrant.java b/android/app/src/main/java/io/flutter/plugins/IsolatePluginRegistrant.java index 9a3be85..25a9b42 100644 --- a/android/app/src/main/java/io/flutter/plugins/IsolatePluginRegistrant.java +++ b/android/app/src/main/java/io/flutter/plugins/IsolatePluginRegistrant.java @@ -1,39 +1,39 @@ -package io.flutter.plugins; - -import androidx.annotation.Keep; -import androidx.annotation.NonNull; - -import io.flutter.embedding.engine.FlutterEngine; -import io.flutter.embedding.engine.plugins.shim.ShimPluginRegistry; -import io.flutter.plugin.common.PluginRegistry; -import io.flutter.plugins.pathprovider.PathProviderPlugin; -import com.tekartik.sqflite.SqflitePlugin; -import io.flutter.plugins.sharedpreferences.SharedPreferencesPlugin; -import vn.hunghd.flutterdownloader.FlutterDownloaderPlugin; - -/** - * Generated file. Do not edit. This file is generated by the Flutter tool based - * on the plugins that support the Android platform. - */ - -@Keep -public final class IsolatePluginRegistrant { - public static void registerWith(PluginRegistry registry) { - if (alreadyRegisteredWith(registry)) { - return; - } - PathProviderPlugin.registerWith(registry.registrarFor("io.flutter.plugins.pathprovider.PathProviderPlugin")); - SqflitePlugin.registerWith(registry.registrarFor("com.tekartik.sqflite.SqflitePlugin")); - SharedPreferencesPlugin.registerWith(registry.registrarFor("io.flutter.plugins.sharedpreferences.SharedPreferencesPlugin")); - FlutterDownloaderPlugin.registerWith(registry.registrarFor("vn.hunghd.flutterdownloader.FlutterDownloaderPlugin")); - } - - private static boolean alreadyRegisteredWith(PluginRegistry registry) { - final String key = IsolatePluginRegistrant.class.getCanonicalName(); - if (registry.hasPlugin(key)) { - return true; - } - registry.registrarFor(key); - return false; - } +package io.flutter.plugins; + +import androidx.annotation.Keep; +import androidx.annotation.NonNull; + +import io.flutter.embedding.engine.FlutterEngine; +import io.flutter.embedding.engine.plugins.shim.ShimPluginRegistry; +import io.flutter.plugin.common.PluginRegistry; +import io.flutter.plugins.pathprovider.PathProviderPlugin; +import com.tekartik.sqflite.SqflitePlugin; +import io.flutter.plugins.sharedpreferences.SharedPreferencesPlugin; +import vn.hunghd.flutterdownloader.FlutterDownloaderPlugin; + +/** + * Generated file. Do not edit. This file is generated by the Flutter tool based + * on the plugins that support the Android platform. + */ + +@Keep +public final class IsolatePluginRegistrant { + public static void registerWith(PluginRegistry registry) { + if (alreadyRegisteredWith(registry)) { + return; + } + PathProviderPlugin.registerWith(registry.registrarFor("io.flutter.plugins.pathprovider.PathProviderPlugin")); + SqflitePlugin.registerWith(registry.registrarFor("com.tekartik.sqflite.SqflitePlugin")); + SharedPreferencesPlugin.registerWith(registry.registrarFor("io.flutter.plugins.sharedpreferences.SharedPreferencesPlugin")); + FlutterDownloaderPlugin.registerWith(registry.registrarFor("vn.hunghd.flutterdownloader.FlutterDownloaderPlugin")); + } + + private static boolean alreadyRegisteredWith(PluginRegistry registry) { + final String key = IsolatePluginRegistrant.class.getCanonicalName(); + if (registry.hasPlugin(key)) { + return true; + } + registry.registrarFor(key); + return false; + } } \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/stonegate/tsacdop/MainActivity.kt b/android/app/src/main/kotlin/com/stonegate/tsacdop/MainActivity.kt index ff5a023..13faed9 100644 --- a/android/app/src/main/kotlin/com/stonegate/tsacdop/MainActivity.kt +++ b/android/app/src/main/kotlin/com/stonegate/tsacdop/MainActivity.kt @@ -1,28 +1,28 @@ -package com.stonegate.tsacdop - -import androidx.annotation.NonNull; -import io.flutter.embedding.android.FlutterActivity -import io.flutter.embedding.engine.FlutterEngine -import io.flutter.view.FlutterNativeView -import io.flutter.plugins.GeneratedPluginRegistrant -import io.flutter.plugins.IsolatePluginRegistrant -import io.flutter.plugin.common.MethodChannel -import io.flutter.plugin.common.MethodChannel.MethodCallHandler -import io.flutter.plugin.common.MethodChannel.Result -import io.flutter.embedding.engine.dart.DartExecutor -import io.flutter.embedding.engine.dart.DartExecutor.DartCallback -import com.rmawatson.flutterisolate.FlutterIsolatePlugin - -class MainActivity: FlutterActivity() { - override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) { - GeneratedPluginRegistrant.registerWith(flutterEngine); - FlutterIsolatePlugin.setCustomIsolateRegistrant(IsolatePluginRegistrant::class.java); - MethodChannel(flutterEngine.dartExecutor, "android_app_retain").apply { - setMethodCallHandler { method, result -> - if (method.method == "sendToBackground") { - moveTaskToBack(true) - } - } - } - } -} +package com.stonegate.tsacdop + +import androidx.annotation.NonNull; +import io.flutter.embedding.android.FlutterActivity +import io.flutter.embedding.engine.FlutterEngine +import io.flutter.view.FlutterNativeView +import io.flutter.plugins.GeneratedPluginRegistrant +import io.flutter.plugins.IsolatePluginRegistrant +import io.flutter.plugin.common.MethodChannel +import io.flutter.plugin.common.MethodChannel.MethodCallHandler +import io.flutter.plugin.common.MethodChannel.Result +import io.flutter.embedding.engine.dart.DartExecutor +import io.flutter.embedding.engine.dart.DartExecutor.DartCallback +import com.rmawatson.flutterisolate.FlutterIsolatePlugin + +class MainActivity: FlutterActivity() { + override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) { + GeneratedPluginRegistrant.registerWith(flutterEngine); + FlutterIsolatePlugin.setCustomIsolateRegistrant(IsolatePluginRegistrant::class.java); + MethodChannel(flutterEngine.dartExecutor, "android_app_retain").apply { + setMethodCallHandler { method, result -> + if (method.method == "sendToBackground") { + moveTaskToBack(true) + } + } + } + } +} diff --git a/android/app/src/main/res/drawable-night/launch_background.xml b/android/app/src/main/res/drawable-night/launch_background.xml index 0feabb0..fea418d 100644 --- a/android/app/src/main/res/drawable-night/launch_background.xml +++ b/android/app/src/main/res/drawable-night/launch_background.xml @@ -1,17 +1,17 @@ - - - - - - - - - - - + + + + + + + + + + + \ No newline at end of file diff --git a/android/app/src/main/res/drawable-night/normal_background.xml b/android/app/src/main/res/drawable-night/normal_background.xml index ce6ada7..345a739 100644 --- a/android/app/src/main/res/drawable-night/normal_background.xml +++ b/android/app/src/main/res/drawable-night/normal_background.xml @@ -1,9 +1,9 @@ - - - - - - - - --> + + + + + + + + --> \ No newline at end of file diff --git a/android/app/src/main/res/drawable/launch_background.xml b/android/app/src/main/res/drawable/launch_background.xml index 38848ce..80b77b6 100644 --- a/android/app/src/main/res/drawable/launch_background.xml +++ b/android/app/src/main/res/drawable/launch_background.xml @@ -1,12 +1,12 @@ - - - - - - - - - - - - + + + + + + + + + + + + diff --git a/android/app/src/main/res/drawable/launch_background_night.xml b/android/app/src/main/res/drawable/launch_background_night.xml index 72c4c7f..5a36c4d 100644 --- a/android/app/src/main/res/drawable/launch_background_night.xml +++ b/android/app/src/main/res/drawable/launch_background_night.xml @@ -1,12 +1,12 @@ - - - - - - - - - - - + + + + + + + + + + + \ No newline at end of file diff --git a/android/app/src/main/res/drawable/normal_background.xml b/android/app/src/main/res/drawable/normal_background.xml index 53e1c32..a398550 100644 --- a/android/app/src/main/res/drawable/normal_background.xml +++ b/android/app/src/main/res/drawable/normal_background.xml @@ -1,9 +1,9 @@ - - - - - - - - + + + + + + + + \ No newline at end of file diff --git a/android/app/src/main/res/drawable/normal_background_night.xml b/android/app/src/main/res/drawable/normal_background_night.xml index 4efc20a..61e1101 100644 --- a/android/app/src/main/res/drawable/normal_background_night.xml +++ b/android/app/src/main/res/drawable/normal_background_night.xml @@ -1,9 +1,9 @@ - - - - - - - - + + + + + + + + \ No newline at end of file diff --git a/android/app/src/main/res/values-night/styles.xml b/android/app/src/main/res/values-night/styles.xml index a38d0b9..d1339be 100644 --- a/android/app/src/main/res/values-night/styles.xml +++ b/android/app/src/main/res/values-night/styles.xml @@ -1,10 +1,10 @@ - - - + + + \ No newline at end of file diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml index 4e30a4a..502d47e 100644 --- a/android/app/src/main/res/values/styles.xml +++ b/android/app/src/main/res/values/styles.xml @@ -1,12 +1,12 @@ - - - - + + + + diff --git a/android/app/src/main/res/xml/network_security_config.xml b/android/app/src/main/res/xml/network_security_config.xml index f18e1f0..ab7ae8f 100644 --- a/android/app/src/main/res/xml/network_security_config.xml +++ b/android/app/src/main/res/xml/network_security_config.xml @@ -1,8 +1,8 @@ - - - - - - - + + + + + + + \ No newline at end of file diff --git a/android/app/src/profile/AndroidManifest.xml b/android/app/src/profile/AndroidManifest.xml index 35c9116..64c8d13 100644 --- a/android/app/src/profile/AndroidManifest.xml +++ b/android/app/src/profile/AndroidManifest.xml @@ -1,7 +1,7 @@ - - - - + + + + diff --git a/android/build.gradle b/android/build.gradle index b3db53a..fdde64e 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -1,32 +1,32 @@ -buildscript { - ext.kotlin_version = '1.3.70' - repositories { - google() - jcenter() - } - - dependencies { - classpath 'com.android.tools.build:gradle:3.6.2' - 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 -} +buildscript { + ext.kotlin_version = '1.3.70' + repositories { + google() + jcenter() + } + + dependencies { + classpath 'com.android.tools.build:gradle:3.6.2' + 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/android/gradle.properties b/android/gradle.properties index 38c8d45..74c1d92 100644 --- a/android/gradle.properties +++ b/android/gradle.properties @@ -1,4 +1,4 @@ -org.gradle.jvmargs=-Xmx1536M -android.enableR8=true -android.useAndroidX=true -android.enableJetifier=true +org.gradle.jvmargs=-Xmx1536M +android.enableR8=true +android.useAndroidX=true +android.enableJetifier=true diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties index c79d946..5faff86 100644 --- a/android/gradle/wrapper/gradle-wrapper.properties +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Fri Mar 20 23:46:20 CST 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 +#Fri Mar 20 23:46:20 CST 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/android/settings.gradle b/android/settings.gradle index 5a2f14f..4f14f8e 100644 --- a/android/settings.gradle +++ b/android/settings.gradle @@ -1,15 +1,15 @@ -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 -} +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/android/settings_aar.gradle b/android/settings_aar.gradle index e7b4def..d3db109 100644 --- a/android/settings_aar.gradle +++ b/android/settings_aar.gradle @@ -1 +1 @@ -include ':app' +include ':app' diff --git a/ios/.gitignore b/ios/.gitignore index e96ef60..0f1df0f 100644 --- a/ios/.gitignore +++ b/ios/.gitignore @@ -1,32 +1,32 @@ -*.mode1v3 -*.mode2v3 -*.moved-aside -*.pbxuser -*.perspectivev3 -**/*sync/ -.sconsign.dblite -.tags* -**/.vagrant/ -**/DerivedData/ -Icon? -**/Pods/ -**/.symlinks/ -profile -xcuserdata -**/.generated/ -Flutter/App.framework -Flutter/Flutter.framework -Flutter/Flutter.podspec -Flutter/Generated.xcconfig -Flutter/app.flx -Flutter/app.zip -Flutter/flutter_assets/ -Flutter/flutter_export_environment.sh -ServiceDefinitions.json -Runner/GeneratedPluginRegistrant.* - -# Exceptions to above rules. -!default.mode1v3 -!default.mode2v3 -!default.pbxuser -!default.perspectivev3 +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/ios/Flutter/AppFrameworkInfo.plist b/ios/Flutter/AppFrameworkInfo.plist index 6b4c0f7..58e65f9 100644 --- a/ios/Flutter/AppFrameworkInfo.plist +++ b/ios/Flutter/AppFrameworkInfo.plist @@ -1,26 +1,26 @@ - - - - - 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 - - + + + + + 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/ios/Flutter/Debug.xcconfig b/ios/Flutter/Debug.xcconfig index e8efba1..f0e2de1 100644 --- a/ios/Flutter/Debug.xcconfig +++ b/ios/Flutter/Debug.xcconfig @@ -1,2 +1,2 @@ -#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" -#include "Generated.xcconfig" +#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" +#include "Generated.xcconfig" diff --git a/ios/Flutter/Release.xcconfig b/ios/Flutter/Release.xcconfig index 399e934..12b9798 100644 --- a/ios/Flutter/Release.xcconfig +++ b/ios/Flutter/Release.xcconfig @@ -1,2 +1,2 @@ -#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" -#include "Generated.xcconfig" +#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" +#include "Generated.xcconfig" diff --git a/ios/Podfile b/ios/Podfile index d87b939..5c127f3 100644 --- a/ios/Podfile +++ b/ios/Podfile @@ -1,88 +1,88 @@ -# Uncomment this line to define a global platform for your project -platform :ios, '11.0' - -# CocoaPods analytics sends network stats synchronously affecting flutter build latency. -ENV['COCOAPODS_DISABLE_STATS'] = 'true' -source 'https://cdn.cocoapods.org/' - -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 - -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 +# Uncomment this line to define a global platform for your project +platform :ios, '11.0' + +# CocoaPods analytics sends network stats synchronously affecting flutter build latency. +ENV['COCOAPODS_DISABLE_STATS'] = 'true' +source 'https://cdn.cocoapods.org/' + +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 + +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/ios/Podfile.lock b/ios/Podfile.lock index a193253..08ca3e1 100644 --- a/ios/Podfile.lock +++ b/ios/Podfile.lock @@ -1,204 +1,204 @@ -PODS: - - audio_service (0.0.1): - - Flutter - - connectivity (0.0.1): - - Flutter - - Reachability - - connectivity_macos (0.0.1): - - Flutter - - DKImagePickerController/Core (4.2.2): - - DKImagePickerController/ImageDataManager - - DKImagePickerController/Resource - - DKImagePickerController/ImageDataManager (4.2.2) - - DKImagePickerController/PhotoGallery (4.2.2): - - DKImagePickerController/Core - - DKPhotoGallery - - DKImagePickerController/Resource (4.2.2) - - DKPhotoGallery (0.0.14): - - DKPhotoGallery/Core (= 0.0.14) - - DKPhotoGallery/Model (= 0.0.14) - - DKPhotoGallery/Preview (= 0.0.14) - - DKPhotoGallery/Resource (= 0.0.14) - - SDWebImage - - SDWebImageFLPlugin - - DKPhotoGallery/Core (0.0.14): - - DKPhotoGallery/Model - - DKPhotoGallery/Preview - - SDWebImage - - SDWebImageFLPlugin - - DKPhotoGallery/Model (0.0.14): - - SDWebImage - - SDWebImageFLPlugin - - DKPhotoGallery/Preview (0.0.14): - - DKPhotoGallery/Model - - DKPhotoGallery/Resource - - SDWebImage - - SDWebImageFLPlugin - - DKPhotoGallery/Resource (0.0.14): - - SDWebImage - - SDWebImageFLPlugin - - file_picker (0.0.1): - - DKImagePickerController/PhotoGallery - - Flutter - - FLAnimatedImage (1.0.12) - - Flutter (1.0.0) - - flutter_downloader (0.0.1): - - Flutter - - flutter_file_dialog (0.0.1): - - Flutter - - flutter_isolate (0.0.1): - - Flutter - - flutter_plugin_android_lifecycle (0.0.1): - - Flutter - - fluttertoast (0.0.2): - - Flutter - - FMDB (2.7.5): - - FMDB/standard (= 2.7.5) - - FMDB/standard (2.7.5) - - just_audio (0.0.1): - - Flutter - - path_provider (0.0.1): - - Flutter - - path_provider_macos (0.0.1): - - Flutter - - "permission_handler (5.0.0+hotfix.5)": - - Flutter - - Reachability (3.2) - - SDWebImage (5.7.4): - - SDWebImage/Core (= 5.7.4) - - SDWebImage/Core (5.7.4) - - SDWebImageFLPlugin (0.4.0): - - FLAnimatedImage (>= 1.0.11) - - SDWebImage/Core (~> 5.6) - - shared_preferences (0.0.1): - - Flutter - - shared_preferences_macos (0.0.1): - - Flutter - - shared_preferences_web (0.0.1): - - Flutter - - sqflite (0.0.1): - - Flutter - - FMDB (~> 2.7.2) - - url_launcher (0.0.1): - - Flutter - - url_launcher_macos (0.0.1): - - Flutter - - url_launcher_web (0.0.1): - - Flutter - - workmanager (0.0.1): - - Flutter - -DEPENDENCIES: - - audio_service (from `.symlinks/plugins/audio_service/ios`) - - connectivity (from `.symlinks/plugins/connectivity/ios`) - - connectivity_macos (from `.symlinks/plugins/connectivity_macos/ios`) - - file_picker (from `.symlinks/plugins/file_picker/ios`) - - Flutter (from `Flutter`) - - flutter_downloader (from `.symlinks/plugins/flutter_downloader/ios`) - - flutter_file_dialog (from `.symlinks/plugins/flutter_file_dialog/ios`) - - flutter_isolate (from `.symlinks/plugins/flutter_isolate/ios`) - - flutter_plugin_android_lifecycle (from `.symlinks/plugins/flutter_plugin_android_lifecycle/ios`) - - fluttertoast (from `.symlinks/plugins/fluttertoast/ios`) - - just_audio (from `.symlinks/plugins/just_audio/ios`) - - path_provider (from `.symlinks/plugins/path_provider/ios`) - - path_provider_macos (from `.symlinks/plugins/path_provider_macos/ios`) - - permission_handler (from `.symlinks/plugins/permission_handler/ios`) - - shared_preferences (from `.symlinks/plugins/shared_preferences/ios`) - - shared_preferences_macos (from `.symlinks/plugins/shared_preferences_macos/ios`) - - shared_preferences_web (from `.symlinks/plugins/shared_preferences_web/ios`) - - sqflite (from `.symlinks/plugins/sqflite/ios`) - - url_launcher (from `.symlinks/plugins/url_launcher/ios`) - - url_launcher_macos (from `.symlinks/plugins/url_launcher_macos/ios`) - - url_launcher_web (from `.symlinks/plugins/url_launcher_web/ios`) - - workmanager (from `.symlinks/plugins/workmanager/ios`) - -SPEC REPOS: - trunk: - - DKImagePickerController - - DKPhotoGallery - - FLAnimatedImage - - FMDB - - Reachability - - SDWebImage - - SDWebImageFLPlugin - -EXTERNAL SOURCES: - audio_service: - :path: ".symlinks/plugins/audio_service/ios" - connectivity: - :path: ".symlinks/plugins/connectivity/ios" - connectivity_macos: - :path: ".symlinks/plugins/connectivity_macos/ios" - file_picker: - :path: ".symlinks/plugins/file_picker/ios" - Flutter: - :path: Flutter - flutter_downloader: - :path: ".symlinks/plugins/flutter_downloader/ios" - flutter_file_dialog: - :path: ".symlinks/plugins/flutter_file_dialog/ios" - flutter_isolate: - :path: ".symlinks/plugins/flutter_isolate/ios" - flutter_plugin_android_lifecycle: - :path: ".symlinks/plugins/flutter_plugin_android_lifecycle/ios" - fluttertoast: - :path: ".symlinks/plugins/fluttertoast/ios" - just_audio: - :path: ".symlinks/plugins/just_audio/ios" - path_provider: - :path: ".symlinks/plugins/path_provider/ios" - path_provider_macos: - :path: ".symlinks/plugins/path_provider_macos/ios" - permission_handler: - :path: ".symlinks/plugins/permission_handler/ios" - shared_preferences: - :path: ".symlinks/plugins/shared_preferences/ios" - shared_preferences_macos: - :path: ".symlinks/plugins/shared_preferences_macos/ios" - shared_preferences_web: - :path: ".symlinks/plugins/shared_preferences_web/ios" - sqflite: - :path: ".symlinks/plugins/sqflite/ios" - url_launcher: - :path: ".symlinks/plugins/url_launcher/ios" - url_launcher_macos: - :path: ".symlinks/plugins/url_launcher_macos/ios" - url_launcher_web: - :path: ".symlinks/plugins/url_launcher_web/ios" - workmanager: - :path: ".symlinks/plugins/workmanager/ios" - -SPEC CHECKSUMS: - audio_service: f509d65da41b9521a61f1c404dd58651f265a567 - connectivity: c4130b2985d4ef6fd26f9702e886bd5260681467 - connectivity_macos: e2e9731b6b22dda39eb1b128f6969d574460e191 - DKImagePickerController: 4a3e7948a848c4348e600b3fe5ce41478835fa10 - DKPhotoGallery: 0290d32343574f06eaa4c26f8f2f8a1035e916be - file_picker: 3e6c3790de664ccf9b882732d9db5eaf6b8d4eb1 - FLAnimatedImage: 4a0b56255d9b05f18b6dd7ee06871be5d3b89e31 - Flutter: 0e3d915762c693b495b44d77113d4970485de6ec - flutter_downloader: 058b9c41564a90500f67f3e432e3524613a7fd83 - flutter_file_dialog: 34ab8c55c460c69cb70e75a8d74bfe8b5c852824 - flutter_isolate: 0edf5081826d071adf21759d1eb10ff5c24503b5 - flutter_plugin_android_lifecycle: dc0b544e129eebb77a6bfb1239d4d1c673a60a35 - fluttertoast: b644586ef3b16f67fae9a1f8754cef6b2d6b634b - FMDB: 2ce00b547f966261cd18927a3ddb07cb6f3db82a - just_audio: c695d6e7e37f9e96672dd84039d7530e7fd5c205 - path_provider: abfe2b5c733d04e238b0d8691db0cfd63a27a93c - path_provider_macos: f760a3c5b04357c380e2fddb6f9db6f3015897e0 - permission_handler: 6226fcb78b97c7c7458a95c7346a11d5184fec12 - Reachability: 33e18b67625424e47b6cde6d202dce689ad7af96 - SDWebImage: 48b88379b798fd1e4298f95bb25d2cdabbf4deb3 - SDWebImageFLPlugin: 6c2295fb1242d44467c6c87dc5db6b0a13228fd8 - shared_preferences: af6bfa751691cdc24be3045c43ec037377ada40d - shared_preferences_macos: f3f29b71ccbb56bf40c9dd6396c9acf15e214087 - shared_preferences_web: 141cce0c3ed1a1c5bf2a0e44f52d31eeb66e5ea9 - sqflite: 4001a31ff81d210346b500c55b17f4d6c7589dd0 - url_launcher: 6fef411d543ceb26efce54b05a0a40bfd74cbbef - url_launcher_macos: fd7894421cd39320dce5f292fc99ea9270b2a313 - url_launcher_web: e5527357f037c87560776e36436bf2b0288b965c - workmanager: ffff78bf18495e2bc5b8c955ead94a81db340681 - -PODFILE CHECKSUM: 7a493bdf8e8fed20acf4793e6605bdc446895cf3 - -COCOAPODS: 1.9.1 +PODS: + - audio_service (0.0.1): + - Flutter + - connectivity (0.0.1): + - Flutter + - Reachability + - connectivity_macos (0.0.1): + - Flutter + - DKImagePickerController/Core (4.2.2): + - DKImagePickerController/ImageDataManager + - DKImagePickerController/Resource + - DKImagePickerController/ImageDataManager (4.2.2) + - DKImagePickerController/PhotoGallery (4.2.2): + - DKImagePickerController/Core + - DKPhotoGallery + - DKImagePickerController/Resource (4.2.2) + - DKPhotoGallery (0.0.14): + - DKPhotoGallery/Core (= 0.0.14) + - DKPhotoGallery/Model (= 0.0.14) + - DKPhotoGallery/Preview (= 0.0.14) + - DKPhotoGallery/Resource (= 0.0.14) + - SDWebImage + - SDWebImageFLPlugin + - DKPhotoGallery/Core (0.0.14): + - DKPhotoGallery/Model + - DKPhotoGallery/Preview + - SDWebImage + - SDWebImageFLPlugin + - DKPhotoGallery/Model (0.0.14): + - SDWebImage + - SDWebImageFLPlugin + - DKPhotoGallery/Preview (0.0.14): + - DKPhotoGallery/Model + - DKPhotoGallery/Resource + - SDWebImage + - SDWebImageFLPlugin + - DKPhotoGallery/Resource (0.0.14): + - SDWebImage + - SDWebImageFLPlugin + - file_picker (0.0.1): + - DKImagePickerController/PhotoGallery + - Flutter + - FLAnimatedImage (1.0.12) + - Flutter (1.0.0) + - flutter_downloader (0.0.1): + - Flutter + - flutter_file_dialog (0.0.1): + - Flutter + - flutter_isolate (0.0.1): + - Flutter + - flutter_plugin_android_lifecycle (0.0.1): + - Flutter + - fluttertoast (0.0.2): + - Flutter + - FMDB (2.7.5): + - FMDB/standard (= 2.7.5) + - FMDB/standard (2.7.5) + - just_audio (0.0.1): + - Flutter + - path_provider (0.0.1): + - Flutter + - path_provider_macos (0.0.1): + - Flutter + - "permission_handler (5.0.0+hotfix.5)": + - Flutter + - Reachability (3.2) + - SDWebImage (5.7.4): + - SDWebImage/Core (= 5.7.4) + - SDWebImage/Core (5.7.4) + - SDWebImageFLPlugin (0.4.0): + - FLAnimatedImage (>= 1.0.11) + - SDWebImage/Core (~> 5.6) + - shared_preferences (0.0.1): + - Flutter + - shared_preferences_macos (0.0.1): + - Flutter + - shared_preferences_web (0.0.1): + - Flutter + - sqflite (0.0.1): + - Flutter + - FMDB (~> 2.7.2) + - url_launcher (0.0.1): + - Flutter + - url_launcher_macos (0.0.1): + - Flutter + - url_launcher_web (0.0.1): + - Flutter + - workmanager (0.0.1): + - Flutter + +DEPENDENCIES: + - audio_service (from `.symlinks/plugins/audio_service/ios`) + - connectivity (from `.symlinks/plugins/connectivity/ios`) + - connectivity_macos (from `.symlinks/plugins/connectivity_macos/ios`) + - file_picker (from `.symlinks/plugins/file_picker/ios`) + - Flutter (from `Flutter`) + - flutter_downloader (from `.symlinks/plugins/flutter_downloader/ios`) + - flutter_file_dialog (from `.symlinks/plugins/flutter_file_dialog/ios`) + - flutter_isolate (from `.symlinks/plugins/flutter_isolate/ios`) + - flutter_plugin_android_lifecycle (from `.symlinks/plugins/flutter_plugin_android_lifecycle/ios`) + - fluttertoast (from `.symlinks/plugins/fluttertoast/ios`) + - just_audio (from `.symlinks/plugins/just_audio/ios`) + - path_provider (from `.symlinks/plugins/path_provider/ios`) + - path_provider_macos (from `.symlinks/plugins/path_provider_macos/ios`) + - permission_handler (from `.symlinks/plugins/permission_handler/ios`) + - shared_preferences (from `.symlinks/plugins/shared_preferences/ios`) + - shared_preferences_macos (from `.symlinks/plugins/shared_preferences_macos/ios`) + - shared_preferences_web (from `.symlinks/plugins/shared_preferences_web/ios`) + - sqflite (from `.symlinks/plugins/sqflite/ios`) + - url_launcher (from `.symlinks/plugins/url_launcher/ios`) + - url_launcher_macos (from `.symlinks/plugins/url_launcher_macos/ios`) + - url_launcher_web (from `.symlinks/plugins/url_launcher_web/ios`) + - workmanager (from `.symlinks/plugins/workmanager/ios`) + +SPEC REPOS: + trunk: + - DKImagePickerController + - DKPhotoGallery + - FLAnimatedImage + - FMDB + - Reachability + - SDWebImage + - SDWebImageFLPlugin + +EXTERNAL SOURCES: + audio_service: + :path: ".symlinks/plugins/audio_service/ios" + connectivity: + :path: ".symlinks/plugins/connectivity/ios" + connectivity_macos: + :path: ".symlinks/plugins/connectivity_macos/ios" + file_picker: + :path: ".symlinks/plugins/file_picker/ios" + Flutter: + :path: Flutter + flutter_downloader: + :path: ".symlinks/plugins/flutter_downloader/ios" + flutter_file_dialog: + :path: ".symlinks/plugins/flutter_file_dialog/ios" + flutter_isolate: + :path: ".symlinks/plugins/flutter_isolate/ios" + flutter_plugin_android_lifecycle: + :path: ".symlinks/plugins/flutter_plugin_android_lifecycle/ios" + fluttertoast: + :path: ".symlinks/plugins/fluttertoast/ios" + just_audio: + :path: ".symlinks/plugins/just_audio/ios" + path_provider: + :path: ".symlinks/plugins/path_provider/ios" + path_provider_macos: + :path: ".symlinks/plugins/path_provider_macos/ios" + permission_handler: + :path: ".symlinks/plugins/permission_handler/ios" + shared_preferences: + :path: ".symlinks/plugins/shared_preferences/ios" + shared_preferences_macos: + :path: ".symlinks/plugins/shared_preferences_macos/ios" + shared_preferences_web: + :path: ".symlinks/plugins/shared_preferences_web/ios" + sqflite: + :path: ".symlinks/plugins/sqflite/ios" + url_launcher: + :path: ".symlinks/plugins/url_launcher/ios" + url_launcher_macos: + :path: ".symlinks/plugins/url_launcher_macos/ios" + url_launcher_web: + :path: ".symlinks/plugins/url_launcher_web/ios" + workmanager: + :path: ".symlinks/plugins/workmanager/ios" + +SPEC CHECKSUMS: + audio_service: f509d65da41b9521a61f1c404dd58651f265a567 + connectivity: c4130b2985d4ef6fd26f9702e886bd5260681467 + connectivity_macos: e2e9731b6b22dda39eb1b128f6969d574460e191 + DKImagePickerController: 4a3e7948a848c4348e600b3fe5ce41478835fa10 + DKPhotoGallery: 0290d32343574f06eaa4c26f8f2f8a1035e916be + file_picker: 3e6c3790de664ccf9b882732d9db5eaf6b8d4eb1 + FLAnimatedImage: 4a0b56255d9b05f18b6dd7ee06871be5d3b89e31 + Flutter: 0e3d915762c693b495b44d77113d4970485de6ec + flutter_downloader: 058b9c41564a90500f67f3e432e3524613a7fd83 + flutter_file_dialog: 34ab8c55c460c69cb70e75a8d74bfe8b5c852824 + flutter_isolate: 0edf5081826d071adf21759d1eb10ff5c24503b5 + flutter_plugin_android_lifecycle: dc0b544e129eebb77a6bfb1239d4d1c673a60a35 + fluttertoast: b644586ef3b16f67fae9a1f8754cef6b2d6b634b + FMDB: 2ce00b547f966261cd18927a3ddb07cb6f3db82a + just_audio: c695d6e7e37f9e96672dd84039d7530e7fd5c205 + path_provider: abfe2b5c733d04e238b0d8691db0cfd63a27a93c + path_provider_macos: f760a3c5b04357c380e2fddb6f9db6f3015897e0 + permission_handler: 6226fcb78b97c7c7458a95c7346a11d5184fec12 + Reachability: 33e18b67625424e47b6cde6d202dce689ad7af96 + SDWebImage: 48b88379b798fd1e4298f95bb25d2cdabbf4deb3 + SDWebImageFLPlugin: 6c2295fb1242d44467c6c87dc5db6b0a13228fd8 + shared_preferences: af6bfa751691cdc24be3045c43ec037377ada40d + shared_preferences_macos: f3f29b71ccbb56bf40c9dd6396c9acf15e214087 + shared_preferences_web: 141cce0c3ed1a1c5bf2a0e44f52d31eeb66e5ea9 + sqflite: 4001a31ff81d210346b500c55b17f4d6c7589dd0 + url_launcher: 6fef411d543ceb26efce54b05a0a40bfd74cbbef + url_launcher_macos: fd7894421cd39320dce5f292fc99ea9270b2a313 + url_launcher_web: e5527357f037c87560776e36436bf2b0288b965c + workmanager: ffff78bf18495e2bc5b8c955ead94a81db340681 + +PODFILE CHECKSUM: 7a493bdf8e8fed20acf4793e6605bdc446895cf3 + +COCOAPODS: 1.9.1 diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj index 1188270..e1233cc 100644 --- a/ios/Runner.xcodeproj/project.pbxproj +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -1,631 +1,631 @@ -// !$*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 */; }; - 8CF9779B9A79168FBFA6066E /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 06AA1B089A6D985A4089F4BD /* Pods_Runner.framework */; }; - 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 */ - 06AA1B089A6D985A4089F4BD /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 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 = ""; }; - 8E4DBAFB2467BE8D00105DDB /* libsqlite3.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libsqlite3.tbd; path = usr/lib/libsqlite3.tbd; sourceTree = SDKROOT; }; - 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 = ""; }; - B827BA8675C74CB4AFD456BC /* 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 = ""; }; - D6D257E2FEE682CAC1D1B896 /* 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 = ""; }; - E41B1437959B0B40C6234702 /* 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 = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 97C146EB1CF9000F007C117D /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 8CF9779B9A79168FBFA6066E /* Pods_Runner.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 3D584C694C8C44F5D212B449 /* Frameworks */ = { - isa = PBXGroup; - children = ( - 8E4DBAFB2467BE8D00105DDB /* libsqlite3.tbd */, - 06AA1B089A6D985A4089F4BD /* 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 */, - D2BCEC9BD06387351E0A72A7 /* Pods */, - 3D584C694C8C44F5D212B449 /* 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 = ""; - }; - D2BCEC9BD06387351E0A72A7 /* Pods */ = { - isa = PBXGroup; - children = ( - B827BA8675C74CB4AFD456BC /* Pods-Runner.debug.xcconfig */, - E41B1437959B0B40C6234702 /* Pods-Runner.release.xcconfig */, - D6D257E2FEE682CAC1D1B896 /* 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 = ( - 4BBE9E1028F71ACA14B5C484 /* [CP] Check Pods Manifest.lock */, - 9740EEB61CF901F6004384FC /* Run Script */, - 97C146EA1CF9000F007C117D /* Sources */, - 97C146EB1CF9000F007C117D /* Frameworks */, - 97C146EC1CF9000F007C117D /* Resources */, - 9705A1C41CF9048500538489 /* Embed Frameworks */, - 3B06AD1E1E4923F5004D2608 /* Thin Binary */, - 677388F870C1161C00B6B196 /* [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 = ""; - TargetAttributes = { - 97C146ED1CF9000F007C117D = { - CreatedOnToolsVersion = 7.3.1; - LastSwiftMigration = 1100; - ProvisioningStyle = Automatic; - }; - }; - }; - 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 */, - 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\n"; - }; - 4BBE9E1028F71ACA14B5C484 /* [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; - }; - 677388F870C1161C00B6B196 /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh", - "${BUILT_PRODUCTS_DIR}/DKImagePickerController/DKImagePickerController.framework", - "${BUILT_PRODUCTS_DIR}/DKPhotoGallery/DKPhotoGallery.framework", - "${BUILT_PRODUCTS_DIR}/FLAnimatedImage/FLAnimatedImage.framework", - "${BUILT_PRODUCTS_DIR}/FMDB/FMDB.framework", - "${PODS_ROOT}/../Flutter/Flutter.framework", - "${BUILT_PRODUCTS_DIR}/Reachability/Reachability.framework", - "${BUILT_PRODUCTS_DIR}/SDWebImage/SDWebImage.framework", - "${BUILT_PRODUCTS_DIR}/SDWebImageFLPlugin/SDWebImageFLPlugin.framework", - "${BUILT_PRODUCTS_DIR}/audio_service/audio_service.framework", - "${BUILT_PRODUCTS_DIR}/connectivity/connectivity.framework", - "${BUILT_PRODUCTS_DIR}/file_picker/file_picker.framework", - "${BUILT_PRODUCTS_DIR}/flutter_downloader/flutter_downloader.framework", - "${BUILT_PRODUCTS_DIR}/flutter_file_dialog/flutter_file_dialog.framework", - "${BUILT_PRODUCTS_DIR}/flutter_isolate/flutter_isolate.framework", - "${BUILT_PRODUCTS_DIR}/flutter_plugin_android_lifecycle/flutter_plugin_android_lifecycle.framework", - "${BUILT_PRODUCTS_DIR}/fluttertoast/fluttertoast.framework", - "${BUILT_PRODUCTS_DIR}/just_audio/just_audio.framework", - "${BUILT_PRODUCTS_DIR}/path_provider/path_provider.framework", - "${BUILT_PRODUCTS_DIR}/shared_preferences/shared_preferences.framework", - "${BUILT_PRODUCTS_DIR}/sqflite/sqflite.framework", - "${BUILT_PRODUCTS_DIR}/url_launcher/url_launcher.framework", - "${BUILT_PRODUCTS_DIR}/workmanager/workmanager.framework", - ); - name = "[CP] Embed Pods Frameworks"; - outputPaths = ( - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/DKImagePickerController.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/DKPhotoGallery.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/FLAnimatedImage.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/FMDB.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Flutter.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Reachability.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SDWebImage.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SDWebImageFLPlugin.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/audio_service.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/connectivity.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/file_picker.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/flutter_downloader.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/flutter_file_dialog.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/flutter_isolate.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/flutter_plugin_android_lifecycle.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/fluttertoast.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/just_audio.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/path_provider.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/shared_preferences.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/sqflite.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/url_launcher.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/workmanager.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 */ - 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; - SUPPORTED_PLATFORMS = iphoneos; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - }; - name = Profile; - }; - 249021D4217E4FDB00AE95B9 /* Profile */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CLANG_ENABLE_MODULES = YES; - CODE_SIGN_IDENTITY = "Apple Development"; - CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; - DEVELOPMENT_TEAM = ""; - 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.stonegate.tsacdop; - PRODUCT_NAME = "$(TARGET_NAME)"; - PROVISIONING_PROFILE_SPECIFIER = ""; - 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; - SUPPORTED_PLATFORMS = 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; - CODE_SIGN_IDENTITY = "Apple Development"; - CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; - DEVELOPMENT_TEAM = ""; - 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.stonegate.tsacdop; - PRODUCT_NAME = "$(TARGET_NAME)"; - PROVISIONING_PROFILE_SPECIFIER = ""; - 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; - CODE_SIGN_IDENTITY = "Apple Development"; - CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; - DEVELOPMENT_TEAM = ""; - 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.stonegate.tsacdop; - PRODUCT_NAME = "$(TARGET_NAME)"; - PROVISIONING_PROFILE_SPECIFIER = ""; - 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 */; -} +// !$*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 */; }; + 8CF9779B9A79168FBFA6066E /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 06AA1B089A6D985A4089F4BD /* Pods_Runner.framework */; }; + 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 */ + 06AA1B089A6D985A4089F4BD /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 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 = ""; }; + 8E4DBAFB2467BE8D00105DDB /* libsqlite3.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libsqlite3.tbd; path = usr/lib/libsqlite3.tbd; sourceTree = SDKROOT; }; + 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 = ""; }; + B827BA8675C74CB4AFD456BC /* 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 = ""; }; + D6D257E2FEE682CAC1D1B896 /* 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 = ""; }; + E41B1437959B0B40C6234702 /* 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 = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 8CF9779B9A79168FBFA6066E /* Pods_Runner.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 3D584C694C8C44F5D212B449 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 8E4DBAFB2467BE8D00105DDB /* libsqlite3.tbd */, + 06AA1B089A6D985A4089F4BD /* 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 */, + D2BCEC9BD06387351E0A72A7 /* Pods */, + 3D584C694C8C44F5D212B449 /* 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 = ""; + }; + D2BCEC9BD06387351E0A72A7 /* Pods */ = { + isa = PBXGroup; + children = ( + B827BA8675C74CB4AFD456BC /* Pods-Runner.debug.xcconfig */, + E41B1437959B0B40C6234702 /* Pods-Runner.release.xcconfig */, + D6D257E2FEE682CAC1D1B896 /* 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 = ( + 4BBE9E1028F71ACA14B5C484 /* [CP] Check Pods Manifest.lock */, + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + 677388F870C1161C00B6B196 /* [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 = ""; + TargetAttributes = { + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + }; + }; + }; + 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 */, + 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\n"; + }; + 4BBE9E1028F71ACA14B5C484 /* [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; + }; + 677388F870C1161C00B6B196 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh", + "${BUILT_PRODUCTS_DIR}/DKImagePickerController/DKImagePickerController.framework", + "${BUILT_PRODUCTS_DIR}/DKPhotoGallery/DKPhotoGallery.framework", + "${BUILT_PRODUCTS_DIR}/FLAnimatedImage/FLAnimatedImage.framework", + "${BUILT_PRODUCTS_DIR}/FMDB/FMDB.framework", + "${PODS_ROOT}/../Flutter/Flutter.framework", + "${BUILT_PRODUCTS_DIR}/Reachability/Reachability.framework", + "${BUILT_PRODUCTS_DIR}/SDWebImage/SDWebImage.framework", + "${BUILT_PRODUCTS_DIR}/SDWebImageFLPlugin/SDWebImageFLPlugin.framework", + "${BUILT_PRODUCTS_DIR}/audio_service/audio_service.framework", + "${BUILT_PRODUCTS_DIR}/connectivity/connectivity.framework", + "${BUILT_PRODUCTS_DIR}/file_picker/file_picker.framework", + "${BUILT_PRODUCTS_DIR}/flutter_downloader/flutter_downloader.framework", + "${BUILT_PRODUCTS_DIR}/flutter_file_dialog/flutter_file_dialog.framework", + "${BUILT_PRODUCTS_DIR}/flutter_isolate/flutter_isolate.framework", + "${BUILT_PRODUCTS_DIR}/flutter_plugin_android_lifecycle/flutter_plugin_android_lifecycle.framework", + "${BUILT_PRODUCTS_DIR}/fluttertoast/fluttertoast.framework", + "${BUILT_PRODUCTS_DIR}/just_audio/just_audio.framework", + "${BUILT_PRODUCTS_DIR}/path_provider/path_provider.framework", + "${BUILT_PRODUCTS_DIR}/shared_preferences/shared_preferences.framework", + "${BUILT_PRODUCTS_DIR}/sqflite/sqflite.framework", + "${BUILT_PRODUCTS_DIR}/url_launcher/url_launcher.framework", + "${BUILT_PRODUCTS_DIR}/workmanager/workmanager.framework", + ); + name = "[CP] Embed Pods Frameworks"; + outputPaths = ( + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/DKImagePickerController.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/DKPhotoGallery.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/FLAnimatedImage.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/FMDB.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Flutter.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Reachability.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SDWebImage.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SDWebImageFLPlugin.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/audio_service.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/connectivity.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/file_picker.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/flutter_downloader.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/flutter_file_dialog.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/flutter_isolate.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/flutter_plugin_android_lifecycle.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/fluttertoast.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/just_audio.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/path_provider.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/shared_preferences.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/sqflite.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/url_launcher.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/workmanager.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 */ + 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; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_IDENTITY = "Apple Development"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = ""; + 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.stonegate.tsacdop; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; + 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; + SUPPORTED_PLATFORMS = 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; + CODE_SIGN_IDENTITY = "Apple Development"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = ""; + 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.stonegate.tsacdop; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; + 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; + CODE_SIGN_IDENTITY = "Apple Development"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = ""; + 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.stonegate.tsacdop; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; + 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/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata index 1d526a1..59c6d39 100644 --- a/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata +++ b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -1,7 +1,7 @@ - - - - - + + + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist index 18d9810..fc6bf80 100644 --- a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -1,8 +1,8 @@ - - - - - IDEDidComputeMac32BitWarning - - - + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings index f9b0d7c..af0309c 100644 --- a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -1,8 +1,8 @@ - - - - - PreviewsEnabled - - - + + + + + PreviewsEnabled + + + diff --git a/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index a28140c..be0b92e 100644 --- a/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -1,91 +1,91 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcworkspace/contents.xcworkspacedata index 21a3cc1..17ccc03 100644 --- a/ios/Runner.xcworkspace/contents.xcworkspacedata +++ b/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -1,10 +1,10 @@ - - - - - - - + + + + + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist index 18d9810..fc6bf80 100644 --- a/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +++ b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -1,8 +1,8 @@ - - - - - IDEDidComputeMac32BitWarning - - - + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings index f9b0d7c..af0309c 100644 --- a/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings +++ b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -1,8 +1,8 @@ - - - - - PreviewsEnabled - - - + + + + + PreviewsEnabled + + + diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift index 42f43db..08dbf08 100644 --- a/ios/Runner/AppDelegate.swift +++ b/ios/Runner/AppDelegate.swift @@ -1,23 +1,23 @@ -import UIKit -import Flutter -import flutter_downloader - -@UIApplicationMain -@objc class AppDelegate: FlutterAppDelegate { - override func application( - _ application: UIApplication, - didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? - ) -> Bool { - GeneratedPluginRegistrant.register(with: self) - FlutterDownloaderPlugin.setPluginRegistrantCallback(registerPlugins) - UIApplication.shared.setMinimumBackgroundFetchInterval(TimeInterval(60*60*4)) - return super.application(application, didFinishLaunchingWithOptions: launchOptions) - } -} - -private func registerPlugins(registry: FlutterPluginRegistry) { - if (!registry.hasPlugin("FlutterDownloaderPlugin")) { - FlutterDownloaderPlugin.register(with: registry.registrar(forPlugin: "FlutterDownloaderPlugin")) - } -} - +import UIKit +import Flutter +import flutter_downloader + +@UIApplicationMain +@objc class AppDelegate: FlutterAppDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + GeneratedPluginRegistrant.register(with: self) + FlutterDownloaderPlugin.setPluginRegistrantCallback(registerPlugins) + UIApplication.shared.setMinimumBackgroundFetchInterval(TimeInterval(60*60*4)) + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } +} + +private func registerPlugins(registry: FlutterPluginRegistry) { + if (!registry.hasPlugin("FlutterDownloaderPlugin")) { + FlutterDownloaderPlugin.register(with: registry.registrar(forPlugin: "FlutterDownloaderPlugin")) + } +} + diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json index d36b1fa..1950fd8 100644 --- a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json +++ b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -1,122 +1,122 @@ -{ - "images" : [ - { - "size" : "20x20", - "idiom" : "iphone", - "filename" : "Icon-App-20x20@2x.png", - "scale" : "2x" - }, - { - "size" : "20x20", - "idiom" : "iphone", - "filename" : "Icon-App-20x20@3x.png", - "scale" : "3x" - }, - { - "size" : "29x29", - "idiom" : "iphone", - "filename" : "Icon-App-29x29@1x.png", - "scale" : "1x" - }, - { - "size" : "29x29", - "idiom" : "iphone", - "filename" : "Icon-App-29x29@2x.png", - "scale" : "2x" - }, - { - "size" : "29x29", - "idiom" : "iphone", - "filename" : "Icon-App-29x29@3x.png", - "scale" : "3x" - }, - { - "size" : "40x40", - "idiom" : "iphone", - "filename" : "Icon-App-40x40@2x.png", - "scale" : "2x" - }, - { - "size" : "40x40", - "idiom" : "iphone", - "filename" : "Icon-App-40x40@3x.png", - "scale" : "3x" - }, - { - "size" : "60x60", - "idiom" : "iphone", - "filename" : "Icon-App-60x60@2x.png", - "scale" : "2x" - }, - { - "size" : "60x60", - "idiom" : "iphone", - "filename" : "Icon-App-60x60@3x.png", - "scale" : "3x" - }, - { - "size" : "20x20", - "idiom" : "ipad", - "filename" : "Icon-App-20x20@1x.png", - "scale" : "1x" - }, - { - "size" : "20x20", - "idiom" : "ipad", - "filename" : "Icon-App-20x20@2x.png", - "scale" : "2x" - }, - { - "size" : "29x29", - "idiom" : "ipad", - "filename" : "Icon-App-29x29@1x.png", - "scale" : "1x" - }, - { - "size" : "29x29", - "idiom" : "ipad", - "filename" : "Icon-App-29x29@2x.png", - "scale" : "2x" - }, - { - "size" : "40x40", - "idiom" : "ipad", - "filename" : "Icon-App-40x40@1x.png", - "scale" : "1x" - }, - { - "size" : "40x40", - "idiom" : "ipad", - "filename" : "Icon-App-40x40@2x.png", - "scale" : "2x" - }, - { - "size" : "76x76", - "idiom" : "ipad", - "filename" : "Icon-App-76x76@1x.png", - "scale" : "1x" - }, - { - "size" : "76x76", - "idiom" : "ipad", - "filename" : "Icon-App-76x76@2x.png", - "scale" : "2x" - }, - { - "size" : "83.5x83.5", - "idiom" : "ipad", - "filename" : "Icon-App-83.5x83.5@2x.png", - "scale" : "2x" - }, - { - "size" : "1024x1024", - "idiom" : "ios-marketing", - "filename" : "Icon-App-1024x1024@1x.png", - "scale" : "1x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} +{ + "images" : [ + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@3x.png", + "scale" : "3x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@3x.png", + "scale" : "3x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@3x.png", + "scale" : "3x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@3x.png", + "scale" : "3x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@1x.png", + "scale" : "1x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@1x.png", + "scale" : "1x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@1x.png", + "scale" : "1x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@2x.png", + "scale" : "2x" + }, + { + "size" : "83.5x83.5", + "idiom" : "ipad", + "filename" : "Icon-App-83.5x83.5@2x.png", + "scale" : "2x" + }, + { + "size" : "1024x1024", + "idiom" : "ios-marketing", + "filename" : "Icon-App-1024x1024@1x.png", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json index 0bedcf2..d08a4de 100644 --- a/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -1,23 +1,23 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "LaunchImage.png", - "scale" : "1x" - }, - { - "idiom" : "universal", - "filename" : "LaunchImage@2x.png", - "scale" : "2x" - }, - { - "idiom" : "universal", - "filename" : "LaunchImage@3x.png", - "scale" : "3x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md index 89c2725..65a94b5 100644 --- a/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -1,5 +1,5 @@ -# Launch Screen Assets - -You can customize the launch screen with your own desired assets by replacing the image files in this directory. - +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/ios/Runner/Base.lproj/LaunchScreen.storyboard b/ios/Runner/Base.lproj/LaunchScreen.storyboard index f2e259c..497371e 100644 --- a/ios/Runner/Base.lproj/LaunchScreen.storyboard +++ b/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -1,37 +1,37 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Base.lproj/Main.storyboard b/ios/Runner/Base.lproj/Main.storyboard index f3c2851..bbb83ca 100644 --- a/ios/Runner/Base.lproj/Main.storyboard +++ b/ios/Runner/Base.lproj/Main.storyboard @@ -1,26 +1,26 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index 8cc6a5c..3b4fdbb 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -1,58 +1,58 @@ - - - - - CFBundleDevelopmentRegion - $(DEVELOPMENT_LANGUAGE) - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - tsacdop_player - CFBundlePackageType - APPL - CFBundleShortVersionString - $(FLUTTER_BUILD_NAME) - CFBundleSignature - ???? - CFBundleVersion - $(FLUTTER_BUILD_NUMBER) - LSRequiresIPhoneOS - - NSAppTransportSecurity - - NSAllowsArbitraryLoads - - NSAllowsArbitraryLoadsForMedia - - - UIBackgroundModes - - audio - fetch - remote-notification - - UILaunchStoryboardName - LaunchScreen - UIMainStoryboardFile - Main - UISupportedInterfaceOrientations - - UIInterfaceOrientationPortrait - UIInterfaceOrientationLandscapeLeft - UIInterfaceOrientationLandscapeRight - - UISupportedInterfaceOrientations~ipad - - UIInterfaceOrientationPortrait - UIInterfaceOrientationPortraitUpsideDown - UIInterfaceOrientationLandscapeLeft - UIInterfaceOrientationLandscapeRight - - UIViewControllerBasedStatusBarAppearance - - + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + tsacdop_player + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + NSAppTransportSecurity + + NSAllowsArbitraryLoads + + NSAllowsArbitraryLoadsForMedia + + + UIBackgroundModes + + audio + fetch + remote-notification + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UIViewControllerBasedStatusBarAppearance + + \ No newline at end of file diff --git a/ios/Runner/Runner-Bridging-Header.h b/ios/Runner/Runner-Bridging-Header.h index 308a2a5..fae207f 100644 --- a/ios/Runner/Runner-Bridging-Header.h +++ b/ios/Runner/Runner-Bridging-Header.h @@ -1 +1 @@ -#import "GeneratedPluginRegistrant.h" +#import "GeneratedPluginRegistrant.h" diff --git a/lib/class/settingstate.dart b/lib/class/settingstate.dart index 7e22d4c..c482214 100644 --- a/lib/class/settingstate.dart +++ b/lib/class/settingstate.dart @@ -1 +1 @@ -export '../state/setting_state.dart'; +export '../state/setting_state.dart'; diff --git a/lib/episodes/episode_detail.dart b/lib/episodes/episode_detail.dart index 4891b85..4c661fe 100644 --- a/lib/episodes/episode_detail.dart +++ b/lib/episodes/episode_detail.dart @@ -1,724 +1,724 @@ -import 'dart:developer' as developer; - -import 'package:flutter/material.dart'; -import 'package:flutter/rendering.dart'; -import 'package:flutter/services.dart'; -import 'package:flutter_html/flutter_html.dart'; -import 'package:fluttertoast/fluttertoast.dart'; -import 'package:intl/intl.dart'; -import 'package:linkify/linkify.dart'; -import 'package:provider/provider.dart'; -import 'package:tuple/tuple.dart'; - -import '../home/audioplayer.dart'; -import '../local_storage/sqflite_localpodcast.dart'; -import '../state/audio_state.dart'; -import '../state/setting_state.dart'; -import '../type/episodebrief.dart'; -import '../type/play_histroy.dart'; -import '../util/audiopanel.dart'; -import '../util/custom_widget.dart'; -import '../util/extension_helper.dart'; -import 'episode_download.dart'; - -class EpisodeDetail extends StatefulWidget { - final EpisodeBrief episodeItem; - final String heroTag; - final bool hide; - EpisodeDetail( - {this.episodeItem, this.heroTag = '', this.hide = false, Key key}) - : super(key: key); - - @override - _EpisodeDetailState createState() => _EpisodeDetailState(); -} - -class _EpisodeDetailState extends State { - final textstyle = TextStyle(fontSize: 15.0, color: Colors.black); - final GlobalKey _playerKey = GlobalKey(); - double downloadProgress; - - /// Show page title. - bool _showTitle; - bool _showMenu; - String path; - - Future _getPosition(EpisodeBrief episode) async { - var dbHelper = DBHelper(); - return await dbHelper.getPosition(episode); - } - - ScrollController _controller; - _scrollListener() { - if (_controller.position.userScrollDirection == ScrollDirection.reverse) { - if (_showMenu && mounted) { - setState(() { - _showMenu = false; - }); - } - } - if (_controller.position.userScrollDirection == ScrollDirection.forward) { - if (!_showMenu && mounted) { - setState(() { - _showMenu = true; - }); - } - } - if (_controller.offset > context.textTheme.headline5.fontSize) { - if (!_showTitle) setState(() => _showTitle = true); - } else if (_showTitle) setState(() => _showTitle = false); - } - - @override - void initState() { - super.initState(); - _showMenu = true; - _showTitle = false; - _controller = ScrollController(); - _controller.addListener(_scrollListener); - } - - @override - void dispose() { - _controller.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - final s = context.s; - final audio = context.watch(); - return AnnotatedRegion( - value: SystemUiOverlayStyle( - statusBarIconBrightness: Theme.of(context).accentColorBrightness, - systemNavigationBarColor: Theme.of(context).primaryColor, - systemNavigationBarIconBrightness: - Theme.of(context).accentColorBrightness, - ), - child: WillPopScope( - onWillPop: () async { - if (_playerKey.currentState != null && - _playerKey.currentState.initSize > 100) { - _playerKey.currentState.backToMini(); - return false; - } else { - return true; - } - }, - child: Scaffold( - backgroundColor: Theme.of(context).primaryColor, - appBar: AppBar( - title: _showTitle - ? Text( - widget.episodeItem.title, - maxLines: 1, - overflow: TextOverflow.ellipsis, - ) - : Center(), - leading: CustomBackButton(), - elevation: _showTitle ? 1 : 0, - //actions: [ - // PopupMenuButton( - // shape: RoundedRectangleBorder( - // borderRadius: BorderRadius.all(Radius.circular(10))), - // elevation: 1, - // tooltip: s.menu, - // itemBuilder: (context) => [ - // PopupMenuItem( - // value: 0, - // child: Container( - // padding: EdgeInsets.only(left: 10), - // child: Row( - // crossAxisAlignment: CrossAxisAlignment.center, - // children: [ - // SizedBox( - // width: 25, - // height: 25, - // child: CustomPaint( - // painter: ListenedAllPainter( - // context.textTheme.bodyText1.color, - // stroke: 2)), - // ), - // Padding( - // padding: EdgeInsets.symmetric(horizontal: 5.0), - // ), - // Text( - // s.markListened, - // ), - // ], - // ), - // ), - // ), - // ], - // onSelected: (value) async { - // switch (value) { - // case 0: - // await _markListened(widget.episodeItem); - // if (mounted) setState(() {}); - // Fluttertoast.showToast( - // msg: s.markListened, - // gravity: ToastGravity.BOTTOM, - // ); - // break; - // default: - // break; - // } - // }, - // ), - //], - ), - body: Stack( - children: [ - Container( - color: context.primaryColor, - child: SingleChildScrollView( - scrollDirection: Axis.vertical, - controller: _controller, - child: Column( - children: [ - Padding( - padding: EdgeInsets.symmetric(horizontal: 20.0), - child: Align( - alignment: Alignment.centerLeft, - child: Text( - widget.episodeItem.title, - textAlign: TextAlign.left, - style: Theme.of(context).textTheme.headline5, - ), - ), - ), - Container( - alignment: Alignment.centerLeft, - padding: EdgeInsets.only( - left: 20.0, right: 20, top: 10, bottom: 10), - child: Row( - children: [ - Text( - s.published(DateFormat.yMMMd().format( - DateTime.fromMillisecondsSinceEpoch( - widget.episodeItem.pubDate))), - style: TextStyle( - color: Theme.of(context).accentColor)), - SizedBox(width: 10), - if (widget.episodeItem.explicit == 1) - Text('E', - style: TextStyle( - fontWeight: FontWeight.bold, - color: Colors.red)) - ], - ), - ), - Padding( - padding: EdgeInsets.only( - left: 20.0, right: 20, top: 5, bottom: 5), - child: Row( - children: [ - if (widget.episodeItem.duration != 0) - Container( - decoration: BoxDecoration( - color: Colors.cyan[300], - borderRadius: BorderRadius.all( - Radius.circular(16.0))), - height: 28.0, - margin: EdgeInsets.only(right: 10.0), - padding: - EdgeInsets.symmetric(horizontal: 10.0), - alignment: Alignment.center, - child: Text( - s.minsCount( - widget.episodeItem.duration ~/ 60), - style: context.textTheme.button)), - if (widget.episodeItem.enclosureLength != null && - widget.episodeItem.enclosureLength != 0) - Container( - decoration: BoxDecoration( - color: Colors.lightBlue[300], - borderRadius: BorderRadius.all( - Radius.circular(16.0))), - height: 28.0, - margin: EdgeInsets.only(right: 10.0), - padding: EdgeInsets.symmetric(horizontal: 10.0), - alignment: Alignment.center, - child: Text( - '${(widget.episodeItem.enclosureLength) ~/ 1000000}MB', - style: context.textTheme.button), - ), - FutureBuilder( - future: _getPosition(widget.episodeItem), - builder: (context, snapshot) { - if (snapshot.hasError) { - developer.log(snapshot.error); - } - if (snapshot.hasData && - snapshot.data.seekValue < 0.9 && - snapshot.data.seconds > 10) { - return ButtonTheme( - height: 28, - padding: - EdgeInsets.symmetric(horizontal: 0), - child: OutlineButton( - shape: RoundedRectangleBorder( - borderRadius: - BorderRadius.circular(100.0), - side: BorderSide( - color: context.accentColor)), - highlightedBorderColor: - Colors.green[700], - onPressed: () => audio.episodeLoad( - widget.episodeItem, - startPosition: - (snapshot.data.seconds * 1000) - .toInt()), - child: Row( - children: [ - SizedBox( - width: 20, - height: 20, - child: CustomPaint( - painter: ListenedPainter( - context.textColor, - stroke: 2.0), - ), - ), - SizedBox(width: 5), - Text(snapshot.data.seconds.toTime), - ], - ), - ), - ); - } else { - return Center(); - } - }), - ], - ), - ), - _ShowNote(episode: widget.episodeItem), - Selector>( - selector: (_, audio) => - Tuple2(audio.playerRunning, audio.playerHeight), - builder: (_, data, __) { - var height = kMinPlayerHeight[data.item2.index]; - return SizedBox( - height: data.item1 ? height : 0, - ); - }), - ], - ), - ), - ), - Selector>( - selector: (_, audio) => - Tuple2(audio.playerRunning, audio.playerHeight), - builder: (_, data, __) { - var height = kMinPlayerHeight[data.item2.index]; - return Container( - alignment: Alignment.bottomCenter, - padding: EdgeInsets.only(bottom: data.item1 ? height : 0), - child: AnimatedContainer( - duration: Duration(milliseconds: 400), - height: _showMenu ? 50 : 0, - child: SingleChildScrollView( - scrollDirection: Axis.vertical, - child: _MenuBar( - episodeItem: widget.episodeItem, - heroTag: widget.heroTag, - hide: widget.hide), - ), - ), - ); - }), - Selector( - selector: (_, audio) => audio.episode, - builder: (_, data, __) => Container( - child: PlayerWidget( - playerKey: _playerKey, - isPlayingPage: data == widget.episodeItem))), - ], - ), - ), - ), - ); - } -} - -class _MenuBar extends StatefulWidget { - final EpisodeBrief episodeItem; - final String heroTag; - final bool hide; - _MenuBar({this.episodeItem, this.heroTag, this.hide, Key key}) - : super(key: key); - @override - __MenuBarState createState() => __MenuBarState(); -} - -class __MenuBarState extends State<_MenuBar> { - Future _isListened(EpisodeBrief episode) async { - var dbHelper = DBHelper(); - return await dbHelper.isListened(episode.enclosureUrl); - } - - Future _saveLiked(String url) async { - var dbHelper = DBHelper(); - await dbHelper.setLiked(url); - if (mounted) setState(() {}); - } - - Future _setUnliked(String url) async { - var dbHelper = DBHelper(); - await dbHelper.setUniked(url); - if (mounted) setState(() {}); - } - - Future _markListened(EpisodeBrief episode) async { - var dbHelper = DBHelper(); - final history = PlayHistory(episode.title, episode.enclosureUrl, 0, 1); - await dbHelper.saveHistory(history); - if (mounted) setState(() {}); - } - - Future _markNotListened(String url) async { - var dbHelper = DBHelper(); - await dbHelper.markNotListened(url); - if (mounted) setState(() {}); - } - - Future _isLiked(EpisodeBrief episode) async { - var dbHelper = DBHelper(); - return await dbHelper.isLiked(episode.enclosureUrl); - } - - Widget _buttonOnMenu({Widget child, VoidCallback onTap}) => Material( - color: Colors.transparent, - child: InkWell( - onTap: onTap, - child: SizedBox( - height: 50, - child: Padding( - padding: EdgeInsets.symmetric(horizontal: 15.0), child: child), - ), - ), - ); - - OverlayEntry _createOverlayEntry() { - RenderBox renderBox = context.findRenderObject(); - var offset = renderBox.localToGlobal(Offset.zero); - return OverlayEntry( - builder: (constext) => Positioned( - left: offset.dx + 50, - top: offset.dy - 60, - child: Container( - width: 70, - height: 100, - //color: Colors.grey[200], - child: HeartOpen(width: 50, height: 80)), - ), - ); - } - - @override - Widget build(BuildContext context) { - var audio = Provider.of(context, listen: false); - final s = context.s; - return Container( - height: 50.0, - decoration: BoxDecoration( - color: context.scaffoldBackgroundColor, - ), - child: Row( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Expanded( - child: SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: Row( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Hero( - tag: widget.episodeItem.enclosureUrl + widget.heroTag, - child: Container( - padding: EdgeInsets.symmetric(horizontal: 10.0), - child: Container( - height: 30.0, - width: 30.0, - color: context.scaffoldBackgroundColor, - child: widget.hide - ? Center() - : CircleAvatar( - radius: 15, - backgroundImage: - widget.episodeItem.avatarImage), - ), - ), - ), - FutureBuilder( - future: _isLiked(widget.episodeItem), - initialData: false, - builder: (context, snapshot) { - return (!snapshot.data) - ? _buttonOnMenu( - child: Icon( - Icons.favorite_border, - color: Colors.grey[700], - ), - onTap: () async { - await _saveLiked( - widget.episodeItem.enclosureUrl); - OverlayEntry _overlayEntry; - _overlayEntry = _createOverlayEntry(); - Overlay.of(context).insert(_overlayEntry); - await Future.delayed(Duration(seconds: 2)); - _overlayEntry?.remove(); - }) - : _buttonOnMenu( - child: Icon( - Icons.favorite, - color: Colors.red, - ), - onTap: () => - _setUnliked(widget.episodeItem.enclosureUrl)); - }, - ), - DownloadButton(episode: widget.episodeItem), - Selector, bool>>( - selector: (_, audio) => - Tuple2(audio.queue.playlist, audio.queueUpdate), - builder: (_, data, __) { - final inPlaylist = - data.item1.contains(widget.episodeItem); - return inPlaylist - ? _buttonOnMenu( - child: Icon(Icons.playlist_add_check, - color: context.accentColor), - onTap: () { - audio.delFromPlaylist(widget.episodeItem); - Fluttertoast.showToast( - msg: s.toastRemovePlaylist, - gravity: ToastGravity.BOTTOM, - ); - }) - : _buttonOnMenu( - child: Icon(Icons.playlist_add, - color: Colors.grey[700]), - onTap: () { - audio.addToPlaylist(widget.episodeItem); - Fluttertoast.showToast( - msg: s.toastAddPlaylist, - gravity: ToastGravity.BOTTOM, - ); - }); - }, - ), - FutureBuilder( - future: _isListened(widget.episodeItem), - initialData: 0, - builder: (context, snapshot) { - return snapshot.data == 0 - ? _buttonOnMenu( - child: Padding( - padding: EdgeInsets.symmetric(vertical: 12), - child: CustomPaint( - size: Size(25, 20), - painter: ListenedAllPainter(Colors.grey[700], - stroke: 2.0), - ), - ), - onTap: () { - _markListened(widget.episodeItem); - Fluttertoast.showToast( - msg: s.markListened, - gravity: ToastGravity.BOTTOM, - ); - }) - : _buttonOnMenu( - child: Padding( - padding: EdgeInsets.symmetric(vertical: 12), - child: CustomPaint( - size: Size(25, 20), - painter: ListenedAllPainter( - context.accentColor, - stroke: 2.0), - ), - ), - onTap: () { - _markNotListened( - widget.episodeItem.enclosureUrl); - Fluttertoast.showToast( - msg: s.markNotListened, - gravity: ToastGravity.BOTTOM, - ); - }); - }, - ), - ], - ), - ), - ), - Selector>( - selector: (_, audio) => Tuple2(audio.episode, audio.playerRunning), - builder: (_, data, __) { - return (widget.episodeItem == data.item1 && data.item2) - ? Container( - padding: EdgeInsets.only(right: 30), - child: SizedBox( - width: 20, - height: 15, - child: WaveLoader(color: context.accentColor))) - : Material( - color: Colors.transparent, - child: InkWell( - onTap: () { - audio.episodeLoad(widget.episodeItem); - }, - child: Container( - alignment: Alignment.center, - height: 50.0, - padding: EdgeInsets.symmetric(horizontal: 20.0), - child: Row( - children: [ - Text(s.play, - style: TextStyle( - color: Theme.of(context).accentColor, - fontSize: 15, - fontWeight: FontWeight.bold, - )), - Icon( - Icons.play_arrow, - color: Theme.of(context).accentColor, - ), - ], - ), - ), - ), - ); - }, - ), - ], - ), - ); - } -} - -class _ShowNote extends StatelessWidget { - final EpisodeBrief episode; - const _ShowNote({this.episode, Key key}) : super(key: key); - - int _getTimeStamp(String url) { - final time = url.substring(3).trim(); - final data = time.split(':'); - var seconds; - if (data.length == 3) { - seconds = int.tryParse(data[0]) * 3600 + - int.tryParse(data[1]) * 60 + - int.tryParse(data[2]); - } else if (data.length == 2) { - seconds = int.tryParse(data[0]) * 60 + int.tryParse(data[1]); - } - return seconds; - } - - Future _getSDescription(String url) async { - var description; - var dbHelper = DBHelper(); - description = (await dbHelper.getDescription(url)) - .replaceAll(RegExp(r'\s?

(
)?

\s?'), '') - .replaceAll('\r', '') - .trim(); - if (!description.contains('<')) { - final linkList = linkify(description, - options: LinkifyOptions(humanize: false), - linkifiers: [UrlLinkifier(), EmailLinkifier()]); - for (var element in linkList) { - if (element is UrlElement) { - description = description.replaceAll(element.url, - '${element.text}'); - } - if (element is EmailElement) { - final address = element.emailAddress; - description = description.replaceAll(address, - '$address'); - } - } - await dbHelper.saveEpisodeDes(url, description: description); - } - return description; - } - - @override - Widget build(BuildContext context) { - var audio = context.watch(); - final s = context.s; - return FutureBuilder( - future: _getSDescription(episode.enclosureUrl), - builder: (context, snapshot) { - if (snapshot.hasData) { - var description = snapshot.data; - return description.length > 0 - ? Selector( - selector: (_, audio) => audio.episode, - builder: (_, playEpisode, __) { - if (playEpisode == episode && - !description.contains('#t=')) { - final linkList = linkify(description, - options: LinkifyOptions(humanize: false), - linkifiers: [TimeStampLinkifier()]); - for (var element in linkList) { - if (element is TimeStampElement) { - final time = element.timeStamp; - description = description.replaceFirst(time, - '$time'); - } - } - } - return Selector( - selector: (_, settings) => settings.showNoteFontStyle, - builder: (_, data, __) => Html( - padding: - EdgeInsets.only(left: 20.0, right: 20, bottom: 50), - defaultTextStyle: data, - data: description, - linkStyle: TextStyle( - color: context.accentColor, - textBaseline: TextBaseline.ideographic), - onLinkTap: (url) { - if (url.substring(0, 3) == '#t=') { - final seconds = _getTimeStamp(url); - if (playEpisode == episode) { - audio.seekTo(seconds * 1000); - } - } else { - url.launchUrl; - } - }, - useRichText: true, - ), - ); - }) - : Container( - height: context.width, - alignment: Alignment.center, - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Image( - image: AssetImage('assets/shownote.png'), - height: 100.0, - ), - Padding(padding: EdgeInsets.all(5.0)), - Text(s.noShownote, - textAlign: TextAlign.center, - style: TextStyle( - color: context.textColor.withOpacity(0.5))), - ], - ), - ); - } else { - return Center(); - } - }, - ); - } -} +import 'dart:developer' as developer; + +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_html/flutter_html.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:intl/intl.dart'; +import 'package:linkify/linkify.dart'; +import 'package:provider/provider.dart'; +import 'package:tuple/tuple.dart'; + +import '../home/audioplayer.dart'; +import '../local_storage/sqflite_localpodcast.dart'; +import '../state/audio_state.dart'; +import '../state/setting_state.dart'; +import '../type/episodebrief.dart'; +import '../type/play_histroy.dart'; +import '../util/audiopanel.dart'; +import '../util/custom_widget.dart'; +import '../util/extension_helper.dart'; +import 'episode_download.dart'; + +class EpisodeDetail extends StatefulWidget { + final EpisodeBrief episodeItem; + final String heroTag; + final bool hide; + EpisodeDetail( + {this.episodeItem, this.heroTag = '', this.hide = false, Key key}) + : super(key: key); + + @override + _EpisodeDetailState createState() => _EpisodeDetailState(); +} + +class _EpisodeDetailState extends State { + final textstyle = TextStyle(fontSize: 15.0, color: Colors.black); + final GlobalKey _playerKey = GlobalKey(); + double downloadProgress; + + /// Show page title. + bool _showTitle; + bool _showMenu; + String path; + + Future _getPosition(EpisodeBrief episode) async { + var dbHelper = DBHelper(); + return await dbHelper.getPosition(episode); + } + + ScrollController _controller; + _scrollListener() { + if (_controller.position.userScrollDirection == ScrollDirection.reverse) { + if (_showMenu && mounted) { + setState(() { + _showMenu = false; + }); + } + } + if (_controller.position.userScrollDirection == ScrollDirection.forward) { + if (!_showMenu && mounted) { + setState(() { + _showMenu = true; + }); + } + } + if (_controller.offset > context.textTheme.headline5.fontSize) { + if (!_showTitle) setState(() => _showTitle = true); + } else if (_showTitle) setState(() => _showTitle = false); + } + + @override + void initState() { + super.initState(); + _showMenu = true; + _showTitle = false; + _controller = ScrollController(); + _controller.addListener(_scrollListener); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final s = context.s; + final audio = context.watch(); + return AnnotatedRegion( + value: SystemUiOverlayStyle( + statusBarIconBrightness: Theme.of(context).accentColorBrightness, + systemNavigationBarColor: Theme.of(context).primaryColor, + systemNavigationBarIconBrightness: + Theme.of(context).accentColorBrightness, + ), + child: WillPopScope( + onWillPop: () async { + if (_playerKey.currentState != null && + _playerKey.currentState.initSize > 100) { + _playerKey.currentState.backToMini(); + return false; + } else { + return true; + } + }, + child: Scaffold( + backgroundColor: Theme.of(context).primaryColor, + appBar: AppBar( + title: _showTitle + ? Text( + widget.episodeItem.title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ) + : Center(), + leading: CustomBackButton(), + elevation: _showTitle ? 1 : 0, + //actions: [ + // PopupMenuButton( + // shape: RoundedRectangleBorder( + // borderRadius: BorderRadius.all(Radius.circular(10))), + // elevation: 1, + // tooltip: s.menu, + // itemBuilder: (context) => [ + // PopupMenuItem( + // value: 0, + // child: Container( + // padding: EdgeInsets.only(left: 10), + // child: Row( + // crossAxisAlignment: CrossAxisAlignment.center, + // children: [ + // SizedBox( + // width: 25, + // height: 25, + // child: CustomPaint( + // painter: ListenedAllPainter( + // context.textTheme.bodyText1.color, + // stroke: 2)), + // ), + // Padding( + // padding: EdgeInsets.symmetric(horizontal: 5.0), + // ), + // Text( + // s.markListened, + // ), + // ], + // ), + // ), + // ), + // ], + // onSelected: (value) async { + // switch (value) { + // case 0: + // await _markListened(widget.episodeItem); + // if (mounted) setState(() {}); + // Fluttertoast.showToast( + // msg: s.markListened, + // gravity: ToastGravity.BOTTOM, + // ); + // break; + // default: + // break; + // } + // }, + // ), + //], + ), + body: Stack( + children: [ + Container( + color: context.primaryColor, + child: SingleChildScrollView( + scrollDirection: Axis.vertical, + controller: _controller, + child: Column( + children: [ + Padding( + padding: EdgeInsets.symmetric(horizontal: 20.0), + child: Align( + alignment: Alignment.centerLeft, + child: Text( + widget.episodeItem.title, + textAlign: TextAlign.left, + style: Theme.of(context).textTheme.headline5, + ), + ), + ), + Container( + alignment: Alignment.centerLeft, + padding: EdgeInsets.only( + left: 20.0, right: 20, top: 10, bottom: 10), + child: Row( + children: [ + Text( + s.published(DateFormat.yMMMd().format( + DateTime.fromMillisecondsSinceEpoch( + widget.episodeItem.pubDate))), + style: TextStyle( + color: Theme.of(context).accentColor)), + SizedBox(width: 10), + if (widget.episodeItem.explicit == 1) + Text('E', + style: TextStyle( + fontWeight: FontWeight.bold, + color: Colors.red)) + ], + ), + ), + Padding( + padding: EdgeInsets.only( + left: 20.0, right: 20, top: 5, bottom: 5), + child: Row( + children: [ + if (widget.episodeItem.duration != 0) + Container( + decoration: BoxDecoration( + color: Colors.cyan[300], + borderRadius: BorderRadius.all( + Radius.circular(16.0))), + height: 28.0, + margin: EdgeInsets.only(right: 10.0), + padding: + EdgeInsets.symmetric(horizontal: 10.0), + alignment: Alignment.center, + child: Text( + s.minsCount( + widget.episodeItem.duration ~/ 60), + style: context.textTheme.button)), + if (widget.episodeItem.enclosureLength != null && + widget.episodeItem.enclosureLength != 0) + Container( + decoration: BoxDecoration( + color: Colors.lightBlue[300], + borderRadius: BorderRadius.all( + Radius.circular(16.0))), + height: 28.0, + margin: EdgeInsets.only(right: 10.0), + padding: EdgeInsets.symmetric(horizontal: 10.0), + alignment: Alignment.center, + child: Text( + '${(widget.episodeItem.enclosureLength) ~/ 1000000}MB', + style: context.textTheme.button), + ), + FutureBuilder( + future: _getPosition(widget.episodeItem), + builder: (context, snapshot) { + if (snapshot.hasError) { + developer.log(snapshot.error); + } + if (snapshot.hasData && + snapshot.data.seekValue < 0.9 && + snapshot.data.seconds > 10) { + return ButtonTheme( + height: 28, + padding: + EdgeInsets.symmetric(horizontal: 0), + child: OutlineButton( + shape: RoundedRectangleBorder( + borderRadius: + BorderRadius.circular(100.0), + side: BorderSide( + color: context.accentColor)), + highlightedBorderColor: + Colors.green[700], + onPressed: () => audio.episodeLoad( + widget.episodeItem, + startPosition: + (snapshot.data.seconds * 1000) + .toInt()), + child: Row( + children: [ + SizedBox( + width: 20, + height: 20, + child: CustomPaint( + painter: ListenedPainter( + context.textColor, + stroke: 2.0), + ), + ), + SizedBox(width: 5), + Text(snapshot.data.seconds.toTime), + ], + ), + ), + ); + } else { + return Center(); + } + }), + ], + ), + ), + _ShowNote(episode: widget.episodeItem), + Selector>( + selector: (_, audio) => + Tuple2(audio.playerRunning, audio.playerHeight), + builder: (_, data, __) { + var height = kMinPlayerHeight[data.item2.index]; + return SizedBox( + height: data.item1 ? height : 0, + ); + }), + ], + ), + ), + ), + Selector>( + selector: (_, audio) => + Tuple2(audio.playerRunning, audio.playerHeight), + builder: (_, data, __) { + var height = kMinPlayerHeight[data.item2.index]; + return Container( + alignment: Alignment.bottomCenter, + padding: EdgeInsets.only(bottom: data.item1 ? height : 0), + child: AnimatedContainer( + duration: Duration(milliseconds: 400), + height: _showMenu ? 50 : 0, + child: SingleChildScrollView( + scrollDirection: Axis.vertical, + child: _MenuBar( + episodeItem: widget.episodeItem, + heroTag: widget.heroTag, + hide: widget.hide), + ), + ), + ); + }), + Selector( + selector: (_, audio) => audio.episode, + builder: (_, data, __) => Container( + child: PlayerWidget( + playerKey: _playerKey, + isPlayingPage: data == widget.episodeItem))), + ], + ), + ), + ), + ); + } +} + +class _MenuBar extends StatefulWidget { + final EpisodeBrief episodeItem; + final String heroTag; + final bool hide; + _MenuBar({this.episodeItem, this.heroTag, this.hide, Key key}) + : super(key: key); + @override + __MenuBarState createState() => __MenuBarState(); +} + +class __MenuBarState extends State<_MenuBar> { + Future _isListened(EpisodeBrief episode) async { + var dbHelper = DBHelper(); + return await dbHelper.isListened(episode.enclosureUrl); + } + + Future _saveLiked(String url) async { + var dbHelper = DBHelper(); + await dbHelper.setLiked(url); + if (mounted) setState(() {}); + } + + Future _setUnliked(String url) async { + var dbHelper = DBHelper(); + await dbHelper.setUniked(url); + if (mounted) setState(() {}); + } + + Future _markListened(EpisodeBrief episode) async { + var dbHelper = DBHelper(); + final history = PlayHistory(episode.title, episode.enclosureUrl, 0, 1); + await dbHelper.saveHistory(history); + if (mounted) setState(() {}); + } + + Future _markNotListened(String url) async { + var dbHelper = DBHelper(); + await dbHelper.markNotListened(url); + if (mounted) setState(() {}); + } + + Future _isLiked(EpisodeBrief episode) async { + var dbHelper = DBHelper(); + return await dbHelper.isLiked(episode.enclosureUrl); + } + + Widget _buttonOnMenu({Widget child, VoidCallback onTap}) => Material( + color: Colors.transparent, + child: InkWell( + onTap: onTap, + child: SizedBox( + height: 50, + child: Padding( + padding: EdgeInsets.symmetric(horizontal: 15.0), child: child), + ), + ), + ); + + OverlayEntry _createOverlayEntry() { + RenderBox renderBox = context.findRenderObject(); + var offset = renderBox.localToGlobal(Offset.zero); + return OverlayEntry( + builder: (constext) => Positioned( + left: offset.dx + 50, + top: offset.dy - 60, + child: Container( + width: 70, + height: 100, + //color: Colors.grey[200], + child: HeartOpen(width: 50, height: 80)), + ), + ); + } + + @override + Widget build(BuildContext context) { + var audio = Provider.of(context, listen: false); + final s = context.s; + return Container( + height: 50.0, + decoration: BoxDecoration( + color: context.scaffoldBackgroundColor, + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Expanded( + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Hero( + tag: widget.episodeItem.enclosureUrl + widget.heroTag, + child: Container( + padding: EdgeInsets.symmetric(horizontal: 10.0), + child: Container( + height: 30.0, + width: 30.0, + color: context.scaffoldBackgroundColor, + child: widget.hide + ? Center() + : CircleAvatar( + radius: 15, + backgroundImage: + widget.episodeItem.avatarImage), + ), + ), + ), + FutureBuilder( + future: _isLiked(widget.episodeItem), + initialData: false, + builder: (context, snapshot) { + return (!snapshot.data) + ? _buttonOnMenu( + child: Icon( + Icons.favorite_border, + color: Colors.grey[700], + ), + onTap: () async { + await _saveLiked( + widget.episodeItem.enclosureUrl); + OverlayEntry _overlayEntry; + _overlayEntry = _createOverlayEntry(); + Overlay.of(context).insert(_overlayEntry); + await Future.delayed(Duration(seconds: 2)); + _overlayEntry?.remove(); + }) + : _buttonOnMenu( + child: Icon( + Icons.favorite, + color: Colors.red, + ), + onTap: () => + _setUnliked(widget.episodeItem.enclosureUrl)); + }, + ), + DownloadButton(episode: widget.episodeItem), + Selector, bool>>( + selector: (_, audio) => + Tuple2(audio.queue.playlist, audio.queueUpdate), + builder: (_, data, __) { + final inPlaylist = + data.item1.contains(widget.episodeItem); + return inPlaylist + ? _buttonOnMenu( + child: Icon(Icons.playlist_add_check, + color: context.accentColor), + onTap: () { + audio.delFromPlaylist(widget.episodeItem); + Fluttertoast.showToast( + msg: s.toastRemovePlaylist, + gravity: ToastGravity.BOTTOM, + ); + }) + : _buttonOnMenu( + child: Icon(Icons.playlist_add, + color: Colors.grey[700]), + onTap: () { + audio.addToPlaylist(widget.episodeItem); + Fluttertoast.showToast( + msg: s.toastAddPlaylist, + gravity: ToastGravity.BOTTOM, + ); + }); + }, + ), + FutureBuilder( + future: _isListened(widget.episodeItem), + initialData: 0, + builder: (context, snapshot) { + return snapshot.data == 0 + ? _buttonOnMenu( + child: Padding( + padding: EdgeInsets.symmetric(vertical: 12), + child: CustomPaint( + size: Size(25, 20), + painter: ListenedAllPainter(Colors.grey[700], + stroke: 2.0), + ), + ), + onTap: () { + _markListened(widget.episodeItem); + Fluttertoast.showToast( + msg: s.markListened, + gravity: ToastGravity.BOTTOM, + ); + }) + : _buttonOnMenu( + child: Padding( + padding: EdgeInsets.symmetric(vertical: 12), + child: CustomPaint( + size: Size(25, 20), + painter: ListenedAllPainter( + context.accentColor, + stroke: 2.0), + ), + ), + onTap: () { + _markNotListened( + widget.episodeItem.enclosureUrl); + Fluttertoast.showToast( + msg: s.markNotListened, + gravity: ToastGravity.BOTTOM, + ); + }); + }, + ), + ], + ), + ), + ), + Selector>( + selector: (_, audio) => Tuple2(audio.episode, audio.playerRunning), + builder: (_, data, __) { + return (widget.episodeItem == data.item1 && data.item2) + ? Container( + padding: EdgeInsets.only(right: 30), + child: SizedBox( + width: 20, + height: 15, + child: WaveLoader(color: context.accentColor))) + : Material( + color: Colors.transparent, + child: InkWell( + onTap: () { + audio.episodeLoad(widget.episodeItem); + }, + child: Container( + alignment: Alignment.center, + height: 50.0, + padding: EdgeInsets.symmetric(horizontal: 20.0), + child: Row( + children: [ + Text(s.play, + style: TextStyle( + color: Theme.of(context).accentColor, + fontSize: 15, + fontWeight: FontWeight.bold, + )), + Icon( + Icons.play_arrow, + color: Theme.of(context).accentColor, + ), + ], + ), + ), + ), + ); + }, + ), + ], + ), + ); + } +} + +class _ShowNote extends StatelessWidget { + final EpisodeBrief episode; + const _ShowNote({this.episode, Key key}) : super(key: key); + + int _getTimeStamp(String url) { + final time = url.substring(3).trim(); + final data = time.split(':'); + var seconds; + if (data.length == 3) { + seconds = int.tryParse(data[0]) * 3600 + + int.tryParse(data[1]) * 60 + + int.tryParse(data[2]); + } else if (data.length == 2) { + seconds = int.tryParse(data[0]) * 60 + int.tryParse(data[1]); + } + return seconds; + } + + Future _getSDescription(String url) async { + var description; + var dbHelper = DBHelper(); + description = (await dbHelper.getDescription(url)) + .replaceAll(RegExp(r'\s?

(
)?

\s?'), '') + .replaceAll('\r', '') + .trim(); + if (!description.contains('<')) { + final linkList = linkify(description, + options: LinkifyOptions(humanize: false), + linkifiers: [UrlLinkifier(), EmailLinkifier()]); + for (var element in linkList) { + if (element is UrlElement) { + description = description.replaceAll(element.url, + '${element.text}'); + } + if (element is EmailElement) { + final address = element.emailAddress; + description = description.replaceAll(address, + '$address'); + } + } + await dbHelper.saveEpisodeDes(url, description: description); + } + return description; + } + + @override + Widget build(BuildContext context) { + var audio = context.watch(); + final s = context.s; + return FutureBuilder( + future: _getSDescription(episode.enclosureUrl), + builder: (context, snapshot) { + if (snapshot.hasData) { + var description = snapshot.data; + return description.length > 0 + ? Selector( + selector: (_, audio) => audio.episode, + builder: (_, playEpisode, __) { + if (playEpisode == episode && + !description.contains('#t=')) { + final linkList = linkify(description, + options: LinkifyOptions(humanize: false), + linkifiers: [TimeStampLinkifier()]); + for (var element in linkList) { + if (element is TimeStampElement) { + final time = element.timeStamp; + description = description.replaceFirst(time, + '$time'); + } + } + } + return Selector( + selector: (_, settings) => settings.showNoteFontStyle, + builder: (_, data, __) => Html( + padding: + EdgeInsets.only(left: 20.0, right: 20, bottom: 50), + defaultTextStyle: data, + data: description, + linkStyle: TextStyle( + color: context.accentColor, + textBaseline: TextBaseline.ideographic), + onLinkTap: (url) { + if (url.substring(0, 3) == '#t=') { + final seconds = _getTimeStamp(url); + if (playEpisode == episode) { + audio.seekTo(seconds * 1000); + } + } else { + url.launchUrl; + } + }, + useRichText: true, + ), + ); + }) + : Container( + height: context.width, + alignment: Alignment.center, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Image( + image: AssetImage('assets/shownote.png'), + height: 100.0, + ), + Padding(padding: EdgeInsets.all(5.0)), + Text(s.noShownote, + textAlign: TextAlign.center, + style: TextStyle( + color: context.textColor.withOpacity(0.5))), + ], + ), + ); + } else { + return Center(); + } + }, + ); + } +} diff --git a/lib/episodes/episode_download.dart b/lib/episodes/episode_download.dart index 5675a07..2ce371b 100644 --- a/lib/episodes/episode_download.dart +++ b/lib/episodes/episode_download.dart @@ -1,266 +1,266 @@ -import 'dart:async'; -import 'dart:math' as math; -import 'dart:ui'; - -import 'package:connectivity/connectivity.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_downloader/flutter_downloader.dart'; -import 'package:fluttertoast/fluttertoast.dart'; -import 'package:permission_handler/permission_handler.dart'; -import 'package:provider/provider.dart'; -import '../local_storage/key_value_storage.dart'; - -import '../state/audio_state.dart'; -import '../state/download_state.dart'; -import '../type/episode_task.dart'; -import '../type/episodebrief.dart'; -import '../util/custom_widget.dart'; -import '../util/extension_helper.dart'; -import '../util/general_dialog.dart'; - -class DownloadButton extends StatefulWidget { - final EpisodeBrief episode; - DownloadButton({this.episode, Key key}) : super(key: key); - @override - _DownloadButtonState createState() => _DownloadButtonState(); -} - -class _DownloadButtonState extends State { - Future _requestDownload(EpisodeBrief episode) async { - final downloadUsingData = await KeyValueStorage(downloadUsingDataKey) - .getBool(defaultValue: true, reverse: true); - final permissionReady = await _checkPermmison(); - final result = await Connectivity().checkConnectivity(); - final usingData = result == ConnectivityResult.mobile; - var dataConfirm = true; - if (permissionReady) { - if (downloadUsingData && usingData) { - dataConfirm = await _useDataConfirm(); - } - if (dataConfirm) { - Provider.of(context, listen: false).startTask(episode); - } - } - } - - void _deleteDownload(EpisodeBrief episode) async { - Provider.of(context, listen: false).delTask(episode); - Fluttertoast.showToast( - msg: context.s.downloadRemovedToast, - gravity: ToastGravity.BOTTOM, - ); - } - - Future _pauseDownload(EpisodeBrief episode) async { - Provider.of(context, listen: false).pauseTask(episode); - } - - Future _resumeDownload(EpisodeBrief episode) async { - Provider.of(context, listen: false).resumeTask(episode); - } - - Future _retryDownload(EpisodeBrief episode) async { - Provider.of(context, listen: false).retryTask(episode); - } - - Future _checkPermmison() async { - var permission = await Permission.storage.status; - if (permission != PermissionStatus.granted) { - var permissions = await [Permission.storage].request(); - if (permissions[Permission.storage] == PermissionStatus.granted) { - return true; - } else { - return false; - } - } else { - return true; - } - } - - Future _useDataConfirm() async { - var ifUseData = false; - final s = context.s; - await generalDialog( - context, - title: Text(s.cellularConfirm), - content: Text(s.cellularConfirmDes), - actions: [ - FlatButton( - onPressed: () { - Navigator.of(context).pop(); - }, - child: Text( - s.cancel, - style: TextStyle(color: Colors.grey[600]), - ), - ), - FlatButton( - onPressed: () { - ifUseData = true; - Navigator.of(context).pop(); - }, - child: Text( - s.confirm, - style: TextStyle(color: Colors.red), - ), - ) - ], - ); - return ifUseData; - } - - Widget _buttonOnMenu(Widget widget, Function() onTap) => Material( - color: Colors.transparent, - child: InkWell( - onTap: onTap, - child: Container( - height: 50.0, - padding: EdgeInsets.symmetric(horizontal: 15.0), - child: widget), - ), - ); - - @override - Widget build(BuildContext context) { - return Consumer(builder: (_, downloader, __) { - var _task = Provider.of(context, listen: false) - .episodeToTask(widget.episode); - return Row( - children: [ - _downloadButton(_task, context), - AnimatedContainer( - duration: Duration(seconds: 1), - decoration: BoxDecoration( - color: Theme.of(context).accentColor, - borderRadius: BorderRadius.all(Radius.circular(15.0))), - height: 20.0, - width: (_task.status == DownloadTaskStatus.running) ? 50.0 : 0, - alignment: Alignment.center, - child: SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: Text('${math.max(_task.progress, 0)}%', - style: TextStyle(color: Colors.white)), - )), - ], - ); - }); - } - - Widget _downloadButton(EpisodeTask task, BuildContext context) { - switch (task.status.value) { - case 0: - return _buttonOnMenu( - Center( - child: SizedBox( - height: 20, - width: 20, - child: CustomPaint( - painter: DownloadPainter( - color: Colors.grey[700], - fraction: 0, - progressColor: context.accentColor, - ), - ), - ), - ), - () => _requestDownload(task.episode)); - break; - case 2: - return Material( - color: Colors.transparent, - child: InkWell( - onTap: () { - if (task.progress > 0) _pauseDownload(task.episode); - }, - child: Container( - height: 50.0, - alignment: Alignment.center, - padding: EdgeInsets.symmetric(horizontal: 15.0), - child: TweenAnimationBuilder( - duration: Duration(milliseconds: 1000), - tween: Tween(begin: 0.0, end: 1.0), - builder: (context, fraction, child) => SizedBox( - height: 20, - width: 20, - child: CustomPaint( - painter: DownloadPainter( - color: context.accentColor, - fraction: fraction, - progressColor: context.accentColor, - progress: task.progress / 100), - ), - ), - ), - ), - ), - ); - break; - case 6: - return Material( - color: Colors.transparent, - child: InkWell( - onTap: () { - _resumeDownload(task.episode); - }, - child: Container( - height: 50.0, - alignment: Alignment.center, - padding: EdgeInsets.symmetric(horizontal: 15), - child: TweenAnimationBuilder( - duration: Duration(milliseconds: 500), - tween: Tween(begin: 0.0, end: 1.0), - builder: (context, fraction, child) => SizedBox( - height: 20, - width: 20, - child: CustomPaint( - painter: DownloadPainter( - color: context.accentColor, - fraction: 1, - progressColor: context.accentColor, - progress: task.progress / 100, - pauseProgress: fraction), - ), - ), - ), - ), - ), - ); - break; - case 3: - Provider.of(context, listen: false) - .updateMediaItem(task.episode); - return Material( - color: Colors.transparent, - child: InkWell( - onTap: () { - _deleteDownload(task.episode); - }, - child: Container( - height: 50.0, - alignment: Alignment.center, - padding: EdgeInsets.symmetric(horizontal: 15), - child: SizedBox( - height: 20, - width: 20, - child: CustomPaint( - painter: DownloadPainter( - color: context.accentColor, - fraction: 1, - progressColor: context.accentColor, - progress: 1, - ), - ), - ), - ), - ), - ); - break; - case 4: - return _buttonOnMenu(Icon(Icons.refresh, color: Colors.red), - () => _retryDownload(task.episode)); - break; - default: - return Center(); - } - } -} +import 'dart:async'; +import 'dart:math' as math; +import 'dart:ui'; + +import 'package:connectivity/connectivity.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_downloader/flutter_downloader.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:permission_handler/permission_handler.dart'; +import 'package:provider/provider.dart'; +import '../local_storage/key_value_storage.dart'; + +import '../state/audio_state.dart'; +import '../state/download_state.dart'; +import '../type/episode_task.dart'; +import '../type/episodebrief.dart'; +import '../util/custom_widget.dart'; +import '../util/extension_helper.dart'; +import '../util/general_dialog.dart'; + +class DownloadButton extends StatefulWidget { + final EpisodeBrief episode; + DownloadButton({this.episode, Key key}) : super(key: key); + @override + _DownloadButtonState createState() => _DownloadButtonState(); +} + +class _DownloadButtonState extends State { + Future _requestDownload(EpisodeBrief episode) async { + final downloadUsingData = await KeyValueStorage(downloadUsingDataKey) + .getBool(defaultValue: true, reverse: true); + final permissionReady = await _checkPermmison(); + final result = await Connectivity().checkConnectivity(); + final usingData = result == ConnectivityResult.mobile; + var dataConfirm = true; + if (permissionReady) { + if (downloadUsingData && usingData) { + dataConfirm = await _useDataConfirm(); + } + if (dataConfirm) { + Provider.of(context, listen: false).startTask(episode); + } + } + } + + void _deleteDownload(EpisodeBrief episode) async { + Provider.of(context, listen: false).delTask(episode); + Fluttertoast.showToast( + msg: context.s.downloadRemovedToast, + gravity: ToastGravity.BOTTOM, + ); + } + + Future _pauseDownload(EpisodeBrief episode) async { + Provider.of(context, listen: false).pauseTask(episode); + } + + Future _resumeDownload(EpisodeBrief episode) async { + Provider.of(context, listen: false).resumeTask(episode); + } + + Future _retryDownload(EpisodeBrief episode) async { + Provider.of(context, listen: false).retryTask(episode); + } + + Future _checkPermmison() async { + var permission = await Permission.storage.status; + if (permission != PermissionStatus.granted) { + var permissions = await [Permission.storage].request(); + if (permissions[Permission.storage] == PermissionStatus.granted) { + return true; + } else { + return false; + } + } else { + return true; + } + } + + Future _useDataConfirm() async { + var ifUseData = false; + final s = context.s; + await generalDialog( + context, + title: Text(s.cellularConfirm), + content: Text(s.cellularConfirmDes), + actions: [ + FlatButton( + onPressed: () { + Navigator.of(context).pop(); + }, + child: Text( + s.cancel, + style: TextStyle(color: Colors.grey[600]), + ), + ), + FlatButton( + onPressed: () { + ifUseData = true; + Navigator.of(context).pop(); + }, + child: Text( + s.confirm, + style: TextStyle(color: Colors.red), + ), + ) + ], + ); + return ifUseData; + } + + Widget _buttonOnMenu(Widget widget, Function() onTap) => Material( + color: Colors.transparent, + child: InkWell( + onTap: onTap, + child: Container( + height: 50.0, + padding: EdgeInsets.symmetric(horizontal: 15.0), + child: widget), + ), + ); + + @override + Widget build(BuildContext context) { + return Consumer(builder: (_, downloader, __) { + var _task = Provider.of(context, listen: false) + .episodeToTask(widget.episode); + return Row( + children: [ + _downloadButton(_task, context), + AnimatedContainer( + duration: Duration(seconds: 1), + decoration: BoxDecoration( + color: Theme.of(context).accentColor, + borderRadius: BorderRadius.all(Radius.circular(15.0))), + height: 20.0, + width: (_task.status == DownloadTaskStatus.running) ? 50.0 : 0, + alignment: Alignment.center, + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Text('${math.max(_task.progress, 0)}%', + style: TextStyle(color: Colors.white)), + )), + ], + ); + }); + } + + Widget _downloadButton(EpisodeTask task, BuildContext context) { + switch (task.status.value) { + case 0: + return _buttonOnMenu( + Center( + child: SizedBox( + height: 20, + width: 20, + child: CustomPaint( + painter: DownloadPainter( + color: Colors.grey[700], + fraction: 0, + progressColor: context.accentColor, + ), + ), + ), + ), + () => _requestDownload(task.episode)); + break; + case 2: + return Material( + color: Colors.transparent, + child: InkWell( + onTap: () { + if (task.progress > 0) _pauseDownload(task.episode); + }, + child: Container( + height: 50.0, + alignment: Alignment.center, + padding: EdgeInsets.symmetric(horizontal: 15.0), + child: TweenAnimationBuilder( + duration: Duration(milliseconds: 1000), + tween: Tween(begin: 0.0, end: 1.0), + builder: (context, fraction, child) => SizedBox( + height: 20, + width: 20, + child: CustomPaint( + painter: DownloadPainter( + color: context.accentColor, + fraction: fraction, + progressColor: context.accentColor, + progress: task.progress / 100), + ), + ), + ), + ), + ), + ); + break; + case 6: + return Material( + color: Colors.transparent, + child: InkWell( + onTap: () { + _resumeDownload(task.episode); + }, + child: Container( + height: 50.0, + alignment: Alignment.center, + padding: EdgeInsets.symmetric(horizontal: 15), + child: TweenAnimationBuilder( + duration: Duration(milliseconds: 500), + tween: Tween(begin: 0.0, end: 1.0), + builder: (context, fraction, child) => SizedBox( + height: 20, + width: 20, + child: CustomPaint( + painter: DownloadPainter( + color: context.accentColor, + fraction: 1, + progressColor: context.accentColor, + progress: task.progress / 100, + pauseProgress: fraction), + ), + ), + ), + ), + ), + ); + break; + case 3: + Provider.of(context, listen: false) + .updateMediaItem(task.episode); + return Material( + color: Colors.transparent, + child: InkWell( + onTap: () { + _deleteDownload(task.episode); + }, + child: Container( + height: 50.0, + alignment: Alignment.center, + padding: EdgeInsets.symmetric(horizontal: 15), + child: SizedBox( + height: 20, + width: 20, + child: CustomPaint( + painter: DownloadPainter( + color: context.accentColor, + fraction: 1, + progressColor: context.accentColor, + progress: 1, + ), + ), + ), + ), + ), + ); + break; + case 4: + return _buttonOnMenu(Icon(Icons.refresh, color: Colors.red), + () => _retryDownload(task.episode)); + break; + default: + return Center(); + } + } +} diff --git a/lib/generated/l10n.dart b/lib/generated/l10n.dart index f87adea..7345b36 100644 --- a/lib/generated/l10n.dart +++ b/lib/generated/l10n.dart @@ -9,6 +9,8 @@ import 'intl/messages_all.dart'; // ************************************************************************** // ignore_for_file: non_constant_identifier_names, lines_longer_than_80_chars +// ignore_for_file: join_return_with_assignment, prefer_final_in_for_each +// ignore_for_file: avoid_redundant_argument_values class S { S(); diff --git a/lib/home/about.dart b/lib/home/about.dart index ddd3de7..9a2d0bc 100644 --- a/lib/home/about.dart +++ b/lib/home/about.dart @@ -1,334 +1,334 @@ -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:line_icons/line_icons.dart'; - -import '../util/custom_widget.dart'; -import '../util/extension_helper.dart'; - -const String version = '0.5.0'; - -class AboutApp extends StatefulWidget { - @override - _AboutAppState createState() => _AboutAppState(); -} - -class _AboutAppState extends State { - ScrollController _scrollController; - bool _scroll; - @override - void initState() { - super.initState(); - _scroll = false; - _scrollController = ScrollController() - ..addListener(() { - if (_scrollController.offset > 0 && !_scroll && mounted) { - setState(() => _scroll = true); - } - if (_scrollController.offset <= 0 && _scroll && mounted) { - setState(() => _scroll = false); - } - }); - } - - Widget _listItem( - BuildContext context, String text, IconData icons, String url) => - InkWell( - onTap: () => url.launchUrl, - child: Container( - height: 50.0, - padding: EdgeInsets.symmetric(horizontal: 20.0), - alignment: Alignment.centerLeft, - decoration: BoxDecoration( - border: Border( - bottom: Divider.createBorderSide(context), - ), - ), - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - mainAxisSize: MainAxisSize.min, - children: [ - Icon(icons, color: Theme.of(context).accentColor), - Padding( - padding: EdgeInsets.symmetric(horizontal: 10), - ), - Text(text), - ], - ), - ), - ); - - Widget _translatorInfo(BuildContext context, {String name, String flag}) => - Container( - height: 50.0, - padding: EdgeInsets.symmetric(horizontal: 20.0), - alignment: Alignment.centerLeft, - decoration: BoxDecoration( - border: Border( - bottom: Divider.createBorderSide(context), - ), - ), - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - mainAxisSize: MainAxisSize.min, - children: [ - Icon(LineIcons.user, color: Theme.of(context).accentColor), - Padding( - padding: EdgeInsets.symmetric(horizontal: 10), - ), - Expanded( - child: Text( - name, - maxLines: 1, - overflow: TextOverflow.fade, - )), - if (flag != null) - ClipRRect( - borderRadius: BorderRadius.circular(4), - child: Image( - image: AssetImage('assets/$flag.png'), - height: 20, - width: 30, - fit: BoxFit.cover, - ), - ), - ], - ), - ); - - @override - Widget build(BuildContext context) { - OverlayEntry _createOverlayEntry(TapDownDetails detail) { - // RenderBox renderBox = context.findRenderObject(); - var offset = detail.globalPosition; - return OverlayEntry( - builder: (constext) => Positioned( - left: offset.dx - 5, - top: offset.dy - 120, - child: Container( - width: 20, - height: 120, - color: Colors.transparent, - alignment: Alignment.topCenter, - child: HeartSet(height: 120, width: 20)), - ), - ); - } - - final s = context.s; - return AnnotatedRegion( - value: SystemUiOverlayStyle( - statusBarIconBrightness: Theme.of(context).accentColorBrightness, - systemNavigationBarColor: Theme.of(context).primaryColor, - systemNavigationBarIconBrightness: - Theme.of(context).accentColorBrightness, - ), - child: Scaffold( - backgroundColor: Theme.of(context).primaryColor, - appBar: AppBar( - title: Text(s.homeToprightMenuAbout), - leading: CustomBackButton(), - elevation: _scroll ? 1 : 0, - ), - body: SafeArea( - child: ScrollConfiguration( - behavior: NoGrowBehavior(), - child: SingleChildScrollView( - controller: _scrollController, - scrollDirection: Axis.vertical, - child: Padding( - padding: const EdgeInsets.all(20.0), - child: Column( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Container( - height: 110.0, - alignment: Alignment.center, - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - mainAxisSize: MainAxisSize.min, - children: [ - Image( - image: AssetImage('assets/logo.png'), - height: 80, - ), - Text(s.version(version)), - ], - ), - ), - Padding( - padding: const EdgeInsets.all(20), - child: Text( - 'Tsacdop is a podcast player built with flutter, a clean, simply beautiful and friendly app.', - textAlign: TextAlign.center, - ), - ), - Row( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - TextButton( - onPressed: () => - 'https://tsacdop.stonegate.me/#/privacy' - .launchUrl, - style: TextButton.styleFrom( - primary: context.accentColor, - textStyle: - TextStyle(fontWeight: FontWeight.bold)), - child: Text( - s.privacyPolicy, - ), - ), - Container( - margin: const EdgeInsets.symmetric(horizontal: 5), - height: 4, - width: 4, - decoration: BoxDecoration( - color: context.accentColor, - shape: BoxShape.circle), - ), - TextButton( - onPressed: () => - 'https://tsacdop.stonegate.me/#/changelog' - .launchUrl, - style: TextButton.styleFrom( - primary: context.accentColor, - textStyle: - TextStyle(fontWeight: FontWeight.bold)), - child: Text(s.changelog, - style: TextStyle(color: context.accentColor)), - ), - ], - ), - Padding( - padding: EdgeInsets.only(top: 20.0, bottom: 10.0), - child: Column( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - _listItem(context, 'Twitter @tsacdop', - LineIcons.twitter, 'https://twitter.com/tsacdop'), - _listItem(context, 'GitHub', LineIcons.github_alt, - 'https://github.com/stonega/tsacdop'), - _listItem(context, 'Telegram', LineIcons.telegram, - 'https://t.me/joinchat/Bk3LkRpTHy40QYC78PK7Qg'), - Center( - child: SizedBox( - width: 200, - child: ElevatedButton( - onPressed: () => - 'https://www.buymeacoffee.com/stonegate' - .launchUrl, - style: ElevatedButton.styleFrom( - primary: context.accentColor), - child: Container( - height: 30.0, - padding: - EdgeInsets.symmetric(horizontal: 4.0), - alignment: Alignment.center, - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - mainAxisSize: MainAxisSize.min, - children: [ - Text('Buy Me A Coffee', - style: TextStyle( - fontWeight: FontWeight.bold)), - SizedBox(width: 10), - Image( - image: AssetImage( - 'assets/buymeacoffee.png'), - height: 20, - fit: BoxFit.fitHeight, - ), - ], - ), - ), - ), - ), - ), - ], - ), - ), - Padding( - padding: EdgeInsets.all(10.0), - ), - Padding( - padding: EdgeInsets.only(top: 20.0, bottom: 10.0), - child: Column( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Row( - children: [ - SizedBox(width: 25), - Text( - s.translators, - style: TextStyle( - color: Theme.of(context).accentColor, - fontWeight: FontWeight.bold), - ), - SizedBox(width: 2), - Icon(Icons.favorite, color: Colors.red, size: 20), - ], - ), - _translatorInfo(context, name: 'Atrate'), - _translatorInfo(context, name: 'ppp', flag: 'fr'), - _translatorInfo(context, - name: 'Joel Israel', flag: 'mx'), - _translatorInfo(context, - name: 'Bruno Pinheiro', flag: 'pt'), - _translatorInfo(context, - name: 'Edoardo Maria Elidoro', flag: 'it'), - ], - ), - ), - //Spacer(), - Padding( - padding: EdgeInsets.symmetric(vertical: 10), - ), - Container( - height: 50, - alignment: Alignment.center, - child: GestureDetector( - onTapDown: (detail) async { - OverlayEntry _overlayEntry; - _overlayEntry = _createOverlayEntry(detail); - Overlay.of(context).insert(_overlayEntry); - await Future.delayed(Duration(seconds: 2)); - _overlayEntry?.remove(); - }, - child: Row( - crossAxisAlignment: CrossAxisAlignment.center, - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Image.asset( - 'assets/text.png', - height: 25, - ), - Padding( - padding: EdgeInsets.symmetric(horizontal: 5), - ), - Icon( - Icons.favorite, - color: Colors.blue, - ), - Padding( - padding: EdgeInsets.symmetric(horizontal: 5), - ), - FlutterLogo( - size: 18, - ), - ], - ), - ), - ), - ], - ), - ), - ), - ), - ), - ), - ); - } -} +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:line_icons/line_icons.dart'; + +import '../util/custom_widget.dart'; +import '../util/extension_helper.dart'; + +const String version = '0.5.0'; + +class AboutApp extends StatefulWidget { + @override + _AboutAppState createState() => _AboutAppState(); +} + +class _AboutAppState extends State { + ScrollController _scrollController; + bool _scroll; + @override + void initState() { + super.initState(); + _scroll = false; + _scrollController = ScrollController() + ..addListener(() { + if (_scrollController.offset > 0 && !_scroll && mounted) { + setState(() => _scroll = true); + } + if (_scrollController.offset <= 0 && _scroll && mounted) { + setState(() => _scroll = false); + } + }); + } + + Widget _listItem( + BuildContext context, String text, IconData icons, String url) => + InkWell( + onTap: () => url.launchUrl, + child: Container( + height: 50.0, + padding: EdgeInsets.symmetric(horizontal: 20.0), + alignment: Alignment.centerLeft, + decoration: BoxDecoration( + border: Border( + bottom: Divider.createBorderSide(context), + ), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icons, color: Theme.of(context).accentColor), + Padding( + padding: EdgeInsets.symmetric(horizontal: 10), + ), + Text(text), + ], + ), + ), + ); + + Widget _translatorInfo(BuildContext context, {String name, String flag}) => + Container( + height: 50.0, + padding: EdgeInsets.symmetric(horizontal: 20.0), + alignment: Alignment.centerLeft, + decoration: BoxDecoration( + border: Border( + bottom: Divider.createBorderSide(context), + ), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + mainAxisSize: MainAxisSize.min, + children: [ + Icon(LineIcons.user, color: Theme.of(context).accentColor), + Padding( + padding: EdgeInsets.symmetric(horizontal: 10), + ), + Expanded( + child: Text( + name, + maxLines: 1, + overflow: TextOverflow.fade, + )), + if (flag != null) + ClipRRect( + borderRadius: BorderRadius.circular(4), + child: Image( + image: AssetImage('assets/$flag.png'), + height: 20, + width: 30, + fit: BoxFit.cover, + ), + ), + ], + ), + ); + + @override + Widget build(BuildContext context) { + OverlayEntry _createOverlayEntry(TapDownDetails detail) { + // RenderBox renderBox = context.findRenderObject(); + var offset = detail.globalPosition; + return OverlayEntry( + builder: (constext) => Positioned( + left: offset.dx - 5, + top: offset.dy - 120, + child: Container( + width: 20, + height: 120, + color: Colors.transparent, + alignment: Alignment.topCenter, + child: HeartSet(height: 120, width: 20)), + ), + ); + } + + final s = context.s; + return AnnotatedRegion( + value: SystemUiOverlayStyle( + statusBarIconBrightness: Theme.of(context).accentColorBrightness, + systemNavigationBarColor: Theme.of(context).primaryColor, + systemNavigationBarIconBrightness: + Theme.of(context).accentColorBrightness, + ), + child: Scaffold( + backgroundColor: Theme.of(context).primaryColor, + appBar: AppBar( + title: Text(s.homeToprightMenuAbout), + leading: CustomBackButton(), + elevation: _scroll ? 1 : 0, + ), + body: SafeArea( + child: ScrollConfiguration( + behavior: NoGrowBehavior(), + child: SingleChildScrollView( + controller: _scrollController, + scrollDirection: Axis.vertical, + child: Padding( + padding: const EdgeInsets.all(20.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Container( + height: 110.0, + alignment: Alignment.center, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + mainAxisSize: MainAxisSize.min, + children: [ + Image( + image: AssetImage('assets/logo.png'), + height: 80, + ), + Text(s.version(version)), + ], + ), + ), + Padding( + padding: const EdgeInsets.all(20), + child: Text( + 'Tsacdop is a podcast player built with flutter, a clean, simply beautiful and friendly app.', + textAlign: TextAlign.center, + ), + ), + Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + TextButton( + onPressed: () => + 'https://tsacdop.stonegate.me/#/privacy' + .launchUrl, + style: TextButton.styleFrom( + primary: context.accentColor, + textStyle: + TextStyle(fontWeight: FontWeight.bold)), + child: Text( + s.privacyPolicy, + ), + ), + Container( + margin: const EdgeInsets.symmetric(horizontal: 5), + height: 4, + width: 4, + decoration: BoxDecoration( + color: context.accentColor, + shape: BoxShape.circle), + ), + TextButton( + onPressed: () => + 'https://tsacdop.stonegate.me/#/changelog' + .launchUrl, + style: TextButton.styleFrom( + primary: context.accentColor, + textStyle: + TextStyle(fontWeight: FontWeight.bold)), + child: Text(s.changelog, + style: TextStyle(color: context.accentColor)), + ), + ], + ), + Padding( + padding: EdgeInsets.only(top: 20.0, bottom: 10.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + _listItem(context, 'Twitter @tsacdop', + LineIcons.twitter, 'https://twitter.com/tsacdop'), + _listItem(context, 'GitHub', LineIcons.github_alt, + 'https://github.com/stonega/tsacdop'), + _listItem(context, 'Telegram', LineIcons.telegram, + 'https://t.me/joinchat/Bk3LkRpTHy40QYC78PK7Qg'), + Center( + child: SizedBox( + width: 200, + child: ElevatedButton( + onPressed: () => + 'https://www.buymeacoffee.com/stonegate' + .launchUrl, + style: ElevatedButton.styleFrom( + primary: context.accentColor), + child: Container( + height: 30.0, + padding: + EdgeInsets.symmetric(horizontal: 4.0), + alignment: Alignment.center, + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + mainAxisSize: MainAxisSize.min, + children: [ + Text('Buy Me A Coffee', + style: TextStyle( + fontWeight: FontWeight.bold)), + SizedBox(width: 10), + Image( + image: AssetImage( + 'assets/buymeacoffee.png'), + height: 20, + fit: BoxFit.fitHeight, + ), + ], + ), + ), + ), + ), + ), + ], + ), + ), + Padding( + padding: EdgeInsets.all(10.0), + ), + Padding( + padding: EdgeInsets.only(top: 20.0, bottom: 10.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Row( + children: [ + SizedBox(width: 25), + Text( + s.translators, + style: TextStyle( + color: Theme.of(context).accentColor, + fontWeight: FontWeight.bold), + ), + SizedBox(width: 2), + Icon(Icons.favorite, color: Colors.red, size: 20), + ], + ), + _translatorInfo(context, name: 'Atrate'), + _translatorInfo(context, name: 'ppp', flag: 'fr'), + _translatorInfo(context, + name: 'Joel Israel', flag: 'mx'), + _translatorInfo(context, + name: 'Bruno Pinheiro', flag: 'pt'), + _translatorInfo(context, + name: 'Edoardo Maria Elidoro', flag: 'it'), + ], + ), + ), + //Spacer(), + Padding( + padding: EdgeInsets.symmetric(vertical: 10), + ), + Container( + height: 50, + alignment: Alignment.center, + child: GestureDetector( + onTapDown: (detail) async { + OverlayEntry _overlayEntry; + _overlayEntry = _createOverlayEntry(detail); + Overlay.of(context).insert(_overlayEntry); + await Future.delayed(Duration(seconds: 2)); + _overlayEntry?.remove(); + }, + child: Row( + crossAxisAlignment: CrossAxisAlignment.center, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Image.asset( + 'assets/text.png', + height: 25, + ), + Padding( + padding: EdgeInsets.symmetric(horizontal: 5), + ), + Icon( + Icons.favorite, + color: Colors.blue, + ), + Padding( + padding: EdgeInsets.symmetric(horizontal: 5), + ), + FlutterLogo( + size: 18, + ), + ], + ), + ), + ), + ], + ), + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/home/audioplayer.dart b/lib/home/audioplayer.dart index 59434ea..d5e3714 100644 --- a/lib/home/audioplayer.dart +++ b/lib/home/audioplayer.dart @@ -1,1512 +1,1512 @@ -import 'dart:io'; -import 'dart:math' as math; - -import 'package:audio_service/audio_service.dart'; -import 'package:flutter/material.dart'; -import 'package:google_fonts/google_fonts.dart'; -import 'package:line_icons/line_icons.dart'; -import 'package:marquee/marquee.dart'; -import 'package:provider/provider.dart'; -import 'package:tuple/tuple.dart'; - -import '../episodes/episode_detail.dart'; -import '../local_storage/key_value_storage.dart'; -import '../local_storage/sqflite_localpodcast.dart'; -import '../state/audio_state.dart'; -import '../type/episodebrief.dart'; -import '../type/play_histroy.dart'; -import '../util/audiopanel.dart'; -import '../util/custom_slider.dart'; -import '../util/custom_widget.dart'; -import '../util/extension_helper.dart'; -import '../util/pageroute.dart'; -import 'playlist.dart'; - -final List _customShadow = [ - BoxShadow(blurRadius: 26, offset: Offset(-6, -6), color: Colors.white), - BoxShadow( - blurRadius: 8, - offset: Offset(2, 2), - color: Colors.grey[600].withOpacity(0.4)) -]; - -final List _customShadowNight = [ - BoxShadow( - blurRadius: 6, - offset: Offset(-1, -1), - color: Colors.grey[100].withOpacity(0.3)), - BoxShadow(blurRadius: 8, offset: Offset(2, 2), color: Colors.black) -]; - -const List kMinsToSelect = [10, 15, 20, 25, 30, 45, 60, 70, 80, 90, 99]; -const List kMinPlayerHeight = [70.0, 75.0, 80.0]; -const List kMaxPlayerHeight = [300.0, 325.0, 350.0]; - -class PlayerWidget extends StatelessWidget { - PlayerWidget({this.playerKey, this.isPlayingPage = false}); - final GlobalKey playerKey; - final bool isPlayingPage; - Widget _miniPanel(BuildContext context) { - var audio = Provider.of(context, listen: false); - final s = context.s; - return Container( - color: context.primaryColor, - height: 60, - child: - Column(mainAxisAlignment: MainAxisAlignment.start, children: [ - Selector>( - selector: (_, audio) => - Tuple2(audio.episode?.primaryColor, audio.seekSliderValue), - builder: (_, data, __) { - final c = context.brightness == Brightness.light - ? data.item1.colorizedark() - : data.item1.colorizeLight(); - return SizedBox( - height: 2, - child: LinearProgressIndicator( - value: data.item2, - backgroundColor: context.primaryColor, - valueColor: AlwaysStoppedAnimation(c), - ), - ); - }, - ), - Expanded( - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 15), - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Expanded( - flex: 4, - child: Selector( - selector: (_, audio) => audio.episode?.title, - builder: (_, title, __) { - return Text( - title, - style: TextStyle(fontWeight: FontWeight.bold), - maxLines: 2, - overflow: TextOverflow.clip, - ); - }, - ), - ), - Expanded( - flex: 2, - child: Selector>( - selector: (_, audio) => Tuple3( - audio.buffering, - (audio.backgroundAudioDuration - - audio.backgroundAudioPosition) / - 1000, - audio.remoteErrorMessage), - builder: (_, data, __) { - return Padding( - padding: const EdgeInsets.symmetric(horizontal: 10), - child: data.item3 != null - ? Text(data.item3, - style: - const TextStyle(color: Color(0xFFFF0000))) - : data.item1 - ? Text( - s.buffering, - style: - TextStyle(color: context.accentColor), - ) - : Text( - s.timeLeft( - (data.item2).toInt().toTime ?? ''), - maxLines: 2, - ), - ); - }, - ), - ), - Expanded( - flex: 2, - child: Selector>( - selector: (_, audio) => - Tuple3(audio.buffering, audio.playing, audio.episode), - builder: (_, data, __) { - return Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - data.item1 - ? Stack( - alignment: Alignment.center, - children: [ - Padding( - padding: const EdgeInsets.symmetric( - vertical: 10.0), - child: SizedBox( - height: 30.0, - width: 30.0, - child: CircleAvatar( - backgroundColor: data.item3 - .backgroudColor(context), - backgroundImage: - data.item3.avatarImage, - ), - ), - ), - Container( - height: 40.0, - decoration: BoxDecoration( - shape: BoxShape.circle, - color: Colors.black), - ), - ]) - : data.item2 - ? InkWell( - onTap: data.item2 - ? () => audio.pauseAduio() - : null, - child: - ImageRotate(episodeItem: data.item3), - ) - : InkWell( - onTap: data.item2 - ? null - : () => audio.resumeAudio(), - child: Stack( - alignment: Alignment.center, - children: [ - Padding( - padding: EdgeInsets.symmetric( - vertical: 10.0), - child: SizedBox( - height: 30.0, - width: 30.0, - child: CircleAvatar( - backgroundColor: data.item3 - .backgroudColor(context), - backgroundImage: - data.item3.avatarImage, - ), - ), - ), - Container( - height: 40.0, - decoration: BoxDecoration( - shape: BoxShape.circle, - color: Colors.black), - ), - if (!data.item1) - Icon( - Icons.play_arrow, - color: Colors.white, - ) - ], - ), - ), - IconButton( - onPressed: () => audio.playNext(), - iconSize: 20.0, - icon: Icon(Icons.skip_next), - color: context.textColor) - ], - ); - }, - ), - ), - ], - ), - ), - ), - ]), - ); - } - - @override - Widget build(BuildContext context) { - return Selector>( - selector: (_, audio) => Tuple2(audio.playerRunning, audio?.playerHeight), - builder: (_, data, __) { - if (!data.item1) { - return Center(); - } else { - var minHeight = kMinPlayerHeight[data.item2.index]; - var maxHeight = kMaxPlayerHeight[data.item2.index]; - return AudioPanel( - minHeight: minHeight, - maxHeight: maxHeight, - key: playerKey, - miniPanel: _miniPanel(context), - expandedPanel: ControlPanel( - maxHeight: maxHeight, - isPlayingPage: isPlayingPage, - onExpand: () { - playerKey.currentState.scrollToTop(); - }, - onClose: () { - playerKey.currentState.backToMini(); - }, - )); - } - }, - ); - } -} - -class LastPosition extends StatelessWidget { - LastPosition({Key key}) : super(key: key); - - Future getPosition(EpisodeBrief episode) async { - var dbHelper = DBHelper(); - return await dbHelper.getPosition(episode); - } - - @override - Widget build(BuildContext context) { - final s = context.s; - var audio = Provider.of(context, listen: false); - return Selector( - selector: (_, audio) => audio.episode, - builder: (context, episode, child) { - return SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - mainAxisSize: MainAxisSize.min, - children: [ - Selector( - selector: (_, audio) => audio.skipSilence, - builder: (_, data, __) => FlatButton( - child: Row( - children: [ - Icon(Icons.flash_on, size: 18), - SizedBox(width: 5), - Text(s.skipSilence), - ], - ), - color: data ? context.accentColor : Colors.transparent, - padding: EdgeInsets.symmetric(horizontal: 10), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(100.0), - side: BorderSide( - color: data - ? context.accentColor - : Theme.of(context) - .colorScheme - .onSurface - .withOpacity(0.12))), - textColor: data ? Colors.white : null, - onPressed: () => - audio.setSkipSilence(skipSilence: !data))), - SizedBox(width: 10), - Selector( - selector: (_, audio) => audio.boostVolume, - builder: (_, data, __) => FlatButton( - child: Row( - children: [ - Icon(Icons.volume_up, size: 18), - SizedBox(width: 5), - Text(s.boostVolume), - ], - ), - color: data ? context.accentColor : Colors.transparent, - padding: EdgeInsets.symmetric(horizontal: 10), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(100.0), - side: BorderSide( - color: data - ? context.accentColor - : Theme.of(context) - .colorScheme - .onSurface - .withOpacity(0.12))), - textColor: data ? Colors.white : null, - onPressed: () => - audio.setBoostVolume(boostVolume: !data))), - SizedBox(width: 10), - FutureBuilder( - future: getPosition(episode), - builder: (context, snapshot) { - return snapshot.hasData - ? snapshot.data.seekValue > 0.90 - ? Container( - height: 20, - padding: EdgeInsets.symmetric(horizontal: 10), - child: SizedBox( - width: 20, - height: 20, - child: CustomPaint( - painter: ListenedAllPainter( - context.accentColor, - stroke: 2.0), - ), - ), - ) - : snapshot.data.seconds < 10 - ? Center() - : OutlineButton( - shape: RoundedRectangleBorder( - borderRadius: - BorderRadius.circular(100.0), - side: BorderSide( - color: context.accentColor)), - highlightedBorderColor: Colors.green[700], - onPressed: () => audio.seekTo( - (snapshot.data.seconds * 1000).toInt()), - child: Row( - children: [ - SizedBox( - width: 20, - height: 20, - child: CustomPaint( - painter: ListenedPainter( - context.textColor, - stroke: 2.0), - ), - ), - SizedBox(width: 5), - Text(snapshot.data.seconds.toTime), - ], - ), - ) - : Center(); - }), - Selector( - selector: (_, audio) => audio.switchValue, - builder: (_, data, __) => data == 1 - ? Container( - height: 20, - width: 40, - child: Transform.rotate( - angle: math.pi * 0.7, - child: Icon(Icons.brightness_2, - size: 18, color: context.accentColor))) - : Center(), - ) - ], - ), - ); - }, - ); - } -} - -class PlaylistWidget extends StatefulWidget { - const PlaylistWidget({Key key}) : super(key: key); - - @override - _PlaylistWidgetState createState() => _PlaylistWidgetState(); -} - -class _PlaylistWidgetState extends State { - final GlobalKey miniPlaylistKey = GlobalKey(); - - @override - Widget build(BuildContext context) { - var audio = Provider.of(context, listen: false); - return Container( - alignment: Alignment.topLeft, - height: 300, - width: double.infinity, - decoration: BoxDecoration( - color: context.accentColor.withAlpha(70), - borderRadius: BorderRadius.circular(10), - ), - child: Column( - children: [ - Expanded( - child: - Selector, bool>>( - selector: (_, audio) => - Tuple2(audio.queue.playlist, audio.queueUpdate), - builder: (_, data, __) { - var episodesToPlay = data.item1.sublist(1); - return AnimatedList( - key: miniPlaylistKey, - shrinkWrap: true, - scrollDirection: Axis.vertical, - initialItemCount: episodesToPlay.length, - itemBuilder: (context, index, animation) => ScaleTransition( - alignment: Alignment.center, - scale: animation, - child: Column( - children: [ - Row( - children: [ - Expanded( - child: Material( - color: Colors.transparent, - child: InkWell( - onTap: () { - audio.episodeLoad(data.item1[index]); - miniPlaylistKey.currentState.removeItem( - index, - (context, animation) => Center()); - }, - child: Container( - height: 60, - padding: - EdgeInsets.symmetric(horizontal: 20), - alignment: Alignment.centerLeft, - child: Row( - mainAxisAlignment: - MainAxisAlignment.center, - crossAxisAlignment: - CrossAxisAlignment.center, - mainAxisSize: MainAxisSize.min, - children: [ - Container( - padding: EdgeInsets.all(10.0), - child: ClipRRect( - borderRadius: BorderRadius.all( - Radius.circular(15.0)), - child: Container( - height: 30.0, - width: 30.0, - child: Image.file(File( - "${episodesToPlay[index].imagePath}"))), - ), - ), - Expanded( - child: Align( - alignment: Alignment.centerLeft, - child: Text( - episodesToPlay[index].title, - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - ), - ), - ], - ), - ), - ), - ), - ), - Padding( - padding: - const EdgeInsets.symmetric(horizontal: 20.0), - child: Material( - borderRadius: BorderRadius.circular(100), - clipBehavior: Clip.hardEdge, - color: context.primaryColor, - child: InkWell( - borderRadius: - BorderRadius.all(Radius.circular(15.0)), - onTap: () async { - var episdoe = - episodesToPlay.removeAt(index); - episodesToPlay.insert(0, episdoe); - miniPlaylistKey.currentState.removeItem( - index, - (context, animation) { - return Center(); - }, - duration: Duration.zero, - ); - miniPlaylistKey.currentState.insertItem(0, - duration: Duration(milliseconds: 100)); - await Future.delayed( - Duration(milliseconds: 100)); - await audio - .moveToTop(data.item1[index + 1]); - }, - child: SizedBox( - height: 30.0, - width: 30.0, - child: Transform.rotate( - angle: math.pi, - child: Icon( - LineIcons.download_solid, - size: 20.0, - ), - ), - ), - ), - ), - ), - ], - ), - Divider(height: 1), - ], - ), - ), - ); - }, - ), - ), - SizedBox( - height: 60.0, - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 20), - child: Row( - children: [ - Text( - context.s.homeMenuPlaylist, - style: TextStyle( - color: context.accentColor, - fontWeight: FontWeight.bold, - fontSize: 16), - ), - Spacer(), - Material( - borderRadius: BorderRadius.circular(100), - color: context.primaryColor, - child: InkWell( - borderRadius: BorderRadius.all(Radius.circular(15)), - onTap: () { - audio.playNext(); - miniPlaylistKey.currentState - .removeItem(0, (context, animation) => Container()); - miniPlaylistKey.currentState.insertItem(0); - }, - child: SizedBox( - height: 30, - width: 60, - child: Icon( - Icons.skip_next, - size: 30, - ), - ), - ), - ), - SizedBox(width: 20), - Material( - borderRadius: BorderRadius.circular(100), - color: context.primaryColor, - child: InkWell( - borderRadius: BorderRadius.circular(15.0), - onTap: () { - Navigator.push( - context, - SlideLeftRoute( - page: PlaylistPage( - initPage: InitPage.playlist, - )), - ); - }, - child: SizedBox( - height: 30.0, - width: 30.0, - child: Transform.rotate( - angle: math.pi, - child: Icon( - LineIcons.database_solid, - size: 20.0, - ), - ), - ), - ), - ), - ], - ), - ), - ), - ], - ), - ); - } -} - -class SleepMode extends StatefulWidget { - SleepMode({Key key}) : super(key: key); - - @override - SleepModeState createState() => SleepModeState(); -} - -class SleepModeState extends State - with SingleTickerProviderStateMixin { - int _minSelected; - AnimationController _controller; - Animation _animation; - Future _getDefaultTime() async { - var defaultSleepTimerStorage = KeyValueStorage(defaultSleepTimerKey); - var defaultTime = await defaultSleepTimerStorage.getInt(defaultValue: 30); - setState(() => _minSelected = defaultTime); - } - - @override - void initState() { - super.initState(); - _minSelected = 30; - _getDefaultTime(); - - _controller = - AnimationController(vsync: this, duration: Duration(milliseconds: 400)); - _animation = Tween(begin: 0.0, end: 1.0).animate(_controller) - ..addListener(() { - if (mounted) { - setState(() {}); - } - }); - - _controller.addStatusListener((status) { - if (status == AnimationStatus.completed) { - Provider.of(context, listen: false) - ..sleepTimer(_minSelected) - ..setSwitchValue = 1; - } - }); - } - - @override - void dispose() { - _controller.dispose(); - super.dispose(); - } - - List customShadow(double scale) => [ - BoxShadow( - blurRadius: 26 * (1 - scale), - offset: Offset(-6, -6) * (1 - scale), - color: Colors.white), - BoxShadow( - blurRadius: 8 * (1 - scale), - offset: Offset(2, 2) * (1 - scale), - color: Colors.grey[600].withOpacity(0.4)) - ]; - List customShadowNight(double scale) => [ - BoxShadow( - blurRadius: 6 * (1 - scale), - offset: Offset(-1, -1) * (1 - scale), - color: Colors.grey[100].withOpacity(0.3)), - BoxShadow( - blurRadius: 8 * (1 - scale), - offset: Offset(2, 2) * (1 - scale), - color: Colors.black) - ]; - - @override - Widget build(BuildContext context) { - final s = context.s; - final _colorTween = - ColorTween(begin: context.accentColor.withAlpha(60), end: Colors.black); - var audio = Provider.of(context, listen: false); - return Selector>( - selector: (_, audio) => - Tuple3(audio?.timeLeft, audio?.switchValue, audio.sleepTimerMode), - builder: (_, data, __) { - var fraction = - data.item2 == 1 ? 1.0 : math.min(_animation.value * 2, 1.0); - var move = - data.item2 == 1 ? 1.0 : math.max(_animation.value * 2 - 1, 0.0); - return LayoutBuilder(builder: (context, constraints) { - var width = constraints.maxWidth; - return Container( - height: 300, - decoration: BoxDecoration( - color: _colorTween.transform(move), - borderRadius: BorderRadius.circular(10)), - child: Stack( - children: [ - Column( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - SizedBox( - height: 10, - ), - Expanded( - child: Padding( - padding: EdgeInsets.symmetric(vertical: 20), - child: move == 1 - ? Center() - : Wrap( - direction: Axis.horizontal, - children: kMinsToSelect - .map((e) => InkWell( - onTap: () => - setState(() => _minSelected = e), - child: Container( - margin: EdgeInsets.all(10.0), - decoration: BoxDecoration( - color: (e == _minSelected) - ? context.accentColor - : context.primaryColor, - shape: BoxShape.circle, - ), - alignment: Alignment.center, - height: 30, - width: 30, - child: Text(e.toString(), - style: TextStyle( - fontWeight: FontWeight.bold, - color: (e == _minSelected) - ? Colors.white - : null)), - ), - )) - .toList(), - ), - ), - ), - Stack( - children: [ - SizedBox( - height: 100, - width: width, - ), - Positioned( - left: data.item3 == SleepTimerMode.timer - ? -width * (move) / 4 - : width * (move) / 4, - child: SizedBox( - height: 100, - width: width, - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - children: [ - Container( - alignment: Alignment.center, - height: 40, - width: 120, - decoration: BoxDecoration( - border: - Border.all(color: context.primaryColor), - color: _colorTween.transform(move), - borderRadius: BorderRadius.circular(20), - ), - child: Material( - color: Colors.transparent, - child: InkWell( - onTap: () { - audio.setSleepTimerMode = - SleepTimerMode.endOfEpisode; - if (fraction == 0) { - _controller.forward(); - } else if (fraction == 1) { - _controller.reverse(); - audio.cancelTimer(); - } - }, - borderRadius: BorderRadius.circular(20), - child: SizedBox( - height: 40, - width: 120, - child: Center( - child: Text( - s.endOfEpisode, - style: TextStyle( - color: (move > 0 - ? Colors.white - : null)), - ), - ), - ), - ), - ), - ), - Container( - height: 100 * (1 - fraction), - width: 1, - color: context.primaryColorDark, - ), - Container( - height: 40, - width: 120, - alignment: Alignment.center, - decoration: BoxDecoration( - border: - Border.all(color: context.primaryColor), - color: _colorTween.transform(move), - borderRadius: BorderRadius.circular(20), - ), - child: Material( - color: Colors.transparent, - child: InkWell( - onTap: () { - audio.setSleepTimerMode = - SleepTimerMode.timer; - if (fraction == 0) { - _controller.forward(); - } else if (fraction == 1) { - _controller.reverse(); - audio.cancelTimer(); - } - }, - borderRadius: BorderRadius.circular(20), - child: SizedBox( - height: 40, - width: 120, - child: Center( - child: Text( - data.item2 == 1 - ? data.item1.toTime - : (_minSelected * 60).toTime, - style: TextStyle( - color: (move > 0 - ? Colors.white - : null)), - ), - ), - ), - ), - ), - ) - ], - ), - ), - ), - ], - ), - SizedBox( - height: 60.0, - child: Padding( - padding: EdgeInsets.symmetric(horizontal: 20.0), - child: Align( - alignment: Alignment.centerLeft, - child: Text( - context.s.sleepTimer, - style: TextStyle( - color: context.accentColor, - fontWeight: FontWeight.bold, - fontSize: 16), - ), - ), - ), - ) - ], - ), - if (move > 0) - Positioned( - bottom: 120, - left: width / 2 - 100, - width: 200, - child: Center( - child: Transform.translate( - offset: Offset(0, -50 * move), - child: Text(s.goodNight, - style: TextStyle( - fontWeight: FontWeight.bold, - fontSize: 20, - color: Colors.white.withOpacity(move))), - ), - ), - ), - if (data.item2 == 1) CustomPaint(painter: StarSky()), - if (data.item2 == 1) MeteorLoader() - ], - ), - ); - }); - }, - ); - } -} - -class ControlPanel extends StatefulWidget { - ControlPanel( - {this.onExpand, - this.onClose, - this.maxHeight, - this.isPlayingPage = false, - Key key}) - : super(key: key); - final VoidCallback onExpand; - final VoidCallback onClose; - final double maxHeight; - final bool isPlayingPage; - @override - _ControlPanelState createState() => _ControlPanelState(); -} - -class _ControlPanelState extends State - with TickerProviderStateMixin { - double _setSpeed; - AnimationController _controller; - Animation _animation; - TabController _tabController; - int _tabIndex = 0; - List customShadow(double scale) => [ - BoxShadow( - blurRadius: 26 * (1 - scale), - offset: Offset(-6, -6) * (1 - scale), - color: Colors.white), - BoxShadow( - blurRadius: 8 * (1 - scale), - offset: Offset(2, 2) * (1 - scale), - color: Colors.grey[600].withOpacity(0.4)) - ]; - List customShadowNight(double scale) => [ - BoxShadow( - blurRadius: 6 * (1 - scale), - offset: Offset(-1, -1) * (1 - scale), - color: Colors.grey[100].withOpacity(0.3)), - BoxShadow( - blurRadius: 8 * (1 - scale), - offset: Offset(2, 2) * (1 - scale), - color: Colors.black) - ]; - - Future> _getSpeedList() async { - var storage = KeyValueStorage('speedListKey'); - return await storage.getSpeedList(); - } - - @override - void initState() { - _setSpeed = 0; - _tabController = TabController(vsync: this, length: 2) - ..addListener(() { - setState(() => _tabIndex = _tabController.index); - }); - _controller = - AnimationController(vsync: this, duration: Duration(milliseconds: 400)); - _animation = Tween(begin: 0.0, end: 1.0).animate(_controller) - ..addListener(() { - setState(() => _setSpeed = _animation.value); - }); - super.initState(); - } - - @override - void dispose() { - _controller.dispose(); - _tabController.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - var audio = Provider.of(context, listen: false); - return LayoutBuilder( - builder: (context, constraints) { - var height = constraints.maxHeight; - return Container( - color: context.primaryColor, - height: 300, - child: Column( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Consumer( - builder: (_, data, __) { - return Column( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Container( - padding: - EdgeInsets.only(top: 20, left: 30, right: 30), - child: SliderTheme( - data: SliderTheme.of(context).copyWith( - activeTrackColor: height <= widget.maxHeight - ? context.accentColor.withAlpha(70) - : Colors.transparent, - inactiveTrackColor: height > widget.maxHeight - ? Colors.transparent - : context.primaryColorDark, - trackHeight: 8.0, - trackShape: MyRectangularTrackShape(), - thumbColor: context.accentColor, - thumbShape: RoundSliderThumbShape( - enabledThumbRadius: 6.0, - disabledThumbRadius: 6.0, - ), - overlayColor: context.accentColor.withAlpha(32), - overlayShape: - RoundSliderOverlayShape(overlayRadius: 4.0), - ), - child: Slider( - value: data.seekSliderValue, - onChanged: (val) { - audio.sliderSeek(val); - }), - ), - ), - Container( - height: 20.0, - padding: EdgeInsets.symmetric(horizontal: 30.0), - child: height > widget.maxHeight - ? Center() - : Row( - children: [ - Text( - (data.backgroundAudioPosition ~/ 1000) - .toTime ?? - '', - style: TextStyle(fontSize: 10), - ), - Expanded( - child: Container( - alignment: Alignment.center, - child: data.remoteErrorMessage != null - ? Text(data.remoteErrorMessage, - style: const TextStyle( - color: Color(0xFFFF0000))) - : Text( - data.audioState == - AudioProcessingState - .buffering || - data.audioState == - AudioProcessingState - .connecting || - data.audioState == - AudioProcessingState - .none || - data.audioState == - AudioProcessingState - .skippingToNext - ? context.s.buffering - : '', - style: TextStyle( - color: context.accentColor), - ), - ), - ), - Text( - (data.backgroundAudioDuration ~/ 1000) - .toTime ?? - '', - style: TextStyle(fontSize: 10), - ), - ], - ), - ), - ], - ); - }, - ), - SizedBox( - height: 100, - child: Selector( - selector: (_, audio) => audio.playing, - builder: (_, playing, __) { - return Material( - color: Colors.transparent, - child: Row( - mainAxisSize: MainAxisSize.min, - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - FlatButton( - color: Colors.transparent, - padding: EdgeInsets.only(right: 10, left: 10), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(100.0), - side: BorderSide(color: Colors.transparent)), - onPressed: playing ? () => audio.rewind() : null, - child: Row( - children: [ - Icon(Icons.fast_rewind, - size: 32, color: Colors.grey[500]), - SizedBox(width: 5), - Selector( - selector: (_, audio) => - audio.rewindSeconds, - builder: (_, seconds, __) => Padding( - padding: - const EdgeInsets.only(top: 5.0), - child: Text('$seconds s', - style: GoogleFonts.teko( - textBaseline: - TextBaseline.ideographic, - textStyle: TextStyle( - color: Colors.grey[500], - fontSize: 25), - )), - )), - ], - ), - ), - Container( - margin: EdgeInsets.symmetric(horizontal: 30), - height: 60, - width: 60, - decoration: BoxDecoration( - color: context.primaryColor, - shape: BoxShape.circle, - border: Border.all( - color: - context.brightness == Brightness.dark - ? Colors.black12 - : Colors.white10, - width: 1), - boxShadow: - context.brightness == Brightness.dark - ? _customShadowNight - : _customShadow), - child: playing - ? Material( - color: Colors.transparent, - child: InkWell( - borderRadius: BorderRadius.all( - Radius.circular(30)), - onTap: playing - ? () { - audio.pauseAduio(); - } - : null, - child: SizedBox( - height: 60, - width: 60, - child: Icon( - Icons.pause, - size: 40, - ), - ), - ), - ) - : Material( - color: Colors.transparent, - child: InkWell( - borderRadius: BorderRadius.all( - Radius.circular(30)), - onTap: playing - ? null - : () { - audio.resumeAudio(); - }, - child: SizedBox( - height: 60, - width: 60, - child: Icon( - Icons.play_arrow, - size: 40, - color: context.accentColor, - ), - ), - ), - ), - ), - FlatButton( - padding: EdgeInsets.only(left: 10.0, right: 10), - onPressed: - playing ? () => audio.fastForward() : null, - color: Colors.transparent, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(100.0), - side: BorderSide(color: Colors.transparent)), - child: Row( - children: [ - Selector( - selector: (_, audio) => - audio.fastForwardSeconds, - builder: (_, seconds, __) => Padding( - padding: - const EdgeInsets.only(top: 5.0), - child: Text('$seconds s', - style: GoogleFonts.teko( - textStyle: TextStyle( - color: Colors.grey[500], - fontSize: 25), - )), - )), - SizedBox(width: 10), - Icon(Icons.fast_forward, - size: 32.0, color: Colors.grey[500]), - ], - ), - ) - ], - ), - ); - }, - ), - ), - SizedBox( - height: 80.0, - child: Column( - crossAxisAlignment: CrossAxisAlignment.center, - mainAxisSize: MainAxisSize.min, - children: [ - Expanded( - child: Selector( - selector: (_, audio) => audio.episode.title, - builder: (_, title, __) { - return Container( - padding: EdgeInsets.only(left: 60, right: 60), - child: LayoutBuilder( - builder: (context, size) { - var span = TextSpan( - text: title, - style: TextStyle( - fontWeight: FontWeight.bold, - fontSize: 20)); - var tp = TextPainter( - text: span, - maxLines: 1, - textDirection: TextDirection.ltr); - tp.layout(maxWidth: size.maxWidth); - if (tp.didExceedMaxLines) { - return Marquee( - text: title, - style: TextStyle( - fontWeight: FontWeight.bold, - fontSize: 18), - scrollAxis: Axis.horizontal, - crossAxisAlignment: - CrossAxisAlignment.start, - blankSpace: 30.0, - velocity: 50.0, - pauseAfterRound: Duration.zero, - startPadding: 30.0, - accelerationDuration: - Duration(milliseconds: 100), - accelerationCurve: Curves.linear, - decelerationDuration: - Duration(milliseconds: 100), - decelerationCurve: Curves.linear, - ); - } else { - return Text( - title, - style: TextStyle( - fontWeight: FontWeight.bold, - fontSize: 20), - ); - } - }, - ), - ); - }, - ), - ), - if (height <= widget.maxHeight) LastPosition() - ], - ), - ), - if (height > widget.maxHeight) - SizedBox( - height: height - widget.maxHeight, - child: SingleChildScrollView( - physics: NeverScrollableScrollPhysics(), - child: SizedBox( - height: 300, - child: ScrollConfiguration( - behavior: NoGrowBehavior(), - child: TabBarView( - controller: _tabController, - children: [ - Padding( - padding: const EdgeInsets.symmetric( - horizontal: 20.0), - child: PlaylistWidget(), - ), - Padding( - padding: const EdgeInsets.symmetric( - horizontal: 20.0), - child: SleepMode(), - ) - ]), - ))), - ), - Expanded( - child: Stack( - alignment: Alignment.center, - children: [ - if (height <= widget.maxHeight) - Selector>( - selector: (_, audio) => Tuple4( - audio.episode, - audio.stopOnComplete, - audio.startSleepTimer, - audio.currentSpeed), - builder: (_, data, __) { - final currentSpeed = data.item4 ?? 1.0; - return Container( - padding: - const EdgeInsets.symmetric(horizontal: 20.0), - child: Row( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - if (_setSpeed == 0) - Expanded( - child: InkWell( - onTap: () async { - widget.onClose(); - if (!widget.isPlayingPage) { - Navigator.push( - context, - FadeRoute( - page: EpisodeDetail( - episodeItem: data.item1, - heroTag: 'playpanel'))); - } - }, - child: Row( - children: [ - SizedBox( - height: 30.0, - width: 30.0, - child: CircleAvatar( - backgroundImage: - data.item1.avatarImage, - ), - ), - SizedBox(width: 5), - SizedBox( - width: 100, - child: Text( - data.item1.feedTitle, - maxLines: 1, - overflow: TextOverflow.fade, - ), - ), - ], - ), - ), - ), - if (_setSpeed > 0) - Expanded( - child: SingleChildScrollView( - padding: EdgeInsets.all(10.0), - scrollDirection: Axis.horizontal, - child: FutureBuilder>( - future: _getSpeedList(), - initialData: [], - builder: (context, snapshot) => Row( - children: snapshot.data - .map((e) => InkWell( - onTap: () { - if (_setSpeed == 1) { - audio.setSpeed(e); - } - }, - child: Container( - height: 30, - width: 30, - margin: EdgeInsets - .symmetric( - horizontal: 5), - decoration: e == - currentSpeed && - _setSpeed > 0 - ? BoxDecoration( - color: context - .accentColor, - shape: BoxShape - .circle, - boxShadow: context - .brightness == - Brightness - .light - ? customShadow( - 1.0) - : customShadowNight( - 1.0), - ) - : BoxDecoration( - color: context - .primaryColor, - shape: BoxShape - .circle, - boxShadow: context - .brightness == - Brightness - .light - ? customShadow(1 - - _setSpeed) - : customShadowNight(1 - - _setSpeed)), - alignment: - Alignment.center, - child: _setSpeed > 0 - ? Text(e.toString(), - style: TextStyle( - fontWeight: - FontWeight - .bold, - color: e == - currentSpeed - ? Colors - .white - : null)) - : Center(), - ), - )) - .toList(), - ), - ), - ), - ), - IconButton( - padding: EdgeInsets.zero, - onPressed: () { - if (_setSpeed == 0) { - _controller.forward(); - } else { - _controller.reverse(); - } - }, - icon: Row( - mainAxisAlignment: - MainAxisAlignment.spaceEvenly, - children: [ - Transform.rotate( - angle: math.pi * _setSpeed, - child: Text('X')), - Text(currentSpeed.toStringAsFixed(1)), - ], - ), - ), - ], - ), - ); - }, - ), - if (_setSpeed == 0) - Positioned( - bottom: widget.maxHeight == kMaxPlayerHeight[2] - ? 35.0 - : widget.maxHeight == kMaxPlayerHeight[1] - ? 25.0 - : 15.0, - child: InkWell( - child: SizedBox( - height: 50, - width: 100, - child: Align( - alignment: Alignment.bottomCenter, - child: CustomPaint( - size: Size(100, 5), - painter: TabIndicator( - index: _tabIndex, - indicatorSize: 20, - fraction: - (height - widget.maxHeight) / 300, - accentColor: context.accentColor, - color: context.textColor)), - ), - ), - onTap: widget.onExpand), - ), - if (_setSpeed == 0 && height > widget.maxHeight) - Transform.translate( - offset: - Offset(0, 5) * (height - widget.maxHeight) / 300, - child: Padding( - padding: EdgeInsets.symmetric( - horizontal: context.width / 2 - 80), - child: TabBar( - controller: _tabController, - indicatorSize: TabBarIndicatorSize.label, - labelColor: context.accentColor, - unselectedLabelColor: context.textColor, - indicator: BoxDecoration(), - tabs: [ - Container( - height: 20, - width: 20, - child: Icon(Icons.playlist_play)), - Container( - height: 20, - width: 20, - child: Transform.rotate( - angle: math.pi * 0.7, - child: Icon(Icons.brightness_2, - size: 18))), - ], - ), - ), - ), - ], - ), - ), - ]), - ); - }, - ); - } -} +import 'dart:io'; +import 'dart:math' as math; + +import 'package:audio_service/audio_service.dart'; +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:line_icons/line_icons.dart'; +import 'package:marquee/marquee.dart'; +import 'package:provider/provider.dart'; +import 'package:tuple/tuple.dart'; + +import '../episodes/episode_detail.dart'; +import '../local_storage/key_value_storage.dart'; +import '../local_storage/sqflite_localpodcast.dart'; +import '../state/audio_state.dart'; +import '../type/episodebrief.dart'; +import '../type/play_histroy.dart'; +import '../util/audiopanel.dart'; +import '../util/custom_slider.dart'; +import '../util/custom_widget.dart'; +import '../util/extension_helper.dart'; +import '../util/pageroute.dart'; +import 'playlist.dart'; + +final List _customShadow = [ + BoxShadow(blurRadius: 26, offset: Offset(-6, -6), color: Colors.white), + BoxShadow( + blurRadius: 8, + offset: Offset(2, 2), + color: Colors.grey[600].withOpacity(0.4)) +]; + +final List _customShadowNight = [ + BoxShadow( + blurRadius: 6, + offset: Offset(-1, -1), + color: Colors.grey[100].withOpacity(0.3)), + BoxShadow(blurRadius: 8, offset: Offset(2, 2), color: Colors.black) +]; + +const List kMinsToSelect = [10, 15, 20, 25, 30, 45, 60, 70, 80, 90, 99]; +const List kMinPlayerHeight = [70.0, 75.0, 80.0]; +const List kMaxPlayerHeight = [300.0, 325.0, 350.0]; + +class PlayerWidget extends StatelessWidget { + PlayerWidget({this.playerKey, this.isPlayingPage = false}); + final GlobalKey playerKey; + final bool isPlayingPage; + Widget _miniPanel(BuildContext context) { + var audio = Provider.of(context, listen: false); + final s = context.s; + return Container( + color: context.primaryColor, + height: 60, + child: + Column(mainAxisAlignment: MainAxisAlignment.start, children: [ + Selector>( + selector: (_, audio) => + Tuple2(audio.episode?.primaryColor, audio.seekSliderValue), + builder: (_, data, __) { + final c = context.brightness == Brightness.light + ? data.item1.colorizedark() + : data.item1.colorizeLight(); + return SizedBox( + height: 2, + child: LinearProgressIndicator( + value: data.item2, + backgroundColor: context.primaryColor, + valueColor: AlwaysStoppedAnimation(c), + ), + ); + }, + ), + Expanded( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 15), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Expanded( + flex: 4, + child: Selector( + selector: (_, audio) => audio.episode?.title, + builder: (_, title, __) { + return Text( + title, + style: TextStyle(fontWeight: FontWeight.bold), + maxLines: 2, + overflow: TextOverflow.clip, + ); + }, + ), + ), + Expanded( + flex: 2, + child: Selector>( + selector: (_, audio) => Tuple3( + audio.buffering, + (audio.backgroundAudioDuration - + audio.backgroundAudioPosition) / + 1000, + audio.remoteErrorMessage), + builder: (_, data, __) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 10), + child: data.item3 != null + ? Text(data.item3, + style: + const TextStyle(color: Color(0xFFFF0000))) + : data.item1 + ? Text( + s.buffering, + style: + TextStyle(color: context.accentColor), + ) + : Text( + s.timeLeft( + (data.item2).toInt().toTime ?? ''), + maxLines: 2, + ), + ); + }, + ), + ), + Expanded( + flex: 2, + child: Selector>( + selector: (_, audio) => + Tuple3(audio.buffering, audio.playing, audio.episode), + builder: (_, data, __) { + return Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + data.item1 + ? Stack( + alignment: Alignment.center, + children: [ + Padding( + padding: const EdgeInsets.symmetric( + vertical: 10.0), + child: SizedBox( + height: 30.0, + width: 30.0, + child: CircleAvatar( + backgroundColor: data.item3 + .backgroudColor(context), + backgroundImage: + data.item3.avatarImage, + ), + ), + ), + Container( + height: 40.0, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: Colors.black), + ), + ]) + : data.item2 + ? InkWell( + onTap: data.item2 + ? () => audio.pauseAduio() + : null, + child: + ImageRotate(episodeItem: data.item3), + ) + : InkWell( + onTap: data.item2 + ? null + : () => audio.resumeAudio(), + child: Stack( + alignment: Alignment.center, + children: [ + Padding( + padding: EdgeInsets.symmetric( + vertical: 10.0), + child: SizedBox( + height: 30.0, + width: 30.0, + child: CircleAvatar( + backgroundColor: data.item3 + .backgroudColor(context), + backgroundImage: + data.item3.avatarImage, + ), + ), + ), + Container( + height: 40.0, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: Colors.black), + ), + if (!data.item1) + Icon( + Icons.play_arrow, + color: Colors.white, + ) + ], + ), + ), + IconButton( + onPressed: () => audio.playNext(), + iconSize: 20.0, + icon: Icon(Icons.skip_next), + color: context.textColor) + ], + ); + }, + ), + ), + ], + ), + ), + ), + ]), + ); + } + + @override + Widget build(BuildContext context) { + return Selector>( + selector: (_, audio) => Tuple2(audio.playerRunning, audio?.playerHeight), + builder: (_, data, __) { + if (!data.item1) { + return Center(); + } else { + var minHeight = kMinPlayerHeight[data.item2.index]; + var maxHeight = kMaxPlayerHeight[data.item2.index]; + return AudioPanel( + minHeight: minHeight, + maxHeight: maxHeight, + key: playerKey, + miniPanel: _miniPanel(context), + expandedPanel: ControlPanel( + maxHeight: maxHeight, + isPlayingPage: isPlayingPage, + onExpand: () { + playerKey.currentState.scrollToTop(); + }, + onClose: () { + playerKey.currentState.backToMini(); + }, + )); + } + }, + ); + } +} + +class LastPosition extends StatelessWidget { + LastPosition({Key key}) : super(key: key); + + Future getPosition(EpisodeBrief episode) async { + var dbHelper = DBHelper(); + return await dbHelper.getPosition(episode); + } + + @override + Widget build(BuildContext context) { + final s = context.s; + var audio = Provider.of(context, listen: false); + return Selector( + selector: (_, audio) => audio.episode, + builder: (context, episode, child) { + return SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + mainAxisSize: MainAxisSize.min, + children: [ + Selector( + selector: (_, audio) => audio.skipSilence, + builder: (_, data, __) => FlatButton( + child: Row( + children: [ + Icon(Icons.flash_on, size: 18), + SizedBox(width: 5), + Text(s.skipSilence), + ], + ), + color: data ? context.accentColor : Colors.transparent, + padding: EdgeInsets.symmetric(horizontal: 10), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(100.0), + side: BorderSide( + color: data + ? context.accentColor + : Theme.of(context) + .colorScheme + .onSurface + .withOpacity(0.12))), + textColor: data ? Colors.white : null, + onPressed: () => + audio.setSkipSilence(skipSilence: !data))), + SizedBox(width: 10), + Selector( + selector: (_, audio) => audio.boostVolume, + builder: (_, data, __) => FlatButton( + child: Row( + children: [ + Icon(Icons.volume_up, size: 18), + SizedBox(width: 5), + Text(s.boostVolume), + ], + ), + color: data ? context.accentColor : Colors.transparent, + padding: EdgeInsets.symmetric(horizontal: 10), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(100.0), + side: BorderSide( + color: data + ? context.accentColor + : Theme.of(context) + .colorScheme + .onSurface + .withOpacity(0.12))), + textColor: data ? Colors.white : null, + onPressed: () => + audio.setBoostVolume(boostVolume: !data))), + SizedBox(width: 10), + FutureBuilder( + future: getPosition(episode), + builder: (context, snapshot) { + return snapshot.hasData + ? snapshot.data.seekValue > 0.90 + ? Container( + height: 20, + padding: EdgeInsets.symmetric(horizontal: 10), + child: SizedBox( + width: 20, + height: 20, + child: CustomPaint( + painter: ListenedAllPainter( + context.accentColor, + stroke: 2.0), + ), + ), + ) + : snapshot.data.seconds < 10 + ? Center() + : OutlineButton( + shape: RoundedRectangleBorder( + borderRadius: + BorderRadius.circular(100.0), + side: BorderSide( + color: context.accentColor)), + highlightedBorderColor: Colors.green[700], + onPressed: () => audio.seekTo( + (snapshot.data.seconds * 1000).toInt()), + child: Row( + children: [ + SizedBox( + width: 20, + height: 20, + child: CustomPaint( + painter: ListenedPainter( + context.textColor, + stroke: 2.0), + ), + ), + SizedBox(width: 5), + Text(snapshot.data.seconds.toTime), + ], + ), + ) + : Center(); + }), + Selector( + selector: (_, audio) => audio.switchValue, + builder: (_, data, __) => data == 1 + ? Container( + height: 20, + width: 40, + child: Transform.rotate( + angle: math.pi * 0.7, + child: Icon(Icons.brightness_2, + size: 18, color: context.accentColor))) + : Center(), + ) + ], + ), + ); + }, + ); + } +} + +class PlaylistWidget extends StatefulWidget { + const PlaylistWidget({Key key}) : super(key: key); + + @override + _PlaylistWidgetState createState() => _PlaylistWidgetState(); +} + +class _PlaylistWidgetState extends State { + final GlobalKey miniPlaylistKey = GlobalKey(); + + @override + Widget build(BuildContext context) { + var audio = Provider.of(context, listen: false); + return Container( + alignment: Alignment.topLeft, + height: 300, + width: double.infinity, + decoration: BoxDecoration( + color: context.accentColor.withAlpha(70), + borderRadius: BorderRadius.circular(10), + ), + child: Column( + children: [ + Expanded( + child: + Selector, bool>>( + selector: (_, audio) => + Tuple2(audio.queue.playlist, audio.queueUpdate), + builder: (_, data, __) { + var episodesToPlay = data.item1.sublist(1); + return AnimatedList( + key: miniPlaylistKey, + shrinkWrap: true, + scrollDirection: Axis.vertical, + initialItemCount: episodesToPlay.length, + itemBuilder: (context, index, animation) => ScaleTransition( + alignment: Alignment.center, + scale: animation, + child: Column( + children: [ + Row( + children: [ + Expanded( + child: Material( + color: Colors.transparent, + child: InkWell( + onTap: () { + audio.episodeLoad(data.item1[index]); + miniPlaylistKey.currentState.removeItem( + index, + (context, animation) => Center()); + }, + child: Container( + height: 60, + padding: + EdgeInsets.symmetric(horizontal: 20), + alignment: Alignment.centerLeft, + child: Row( + mainAxisAlignment: + MainAxisAlignment.center, + crossAxisAlignment: + CrossAxisAlignment.center, + mainAxisSize: MainAxisSize.min, + children: [ + Container( + padding: EdgeInsets.all(10.0), + child: ClipRRect( + borderRadius: BorderRadius.all( + Radius.circular(15.0)), + child: Container( + height: 30.0, + width: 30.0, + child: Image.file(File( + "${episodesToPlay[index].imagePath}"))), + ), + ), + Expanded( + child: Align( + alignment: Alignment.centerLeft, + child: Text( + episodesToPlay[index].title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + ), + ], + ), + ), + ), + ), + ), + Padding( + padding: + const EdgeInsets.symmetric(horizontal: 20.0), + child: Material( + borderRadius: BorderRadius.circular(100), + clipBehavior: Clip.hardEdge, + color: context.primaryColor, + child: InkWell( + borderRadius: + BorderRadius.all(Radius.circular(15.0)), + onTap: () async { + var episdoe = + episodesToPlay.removeAt(index); + episodesToPlay.insert(0, episdoe); + miniPlaylistKey.currentState.removeItem( + index, + (context, animation) { + return Center(); + }, + duration: Duration.zero, + ); + miniPlaylistKey.currentState.insertItem(0, + duration: Duration(milliseconds: 100)); + await Future.delayed( + Duration(milliseconds: 100)); + await audio + .moveToTop(data.item1[index + 1]); + }, + child: SizedBox( + height: 30.0, + width: 30.0, + child: Transform.rotate( + angle: math.pi, + child: Icon( + LineIcons.download_solid, + size: 20.0, + ), + ), + ), + ), + ), + ), + ], + ), + Divider(height: 1), + ], + ), + ), + ); + }, + ), + ), + SizedBox( + height: 60.0, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 20), + child: Row( + children: [ + Text( + context.s.homeMenuPlaylist, + style: TextStyle( + color: context.accentColor, + fontWeight: FontWeight.bold, + fontSize: 16), + ), + Spacer(), + Material( + borderRadius: BorderRadius.circular(100), + color: context.primaryColor, + child: InkWell( + borderRadius: BorderRadius.all(Radius.circular(15)), + onTap: () { + audio.playNext(); + miniPlaylistKey.currentState + .removeItem(0, (context, animation) => Container()); + miniPlaylistKey.currentState.insertItem(0); + }, + child: SizedBox( + height: 30, + width: 60, + child: Icon( + Icons.skip_next, + size: 30, + ), + ), + ), + ), + SizedBox(width: 20), + Material( + borderRadius: BorderRadius.circular(100), + color: context.primaryColor, + child: InkWell( + borderRadius: BorderRadius.circular(15.0), + onTap: () { + Navigator.push( + context, + SlideLeftRoute( + page: PlaylistPage( + initPage: InitPage.playlist, + )), + ); + }, + child: SizedBox( + height: 30.0, + width: 30.0, + child: Transform.rotate( + angle: math.pi, + child: Icon( + LineIcons.database_solid, + size: 20.0, + ), + ), + ), + ), + ), + ], + ), + ), + ), + ], + ), + ); + } +} + +class SleepMode extends StatefulWidget { + SleepMode({Key key}) : super(key: key); + + @override + SleepModeState createState() => SleepModeState(); +} + +class SleepModeState extends State + with SingleTickerProviderStateMixin { + int _minSelected; + AnimationController _controller; + Animation _animation; + Future _getDefaultTime() async { + var defaultSleepTimerStorage = KeyValueStorage(defaultSleepTimerKey); + var defaultTime = await defaultSleepTimerStorage.getInt(defaultValue: 30); + setState(() => _minSelected = defaultTime); + } + + @override + void initState() { + super.initState(); + _minSelected = 30; + _getDefaultTime(); + + _controller = + AnimationController(vsync: this, duration: Duration(milliseconds: 400)); + _animation = Tween(begin: 0.0, end: 1.0).animate(_controller) + ..addListener(() { + if (mounted) { + setState(() {}); + } + }); + + _controller.addStatusListener((status) { + if (status == AnimationStatus.completed) { + Provider.of(context, listen: false) + ..sleepTimer(_minSelected) + ..setSwitchValue = 1; + } + }); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + List customShadow(double scale) => [ + BoxShadow( + blurRadius: 26 * (1 - scale), + offset: Offset(-6, -6) * (1 - scale), + color: Colors.white), + BoxShadow( + blurRadius: 8 * (1 - scale), + offset: Offset(2, 2) * (1 - scale), + color: Colors.grey[600].withOpacity(0.4)) + ]; + List customShadowNight(double scale) => [ + BoxShadow( + blurRadius: 6 * (1 - scale), + offset: Offset(-1, -1) * (1 - scale), + color: Colors.grey[100].withOpacity(0.3)), + BoxShadow( + blurRadius: 8 * (1 - scale), + offset: Offset(2, 2) * (1 - scale), + color: Colors.black) + ]; + + @override + Widget build(BuildContext context) { + final s = context.s; + final _colorTween = + ColorTween(begin: context.accentColor.withAlpha(60), end: Colors.black); + var audio = Provider.of(context, listen: false); + return Selector>( + selector: (_, audio) => + Tuple3(audio?.timeLeft, audio?.switchValue, audio.sleepTimerMode), + builder: (_, data, __) { + var fraction = + data.item2 == 1 ? 1.0 : math.min(_animation.value * 2, 1.0); + var move = + data.item2 == 1 ? 1.0 : math.max(_animation.value * 2 - 1, 0.0); + return LayoutBuilder(builder: (context, constraints) { + var width = constraints.maxWidth; + return Container( + height: 300, + decoration: BoxDecoration( + color: _colorTween.transform(move), + borderRadius: BorderRadius.circular(10)), + child: Stack( + children: [ + Column( + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + SizedBox( + height: 10, + ), + Expanded( + child: Padding( + padding: EdgeInsets.symmetric(vertical: 20), + child: move == 1 + ? Center() + : Wrap( + direction: Axis.horizontal, + children: kMinsToSelect + .map((e) => InkWell( + onTap: () => + setState(() => _minSelected = e), + child: Container( + margin: EdgeInsets.all(10.0), + decoration: BoxDecoration( + color: (e == _minSelected) + ? context.accentColor + : context.primaryColor, + shape: BoxShape.circle, + ), + alignment: Alignment.center, + height: 30, + width: 30, + child: Text(e.toString(), + style: TextStyle( + fontWeight: FontWeight.bold, + color: (e == _minSelected) + ? Colors.white + : null)), + ), + )) + .toList(), + ), + ), + ), + Stack( + children: [ + SizedBox( + height: 100, + width: width, + ), + Positioned( + left: data.item3 == SleepTimerMode.timer + ? -width * (move) / 4 + : width * (move) / 4, + child: SizedBox( + height: 100, + width: width, + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Container( + alignment: Alignment.center, + height: 40, + width: 120, + decoration: BoxDecoration( + border: + Border.all(color: context.primaryColor), + color: _colorTween.transform(move), + borderRadius: BorderRadius.circular(20), + ), + child: Material( + color: Colors.transparent, + child: InkWell( + onTap: () { + audio.setSleepTimerMode = + SleepTimerMode.endOfEpisode; + if (fraction == 0) { + _controller.forward(); + } else if (fraction == 1) { + _controller.reverse(); + audio.cancelTimer(); + } + }, + borderRadius: BorderRadius.circular(20), + child: SizedBox( + height: 40, + width: 120, + child: Center( + child: Text( + s.endOfEpisode, + style: TextStyle( + color: (move > 0 + ? Colors.white + : null)), + ), + ), + ), + ), + ), + ), + Container( + height: 100 * (1 - fraction), + width: 1, + color: context.primaryColorDark, + ), + Container( + height: 40, + width: 120, + alignment: Alignment.center, + decoration: BoxDecoration( + border: + Border.all(color: context.primaryColor), + color: _colorTween.transform(move), + borderRadius: BorderRadius.circular(20), + ), + child: Material( + color: Colors.transparent, + child: InkWell( + onTap: () { + audio.setSleepTimerMode = + SleepTimerMode.timer; + if (fraction == 0) { + _controller.forward(); + } else if (fraction == 1) { + _controller.reverse(); + audio.cancelTimer(); + } + }, + borderRadius: BorderRadius.circular(20), + child: SizedBox( + height: 40, + width: 120, + child: Center( + child: Text( + data.item2 == 1 + ? data.item1.toTime + : (_minSelected * 60).toTime, + style: TextStyle( + color: (move > 0 + ? Colors.white + : null)), + ), + ), + ), + ), + ), + ) + ], + ), + ), + ), + ], + ), + SizedBox( + height: 60.0, + child: Padding( + padding: EdgeInsets.symmetric(horizontal: 20.0), + child: Align( + alignment: Alignment.centerLeft, + child: Text( + context.s.sleepTimer, + style: TextStyle( + color: context.accentColor, + fontWeight: FontWeight.bold, + fontSize: 16), + ), + ), + ), + ) + ], + ), + if (move > 0) + Positioned( + bottom: 120, + left: width / 2 - 100, + width: 200, + child: Center( + child: Transform.translate( + offset: Offset(0, -50 * move), + child: Text(s.goodNight, + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 20, + color: Colors.white.withOpacity(move))), + ), + ), + ), + if (data.item2 == 1) CustomPaint(painter: StarSky()), + if (data.item2 == 1) MeteorLoader() + ], + ), + ); + }); + }, + ); + } +} + +class ControlPanel extends StatefulWidget { + ControlPanel( + {this.onExpand, + this.onClose, + this.maxHeight, + this.isPlayingPage = false, + Key key}) + : super(key: key); + final VoidCallback onExpand; + final VoidCallback onClose; + final double maxHeight; + final bool isPlayingPage; + @override + _ControlPanelState createState() => _ControlPanelState(); +} + +class _ControlPanelState extends State + with TickerProviderStateMixin { + double _setSpeed; + AnimationController _controller; + Animation _animation; + TabController _tabController; + int _tabIndex = 0; + List customShadow(double scale) => [ + BoxShadow( + blurRadius: 26 * (1 - scale), + offset: Offset(-6, -6) * (1 - scale), + color: Colors.white), + BoxShadow( + blurRadius: 8 * (1 - scale), + offset: Offset(2, 2) * (1 - scale), + color: Colors.grey[600].withOpacity(0.4)) + ]; + List customShadowNight(double scale) => [ + BoxShadow( + blurRadius: 6 * (1 - scale), + offset: Offset(-1, -1) * (1 - scale), + color: Colors.grey[100].withOpacity(0.3)), + BoxShadow( + blurRadius: 8 * (1 - scale), + offset: Offset(2, 2) * (1 - scale), + color: Colors.black) + ]; + + Future> _getSpeedList() async { + var storage = KeyValueStorage('speedListKey'); + return await storage.getSpeedList(); + } + + @override + void initState() { + _setSpeed = 0; + _tabController = TabController(vsync: this, length: 2) + ..addListener(() { + setState(() => _tabIndex = _tabController.index); + }); + _controller = + AnimationController(vsync: this, duration: Duration(milliseconds: 400)); + _animation = Tween(begin: 0.0, end: 1.0).animate(_controller) + ..addListener(() { + setState(() => _setSpeed = _animation.value); + }); + super.initState(); + } + + @override + void dispose() { + _controller.dispose(); + _tabController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + var audio = Provider.of(context, listen: false); + return LayoutBuilder( + builder: (context, constraints) { + var height = constraints.maxHeight; + return Container( + color: context.primaryColor, + height: 300, + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Consumer( + builder: (_, data, __) { + return Column( + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Container( + padding: + EdgeInsets.only(top: 20, left: 30, right: 30), + child: SliderTheme( + data: SliderTheme.of(context).copyWith( + activeTrackColor: height <= widget.maxHeight + ? context.accentColor.withAlpha(70) + : Colors.transparent, + inactiveTrackColor: height > widget.maxHeight + ? Colors.transparent + : context.primaryColorDark, + trackHeight: 8.0, + trackShape: MyRectangularTrackShape(), + thumbColor: context.accentColor, + thumbShape: RoundSliderThumbShape( + enabledThumbRadius: 6.0, + disabledThumbRadius: 6.0, + ), + overlayColor: context.accentColor.withAlpha(32), + overlayShape: + RoundSliderOverlayShape(overlayRadius: 4.0), + ), + child: Slider( + value: data.seekSliderValue, + onChanged: (val) { + audio.sliderSeek(val); + }), + ), + ), + Container( + height: 20.0, + padding: EdgeInsets.symmetric(horizontal: 30.0), + child: height > widget.maxHeight + ? Center() + : Row( + children: [ + Text( + (data.backgroundAudioPosition ~/ 1000) + .toTime ?? + '', + style: TextStyle(fontSize: 10), + ), + Expanded( + child: Container( + alignment: Alignment.center, + child: data.remoteErrorMessage != null + ? Text(data.remoteErrorMessage, + style: const TextStyle( + color: Color(0xFFFF0000))) + : Text( + data.audioState == + AudioProcessingState + .buffering || + data.audioState == + AudioProcessingState + .connecting || + data.audioState == + AudioProcessingState + .none || + data.audioState == + AudioProcessingState + .skippingToNext + ? context.s.buffering + : '', + style: TextStyle( + color: context.accentColor), + ), + ), + ), + Text( + (data.backgroundAudioDuration ~/ 1000) + .toTime ?? + '', + style: TextStyle(fontSize: 10), + ), + ], + ), + ), + ], + ); + }, + ), + SizedBox( + height: 100, + child: Selector( + selector: (_, audio) => audio.playing, + builder: (_, playing, __) { + return Material( + color: Colors.transparent, + child: Row( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + FlatButton( + color: Colors.transparent, + padding: EdgeInsets.only(right: 10, left: 10), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(100.0), + side: BorderSide(color: Colors.transparent)), + onPressed: playing ? () => audio.rewind() : null, + child: Row( + children: [ + Icon(Icons.fast_rewind, + size: 32, color: Colors.grey[500]), + SizedBox(width: 5), + Selector( + selector: (_, audio) => + audio.rewindSeconds, + builder: (_, seconds, __) => Padding( + padding: + const EdgeInsets.only(top: 5.0), + child: Text('$seconds s', + style: GoogleFonts.teko( + textBaseline: + TextBaseline.ideographic, + textStyle: TextStyle( + color: Colors.grey[500], + fontSize: 25), + )), + )), + ], + ), + ), + Container( + margin: EdgeInsets.symmetric(horizontal: 30), + height: 60, + width: 60, + decoration: BoxDecoration( + color: context.primaryColor, + shape: BoxShape.circle, + border: Border.all( + color: + context.brightness == Brightness.dark + ? Colors.black12 + : Colors.white10, + width: 1), + boxShadow: + context.brightness == Brightness.dark + ? _customShadowNight + : _customShadow), + child: playing + ? Material( + color: Colors.transparent, + child: InkWell( + borderRadius: BorderRadius.all( + Radius.circular(30)), + onTap: playing + ? () { + audio.pauseAduio(); + } + : null, + child: SizedBox( + height: 60, + width: 60, + child: Icon( + Icons.pause, + size: 40, + ), + ), + ), + ) + : Material( + color: Colors.transparent, + child: InkWell( + borderRadius: BorderRadius.all( + Radius.circular(30)), + onTap: playing + ? null + : () { + audio.resumeAudio(); + }, + child: SizedBox( + height: 60, + width: 60, + child: Icon( + Icons.play_arrow, + size: 40, + color: context.accentColor, + ), + ), + ), + ), + ), + FlatButton( + padding: EdgeInsets.only(left: 10.0, right: 10), + onPressed: + playing ? () => audio.fastForward() : null, + color: Colors.transparent, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(100.0), + side: BorderSide(color: Colors.transparent)), + child: Row( + children: [ + Selector( + selector: (_, audio) => + audio.fastForwardSeconds, + builder: (_, seconds, __) => Padding( + padding: + const EdgeInsets.only(top: 5.0), + child: Text('$seconds s', + style: GoogleFonts.teko( + textStyle: TextStyle( + color: Colors.grey[500], + fontSize: 25), + )), + )), + SizedBox(width: 10), + Icon(Icons.fast_forward, + size: 32.0, color: Colors.grey[500]), + ], + ), + ) + ], + ), + ); + }, + ), + ), + SizedBox( + height: 80.0, + child: Column( + crossAxisAlignment: CrossAxisAlignment.center, + mainAxisSize: MainAxisSize.min, + children: [ + Expanded( + child: Selector( + selector: (_, audio) => audio.episode.title, + builder: (_, title, __) { + return Container( + padding: EdgeInsets.only(left: 60, right: 60), + child: LayoutBuilder( + builder: (context, size) { + var span = TextSpan( + text: title, + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 20)); + var tp = TextPainter( + text: span, + maxLines: 1, + textDirection: TextDirection.ltr); + tp.layout(maxWidth: size.maxWidth); + if (tp.didExceedMaxLines) { + return Marquee( + text: title, + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 18), + scrollAxis: Axis.horizontal, + crossAxisAlignment: + CrossAxisAlignment.start, + blankSpace: 30.0, + velocity: 50.0, + pauseAfterRound: Duration.zero, + startPadding: 30.0, + accelerationDuration: + Duration(milliseconds: 100), + accelerationCurve: Curves.linear, + decelerationDuration: + Duration(milliseconds: 100), + decelerationCurve: Curves.linear, + ); + } else { + return Text( + title, + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 20), + ); + } + }, + ), + ); + }, + ), + ), + if (height <= widget.maxHeight) LastPosition() + ], + ), + ), + if (height > widget.maxHeight) + SizedBox( + height: height - widget.maxHeight, + child: SingleChildScrollView( + physics: NeverScrollableScrollPhysics(), + child: SizedBox( + height: 300, + child: ScrollConfiguration( + behavior: NoGrowBehavior(), + child: TabBarView( + controller: _tabController, + children: [ + Padding( + padding: const EdgeInsets.symmetric( + horizontal: 20.0), + child: PlaylistWidget(), + ), + Padding( + padding: const EdgeInsets.symmetric( + horizontal: 20.0), + child: SleepMode(), + ) + ]), + ))), + ), + Expanded( + child: Stack( + alignment: Alignment.center, + children: [ + if (height <= widget.maxHeight) + Selector>( + selector: (_, audio) => Tuple4( + audio.episode, + audio.stopOnComplete, + audio.startSleepTimer, + audio.currentSpeed), + builder: (_, data, __) { + final currentSpeed = data.item4 ?? 1.0; + return Container( + padding: + const EdgeInsets.symmetric(horizontal: 20.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + if (_setSpeed == 0) + Expanded( + child: InkWell( + onTap: () async { + widget.onClose(); + if (!widget.isPlayingPage) { + Navigator.push( + context, + FadeRoute( + page: EpisodeDetail( + episodeItem: data.item1, + heroTag: 'playpanel'))); + } + }, + child: Row( + children: [ + SizedBox( + height: 30.0, + width: 30.0, + child: CircleAvatar( + backgroundImage: + data.item1.avatarImage, + ), + ), + SizedBox(width: 5), + SizedBox( + width: 100, + child: Text( + data.item1.feedTitle, + maxLines: 1, + overflow: TextOverflow.fade, + ), + ), + ], + ), + ), + ), + if (_setSpeed > 0) + Expanded( + child: SingleChildScrollView( + padding: EdgeInsets.all(10.0), + scrollDirection: Axis.horizontal, + child: FutureBuilder>( + future: _getSpeedList(), + initialData: [], + builder: (context, snapshot) => Row( + children: snapshot.data + .map((e) => InkWell( + onTap: () { + if (_setSpeed == 1) { + audio.setSpeed(e); + } + }, + child: Container( + height: 30, + width: 30, + margin: EdgeInsets + .symmetric( + horizontal: 5), + decoration: e == + currentSpeed && + _setSpeed > 0 + ? BoxDecoration( + color: context + .accentColor, + shape: BoxShape + .circle, + boxShadow: context + .brightness == + Brightness + .light + ? customShadow( + 1.0) + : customShadowNight( + 1.0), + ) + : BoxDecoration( + color: context + .primaryColor, + shape: BoxShape + .circle, + boxShadow: context + .brightness == + Brightness + .light + ? customShadow(1 - + _setSpeed) + : customShadowNight(1 - + _setSpeed)), + alignment: + Alignment.center, + child: _setSpeed > 0 + ? Text(e.toString(), + style: TextStyle( + fontWeight: + FontWeight + .bold, + color: e == + currentSpeed + ? Colors + .white + : null)) + : Center(), + ), + )) + .toList(), + ), + ), + ), + ), + IconButton( + padding: EdgeInsets.zero, + onPressed: () { + if (_setSpeed == 0) { + _controller.forward(); + } else { + _controller.reverse(); + } + }, + icon: Row( + mainAxisAlignment: + MainAxisAlignment.spaceEvenly, + children: [ + Transform.rotate( + angle: math.pi * _setSpeed, + child: Text('X')), + Text(currentSpeed.toStringAsFixed(1)), + ], + ), + ), + ], + ), + ); + }, + ), + if (_setSpeed == 0) + Positioned( + bottom: widget.maxHeight == kMaxPlayerHeight[2] + ? 35.0 + : widget.maxHeight == kMaxPlayerHeight[1] + ? 25.0 + : 15.0, + child: InkWell( + child: SizedBox( + height: 50, + width: 100, + child: Align( + alignment: Alignment.bottomCenter, + child: CustomPaint( + size: Size(100, 5), + painter: TabIndicator( + index: _tabIndex, + indicatorSize: 20, + fraction: + (height - widget.maxHeight) / 300, + accentColor: context.accentColor, + color: context.textColor)), + ), + ), + onTap: widget.onExpand), + ), + if (_setSpeed == 0 && height > widget.maxHeight) + Transform.translate( + offset: + Offset(0, 5) * (height - widget.maxHeight) / 300, + child: Padding( + padding: EdgeInsets.symmetric( + horizontal: context.width / 2 - 80), + child: TabBar( + controller: _tabController, + indicatorSize: TabBarIndicatorSize.label, + labelColor: context.accentColor, + unselectedLabelColor: context.textColor, + indicator: BoxDecoration(), + tabs: [ + Container( + height: 20, + width: 20, + child: Icon(Icons.playlist_play)), + Container( + height: 20, + width: 20, + child: Transform.rotate( + angle: math.pi * 0.7, + child: Icon(Icons.brightness_2, + size: 18))), + ], + ), + ), + ), + ], + ), + ), + ]), + ); + }, + ); + } +} diff --git a/lib/home/download_list.dart b/lib/home/download_list.dart index e5100a4..e143486 100644 --- a/lib/home/download_list.dart +++ b/lib/home/download_list.dart @@ -1,154 +1,154 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_downloader/flutter_downloader.dart'; -import 'package:provider/provider.dart'; - -import '../episodes/episode_detail.dart'; -import '../state/download_state.dart'; -import '../type/episode_task.dart'; -import '../util/pageroute.dart'; - -class DownloadList extends StatefulWidget { - DownloadList({Key key}) : super(key: key); - - @override - _DownloadListState createState() => _DownloadListState(); -} - -Widget _downloadButton(EpisodeTask task, BuildContext context) { - var downloader = Provider.of(context, listen: false); - switch (task.status.value) { - case 2: - return Row( - mainAxisSize: MainAxisSize.min, - children: [ - IconButton( - icon: Icon( - Icons.pause_circle_filled, - ), - onPressed: () => downloader.pauseTask(task.episode), - ), - IconButton( - icon: Icon(Icons.close), - onPressed: () => downloader.delTask(task.episode), - ), - ], - ); - case 4: - return Row( - mainAxisSize: MainAxisSize.min, - children: [ - IconButton( - icon: Icon(Icons.refresh, color: Colors.red), - onPressed: () => downloader.retryTask(task.episode), - ), - IconButton( - icon: Icon(Icons.close), - onPressed: () => downloader.delTask(task.episode), - ), - ], - ); - case 6: - return Row(mainAxisSize: MainAxisSize.min, children: [ - IconButton( - icon: Icon(Icons.play_circle_filled), - onPressed: () => downloader.resumeTask(task.episode), - ), - IconButton( - icon: Icon(Icons.close), - onPressed: () => downloader.delTask(task.episode), - ), - ]); - break; - default: - return SizedBox( - width: 10, - height: 10, - ); - } -} - -class _DownloadListState extends State { - @override - Widget build(BuildContext context) { - return Consumer(builder: (_, downloader, __) { - final tasks = downloader.episodeTasks - .where((task) => task.status.value != 3) - .toList(); - return tasks.length > 0 - ? SliverPadding( - padding: EdgeInsets.symmetric(vertical: 5.0), - sliver: SliverList( - delegate: SliverChildBuilderDelegate( - (context, index) { - return ListTile( - onTap: () => Navigator.push( - context, - ScaleRoute( - page: EpisodeDetail( - episodeItem: tasks[index].episode, - )), - ), - title: SizedBox( - height: 40, - child: Row( - mainAxisSize: MainAxisSize.min, - mainAxisAlignment: MainAxisAlignment.start, - children: [ - Expanded( - flex: 5, - child: Text( - tasks[index].episode.title, - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - ), - Expanded( - flex: 1, - child: tasks[index].progress >= 0 && - tasks[index].status != - DownloadTaskStatus.failed - ? Container( - width: 40.0, - height: 20.0, - padding: - EdgeInsets.symmetric(horizontal: 2), - alignment: Alignment.center, - decoration: BoxDecoration( - borderRadius: BorderRadius.all( - Radius.circular(6)), - color: Colors.red), - child: Text( - '${tasks[index].progress}%', - textAlign: TextAlign.center, - maxLines: 1, - style: TextStyle(color: Colors.white), - )) - : Container( - height: 40, - ), - ), - ], - ), - ), - subtitle: SizedBox( - height: 2, - child: LinearProgressIndicator( - value: tasks[index].progress / 100, - ), - ), - leading: CircleAvatar( - radius: 20, - backgroundImage: tasks[index].episode.avatarImage), - trailing: _downloadButton(tasks[index], context), - ); - }, - childCount: tasks.length, - ), - ), - ) - : SliverToBoxAdapter( - child: Center(), - ); - }); - } -} +import 'package:flutter/material.dart'; +import 'package:flutter_downloader/flutter_downloader.dart'; +import 'package:provider/provider.dart'; + +import '../episodes/episode_detail.dart'; +import '../state/download_state.dart'; +import '../type/episode_task.dart'; +import '../util/pageroute.dart'; + +class DownloadList extends StatefulWidget { + DownloadList({Key key}) : super(key: key); + + @override + _DownloadListState createState() => _DownloadListState(); +} + +Widget _downloadButton(EpisodeTask task, BuildContext context) { + var downloader = Provider.of(context, listen: false); + switch (task.status.value) { + case 2: + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + icon: Icon( + Icons.pause_circle_filled, + ), + onPressed: () => downloader.pauseTask(task.episode), + ), + IconButton( + icon: Icon(Icons.close), + onPressed: () => downloader.delTask(task.episode), + ), + ], + ); + case 4: + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + icon: Icon(Icons.refresh, color: Colors.red), + onPressed: () => downloader.retryTask(task.episode), + ), + IconButton( + icon: Icon(Icons.close), + onPressed: () => downloader.delTask(task.episode), + ), + ], + ); + case 6: + return Row(mainAxisSize: MainAxisSize.min, children: [ + IconButton( + icon: Icon(Icons.play_circle_filled), + onPressed: () => downloader.resumeTask(task.episode), + ), + IconButton( + icon: Icon(Icons.close), + onPressed: () => downloader.delTask(task.episode), + ), + ]); + break; + default: + return SizedBox( + width: 10, + height: 10, + ); + } +} + +class _DownloadListState extends State { + @override + Widget build(BuildContext context) { + return Consumer(builder: (_, downloader, __) { + final tasks = downloader.episodeTasks + .where((task) => task.status.value != 3) + .toList(); + return tasks.length > 0 + ? SliverPadding( + padding: EdgeInsets.symmetric(vertical: 5.0), + sliver: SliverList( + delegate: SliverChildBuilderDelegate( + (context, index) { + return ListTile( + onTap: () => Navigator.push( + context, + ScaleRoute( + page: EpisodeDetail( + episodeItem: tasks[index].episode, + )), + ), + title: SizedBox( + height: 40, + child: Row( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.start, + children: [ + Expanded( + flex: 5, + child: Text( + tasks[index].episode.title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + Expanded( + flex: 1, + child: tasks[index].progress >= 0 && + tasks[index].status != + DownloadTaskStatus.failed + ? Container( + width: 40.0, + height: 20.0, + padding: + EdgeInsets.symmetric(horizontal: 2), + alignment: Alignment.center, + decoration: BoxDecoration( + borderRadius: BorderRadius.all( + Radius.circular(6)), + color: Colors.red), + child: Text( + '${tasks[index].progress}%', + textAlign: TextAlign.center, + maxLines: 1, + style: TextStyle(color: Colors.white), + )) + : Container( + height: 40, + ), + ), + ], + ), + ), + subtitle: SizedBox( + height: 2, + child: LinearProgressIndicator( + value: tasks[index].progress / 100, + ), + ), + leading: CircleAvatar( + radius: 20, + backgroundImage: tasks[index].episode.avatarImage), + trailing: _downloadButton(tasks[index], context), + ); + }, + childCount: tasks.length, + ), + ), + ) + : SliverToBoxAdapter( + child: Center(), + ); + }); + } +} diff --git a/lib/home/home.dart b/lib/home/home.dart index df4fcfc..a7481cd 100644 --- a/lib/home/home.dart +++ b/lib/home/home.dart @@ -1,1563 +1,1563 @@ -import 'dart:async'; -import 'dart:io'; - -import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart'; -import 'package:feature_discovery/feature_discovery.dart'; -import 'package:flutter/material.dart' hide NestedScrollView; -import 'package:flutter/services.dart'; -import 'package:fluttertoast/fluttertoast.dart'; -import 'package:line_icons/line_icons.dart'; -import 'package:provider/provider.dart'; -import 'package:tuple/tuple.dart'; - -import '../local_storage/key_value_storage.dart'; -import '../local_storage/sqflite_localpodcast.dart'; -import '../state/audio_state.dart'; -import '../state/download_state.dart'; -import '../state/podcast_group.dart'; -import '../state/refresh_podcast.dart'; -import '../state/setting_state.dart'; -import '../type/episodebrief.dart'; -import '../type/playlist.dart'; -import '../util/audiopanel.dart'; -import '../util/custom_popupmenu.dart'; -import '../util/custom_widget.dart'; -import '../util/episodegrid.dart'; -import '../util/extension_helper.dart'; -import '../util/muiliselect_bar.dart'; -import 'audioplayer.dart'; -import 'download_list.dart'; -import 'home_groups.dart'; -import 'home_menu.dart'; -import 'import_ompl.dart'; -import 'playlist.dart'; -import 'search_podcast.dart'; - -const String addFeature = 'addFeature'; -const String menuFeature = 'menuFeature'; -const String playlistFeature = 'playlistFeature'; -const String longTapFeature = 'longTapFeature'; -const String groupsFeature = 'groupsFeature'; -const String podcastFeature = 'podcastFeature'; - -class Home extends StatefulWidget { - @override - _HomeState createState() => _HomeState(); -} - -class _HomeState extends State with SingleTickerProviderStateMixin { - final GlobalKey _scaffoldKey = GlobalKey(); - final GlobalKey _playerKey = GlobalKey(); - TabController _controller; - Decoration _getIndicator(BuildContext context) { - return UnderlineTabIndicator( - borderSide: BorderSide(color: Theme.of(context).accentColor, width: 3), - insets: EdgeInsets.only( - left: 10.0, - right: 10.0, - top: 10.0, - )); - } - - final _androidAppRetain = MethodChannel("android_app_retain"); - var feature1OverflowMode = OverflowMode.clipContent; - var feature1EnablePulsingAnimation = false; - - @override - void initState() { - super.initState(); - _controller = TabController(length: 3, vsync: this); - FeatureDiscovery.isDisplayed(context, addFeature).then((value) { - if (!value) { - WidgetsBinding.instance.addPostFrameCallback((_) { - FeatureDiscovery.discoverFeatures( - context, - const { - addFeature, - menuFeature, - playlistFeature, - groupsFeature, - podcastFeature, - }, - ); - }); - } - }); - } - - @override - void dispose() { - _controller.dispose(); - super.dispose(); - } - - double top = 0; - @override - Widget build(BuildContext context) { - var width = MediaQuery.of(context).size.width; - var height = (width - 20) / 3 + 140; - var settings = Provider.of(context, listen: false); - final s = context.s; - return AnnotatedRegion( - value: SystemUiOverlayStyle( - systemNavigationBarIconBrightness: - Theme.of(context).accentColorBrightness, - statusBarIconBrightness: Theme.of(context).accentColorBrightness, - systemNavigationBarColor: Theme.of(context).primaryColor, - ), - child: Scaffold( - key: _scaffoldKey, - body: WillPopScope( - onWillPop: () async { - if (_playerKey.currentState != null && - _playerKey.currentState.initSize > 100) { - _playerKey.currentState.backToMini(); - return false; - } else if (Platform.isAndroid) { - _androidAppRetain.invokeMethod('sendToBackground'); - return false; - } else { - return true; - } - }, - child: SafeArea( - child: Stack( - children: [ - Column( - children: [ - Expanded( - child: NestedScrollView( - innerScrollPositionKeyBuilder: () { - return Key('tab${_controller.index}'); - }, - pinnedHeaderSliverHeightBuilder: () => 50, - headerSliverBuilder: (context, innerBoxScrolled) { - return [ - SliverToBoxAdapter( - child: Column( - children: [ - SizedBox( - height: 50.0, - child: Row( - mainAxisAlignment: - MainAxisAlignment.spaceBetween, - children: [ - DescribedFeatureOverlay( - featureId: addFeature, - tapTarget: - Icon(Icons.add_circle_outline), - title: Text(s.featureDiscoverySearch), - backgroundColor: Colors.cyan[600], - overflowMode: feature1OverflowMode, - onDismiss: () { - return Future.value(true); - }, - description: Column( - crossAxisAlignment: - CrossAxisAlignment.start, - children: [ - Text(s.featureDiscoverySearchDes), - FlatButton( - color: Colors.cyan[500], - padding: - const EdgeInsets.all(0), - child: Text(s.understood, - style: context - .textTheme.button - .copyWith( - color: - Colors.white)), - onPressed: () async => - FeatureDiscovery - .completeCurrentStep( - context), - ), - FlatButton( - color: Colors.cyan[500], - padding: - const EdgeInsets.all(0), - child: Text(s.dismiss, - style: Theme.of(context) - .textTheme - .button - .copyWith( - color: - Colors.white)), - onPressed: () => - FeatureDiscovery.dismissAll( - context), - ), - ], - ), - child: IconButton( - tooltip: s.add, - splashRadius: 25, - icon: const Icon( - Icons.add_circle_outline), - onPressed: () async { - await showSearch( - context: context, - delegate: MyHomePageDelegate( - searchFieldLabel: - s.searchPodcast), - ); - }, - ), - ), - GestureDetector( - onTap: () => { - Theme.of(context).brightness == - Brightness.light - ? settings.setTheme = - ThemeMode.dark - : settings.setTheme = - ThemeMode.light - }, - child: Image( - image: Theme.of(context) - .brightness == - Brightness.light - ? AssetImage('assets/text.png') - : AssetImage( - 'assets/text_light.png'), - height: 30, - ), - ), - DescribedFeatureOverlay( - featureId: menuFeature, - tapTarget: Icon(Icons.more_vert), - backgroundColor: Colors.cyan[500], - onDismiss: () => Future.value(true), - title: Text(s.featureDiscoveryOMPL), - description: Column( - crossAxisAlignment: - CrossAxisAlignment.end, - children: [ - Text(s.featureDiscoveryOMPLDes), - FlatButton( - color: Colors.cyan[600], - padding: EdgeInsets.zero, - child: Text(s.understood, - style: Theme.of(context) - .textTheme - .button - .copyWith( - color: Colors - .white)), - onPressed: () async => - FeatureDiscovery - .completeCurrentStep( - context), - ), - FlatButton( - color: Colors.cyan[600], - padding: - const EdgeInsets.all(0), - child: Text(s.dismiss, - style: Theme.of(context) - .textTheme - .button - .copyWith( - color: Colors - .white)), - onPressed: () => - FeatureDiscovery - .dismissAll(context), - ), - ], - ), - child: PopupMenu()), - ], - ), - ), - Import(), - ], - ), - ), - SliverList( - delegate: SliverChildBuilderDelegate( - (context, index) { - return DescribedFeatureOverlay( - featureId: groupsFeature, - tapTarget: Center( - child: Text( - s.featureDiscoveryPodcast, - textAlign: TextAlign.center, - )), - backgroundColor: Colors.cyan[500], - enablePulsingAnimation: false, - onDismiss: () => Future.value(true), - title: Text(s.featureDiscoveryPodcastTitle), - description: Column( - crossAxisAlignment: - CrossAxisAlignment.start, - children: [ - Text(s.featureDiscoveryPodcastDes), - Row( - children: [ - FlatButton( - color: Colors.cyan[600], - padding: const EdgeInsets.all(0), - child: Text(s.understood, - style: Theme.of(context) - .textTheme - .button - .copyWith( - color: Colors.white)), - onPressed: () async => - FeatureDiscovery - .completeCurrentStep( - context), - ), - Padding( - padding: EdgeInsets.symmetric( - horizontal: 5)), - FlatButton( - color: Colors.cyan[600], - padding: const EdgeInsets.all(0), - child: Text(s.dismiss, - style: context - .textTheme.button - .copyWith( - color: Colors.white)), - onPressed: () => - FeatureDiscovery.dismissAll( - context), - ), - ], - ), - ], - ), - child: SizedBox( - height: height, - width: width, - child: ScrollPodcasts(), - ), - ); - }, - childCount: 1, - ), - ), - SliverPersistentHeader( - delegate: _SliverAppBarDelegate( - TabBar( - indicator: _getIndicator(context), - isScrollable: true, - indicatorSize: TabBarIndicatorSize.tab, - controller: _controller, - tabs: [ - Tab( - child: Text(s.homeTabMenuRecent), - ), - Tab( - child: Text(s.homeTabMenuFavotite), - ), - Tab( - child: Text(s.download), - ) - ], - ), - ), - pinned: true, - ), - ]; - }, - body: TabBarView( - controller: _controller, - children: [ - NestedScrollViewInnerScrollPositionKeyWidget( - Key('tab0'), - DescribedFeatureOverlay( - featureId: podcastFeature, - tapTarget: Text(s.featureDiscoveryEpisode, - textAlign: TextAlign.center), - backgroundColor: Colors.cyan[500], - enablePulsingAnimation: false, - onDismiss: () => Future.value(true), - title: Text(s.featureDiscoveryEpisodeTitle), - description: Column( - crossAxisAlignment: - CrossAxisAlignment.start, - children: [ - Text(s.featureDiscoveryEpisodeDes), - Row( - children: [ - FlatButton( - color: Colors.cyan[600], - padding: const EdgeInsets.all(0), - child: Text(s.understood, - style: Theme.of(context) - .textTheme - .button - .copyWith( - color: Colors.white)), - onPressed: () async => - FeatureDiscovery - .completeCurrentStep( - context), - ), - Padding( - padding: EdgeInsets.symmetric( - horizontal: 5)), - FlatButton( - color: Colors.cyan[600], - padding: const EdgeInsets.all(0), - child: Text(s.dismiss, - style: Theme.of(context) - .textTheme - .button - .copyWith( - color: Colors.white)), - onPressed: () => - FeatureDiscovery.dismissAll( - context), - ), - ], - ), - ], - ), - child: _RecentUpdate())), - NestedScrollViewInnerScrollPositionKeyWidget( - Key('tab1'), _MyFavorite()), - NestedScrollViewInnerScrollPositionKeyWidget( - Key('tab2'), _MyDownload()), - ], - ), - ), - ), - Selector( - selector: (_, audio) => audio.playerRunning, - builder: (_, data, __) { - return Padding( - padding: EdgeInsets.only(bottom: data ? 60.0 : 0), - ); - }), - ], - ), - Container(child: PlayerWidget(playerKey: _playerKey)), - ], - ), - ), - ), - ), - ); - } -} - -class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate { - _SliverAppBarDelegate(this._tabBar); - final TabBar _tabBar; - - @override - double get minExtent => _tabBar.preferredSize.height + 2; - @override - double get maxExtent => _tabBar.preferredSize.height + 2; - - @override - Widget build( - BuildContext context, double shrinkOffset, bool overlapsContent) { - final s = context.s; - return Container( - color: context.scaffoldBackgroundColor, - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - mainAxisAlignment: MainAxisAlignment.start, - children: [ - _tabBar, - Spacer(), - DescribedFeatureOverlay( - featureId: playlistFeature, - tapTarget: Icon(Icons.playlist_play), - backgroundColor: Colors.cyan[500], - title: Text(s.featureDiscoveryPlaylist), - onDismiss: () => Future.value(true), - description: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(s.featureDiscoveryPlaylistDes), - FlatButton( - color: Colors.cyan[600], - padding: const EdgeInsets.all(0), - child: Text(s.understood, - style: Theme.of(context) - .textTheme - .button - .copyWith(color: Colors.white)), - onPressed: () async => - FeatureDiscovery.completeCurrentStep(context), - ), - FlatButton( - color: Colors.cyan[600], - padding: const EdgeInsets.all(0), - child: Text(s.dismiss, - style: Theme.of(context) - .textTheme - .button - .copyWith(color: Colors.white)), - onPressed: () => FeatureDiscovery.dismissAll(context), - ), - ], - ), - child: _PlaylistButton()), - ], - ), - Container(height: 2, color: context.primaryColor), - ], - ), - ); - } - - @override - bool shouldRebuild(_SliverAppBarDelegate oldDelegate) { - return true; - } -} - -class _PlaylistButton extends StatefulWidget { - _PlaylistButton({Key key}) : super(key: key); - - @override - __PlaylistButtonState createState() => __PlaylistButtonState(); -} - -class __PlaylistButtonState extends State<_PlaylistButton> { - bool _loadPlay; - - Future _getPlaylist() async { - await context.read().loadPlaylist(); - if (mounted) { - setState(() { - _loadPlay = true; - }); - } - } - - @override - void initState() { - super.initState(); - _loadPlay = false; - _getPlaylist(); - } - - @override - Widget build(BuildContext context) { - final audio = context.watch(); - final s = context.s; - return Material( - color: Colors.transparent, - borderRadius: BorderRadius.circular(100), - clipBehavior: Clip.hardEdge, - child: MyPopupMenuButton( - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(10))), - elevation: 1, - icon: Icon(Icons.playlist_play), - tooltip: s.menu, - itemBuilder: (context) => [ - MyPopupMenuItem( - height: 50, - value: 1, - child: Container( - decoration: BoxDecoration( - borderRadius: BorderRadius.only( - topLeft: Radius.circular(10.0), - topRight: Radius.circular(10.0)), - ), - child: Selector>( - selector: (_, audio) => - Tuple3(audio.playerRunning, audio.queue, audio.lastPositin), - builder: (_, data, __) => !_loadPlay - ? SizedBox( - height: 8.0, - ) - : data.item1 || data.item2.playlist.length == 0 - ? SizedBox( - height: 8.0, - ) - : InkWell( - borderRadius: BorderRadius.only( - topLeft: Radius.circular(10.0), - topRight: Radius.circular(10.0)), - onTap: () { - audio.playlistLoad(); - Navigator.pop(context); - }, - child: Column( - children: [ - Padding( - padding: EdgeInsets.symmetric(vertical: 5), - ), - Stack( - alignment: Alignment.center, - children: [ - CircleAvatar( - radius: 20, - backgroundImage: data - .item2.playlist.first.avatarImage), - Container( - height: 40.0, - width: 40.0, - decoration: BoxDecoration( - shape: BoxShape.circle, - color: Colors.black12), - child: Icon( - Icons.play_arrow, - color: Colors.white, - ), - ), - ], - ), - Padding( - padding: EdgeInsets.symmetric(vertical: 2), - ), - Container( - height: 70, - width: 140, - child: Column( - children: [ - Text( - (data.item3 ~/ 1000).toTime, - // style: - // TextStyle(color: Colors.white) - ), - Text( - data.item2.playlist.first.title, - maxLines: 2, - textAlign: TextAlign.center, - overflow: TextOverflow.fade, - // style: TextStyle(color: Colors.white), - ), - ], - ), - ), - Divider( - height: 1, - ), - ], - ), - ), - ), - ), - ), - PopupMenuItem( - value: 0, - child: Container( - padding: EdgeInsets.only(left: 10), - child: Row( - children: [ - Icon(Icons.playlist_play), - Padding( - padding: EdgeInsets.symmetric(horizontal: 5.0), - ), - Text(s.homeMenuPlaylist), - ], - ), - ), - ), - PopupMenuDivider( - height: 1, - ), - PopupMenuItem( - value: 2, - child: Container( - padding: EdgeInsets.only(left: 10), - child: Row( - children: [ - Icon(Icons.history), - Padding( - padding: const EdgeInsets.symmetric(horizontal: 5.0), - ), - Text(s.settingsHistory), - ], - ), - ), - ), - PopupMenuDivider( - height: 1, - ), - ], - onSelected: (value) { - if (value == 0) { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => PlaylistPage( - initPage: InitPage.playlist, - ), - ), - ); - } else if (value == 2) { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => PlaylistPage( - initPage: InitPage.history, - ), - ), - ); - } - }, - ), - ); - } -} - -class _RecentUpdate extends StatefulWidget { - @override - _RecentUpdateState createState() => _RecentUpdateState(); -} - -class _RecentUpdateState extends State<_RecentUpdate> - with AutomaticKeepAliveClientMixin, SingleTickerProviderStateMixin { - final GlobalKey _refreshIndicatorKey = - GlobalKey(); - final _dbHelper = DBHelper(); - - /// Episodes loaded first time. - int _top = 90; - - /// Load more episodes when scroll to bottom. - bool _loadMore; - - /// For group fliter. - String _groupName; - List _group; - Layout _layout; - bool _hideListened; - bool _scroll; - - ///Selected episode list. - List _selectedEpisodes; - - ///Toggle for multi-select. - bool _multiSelect; - - @override - void initState() { - super.initState(); - _loadMore = false; - _groupName = 'All'; - _group = []; - _scroll = false; - _multiSelect = false; - } - - Future _updateRssItem() async { - final refreshWorker = context.read(); - refreshWorker.start(_group); - await Future.delayed(Duration(seconds: 1)); - Fluttertoast.showToast( - msg: context.s.refreshStarted, - gravity: ToastGravity.BOTTOM, - ); - } - - Future> _getRssItem(int top, List group, - {bool hideListened}) async { - var storage = KeyValueStorage(recentLayoutKey); - var hideListenedStorage = KeyValueStorage(hideListenedKey); - var index = await storage.getInt(defaultValue: 1); - if (_layout == null) _layout = Layout.values[index]; - if (_hideListened == null) { - _hideListened = await hideListenedStorage.getBool(defaultValue: false); - } - - List episodes; - if (group.isEmpty) { - episodes = - await _dbHelper.getRecentRssItem(top, hideListened: _hideListened); - } else { - episodes = await _dbHelper.getGroupRssItem(top, group, - hideListened: _hideListened); - } - return episodes; - } - - Future _getUpdateCounts(List group) async { - var episodes = []; - - if (group.isEmpty) { - episodes = await _dbHelper.getRecentNewRssItem(); - } else { - episodes = await _dbHelper.getGroupNewRssItem(group); - } - return episodes.length; - } - - /// Load more episodes. - Future _loadMoreEpisode() async { - if (mounted) setState(() => _loadMore = true); - await Future.delayed(Duration(seconds: 3)); - if (mounted) { - setState(() { - _top = _top + 30; - _loadMore = false; - }); - } - } - - Widget _switchGroupButton() { - return Consumer( - builder: (context, groupList, child) => PopupMenuButton( - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), - elevation: 1, - tooltip: context.s.groupFilter, - child: Container( - padding: EdgeInsets.symmetric(horizontal: 20), - height: 50, - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Text(_groupName == 'All' ? context.s.all : _groupName), - Padding( - padding: EdgeInsets.symmetric(horizontal: 5), - ), - Icon( - LineIcons.filter_solid, - size: 18, - ) - ], - )), - itemBuilder: (context) => [ - PopupMenuItem( - child: Row(children: [ - Text(context.s.all), - Spacer(), - if (_groupName == 'All') DotIndicator() - ]), - value: 'All') - ]..addAll(groupList.groups - .map>((e) => PopupMenuItem( - value: e.name, - child: Row( - children: [ - Text(e.name), - Spacer(), - if (e.name == _groupName) DotIndicator() - ], - ))) - .toList()), - onSelected: (value) { - if (value == 'All') { - setState(() { - _groupName = 'All'; - _group = []; - }); - } else { - for (var group in groupList.groups) { - if (group.name == value) { - setState(() { - _groupName = value; - _group = group.podcastList; - }); - } - } - } - }, - ), - ); - } - - Widget _addNewButton() { - final audio = context.read(); - final s = context.s; - return FutureBuilder( - future: _getUpdateCounts(_group), - initialData: 0, - builder: (context, snapshot) { - return snapshot.data != 0 - ? Material( - color: Colors.transparent, - child: IconButton( - tooltip: s.addNewEpisodeTooltip, - icon: SizedBox( - height: 15, - width: 20, - child: CustomPaint( - painter: AddToPlaylistPainter( - context.textTheme.bodyText1.color, - Colors.red))), - onPressed: () async { - await audio.addNewEpisode(_group); - if (mounted) { - setState(() {}); - } - Fluttertoast.showToast( - msg: _groupName == 'All' - ? s.addNewEpisodeAll(snapshot.data) - : s.addEpisodeGroup(_groupName, snapshot.data), - gravity: ToastGravity.BOTTOM, - ); - }), - ) - : Center(); - // Material( - // color: Colors.transparent, - // child: IconButton( - // tooltip: s.addNewEpisodeTooltip, - // icon: SizedBox( - // height: 15, - // width: 20, - // child: CustomPaint( - // painter: AddToPlaylistPainter( - // context.textColor, - // context.textColor, - // ))), - // onPressed: () {}), - // ); - }); - } - - @override - Widget build(BuildContext context) { - super.build(context); - final s = context.s; - return Selector( - selector: (_, worker) => worker.complete, - builder: (_, complete, __) => Selector( - selector: (_, worker) => worker.created, - builder: (context, created, child) { - return FutureBuilder>( - future: _getRssItem(_top, _group, hideListened: _hideListened), - builder: (context, snapshot) { - return (snapshot.hasData) - ? snapshot.data.length == 0 - ? Padding( - padding: EdgeInsets.only(top: 150), - child: Column( - mainAxisAlignment: MainAxisAlignment.start, - children: [ - Icon(LineIcons.cloud_download_alt_solid, - size: 80, color: Colors.grey[500]), - Padding( - padding: - EdgeInsets.symmetric(vertical: 10)), - Text( - s.noEpisodeRecent, - style: TextStyle(color: Colors.grey[500]), - ) - ], - ), - ) - : NotificationListener( - onNotification: (scrollInfo) { - if (scrollInfo is ScrollStartNotification && - mounted && - !_scroll) { - setState(() => _scroll = true); - } - if (scrollInfo.metrics.pixels == - scrollInfo.metrics.maxScrollExtent && - snapshot.data.length == _top) { - if (!_loadMore) { - _loadMoreEpisode(); - } - } - return true; - }, - child: RefreshIndicator( - key: _refreshIndicatorKey, - color: Colors.white, - backgroundColor: context.accentColor, - semanticsLabel: s.refreshStarted, - onRefresh: _updateRssItem, - child: Stack( - children: [ - ScrollConfiguration( - behavior: NoGrowBehavior(), - child: CustomScrollView( - key: PageStorageKey('update'), - physics: - const AlwaysScrollableScrollPhysics(), - slivers: [ - SliverToBoxAdapter( - child: SizedBox( - height: 40, - // color: context.primaryColor, - // child: Material( - // color: Colors.transparent, - // child: Row( - // children: [ - // _switchGroupButton(), - // Spacer(), - // _addNewButton(), - // Material( - // color: Colors.transparent, - // child: IconButton( - // tooltip: s - // .hideListenedSetting, - // icon: SizedBox( - // width: 30, - // height: 15, - // child: HideListened( - // hideListened: - // _hideListened ?? - // false, - // ), - // ), - // onPressed: () { - // setState(() => - // _hideListened = - // !_hideListened); - // }, - // ), - // ), - // Material( - // color: Colors.transparent, - // child: LayoutButton( - // layout: _layout, - // onPressed: (layout) => - // setState(() { - // _layout = layout; - // }), - // ), - // ), - // Material( - // color: - // Colors.transparent, - // clipBehavior: - // Clip.hardEdge, - // borderRadius: - // BorderRadius - // .circular(100), - // child: IconButton( - // icon: SizedBox( - // width: 20, - // height: 10, - // child: CustomPaint( - // painter: MultiSelectPainter( - // color: context - // .accentColor)), - // ), - // onPressed: () { - // setState(() { - // _selectedEpisodes = - // []; - // _multiSelect = - // true; - // }); - // }, - // )), - // ], - // ), - // ), - ), - ), - EpisodeGrid( - episodes: snapshot.data, - layout: _layout, - initNum: _scroll ? 0 : 12, - multiSelect: _multiSelect, - selectedList: - _selectedEpisodes ?? [], - onSelect: (value) => setState(() { - _selectedEpisodes = value; - }), - ), - SliverList( - delegate: - SliverChildBuilderDelegate( - (context, index) { - return _loadMore - ? Container( - height: 2, - child: - LinearProgressIndicator()) - : Center(); - }, - childCount: 1, - ), - ), - ]), - ), - Column( - children: [ - if (!_multiSelect) - Container( - height: 40, - color: context.primaryColor, - child: Material( - color: Colors.transparent, - child: Row( - children: [ - _switchGroupButton(), - Spacer(), - _addNewButton(), - Material( - color: Colors.transparent, - child: IconButton( - tooltip: - s.hideListenedSetting, - icon: SizedBox( - width: 30, - height: 15, - child: HideListened( - hideListened: - _hideListened ?? - false, - ), - ), - onPressed: () { - setState(() => - _hideListened = - !_hideListened); - }, - ), - ), - Material( - color: Colors.transparent, - child: LayoutButton( - layout: _layout, - onPressed: (layout) => - setState(() { - _layout = layout; - }), - ), - ), - Material( - color: Colors.transparent, - child: IconButton( - icon: SizedBox( - width: 20, - height: 10, - child: CustomPaint( - painter: MultiSelectPainter( - color: context - .accentColor)), - ), - onPressed: () { - setState(() { - _selectedEpisodes = - []; - _multiSelect = true; - }); - }, - )), - ], - ), - )), - if (_multiSelect) - MultiSelectMenuBar( - selectedList: _selectedEpisodes, - onClose: (value) { - setState(() { - if (value) { - _multiSelect = false; - } - }); - }, - ), - ], - ), - ], - ), - ), - ) - : Center(); - }, - ); - }), - ); - } - - @override - bool get wantKeepAlive => true; -} - -class _MyFavorite extends StatefulWidget { - @override - _MyFavoriteState createState() => _MyFavoriteState(); -} - -class _MyFavoriteState extends State<_MyFavorite> - with AutomaticKeepAliveClientMixin { - Future> _getLikedRssItem(int top, int sortBy, - {bool hideListened}) async { - var storage = KeyValueStorage(favLayoutKey); - var index = await storage.getInt(defaultValue: 1); - var hideListenedStorage = KeyValueStorage(hideListenedKey); - if (_layout == null) _layout = Layout.values[index]; - if (_hideListened == null) { - _hideListened = await hideListenedStorage.getBool(defaultValue: false); - } - var dbHelper = DBHelper(); - var episodes = await dbHelper.getLikedRssItem(top, sortBy, - hideListened: _hideListened); - return episodes; - } - - Future _loadMoreEpisode() async { - if (mounted) setState(() => _loadMore = true); - await Future.delayed(Duration(seconds: 3)); - if (mounted) { - setState(() { - _top = _top + 30; - _loadMore = false; - }); - } - } - - int _top = 90; - bool _loadMore; - Layout _layout; - int _sortBy; - bool _hideListened; - - ///Selected episode list. - List _selectedEpisodes; - - ///Toggle for multi-select. - bool _multiSelect; - - @override - void initState() { - super.initState(); - _loadMore = false; - _sortBy = 0; - _multiSelect = false; - } - - @override - Widget build(BuildContext context) { - super.build(context); - final s = context.s; - return Selector( - selector: (_, audio) => audio.episodeState, - builder: (context, episodeState, child) { - return FutureBuilder>( - future: - _getLikedRssItem(_top, _sortBy, hideListened: _hideListened), - builder: (context, snapshot) { - return (snapshot.hasData) - ? snapshot.data.length == 0 - ? Padding( - padding: EdgeInsets.only(top: 150), - child: Column( - mainAxisAlignment: MainAxisAlignment.start, - children: [ - Icon(LineIcons.heartbeat_solid, - size: 80, color: Colors.grey[500]), - Padding( - padding: EdgeInsets.symmetric(vertical: 10)), - Text( - s.noEpisodeFavorite, - style: TextStyle(color: Colors.grey[500]), - ) - ], - ), - ) - : NotificationListener( - onNotification: (scrollInfo) { - if (scrollInfo.metrics.pixels == - scrollInfo.metrics.maxScrollExtent && - snapshot.data.length == _top) { - if (!_loadMore) { - _loadMoreEpisode(); - } - } - return true; - }, - child: Stack( - children: [ - ScrollConfiguration( - behavior: NoGrowBehavior(), - child: CustomScrollView( - key: PageStorageKey('favorite'), - slivers: [ - SliverToBoxAdapter( - child: SizedBox(height: 40)), - EpisodeGrid( - episodes: snapshot.data, - layout: _layout, - initNum: 0, - multiSelect: _multiSelect, - selectedList: _selectedEpisodes ?? [], - onSelect: (value) => setState(() { - _selectedEpisodes = value; - }), - ), - SliverList( - delegate: SliverChildBuilderDelegate( - (context, index) { - return _loadMore - ? Container( - height: 2, - child: - LinearProgressIndicator()) - : Center(); - }, - childCount: 1, - ), - ), - ], - ), - ), - Column( - children: [ - if (!_multiSelect) - Container( - height: 40, - color: context.primaryColor, - child: Row( - children: [ - Material( - color: Colors.transparent, - child: PopupMenuButton( - shape: RoundedRectangleBorder( - borderRadius: - BorderRadius.all( - Radius.circular(10))), - elevation: 1, - tooltip: s.homeSubMenuSortBy, - child: Container( - height: 50, - padding: EdgeInsets.symmetric( - horizontal: 20), - child: Row( - mainAxisSize: - MainAxisSize.min, - children: [ - Text(s.homeSubMenuSortBy), - Padding( - padding: EdgeInsets - .symmetric( - horizontal: 5), - ), - Icon( - LineIcons - .hourglass_start_solid, - size: 18, - ) - ], - )), - itemBuilder: (context) => [ - PopupMenuItem( - value: 0, - child: Row( - children: [ - Text(s.updateDate), - Spacer(), - if (_sortBy == 0) - DotIndicator() - ], - ), - ), - PopupMenuItem( - value: 1, - child: Row( - children: [ - Text(s.likeDate), - Spacer(), - if (_sortBy == 1) - DotIndicator() - ], - ), - ) - ], - onSelected: (value) { - if (value == 0) { - setState(() => _sortBy = 0); - } else if (value == 1) { - setState(() => _sortBy = 1); - } - }, - ), - ), - Spacer(), - Material( - color: Colors.transparent, - child: IconButton( - icon: SizedBox( - width: 30, - height: 15, - child: HideListened( - hideListened: - _hideListened ?? false, - ), - ), - onPressed: () { - setState(() => _hideListened = - !_hideListened); - }, - ), - ), - Material( - color: Colors.transparent, - child: LayoutButton( - layout: _layout, - onPressed: (layout) => - setState(() { - _layout = layout; - }), - ), - ), - Material( - color: Colors.transparent, - child: IconButton( - icon: SizedBox( - width: 20, - height: 10, - child: CustomPaint( - painter: - MultiSelectPainter( - color: context - .accentColor)), - ), - onPressed: () { - setState(() { - _selectedEpisodes = []; - _multiSelect = true; - }); - }, - )), - ], - ), - ), - if (_multiSelect) - MultiSelectMenuBar( - selectedList: _selectedEpisodes, - hideFavorite: true, - onClose: (value) { - setState(() { - if (value) { - _multiSelect = false; - } - }); - }, - ), - ], - ), - ], - ), - ) - : Center(); - }, - ); - }); - } - - @override - bool get wantKeepAlive => true; -} - -class _MyDownload extends StatefulWidget { - @override - _MyDownloadState createState() => _MyDownloadState(); -} - -class _MyDownloadState extends State<_MyDownload> - with AutomaticKeepAliveClientMixin { - Layout _layout; - int _sortBy; - bool _hideListened; - Future> _getDownloadedEpisodes(int sortBy, - {bool hideListened}) async { - var storage = KeyValueStorage(downloadLayoutKey); - var index = await storage.getInt(defaultValue: 1); - var hideListenedStorage = KeyValueStorage(hideListenedKey); - if (_layout == null) _layout = Layout.values[index]; - if (_hideListened == null) { - _hideListened = await hideListenedStorage.getBool(defaultValue: false); - } - var dbHelper = DBHelper(); - var episodes = await dbHelper.getDownloadedEpisode(sortBy, - hideListened: _hideListened); - return episodes; - } - - @override - void initState() { - super.initState(); - _sortBy = 0; - } - - @override - Widget build(BuildContext context) { - super.build(context); - final s = context.s; - return Consumer( - builder: (_, data, __) => FutureBuilder>( - future: _getDownloadedEpisodes(_sortBy, hideListened: _hideListened), - builder: (context, snapshot) { - var episodes = snapshot.data ?? []; - return ScrollConfiguration( - behavior: NoGrowBehavior(), - child: CustomScrollView( - key: PageStorageKey('download_list'), - slivers: [ - DownloadList(), - SliverToBoxAdapter( - child: Container( - height: 40, - color: context.primaryColor, - child: Row( - children: [ - Container( - padding: EdgeInsets.symmetric(horizontal: 20), - child: Text(s.downloaded)), - Spacer(), - Material( - color: Colors.transparent, - child: IconButton( - icon: SizedBox( - width: 30, - height: 15, - child: HideListened( - hideListened: _hideListened ?? false, - ), - ), - onPressed: () { - setState( - () => _hideListened = !_hideListened); - }, - ), - ), - Material( - color: Colors.transparent, - child: LayoutButton( - layout: _layout ?? Layout.one, - onPressed: (layout) => setState(() { - _layout = layout; - }), - ), - ), - ], - )), - ), - episodes.length == 0 - ? SliverToBoxAdapter( - child: Padding( - padding: const EdgeInsets.only(top: 110), - child: Column( - mainAxisAlignment: MainAxisAlignment.start, - children: [ - Icon(LineIcons.download_solid, - size: 80, color: Colors.grey[500]), - Padding( - padding: - EdgeInsets.symmetric(vertical: 10)), - Text( - s.noEpisodeDownload, - style: TextStyle(color: Colors.grey[500]), - ) - ], - ), - ), - ) - : EpisodeGrid( - episodes: episodes, - layout: _layout, - initNum: 0, - ), - ], - ), - ); - }), - ); - } - - @override - bool get wantKeepAlive => true; -} +import 'dart:async'; +import 'dart:io'; + +import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart'; +import 'package:feature_discovery/feature_discovery.dart'; +import 'package:flutter/material.dart' hide NestedScrollView; +import 'package:flutter/services.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:line_icons/line_icons.dart'; +import 'package:provider/provider.dart'; +import 'package:tuple/tuple.dart'; + +import '../local_storage/key_value_storage.dart'; +import '../local_storage/sqflite_localpodcast.dart'; +import '../state/audio_state.dart'; +import '../state/download_state.dart'; +import '../state/podcast_group.dart'; +import '../state/refresh_podcast.dart'; +import '../state/setting_state.dart'; +import '../type/episodebrief.dart'; +import '../type/playlist.dart'; +import '../util/audiopanel.dart'; +import '../util/custom_popupmenu.dart'; +import '../util/custom_widget.dart'; +import '../util/episodegrid.dart'; +import '../util/extension_helper.dart'; +import '../util/muiliselect_bar.dart'; +import 'audioplayer.dart'; +import 'download_list.dart'; +import 'home_groups.dart'; +import 'home_menu.dart'; +import 'import_ompl.dart'; +import 'playlist.dart'; +import 'search_podcast.dart'; + +const String addFeature = 'addFeature'; +const String menuFeature = 'menuFeature'; +const String playlistFeature = 'playlistFeature'; +const String longTapFeature = 'longTapFeature'; +const String groupsFeature = 'groupsFeature'; +const String podcastFeature = 'podcastFeature'; + +class Home extends StatefulWidget { + @override + _HomeState createState() => _HomeState(); +} + +class _HomeState extends State with SingleTickerProviderStateMixin { + final GlobalKey _scaffoldKey = GlobalKey(); + final GlobalKey _playerKey = GlobalKey(); + TabController _controller; + Decoration _getIndicator(BuildContext context) { + return UnderlineTabIndicator( + borderSide: BorderSide(color: Theme.of(context).accentColor, width: 3), + insets: EdgeInsets.only( + left: 10.0, + right: 10.0, + top: 10.0, + )); + } + + final _androidAppRetain = MethodChannel("android_app_retain"); + var feature1OverflowMode = OverflowMode.clipContent; + var feature1EnablePulsingAnimation = false; + + @override + void initState() { + super.initState(); + _controller = TabController(length: 3, vsync: this); + FeatureDiscovery.isDisplayed(context, addFeature).then((value) { + if (!value) { + WidgetsBinding.instance.addPostFrameCallback((_) { + FeatureDiscovery.discoverFeatures( + context, + const { + addFeature, + menuFeature, + playlistFeature, + groupsFeature, + podcastFeature, + }, + ); + }); + } + }); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + double top = 0; + @override + Widget build(BuildContext context) { + var width = MediaQuery.of(context).size.width; + var height = (width - 20) / 3 + 140; + var settings = Provider.of(context, listen: false); + final s = context.s; + return AnnotatedRegion( + value: SystemUiOverlayStyle( + systemNavigationBarIconBrightness: + Theme.of(context).accentColorBrightness, + statusBarIconBrightness: Theme.of(context).accentColorBrightness, + systemNavigationBarColor: Theme.of(context).primaryColor, + ), + child: Scaffold( + key: _scaffoldKey, + body: WillPopScope( + onWillPop: () async { + if (_playerKey.currentState != null && + _playerKey.currentState.initSize > 100) { + _playerKey.currentState.backToMini(); + return false; + } else if (Platform.isAndroid) { + _androidAppRetain.invokeMethod('sendToBackground'); + return false; + } else { + return true; + } + }, + child: SafeArea( + child: Stack( + children: [ + Column( + children: [ + Expanded( + child: NestedScrollView( + innerScrollPositionKeyBuilder: () { + return Key('tab${_controller.index}'); + }, + pinnedHeaderSliverHeightBuilder: () => 50, + headerSliverBuilder: (context, innerBoxScrolled) { + return [ + SliverToBoxAdapter( + child: Column( + children: [ + SizedBox( + height: 50.0, + child: Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + DescribedFeatureOverlay( + featureId: addFeature, + tapTarget: + Icon(Icons.add_circle_outline), + title: Text(s.featureDiscoverySearch), + backgroundColor: Colors.cyan[600], + overflowMode: feature1OverflowMode, + onDismiss: () { + return Future.value(true); + }, + description: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text(s.featureDiscoverySearchDes), + FlatButton( + color: Colors.cyan[500], + padding: + const EdgeInsets.all(0), + child: Text(s.understood, + style: context + .textTheme.button + .copyWith( + color: + Colors.white)), + onPressed: () async => + FeatureDiscovery + .completeCurrentStep( + context), + ), + FlatButton( + color: Colors.cyan[500], + padding: + const EdgeInsets.all(0), + child: Text(s.dismiss, + style: Theme.of(context) + .textTheme + .button + .copyWith( + color: + Colors.white)), + onPressed: () => + FeatureDiscovery.dismissAll( + context), + ), + ], + ), + child: IconButton( + tooltip: s.add, + splashRadius: 25, + icon: const Icon( + Icons.add_circle_outline), + onPressed: () async { + await showSearch( + context: context, + delegate: MyHomePageDelegate( + searchFieldLabel: + s.searchPodcast), + ); + }, + ), + ), + GestureDetector( + onTap: () => { + Theme.of(context).brightness == + Brightness.light + ? settings.setTheme = + ThemeMode.dark + : settings.setTheme = + ThemeMode.light + }, + child: Image( + image: Theme.of(context) + .brightness == + Brightness.light + ? AssetImage('assets/text.png') + : AssetImage( + 'assets/text_light.png'), + height: 30, + ), + ), + DescribedFeatureOverlay( + featureId: menuFeature, + tapTarget: Icon(Icons.more_vert), + backgroundColor: Colors.cyan[500], + onDismiss: () => Future.value(true), + title: Text(s.featureDiscoveryOMPL), + description: Column( + crossAxisAlignment: + CrossAxisAlignment.end, + children: [ + Text(s.featureDiscoveryOMPLDes), + FlatButton( + color: Colors.cyan[600], + padding: EdgeInsets.zero, + child: Text(s.understood, + style: Theme.of(context) + .textTheme + .button + .copyWith( + color: Colors + .white)), + onPressed: () async => + FeatureDiscovery + .completeCurrentStep( + context), + ), + FlatButton( + color: Colors.cyan[600], + padding: + const EdgeInsets.all(0), + child: Text(s.dismiss, + style: Theme.of(context) + .textTheme + .button + .copyWith( + color: Colors + .white)), + onPressed: () => + FeatureDiscovery + .dismissAll(context), + ), + ], + ), + child: PopupMenu()), + ], + ), + ), + Import(), + ], + ), + ), + SliverList( + delegate: SliverChildBuilderDelegate( + (context, index) { + return DescribedFeatureOverlay( + featureId: groupsFeature, + tapTarget: Center( + child: Text( + s.featureDiscoveryPodcast, + textAlign: TextAlign.center, + )), + backgroundColor: Colors.cyan[500], + enablePulsingAnimation: false, + onDismiss: () => Future.value(true), + title: Text(s.featureDiscoveryPodcastTitle), + description: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text(s.featureDiscoveryPodcastDes), + Row( + children: [ + FlatButton( + color: Colors.cyan[600], + padding: const EdgeInsets.all(0), + child: Text(s.understood, + style: Theme.of(context) + .textTheme + .button + .copyWith( + color: Colors.white)), + onPressed: () async => + FeatureDiscovery + .completeCurrentStep( + context), + ), + Padding( + padding: EdgeInsets.symmetric( + horizontal: 5)), + FlatButton( + color: Colors.cyan[600], + padding: const EdgeInsets.all(0), + child: Text(s.dismiss, + style: context + .textTheme.button + .copyWith( + color: Colors.white)), + onPressed: () => + FeatureDiscovery.dismissAll( + context), + ), + ], + ), + ], + ), + child: SizedBox( + height: height, + width: width, + child: ScrollPodcasts(), + ), + ); + }, + childCount: 1, + ), + ), + SliverPersistentHeader( + delegate: _SliverAppBarDelegate( + TabBar( + indicator: _getIndicator(context), + isScrollable: true, + indicatorSize: TabBarIndicatorSize.tab, + controller: _controller, + tabs: [ + Tab( + child: Text(s.homeTabMenuRecent), + ), + Tab( + child: Text(s.homeTabMenuFavotite), + ), + Tab( + child: Text(s.download), + ) + ], + ), + ), + pinned: true, + ), + ]; + }, + body: TabBarView( + controller: _controller, + children: [ + NestedScrollViewInnerScrollPositionKeyWidget( + Key('tab0'), + DescribedFeatureOverlay( + featureId: podcastFeature, + tapTarget: Text(s.featureDiscoveryEpisode, + textAlign: TextAlign.center), + backgroundColor: Colors.cyan[500], + enablePulsingAnimation: false, + onDismiss: () => Future.value(true), + title: Text(s.featureDiscoveryEpisodeTitle), + description: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text(s.featureDiscoveryEpisodeDes), + Row( + children: [ + FlatButton( + color: Colors.cyan[600], + padding: const EdgeInsets.all(0), + child: Text(s.understood, + style: Theme.of(context) + .textTheme + .button + .copyWith( + color: Colors.white)), + onPressed: () async => + FeatureDiscovery + .completeCurrentStep( + context), + ), + Padding( + padding: EdgeInsets.symmetric( + horizontal: 5)), + FlatButton( + color: Colors.cyan[600], + padding: const EdgeInsets.all(0), + child: Text(s.dismiss, + style: Theme.of(context) + .textTheme + .button + .copyWith( + color: Colors.white)), + onPressed: () => + FeatureDiscovery.dismissAll( + context), + ), + ], + ), + ], + ), + child: _RecentUpdate())), + NestedScrollViewInnerScrollPositionKeyWidget( + Key('tab1'), _MyFavorite()), + NestedScrollViewInnerScrollPositionKeyWidget( + Key('tab2'), _MyDownload()), + ], + ), + ), + ), + Selector( + selector: (_, audio) => audio.playerRunning, + builder: (_, data, __) { + return Padding( + padding: EdgeInsets.only(bottom: data ? 60.0 : 0), + ); + }), + ], + ), + Container(child: PlayerWidget(playerKey: _playerKey)), + ], + ), + ), + ), + ), + ); + } +} + +class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate { + _SliverAppBarDelegate(this._tabBar); + final TabBar _tabBar; + + @override + double get minExtent => _tabBar.preferredSize.height + 2; + @override + double get maxExtent => _tabBar.preferredSize.height + 2; + + @override + Widget build( + BuildContext context, double shrinkOffset, bool overlapsContent) { + final s = context.s; + return Container( + color: context.scaffoldBackgroundColor, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + _tabBar, + Spacer(), + DescribedFeatureOverlay( + featureId: playlistFeature, + tapTarget: Icon(Icons.playlist_play), + backgroundColor: Colors.cyan[500], + title: Text(s.featureDiscoveryPlaylist), + onDismiss: () => Future.value(true), + description: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(s.featureDiscoveryPlaylistDes), + FlatButton( + color: Colors.cyan[600], + padding: const EdgeInsets.all(0), + child: Text(s.understood, + style: Theme.of(context) + .textTheme + .button + .copyWith(color: Colors.white)), + onPressed: () async => + FeatureDiscovery.completeCurrentStep(context), + ), + FlatButton( + color: Colors.cyan[600], + padding: const EdgeInsets.all(0), + child: Text(s.dismiss, + style: Theme.of(context) + .textTheme + .button + .copyWith(color: Colors.white)), + onPressed: () => FeatureDiscovery.dismissAll(context), + ), + ], + ), + child: _PlaylistButton()), + ], + ), + Container(height: 2, color: context.primaryColor), + ], + ), + ); + } + + @override + bool shouldRebuild(_SliverAppBarDelegate oldDelegate) { + return true; + } +} + +class _PlaylistButton extends StatefulWidget { + _PlaylistButton({Key key}) : super(key: key); + + @override + __PlaylistButtonState createState() => __PlaylistButtonState(); +} + +class __PlaylistButtonState extends State<_PlaylistButton> { + bool _loadPlay; + + Future _getPlaylist() async { + await context.read().loadPlaylist(); + if (mounted) { + setState(() { + _loadPlay = true; + }); + } + } + + @override + void initState() { + super.initState(); + _loadPlay = false; + _getPlaylist(); + } + + @override + Widget build(BuildContext context) { + final audio = context.watch(); + final s = context.s; + return Material( + color: Colors.transparent, + borderRadius: BorderRadius.circular(100), + clipBehavior: Clip.hardEdge, + child: MyPopupMenuButton( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(10))), + elevation: 1, + icon: Icon(Icons.playlist_play), + tooltip: s.menu, + itemBuilder: (context) => [ + MyPopupMenuItem( + height: 50, + value: 1, + child: Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.only( + topLeft: Radius.circular(10.0), + topRight: Radius.circular(10.0)), + ), + child: Selector>( + selector: (_, audio) => + Tuple3(audio.playerRunning, audio.queue, audio.lastPositin), + builder: (_, data, __) => !_loadPlay + ? SizedBox( + height: 8.0, + ) + : data.item1 || data.item2.playlist.length == 0 + ? SizedBox( + height: 8.0, + ) + : InkWell( + borderRadius: BorderRadius.only( + topLeft: Radius.circular(10.0), + topRight: Radius.circular(10.0)), + onTap: () { + audio.playlistLoad(); + Navigator.pop(context); + }, + child: Column( + children: [ + Padding( + padding: EdgeInsets.symmetric(vertical: 5), + ), + Stack( + alignment: Alignment.center, + children: [ + CircleAvatar( + radius: 20, + backgroundImage: data + .item2.playlist.first.avatarImage), + Container( + height: 40.0, + width: 40.0, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: Colors.black12), + child: Icon( + Icons.play_arrow, + color: Colors.white, + ), + ), + ], + ), + Padding( + padding: EdgeInsets.symmetric(vertical: 2), + ), + Container( + height: 70, + width: 140, + child: Column( + children: [ + Text( + (data.item3 ~/ 1000).toTime, + // style: + // TextStyle(color: Colors.white) + ), + Text( + data.item2.playlist.first.title, + maxLines: 2, + textAlign: TextAlign.center, + overflow: TextOverflow.fade, + // style: TextStyle(color: Colors.white), + ), + ], + ), + ), + Divider( + height: 1, + ), + ], + ), + ), + ), + ), + ), + PopupMenuItem( + value: 0, + child: Container( + padding: EdgeInsets.only(left: 10), + child: Row( + children: [ + Icon(Icons.playlist_play), + Padding( + padding: EdgeInsets.symmetric(horizontal: 5.0), + ), + Text(s.homeMenuPlaylist), + ], + ), + ), + ), + PopupMenuDivider( + height: 1, + ), + PopupMenuItem( + value: 2, + child: Container( + padding: EdgeInsets.only(left: 10), + child: Row( + children: [ + Icon(Icons.history), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 5.0), + ), + Text(s.settingsHistory), + ], + ), + ), + ), + PopupMenuDivider( + height: 1, + ), + ], + onSelected: (value) { + if (value == 0) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => PlaylistPage( + initPage: InitPage.playlist, + ), + ), + ); + } else if (value == 2) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => PlaylistPage( + initPage: InitPage.history, + ), + ), + ); + } + }, + ), + ); + } +} + +class _RecentUpdate extends StatefulWidget { + @override + _RecentUpdateState createState() => _RecentUpdateState(); +} + +class _RecentUpdateState extends State<_RecentUpdate> + with AutomaticKeepAliveClientMixin, SingleTickerProviderStateMixin { + final GlobalKey _refreshIndicatorKey = + GlobalKey(); + final _dbHelper = DBHelper(); + + /// Episodes loaded first time. + int _top = 90; + + /// Load more episodes when scroll to bottom. + bool _loadMore; + + /// For group fliter. + String _groupName; + List _group; + Layout _layout; + bool _hideListened; + bool _scroll; + + ///Selected episode list. + List _selectedEpisodes; + + ///Toggle for multi-select. + bool _multiSelect; + + @override + void initState() { + super.initState(); + _loadMore = false; + _groupName = 'All'; + _group = []; + _scroll = false; + _multiSelect = false; + } + + Future _updateRssItem() async { + final refreshWorker = context.read(); + refreshWorker.start(_group); + await Future.delayed(Duration(seconds: 1)); + Fluttertoast.showToast( + msg: context.s.refreshStarted, + gravity: ToastGravity.BOTTOM, + ); + } + + Future> _getRssItem(int top, List group, + {bool hideListened}) async { + var storage = KeyValueStorage(recentLayoutKey); + var hideListenedStorage = KeyValueStorage(hideListenedKey); + var index = await storage.getInt(defaultValue: 1); + if (_layout == null) _layout = Layout.values[index]; + if (_hideListened == null) { + _hideListened = await hideListenedStorage.getBool(defaultValue: false); + } + + List episodes; + if (group.isEmpty) { + episodes = + await _dbHelper.getRecentRssItem(top, hideListened: _hideListened); + } else { + episodes = await _dbHelper.getGroupRssItem(top, group, + hideListened: _hideListened); + } + return episodes; + } + + Future _getUpdateCounts(List group) async { + var episodes = []; + + if (group.isEmpty) { + episodes = await _dbHelper.getRecentNewRssItem(); + } else { + episodes = await _dbHelper.getGroupNewRssItem(group); + } + return episodes.length; + } + + /// Load more episodes. + Future _loadMoreEpisode() async { + if (mounted) setState(() => _loadMore = true); + await Future.delayed(Duration(seconds: 3)); + if (mounted) { + setState(() { + _top = _top + 30; + _loadMore = false; + }); + } + } + + Widget _switchGroupButton() { + return Consumer( + builder: (context, groupList, child) => PopupMenuButton( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), + elevation: 1, + tooltip: context.s.groupFilter, + child: Container( + padding: EdgeInsets.symmetric(horizontal: 20), + height: 50, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text(_groupName == 'All' ? context.s.all : _groupName), + Padding( + padding: EdgeInsets.symmetric(horizontal: 5), + ), + Icon( + LineIcons.filter_solid, + size: 18, + ) + ], + )), + itemBuilder: (context) => [ + PopupMenuItem( + child: Row(children: [ + Text(context.s.all), + Spacer(), + if (_groupName == 'All') DotIndicator() + ]), + value: 'All') + ]..addAll(groupList.groups + .map>((e) => PopupMenuItem( + value: e.name, + child: Row( + children: [ + Text(e.name), + Spacer(), + if (e.name == _groupName) DotIndicator() + ], + ))) + .toList()), + onSelected: (value) { + if (value == 'All') { + setState(() { + _groupName = 'All'; + _group = []; + }); + } else { + for (var group in groupList.groups) { + if (group.name == value) { + setState(() { + _groupName = value; + _group = group.podcastList; + }); + } + } + } + }, + ), + ); + } + + Widget _addNewButton() { + final audio = context.read(); + final s = context.s; + return FutureBuilder( + future: _getUpdateCounts(_group), + initialData: 0, + builder: (context, snapshot) { + return snapshot.data != 0 + ? Material( + color: Colors.transparent, + child: IconButton( + tooltip: s.addNewEpisodeTooltip, + icon: SizedBox( + height: 15, + width: 20, + child: CustomPaint( + painter: AddToPlaylistPainter( + context.textTheme.bodyText1.color, + Colors.red))), + onPressed: () async { + await audio.addNewEpisode(_group); + if (mounted) { + setState(() {}); + } + Fluttertoast.showToast( + msg: _groupName == 'All' + ? s.addNewEpisodeAll(snapshot.data) + : s.addEpisodeGroup(_groupName, snapshot.data), + gravity: ToastGravity.BOTTOM, + ); + }), + ) + : Center(); + // Material( + // color: Colors.transparent, + // child: IconButton( + // tooltip: s.addNewEpisodeTooltip, + // icon: SizedBox( + // height: 15, + // width: 20, + // child: CustomPaint( + // painter: AddToPlaylistPainter( + // context.textColor, + // context.textColor, + // ))), + // onPressed: () {}), + // ); + }); + } + + @override + Widget build(BuildContext context) { + super.build(context); + final s = context.s; + return Selector( + selector: (_, worker) => worker.complete, + builder: (_, complete, __) => Selector( + selector: (_, worker) => worker.created, + builder: (context, created, child) { + return FutureBuilder>( + future: _getRssItem(_top, _group, hideListened: _hideListened), + builder: (context, snapshot) { + return (snapshot.hasData) + ? snapshot.data.length == 0 + ? Padding( + padding: EdgeInsets.only(top: 150), + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + Icon(LineIcons.cloud_download_alt_solid, + size: 80, color: Colors.grey[500]), + Padding( + padding: + EdgeInsets.symmetric(vertical: 10)), + Text( + s.noEpisodeRecent, + style: TextStyle(color: Colors.grey[500]), + ) + ], + ), + ) + : NotificationListener( + onNotification: (scrollInfo) { + if (scrollInfo is ScrollStartNotification && + mounted && + !_scroll) { + setState(() => _scroll = true); + } + if (scrollInfo.metrics.pixels == + scrollInfo.metrics.maxScrollExtent && + snapshot.data.length == _top) { + if (!_loadMore) { + _loadMoreEpisode(); + } + } + return true; + }, + child: RefreshIndicator( + key: _refreshIndicatorKey, + color: Colors.white, + backgroundColor: context.accentColor, + semanticsLabel: s.refreshStarted, + onRefresh: _updateRssItem, + child: Stack( + children: [ + ScrollConfiguration( + behavior: NoGrowBehavior(), + child: CustomScrollView( + key: PageStorageKey('update'), + physics: + const AlwaysScrollableScrollPhysics(), + slivers: [ + SliverToBoxAdapter( + child: SizedBox( + height: 40, + // color: context.primaryColor, + // child: Material( + // color: Colors.transparent, + // child: Row( + // children: [ + // _switchGroupButton(), + // Spacer(), + // _addNewButton(), + // Material( + // color: Colors.transparent, + // child: IconButton( + // tooltip: s + // .hideListenedSetting, + // icon: SizedBox( + // width: 30, + // height: 15, + // child: HideListened( + // hideListened: + // _hideListened ?? + // false, + // ), + // ), + // onPressed: () { + // setState(() => + // _hideListened = + // !_hideListened); + // }, + // ), + // ), + // Material( + // color: Colors.transparent, + // child: LayoutButton( + // layout: _layout, + // onPressed: (layout) => + // setState(() { + // _layout = layout; + // }), + // ), + // ), + // Material( + // color: + // Colors.transparent, + // clipBehavior: + // Clip.hardEdge, + // borderRadius: + // BorderRadius + // .circular(100), + // child: IconButton( + // icon: SizedBox( + // width: 20, + // height: 10, + // child: CustomPaint( + // painter: MultiSelectPainter( + // color: context + // .accentColor)), + // ), + // onPressed: () { + // setState(() { + // _selectedEpisodes = + // []; + // _multiSelect = + // true; + // }); + // }, + // )), + // ], + // ), + // ), + ), + ), + EpisodeGrid( + episodes: snapshot.data, + layout: _layout, + initNum: _scroll ? 0 : 12, + multiSelect: _multiSelect, + selectedList: + _selectedEpisodes ?? [], + onSelect: (value) => setState(() { + _selectedEpisodes = value; + }), + ), + SliverList( + delegate: + SliverChildBuilderDelegate( + (context, index) { + return _loadMore + ? Container( + height: 2, + child: + LinearProgressIndicator()) + : Center(); + }, + childCount: 1, + ), + ), + ]), + ), + Column( + children: [ + if (!_multiSelect) + Container( + height: 40, + color: context.primaryColor, + child: Material( + color: Colors.transparent, + child: Row( + children: [ + _switchGroupButton(), + Spacer(), + _addNewButton(), + Material( + color: Colors.transparent, + child: IconButton( + tooltip: + s.hideListenedSetting, + icon: SizedBox( + width: 30, + height: 15, + child: HideListened( + hideListened: + _hideListened ?? + false, + ), + ), + onPressed: () { + setState(() => + _hideListened = + !_hideListened); + }, + ), + ), + Material( + color: Colors.transparent, + child: LayoutButton( + layout: _layout, + onPressed: (layout) => + setState(() { + _layout = layout; + }), + ), + ), + Material( + color: Colors.transparent, + child: IconButton( + icon: SizedBox( + width: 20, + height: 10, + child: CustomPaint( + painter: MultiSelectPainter( + color: context + .accentColor)), + ), + onPressed: () { + setState(() { + _selectedEpisodes = + []; + _multiSelect = true; + }); + }, + )), + ], + ), + )), + if (_multiSelect) + MultiSelectMenuBar( + selectedList: _selectedEpisodes, + onClose: (value) { + setState(() { + if (value) { + _multiSelect = false; + } + }); + }, + ), + ], + ), + ], + ), + ), + ) + : Center(); + }, + ); + }), + ); + } + + @override + bool get wantKeepAlive => true; +} + +class _MyFavorite extends StatefulWidget { + @override + _MyFavoriteState createState() => _MyFavoriteState(); +} + +class _MyFavoriteState extends State<_MyFavorite> + with AutomaticKeepAliveClientMixin { + Future> _getLikedRssItem(int top, int sortBy, + {bool hideListened}) async { + var storage = KeyValueStorage(favLayoutKey); + var index = await storage.getInt(defaultValue: 1); + var hideListenedStorage = KeyValueStorage(hideListenedKey); + if (_layout == null) _layout = Layout.values[index]; + if (_hideListened == null) { + _hideListened = await hideListenedStorage.getBool(defaultValue: false); + } + var dbHelper = DBHelper(); + var episodes = await dbHelper.getLikedRssItem(top, sortBy, + hideListened: _hideListened); + return episodes; + } + + Future _loadMoreEpisode() async { + if (mounted) setState(() => _loadMore = true); + await Future.delayed(Duration(seconds: 3)); + if (mounted) { + setState(() { + _top = _top + 30; + _loadMore = false; + }); + } + } + + int _top = 90; + bool _loadMore; + Layout _layout; + int _sortBy; + bool _hideListened; + + ///Selected episode list. + List _selectedEpisodes; + + ///Toggle for multi-select. + bool _multiSelect; + + @override + void initState() { + super.initState(); + _loadMore = false; + _sortBy = 0; + _multiSelect = false; + } + + @override + Widget build(BuildContext context) { + super.build(context); + final s = context.s; + return Selector( + selector: (_, audio) => audio.episodeState, + builder: (context, episodeState, child) { + return FutureBuilder>( + future: + _getLikedRssItem(_top, _sortBy, hideListened: _hideListened), + builder: (context, snapshot) { + return (snapshot.hasData) + ? snapshot.data.length == 0 + ? Padding( + padding: EdgeInsets.only(top: 150), + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + Icon(LineIcons.heartbeat_solid, + size: 80, color: Colors.grey[500]), + Padding( + padding: EdgeInsets.symmetric(vertical: 10)), + Text( + s.noEpisodeFavorite, + style: TextStyle(color: Colors.grey[500]), + ) + ], + ), + ) + : NotificationListener( + onNotification: (scrollInfo) { + if (scrollInfo.metrics.pixels == + scrollInfo.metrics.maxScrollExtent && + snapshot.data.length == _top) { + if (!_loadMore) { + _loadMoreEpisode(); + } + } + return true; + }, + child: Stack( + children: [ + ScrollConfiguration( + behavior: NoGrowBehavior(), + child: CustomScrollView( + key: PageStorageKey('favorite'), + slivers: [ + SliverToBoxAdapter( + child: SizedBox(height: 40)), + EpisodeGrid( + episodes: snapshot.data, + layout: _layout, + initNum: 0, + multiSelect: _multiSelect, + selectedList: _selectedEpisodes ?? [], + onSelect: (value) => setState(() { + _selectedEpisodes = value; + }), + ), + SliverList( + delegate: SliverChildBuilderDelegate( + (context, index) { + return _loadMore + ? Container( + height: 2, + child: + LinearProgressIndicator()) + : Center(); + }, + childCount: 1, + ), + ), + ], + ), + ), + Column( + children: [ + if (!_multiSelect) + Container( + height: 40, + color: context.primaryColor, + child: Row( + children: [ + Material( + color: Colors.transparent, + child: PopupMenuButton( + shape: RoundedRectangleBorder( + borderRadius: + BorderRadius.all( + Radius.circular(10))), + elevation: 1, + tooltip: s.homeSubMenuSortBy, + child: Container( + height: 50, + padding: EdgeInsets.symmetric( + horizontal: 20), + child: Row( + mainAxisSize: + MainAxisSize.min, + children: [ + Text(s.homeSubMenuSortBy), + Padding( + padding: EdgeInsets + .symmetric( + horizontal: 5), + ), + Icon( + LineIcons + .hourglass_start_solid, + size: 18, + ) + ], + )), + itemBuilder: (context) => [ + PopupMenuItem( + value: 0, + child: Row( + children: [ + Text(s.updateDate), + Spacer(), + if (_sortBy == 0) + DotIndicator() + ], + ), + ), + PopupMenuItem( + value: 1, + child: Row( + children: [ + Text(s.likeDate), + Spacer(), + if (_sortBy == 1) + DotIndicator() + ], + ), + ) + ], + onSelected: (value) { + if (value == 0) { + setState(() => _sortBy = 0); + } else if (value == 1) { + setState(() => _sortBy = 1); + } + }, + ), + ), + Spacer(), + Material( + color: Colors.transparent, + child: IconButton( + icon: SizedBox( + width: 30, + height: 15, + child: HideListened( + hideListened: + _hideListened ?? false, + ), + ), + onPressed: () { + setState(() => _hideListened = + !_hideListened); + }, + ), + ), + Material( + color: Colors.transparent, + child: LayoutButton( + layout: _layout, + onPressed: (layout) => + setState(() { + _layout = layout; + }), + ), + ), + Material( + color: Colors.transparent, + child: IconButton( + icon: SizedBox( + width: 20, + height: 10, + child: CustomPaint( + painter: + MultiSelectPainter( + color: context + .accentColor)), + ), + onPressed: () { + setState(() { + _selectedEpisodes = []; + _multiSelect = true; + }); + }, + )), + ], + ), + ), + if (_multiSelect) + MultiSelectMenuBar( + selectedList: _selectedEpisodes, + hideFavorite: true, + onClose: (value) { + setState(() { + if (value) { + _multiSelect = false; + } + }); + }, + ), + ], + ), + ], + ), + ) + : Center(); + }, + ); + }); + } + + @override + bool get wantKeepAlive => true; +} + +class _MyDownload extends StatefulWidget { + @override + _MyDownloadState createState() => _MyDownloadState(); +} + +class _MyDownloadState extends State<_MyDownload> + with AutomaticKeepAliveClientMixin { + Layout _layout; + int _sortBy; + bool _hideListened; + Future> _getDownloadedEpisodes(int sortBy, + {bool hideListened}) async { + var storage = KeyValueStorage(downloadLayoutKey); + var index = await storage.getInt(defaultValue: 1); + var hideListenedStorage = KeyValueStorage(hideListenedKey); + if (_layout == null) _layout = Layout.values[index]; + if (_hideListened == null) { + _hideListened = await hideListenedStorage.getBool(defaultValue: false); + } + var dbHelper = DBHelper(); + var episodes = await dbHelper.getDownloadedEpisode(sortBy, + hideListened: _hideListened); + return episodes; + } + + @override + void initState() { + super.initState(); + _sortBy = 0; + } + + @override + Widget build(BuildContext context) { + super.build(context); + final s = context.s; + return Consumer( + builder: (_, data, __) => FutureBuilder>( + future: _getDownloadedEpisodes(_sortBy, hideListened: _hideListened), + builder: (context, snapshot) { + var episodes = snapshot.data ?? []; + return ScrollConfiguration( + behavior: NoGrowBehavior(), + child: CustomScrollView( + key: PageStorageKey('download_list'), + slivers: [ + DownloadList(), + SliverToBoxAdapter( + child: Container( + height: 40, + color: context.primaryColor, + child: Row( + children: [ + Container( + padding: EdgeInsets.symmetric(horizontal: 20), + child: Text(s.downloaded)), + Spacer(), + Material( + color: Colors.transparent, + child: IconButton( + icon: SizedBox( + width: 30, + height: 15, + child: HideListened( + hideListened: _hideListened ?? false, + ), + ), + onPressed: () { + setState( + () => _hideListened = !_hideListened); + }, + ), + ), + Material( + color: Colors.transparent, + child: LayoutButton( + layout: _layout ?? Layout.one, + onPressed: (layout) => setState(() { + _layout = layout; + }), + ), + ), + ], + )), + ), + episodes.length == 0 + ? SliverToBoxAdapter( + child: Padding( + padding: const EdgeInsets.only(top: 110), + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + Icon(LineIcons.download_solid, + size: 80, color: Colors.grey[500]), + Padding( + padding: + EdgeInsets.symmetric(vertical: 10)), + Text( + s.noEpisodeDownload, + style: TextStyle(color: Colors.grey[500]), + ) + ], + ), + ), + ) + : EpisodeGrid( + episodes: episodes, + layout: _layout, + initNum: 0, + ), + ], + ), + ); + }), + ); + } + + @override + bool get wantKeepAlive => true; +} diff --git a/lib/home/home_groups.dart b/lib/home/home_groups.dart index 5ebf2e0..adcb353 100644 --- a/lib/home/home_groups.dart +++ b/lib/home/home_groups.dart @@ -1,1070 +1,1070 @@ -import 'dart:async'; -import 'dart:math' as math; - -import 'package:connectivity/connectivity.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; -import 'package:fluttertoast/fluttertoast.dart'; -import 'package:focused_menu/focused_menu.dart'; -import 'package:focused_menu/modals.dart'; -import 'package:line_icons/line_icons.dart'; -import 'package:permission_handler/permission_handler.dart'; -import 'package:provider/provider.dart'; -import 'package:tuple/tuple.dart'; - -import '../episodes/episode_detail.dart'; -import '../local_storage/key_value_storage.dart'; -import '../local_storage/sqflite_localpodcast.dart'; -import '../podcasts/podcast_detail.dart'; -import '../podcasts/podcast_manage.dart'; -import '../podcasts/podcastlist.dart'; -import '../state/audio_state.dart'; -import '../state/download_state.dart'; -import '../state/podcast_group.dart'; -import '../type/episodebrief.dart'; -import '../type/play_histroy.dart'; -import '../type/podcastlocal.dart'; -import '../util/custom_widget.dart'; -import '../util/extension_helper.dart'; -import '../util/general_dialog.dart'; -import '../util/pageroute.dart'; - -class ScrollPodcasts extends StatefulWidget { - @override - _ScrollPodcastsState createState() => _ScrollPodcastsState(); -} - -class _ScrollPodcastsState extends State - with SingleTickerProviderStateMixin { - int _groupIndex = 0; - AnimationController _controller; - TweenSequence _slideTween; - TweenSequence _getSlideTween(double value) => TweenSequence([ - TweenSequenceItem( - tween: Tween(begin: 0.0, end: value), weight: 3 / 5), - TweenSequenceItem(tween: ConstantTween(value), weight: 1 / 5), - TweenSequenceItem( - tween: Tween(begin: -value, end: 0), weight: 1 / 5) - ]); - - @override - void initState() { - super.initState(); - _groupIndex = 0; - _controller = - AnimationController(vsync: this, duration: Duration(milliseconds: 150)) - ..addListener(() { - if (mounted) setState(() {}); - }) - ..addStatusListener((status) { - if (status == AnimationStatus.completed) _controller.reset(); - }); - _slideTween = _getSlideTween(0.0); - } - - @override - void dispose() { - _controller.dispose(); - super.dispose(); - } - - Future _getPodcastUpdateCounts(String id) async { - var dbHelper = DBHelper(); - return await dbHelper.getPodcastUpdateCounts(id); - } - - Widget _circleContainer(BuildContext context) => Container( - margin: EdgeInsets.symmetric(horizontal: 10), - height: 50, - width: 50, - decoration: - BoxDecoration(shape: BoxShape.circle, color: context.primaryColor), - ); - - @override - Widget build(BuildContext context) { - final width = MediaQuery.of(context).size.width; - final s = context.s; - return Selector, bool, bool>>( - selector: (_, groupList) => - Tuple3(groupList.groups, groupList.created, groupList.isLoading), - builder: (_, data, __) { - var groups = data.item1; - var import = data.item2; - var isLoading = data.item3; - return isLoading - ? Container( - height: (width - 20) / 3 + 140, - ) - : groups[_groupIndex].podcastList.length == 0 - ? Container( - height: (width - 20) / 3 + 140, - child: Column( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - GestureDetector( - onVerticalDragEnd: (event) { - if (event.primaryVelocity > 200) { - if (groups.length == 1) { - Fluttertoast.showToast( - msg: s.addSomeGroups, - gravity: ToastGravity.BOTTOM, - ); - } else { - if (mounted) { - setState(() { - (_groupIndex != 0) - ? _groupIndex-- - : _groupIndex = groups.length - 1; - }); - } - } - } else if (event.primaryVelocity < -200) { - if (groups.length == 1) { - Fluttertoast.showToast( - msg: s.addSomeGroups, - gravity: ToastGravity.BOTTOM, - ); - } else { - if (mounted) { - setState(() { - (_groupIndex < groups.length - 1) - ? _groupIndex++ - : _groupIndex = 0; - }); - } - } - } - }, - child: Column( - children: [ - SizedBox( - height: 30, - child: Row( - children: [ - Padding( - padding: EdgeInsets.symmetric( - horizontal: 15.0), - child: Text( - groups[_groupIndex].name, - style: context.textTheme.bodyText1 - .copyWith( - color: context.accentColor), - )), - Spacer(), - Padding( - padding: EdgeInsets.symmetric( - horizontal: 15), - child: InkWell( - onTap: () { - if (!import) { - Navigator.push( - context, - SlideLeftRoute( - page: PodcastManage()), - ); - } - }, - onLongPress: () { - if (!import) { - Navigator.push( - context, - SlideLeftRoute( - page: PodcastList()), - ); - } - }, - borderRadius: - BorderRadius.circular(5), - child: Padding( - padding: const EdgeInsets.all(5.0), - child: Text( - s.homeGroupsSeeAll, - style: context.textTheme.bodyText1 - .copyWith( - color: import - ? context - .primaryColorDark - : context - .accentColor), - ), - ), - ), - ), - ], - ), - ), - Container( - height: 70, - color: context.scaffoldBackgroundColor, - child: Row( - children: [ - _circleContainer(context), - _circleContainer(context), - _circleContainer(context) - ], - )), - ], - )), - Container( - height: (width - 20) / 3 + 40, - color: context.primaryColor, - margin: EdgeInsets.symmetric(horizontal: 15), - child: Center( - child: _groupIndex == 0 - ? Text.rich(TextSpan( - style: context.textTheme.headline6 - .copyWith(height: 2), - children: [ - TextSpan( - text: 'Welcome to Tsacdop\n', - style: context.textTheme.headline6 - .copyWith( - color: - context.accentColor)), - TextSpan( - text: 'Get started\n', - style: context.textTheme.headline6 - .copyWith( - color: - context.accentColor)), - TextSpan(text: 'Tap '), - WidgetSpan( - child: - Icon(Icons.add_circle_outline)), - TextSpan(text: ' to search podcasts') - ], - )) - : Text(s.noPodcastGroup, - style: TextStyle( - color: context - .textTheme.bodyText2.color - .withOpacity(0.5)))), - ), - ], - ), - ) - : DefaultTabController( - length: groups[_groupIndex].podcastList.length, - child: Column( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - GestureDetector( - onVerticalDragEnd: (event) async { - if (event.primaryVelocity > 200) { - if (groups.length == 1) { - Fluttertoast.showToast( - msg: s.addSomeGroups, - gravity: ToastGravity.BOTTOM, - ); - } else { - if (mounted) { - setState( - () => _slideTween = _getSlideTween(20)); - _controller.forward(); - await Future.delayed( - Duration(milliseconds: 50)); - if (mounted) { - setState(() { - (_groupIndex != 0) - ? _groupIndex-- - : _groupIndex = groups.length - 1; - }); - } - } - } - } else if (event.primaryVelocity < -200) { - if (groups.length == 1) { - Fluttertoast.showToast( - msg: s.addSomeGroups, - gravity: ToastGravity.BOTTOM, - ); - } else { - setState( - () => _slideTween = _getSlideTween(-20)); - await Future.delayed( - Duration(milliseconds: 50)); - _controller.forward(); - if (mounted) { - setState(() { - (_groupIndex < groups.length - 1) - ? _groupIndex++ - : _groupIndex = 0; - }); - } - } - } - }, - child: Column( - children: [ - SizedBox( - height: 30, - child: Row( - children: [ - Padding( - padding: const EdgeInsets.symmetric( - horizontal: 15.0), - child: Text( - groups[_groupIndex].name, - style: context.textTheme.bodyText1 - .copyWith( - color: context.accentColor), - )), - Spacer(), - Padding( - padding: const EdgeInsets.symmetric( - horizontal: 15), - child: InkWell( - onTap: () { - if (!import) { - Navigator.push( - context, - SlideLeftRoute( - page: PodcastManage()), - ); - } - }, - onLongPress: () { - if (!import) { - Navigator.push( - context, - SlideLeftRoute( - page: PodcastList()), - ); - } - }, - borderRadius: - BorderRadius.circular(5), - child: Padding( - padding: const EdgeInsets.all(5.0), - child: Text( - s.homeGroupsSeeAll, - style: context.textTheme.bodyText1 - .copyWith( - color: import - ? context - .primaryColorDark - : context - .accentColor), - ), - )), - ) - ], - ), - ), - Container( - height: 70, - width: width, - alignment: Alignment.centerLeft, - color: context.scaffoldBackgroundColor, - child: TabBar( - labelPadding: - EdgeInsets.fromLTRB(6.0, 5.0, 6.0, 10.0), - indicator: CircleTabIndicator( - color: context.accentColor, radius: 3), - isScrollable: true, - tabs: groups[_groupIndex] - .podcasts - .map((podcastLocal) { - final color = - podcastLocal.backgroudColor(context); - return Tab( - child: Transform.translate( - offset: Offset( - 0, - _slideTween - .animate(_controller) - .value), - child: LimitedBox( - maxHeight: 50, - maxWidth: 50, - child: CircleAvatar( - backgroundColor: - color.withOpacity(0.5), - backgroundImage: - podcastLocal.avatarImage, - child: FutureBuilder( - future: _getPodcastUpdateCounts( - podcastLocal.id), - initialData: 0, - builder: (context, snapshot) { - return snapshot.data > 0 - ? Align( - alignment: Alignment - .bottomRight, - child: Container( - alignment: Alignment - .center, - height: 10, - width: 10, - decoration: BoxDecoration( - color: - Colors.red, - border: Border.all( - color: context - .primaryColor, - width: 2), - shape: BoxShape - .circle), - ), - ) - : Center(); - }), - ), - ), - ), - ); - }).toList(), - ), - ), - ], - ), - ), - Container( - height: (width - 20) / 3 + 40, - margin: const EdgeInsets.symmetric(horizontal: 10), - decoration: BoxDecoration( - color: context.scaffoldBackgroundColor, - ), - child: ScrollConfiguration( - behavior: NoGrowBehavior(), - child: TabBarView( - children: groups[_groupIndex] - .podcasts - .map((podcastLocal) { - return Container( - decoration: BoxDecoration( - color: context.brightness == - Brightness.light - ? context.primaryColor - : Colors.black12), - margin: - EdgeInsets.symmetric(horizontal: 5.0), - key: ObjectKey(podcastLocal.title), - child: Material( - color: Colors.transparent, - child: InkWell( - onTap: () { - Navigator.push( - context, - SlideLeftRoute( - page: PodcastDetail( - podcastLocal: podcastLocal, - )), - ); - }, - child: PodcastPreview( - podcastLocal: podcastLocal, - ), - ))); - }).toList(), - ), - ), - ), - ], - ), - ); - }, - ); - } -} - -class PodcastPreview extends StatefulWidget { - final PodcastLocal podcastLocal; - - PodcastPreview({this.podcastLocal, Key key}) : super(key: key); - - @override - _PodcastPreviewState createState() => _PodcastPreviewState(); -} - -class _PodcastPreviewState extends State { - Future _getRssItem; - - Future> _getRssItemTop(PodcastLocal podcastLocal) async { - var dbHelper = DBHelper(); - var episodes = await dbHelper.getRssItemTop(podcastLocal.id); - return episodes; - } - - @override - void initState() { - super.initState(); - _getRssItem = _getRssItemTop(widget.podcastLocal); - } - - @override - Widget build(BuildContext context) { - final c = widget.podcastLocal.backgroudColor(context); - return Column( - children: [ - Expanded( - child: Selector( - selector: (_, worker) => worker.created, - builder: (context, created, child) { - return FutureBuilder>( - future: _getRssItem, - builder: (context, snapshot) { - return (snapshot.hasData) - ? ShowEpisode( - episodes: snapshot.data, - podcastLocal: widget.podcastLocal, - ) - : Padding( - padding: const EdgeInsets.all(5.0), - ); - }, - ); - }), - ), - Container( - height: 40, - padding: EdgeInsets.only(left: 10.0), - alignment: Alignment.center, - child: Row( - mainAxisAlignment: MainAxisAlignment.start, - children: [ - Expanded( - flex: 4, - child: Text(widget.podcastLocal.title, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle(fontWeight: FontWeight.bold, color: c)), - ), - Expanded( - flex: 1, - child: Align( - alignment: Alignment.centerRight, - child: Padding( - padding: const EdgeInsets.only(right: 8.0), - child: Icon(Icons.arrow_forward), - )), - ), - ], - ), - ), - ], - ); - } -} - -class ShowEpisode extends StatelessWidget { - final List episodes; - final PodcastLocal podcastLocal; - final DBHelper _dbHelper = DBHelper(); - ShowEpisode({Key key, this.episodes, this.podcastLocal}) : super(key: key); - - Future>> _initData( - EpisodeBrief episode) async { - final menuList = await _getEpisodeMenu(); - final tapToOpen = await _getTapToOpenPopupMenu(); - final listened = await _isListened(episode); - final liked = await _isLiked(episode); - final downloaded = await _isDownloaded(episode); - - return Tuple5(listened, liked, downloaded, tapToOpen, menuList); - } - - Future _isListened(EpisodeBrief episode) async { - return await _dbHelper.isListened(episode.enclosureUrl); - } - - Future _isLiked(EpisodeBrief episode) async { - return await _dbHelper.isLiked(episode.enclosureUrl); - } - - Future> _getEpisodeMenu() async { - var popupMenuStorage = KeyValueStorage(episodePopupMenuKey); - var list = await popupMenuStorage.getMenu(); - return list; - } - - Future _isDownloaded(EpisodeBrief episode) async { - return await _dbHelper.isDownloaded(episode.enclosureUrl); - } - - Future _getTapToOpenPopupMenu() async { - final tapToOpenPopupMenuStorage = KeyValueStorage(tapToOpenPopupMenuKey); - var boo = await tapToOpenPopupMenuStorage.getInt(defaultValue: 0); - return boo == 1; - } - - Future _markListened(EpisodeBrief episode) async { - var marked = await _dbHelper.checkMarked(episode); - if (!marked) { - final history = PlayHistory(episode.title, episode.enclosureUrl, 0, 1); - await _dbHelper.saveHistory(history); - } - } - - Future _saveLiked(String url) async { - await _dbHelper.setLiked(url); - } - - Future _setUnliked(String url) async { - await _dbHelper.setUniked(url); - } - - Future _requestDownload(BuildContext context, - {EpisodeBrief episode}) async { - final permissionReady = await _checkPermmison(); - final downloadUsingData = await KeyValueStorage(downloadUsingDataKey) - .getBool(defaultValue: true, reverse: true); - final result = await Connectivity().checkConnectivity(); - final usingData = result == ConnectivityResult.mobile; - var dataConfirm = true; - if (permissionReady) { - if (downloadUsingData && usingData) { - dataConfirm = await _useDataConfirm(context); - } - if (dataConfirm) { - Provider.of(context, listen: false).startTask(episode); - } - } - } - - Future _checkPermmison() async { - var permission = await Permission.storage.status; - if (permission != PermissionStatus.granted) { - var permissions = await [Permission.storage].request(); - if (permissions[Permission.storage] == PermissionStatus.granted) { - return true; - } else { - return false; - } - } else { - return true; - } - } - - Future _useDataConfirm(BuildContext context) async { - var ifUseData = false; - final s = context.s; - await generalDialog( - context, - title: Text(s.cellularConfirm), - content: Text(s.cellularConfirmDes), - actions: [ - FlatButton( - onPressed: () { - Navigator.of(context).pop(); - }, - child: Text( - s.cancel, - style: TextStyle(color: Colors.grey[600]), - ), - ), - FlatButton( - onPressed: () { - ifUseData = true; - Navigator.of(context).pop(); - }, - child: Text( - s.confirm, - style: TextStyle(color: Colors.red), - ), - ) - ], - ); - return ifUseData; - } - - @override - Widget build(BuildContext context) { - final width = context.width; - final s = context.s; - final audio = Provider.of(context, listen: false); - return CustomScrollView( - physics: NeverScrollableScrollPhysics(), - primary: false, - slivers: [ - SliverPadding( - padding: const EdgeInsets.all(5.0), - sliver: SliverGrid( - gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( - childAspectRatio: 1.5, - crossAxisCount: 2, - mainAxisSpacing: 6.0, - crossAxisSpacing: 6.0, - ), - delegate: SliverChildBuilderDelegate( - (context, index) { - final c = podcastLocal.backgroudColor(context); - return Selector>>( - selector: (_, audio) => Tuple2( - audio?.episode, - audio.queue.playlist - .map((e) => e.enclosureUrl) - .toList(), - ), - builder: (_, data, __) => FutureBuilder< - Tuple5>>( - future: _initData(episodes[index]), - initialData: Tuple5(0, false, false, false, []), - builder: (context, snapshot) { - final isListened = snapshot.data.item1; - final isLiked = snapshot.data.item2; - final isDownloaded = snapshot.data.item3; - final tapToOpen = snapshot.data.item4; - final menuList = snapshot.data.item5; - return Container( - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(5.0), - color: context.scaffoldBackgroundColor, - ), - alignment: Alignment.center, - child: FocusedMenuHolder( - blurSize: 0.0, - menuItemExtent: 45, - menuBoxDecoration: BoxDecoration( - color: Colors.transparent, - borderRadius: - BorderRadius.all(Radius.circular(15.0))), - duration: Duration(milliseconds: 100), - tapMode: tapToOpen - ? TapMode.onTap - : TapMode.onLongPress, - animateMenuItems: false, - blurBackgroundColor: - context.brightness == Brightness.light - ? Colors.white38 - : Colors.black38, - bottomOffsetHeight: 10, - menuOffset: 6, - menuItems: [ - FocusedMenuItem( - backgroundColor: - context.brightness == Brightness.light - ? context.primaryColor - : context.dialogBackgroundColor, - title: Text(data.item1 != episodes[index] - ? s.play - : s.playing), - trailingIcon: Icon( - LineIcons.play_circle_solid, - color: context.accentColor, - ), - onPressed: () { - if (data != episodes[index]) { - audio.episodeLoad(episodes[index]); - } - }), - menuList.contains(1) - ? FocusedMenuItem( - backgroundColor: context.brightness == - Brightness.light - ? context.primaryColor - : context.dialogBackgroundColor, - title: data.item2.contains( - episodes[index].enclosureUrl) - ? Text(s.remove) - : Text(s.later), - trailingIcon: Icon( - LineIcons.clock_solid, - color: Colors.cyan, - ), - onPressed: () { - if (!data.item2.contains( - episodes[index].enclosureUrl)) { - audio - .addToPlaylist(episodes[index]); - Fluttertoast.showToast( - msg: s.toastAddPlaylist, - gravity: ToastGravity.BOTTOM, - ); - } else { - audio.delFromPlaylist( - episodes[index]); - Fluttertoast.showToast( - msg: s.toastRemovePlaylist, - gravity: ToastGravity.BOTTOM, - ); - } - }) - : null, - menuList.contains(2) - ? FocusedMenuItem( - backgroundColor: context.brightness == - Brightness.light - ? context.primaryColor - : context.dialogBackgroundColor, - title: isLiked - ? Text(s.unlike) - : Text(s.like), - trailingIcon: Icon(LineIcons.heart, - color: Colors.red, size: 21), - onPressed: () async { - if (isLiked) { - await _setUnliked( - episodes[index].enclosureUrl); - audio.setEpisodeState = true; - Fluttertoast.showToast( - msg: s.unliked, - gravity: ToastGravity.BOTTOM, - ); - } else { - await _saveLiked( - episodes[index].enclosureUrl); - audio.setEpisodeState = true; - Fluttertoast.showToast( - msg: s.liked, - gravity: ToastGravity.BOTTOM, - ); - } - }) - : null, - menuList.contains(3) - ? FocusedMenuItem( - backgroundColor: context.brightness == - Brightness.light - ? context.primaryColor - : context.dialogBackgroundColor, - title: isListened > 0 - ? Text(s.listened, - style: TextStyle( - color: context.textColor - .withOpacity(0.5))) - : Text( - s.markListened, - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - trailingIcon: SizedBox( - width: 23, - height: 23, - child: CustomPaint( - painter: ListenedAllPainter( - Colors.blue, - stroke: 1.5)), - ), - onPressed: () async { - if (isListened < 1) { - await _markListened( - episodes[index]); - audio.setEpisodeState = true; - Fluttertoast.showToast( - msg: s.markListened, - gravity: ToastGravity.BOTTOM, - ); - } - }) - : null, - menuList.contains(4) - ? FocusedMenuItem( - backgroundColor: context.brightness == - Brightness.light - ? context.primaryColor - : context.dialogBackgroundColor, - title: isDownloaded - ? Text(s.downloaded, - style: TextStyle( - color: context.textColor - .withOpacity(0.5))) - : Text(s.download), - trailingIcon: Icon( - LineIcons.download_solid, - color: Colors.green), - onPressed: () { - if (!isDownloaded) { - _requestDownload(context, - episode: episodes[index]); - // downloader - // .startTask(episodes[index]); - } - }) - : null - ], - action: () => Navigator.push( - context, - ScaleRoute( - page: EpisodeDetail( - episodeItem: episodes[index], - heroTag: 'scroll', - //unique hero tag - )), - ), - child: Container( - padding: EdgeInsets.all(10.0), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Expanded( - flex: 2, - child: Row( - mainAxisAlignment: - MainAxisAlignment.start, - children: [ - Hero( - tag: - '${episodes[index].enclosureUrl}scroll', - child: Container( - height: width / 18, - width: width / 18, - child: CircleAvatar( - backgroundImage: - podcastLocal.avatarImage, - ), - ), - ), - Spacer(), - Selector>( - selector: (_, audio) => Tuple2( - audio.episode, - audio.playerRunning), - builder: (_, data, __) { - return (episodes[index] - .enclosureUrl == - data.item1 - ?.enclosureUrl && - data.item2) - ? Container( - height: 20, - width: 20, - margin: EdgeInsets - .symmetric( - horizontal: 2), - decoration: - BoxDecoration( - shape: - BoxShape.circle, - ), - child: WaveLoader( - color: context - .accentColor)) - : Center(); - }), - episodes[index].isNew == 1 - ? Text( - 'New', - style: TextStyle( - color: Colors.red, - fontStyle: - FontStyle.italic), - ) - : Center(), - ], - ), - ), - Expanded( - flex: 5, - child: Container( - padding: EdgeInsets.only(top: 2.0), - alignment: Alignment.topLeft, - child: Text( - episodes[index].title, - style: TextStyle( - //fontSize: _width / 32, - ), - maxLines: 4, - overflow: TextOverflow.fade, - ), - ), - ), - Expanded( - flex: 1, - child: Row( - crossAxisAlignment: - CrossAxisAlignment.center, - children: [ - Text( - episodes[index] - .pubDate - .toDate(context), - overflow: TextOverflow.visible, - style: TextStyle( - height: 1, - fontSize: width / 35, - color: c, - fontStyle: FontStyle.italic, - ), - ), - Spacer(), - if (episodes[index].duration != 0) - Align( - alignment: Alignment.center, - child: Text( - episodes[index] - .duration - .toTime, - style: TextStyle( - fontSize: width / 35, - // color: _c, - // fontStyle: FontStyle.italic, - ), - ), - ), - episodes[index].duration == 0 || - episodes[index] - .enclosureLength == - null || - episodes[index] - .enclosureLength == - 0 - ? Center() - : Text( - '|', - style: TextStyle( - fontSize: width / 35, - ), - ), - if (episodes[index] - .enclosureLength != - null && - episodes[index] - .enclosureLength != - 0) - Container( - alignment: Alignment.center, - child: Text( - '${(episodes[index].enclosureLength) ~/ 1000000}MB', - style: TextStyle( - fontSize: width / 35), - ), - ), - ], - )), - ], - ), - ), - ), - ); - })); - }, - childCount: math.min(episodes.length, 2), - ), - ), - ), - ], - ); - } -} - -//Circle Indicator -class CircleTabIndicator extends Decoration { - final BoxPainter _painter; - CircleTabIndicator({@required Color color, @required double radius}) - : _painter = _CirclePainter(color, radius); - @override - BoxPainter createBoxPainter([onChanged]) => _painter; -} - -class _CirclePainter extends BoxPainter { - final Paint _paint; - final double radius; - - _CirclePainter(Color color, this.radius) - : _paint = Paint() - ..color = color - ..isAntiAlias = true; - - @override - void paint(Canvas canvas, Offset offset, ImageConfiguration cfg) { - final circleOffset = - offset + Offset(cfg.size.width / 2, cfg.size.height - radius); - canvas.drawCircle(circleOffset, radius, _paint); - } -} +import 'dart:async'; +import 'dart:math' as math; + +import 'package:connectivity/connectivity.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:focused_menu/focused_menu.dart'; +import 'package:focused_menu/modals.dart'; +import 'package:line_icons/line_icons.dart'; +import 'package:permission_handler/permission_handler.dart'; +import 'package:provider/provider.dart'; +import 'package:tuple/tuple.dart'; + +import '../episodes/episode_detail.dart'; +import '../local_storage/key_value_storage.dart'; +import '../local_storage/sqflite_localpodcast.dart'; +import '../podcasts/podcast_detail.dart'; +import '../podcasts/podcast_manage.dart'; +import '../podcasts/podcastlist.dart'; +import '../state/audio_state.dart'; +import '../state/download_state.dart'; +import '../state/podcast_group.dart'; +import '../type/episodebrief.dart'; +import '../type/play_histroy.dart'; +import '../type/podcastlocal.dart'; +import '../util/custom_widget.dart'; +import '../util/extension_helper.dart'; +import '../util/general_dialog.dart'; +import '../util/pageroute.dart'; + +class ScrollPodcasts extends StatefulWidget { + @override + _ScrollPodcastsState createState() => _ScrollPodcastsState(); +} + +class _ScrollPodcastsState extends State + with SingleTickerProviderStateMixin { + int _groupIndex = 0; + AnimationController _controller; + TweenSequence _slideTween; + TweenSequence _getSlideTween(double value) => TweenSequence([ + TweenSequenceItem( + tween: Tween(begin: 0.0, end: value), weight: 3 / 5), + TweenSequenceItem(tween: ConstantTween(value), weight: 1 / 5), + TweenSequenceItem( + tween: Tween(begin: -value, end: 0), weight: 1 / 5) + ]); + + @override + void initState() { + super.initState(); + _groupIndex = 0; + _controller = + AnimationController(vsync: this, duration: Duration(milliseconds: 150)) + ..addListener(() { + if (mounted) setState(() {}); + }) + ..addStatusListener((status) { + if (status == AnimationStatus.completed) _controller.reset(); + }); + _slideTween = _getSlideTween(0.0); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + Future _getPodcastUpdateCounts(String id) async { + var dbHelper = DBHelper(); + return await dbHelper.getPodcastUpdateCounts(id); + } + + Widget _circleContainer(BuildContext context) => Container( + margin: EdgeInsets.symmetric(horizontal: 10), + height: 50, + width: 50, + decoration: + BoxDecoration(shape: BoxShape.circle, color: context.primaryColor), + ); + + @override + Widget build(BuildContext context) { + final width = MediaQuery.of(context).size.width; + final s = context.s; + return Selector, bool, bool>>( + selector: (_, groupList) => + Tuple3(groupList.groups, groupList.created, groupList.isLoading), + builder: (_, data, __) { + var groups = data.item1; + var import = data.item2; + var isLoading = data.item3; + return isLoading + ? Container( + height: (width - 20) / 3 + 140, + ) + : groups[_groupIndex].podcastList.length == 0 + ? Container( + height: (width - 20) / 3 + 140, + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + GestureDetector( + onVerticalDragEnd: (event) { + if (event.primaryVelocity > 200) { + if (groups.length == 1) { + Fluttertoast.showToast( + msg: s.addSomeGroups, + gravity: ToastGravity.BOTTOM, + ); + } else { + if (mounted) { + setState(() { + (_groupIndex != 0) + ? _groupIndex-- + : _groupIndex = groups.length - 1; + }); + } + } + } else if (event.primaryVelocity < -200) { + if (groups.length == 1) { + Fluttertoast.showToast( + msg: s.addSomeGroups, + gravity: ToastGravity.BOTTOM, + ); + } else { + if (mounted) { + setState(() { + (_groupIndex < groups.length - 1) + ? _groupIndex++ + : _groupIndex = 0; + }); + } + } + } + }, + child: Column( + children: [ + SizedBox( + height: 30, + child: Row( + children: [ + Padding( + padding: EdgeInsets.symmetric( + horizontal: 15.0), + child: Text( + groups[_groupIndex].name, + style: context.textTheme.bodyText1 + .copyWith( + color: context.accentColor), + )), + Spacer(), + Padding( + padding: EdgeInsets.symmetric( + horizontal: 15), + child: InkWell( + onTap: () { + if (!import) { + Navigator.push( + context, + SlideLeftRoute( + page: PodcastManage()), + ); + } + }, + onLongPress: () { + if (!import) { + Navigator.push( + context, + SlideLeftRoute( + page: PodcastList()), + ); + } + }, + borderRadius: + BorderRadius.circular(5), + child: Padding( + padding: const EdgeInsets.all(5.0), + child: Text( + s.homeGroupsSeeAll, + style: context.textTheme.bodyText1 + .copyWith( + color: import + ? context + .primaryColorDark + : context + .accentColor), + ), + ), + ), + ), + ], + ), + ), + Container( + height: 70, + color: context.scaffoldBackgroundColor, + child: Row( + children: [ + _circleContainer(context), + _circleContainer(context), + _circleContainer(context) + ], + )), + ], + )), + Container( + height: (width - 20) / 3 + 40, + color: context.primaryColor, + margin: EdgeInsets.symmetric(horizontal: 15), + child: Center( + child: _groupIndex == 0 + ? Text.rich(TextSpan( + style: context.textTheme.headline6 + .copyWith(height: 2), + children: [ + TextSpan( + text: 'Welcome to Tsacdop\n', + style: context.textTheme.headline6 + .copyWith( + color: + context.accentColor)), + TextSpan( + text: 'Get started\n', + style: context.textTheme.headline6 + .copyWith( + color: + context.accentColor)), + TextSpan(text: 'Tap '), + WidgetSpan( + child: + Icon(Icons.add_circle_outline)), + TextSpan(text: ' to search podcasts') + ], + )) + : Text(s.noPodcastGroup, + style: TextStyle( + color: context + .textTheme.bodyText2.color + .withOpacity(0.5)))), + ), + ], + ), + ) + : DefaultTabController( + length: groups[_groupIndex].podcastList.length, + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + GestureDetector( + onVerticalDragEnd: (event) async { + if (event.primaryVelocity > 200) { + if (groups.length == 1) { + Fluttertoast.showToast( + msg: s.addSomeGroups, + gravity: ToastGravity.BOTTOM, + ); + } else { + if (mounted) { + setState( + () => _slideTween = _getSlideTween(20)); + _controller.forward(); + await Future.delayed( + Duration(milliseconds: 50)); + if (mounted) { + setState(() { + (_groupIndex != 0) + ? _groupIndex-- + : _groupIndex = groups.length - 1; + }); + } + } + } + } else if (event.primaryVelocity < -200) { + if (groups.length == 1) { + Fluttertoast.showToast( + msg: s.addSomeGroups, + gravity: ToastGravity.BOTTOM, + ); + } else { + setState( + () => _slideTween = _getSlideTween(-20)); + await Future.delayed( + Duration(milliseconds: 50)); + _controller.forward(); + if (mounted) { + setState(() { + (_groupIndex < groups.length - 1) + ? _groupIndex++ + : _groupIndex = 0; + }); + } + } + } + }, + child: Column( + children: [ + SizedBox( + height: 30, + child: Row( + children: [ + Padding( + padding: const EdgeInsets.symmetric( + horizontal: 15.0), + child: Text( + groups[_groupIndex].name, + style: context.textTheme.bodyText1 + .copyWith( + color: context.accentColor), + )), + Spacer(), + Padding( + padding: const EdgeInsets.symmetric( + horizontal: 15), + child: InkWell( + onTap: () { + if (!import) { + Navigator.push( + context, + SlideLeftRoute( + page: PodcastManage()), + ); + } + }, + onLongPress: () { + if (!import) { + Navigator.push( + context, + SlideLeftRoute( + page: PodcastList()), + ); + } + }, + borderRadius: + BorderRadius.circular(5), + child: Padding( + padding: const EdgeInsets.all(5.0), + child: Text( + s.homeGroupsSeeAll, + style: context.textTheme.bodyText1 + .copyWith( + color: import + ? context + .primaryColorDark + : context + .accentColor), + ), + )), + ) + ], + ), + ), + Container( + height: 70, + width: width, + alignment: Alignment.centerLeft, + color: context.scaffoldBackgroundColor, + child: TabBar( + labelPadding: + EdgeInsets.fromLTRB(6.0, 5.0, 6.0, 10.0), + indicator: CircleTabIndicator( + color: context.accentColor, radius: 3), + isScrollable: true, + tabs: groups[_groupIndex] + .podcasts + .map((podcastLocal) { + final color = + podcastLocal.backgroudColor(context); + return Tab( + child: Transform.translate( + offset: Offset( + 0, + _slideTween + .animate(_controller) + .value), + child: LimitedBox( + maxHeight: 50, + maxWidth: 50, + child: CircleAvatar( + backgroundColor: + color.withOpacity(0.5), + backgroundImage: + podcastLocal.avatarImage, + child: FutureBuilder( + future: _getPodcastUpdateCounts( + podcastLocal.id), + initialData: 0, + builder: (context, snapshot) { + return snapshot.data > 0 + ? Align( + alignment: Alignment + .bottomRight, + child: Container( + alignment: Alignment + .center, + height: 10, + width: 10, + decoration: BoxDecoration( + color: + Colors.red, + border: Border.all( + color: context + .primaryColor, + width: 2), + shape: BoxShape + .circle), + ), + ) + : Center(); + }), + ), + ), + ), + ); + }).toList(), + ), + ), + ], + ), + ), + Container( + height: (width - 20) / 3 + 40, + margin: const EdgeInsets.symmetric(horizontal: 10), + decoration: BoxDecoration( + color: context.scaffoldBackgroundColor, + ), + child: ScrollConfiguration( + behavior: NoGrowBehavior(), + child: TabBarView( + children: groups[_groupIndex] + .podcasts + .map((podcastLocal) { + return Container( + decoration: BoxDecoration( + color: context.brightness == + Brightness.light + ? context.primaryColor + : Colors.black12), + margin: + EdgeInsets.symmetric(horizontal: 5.0), + key: ObjectKey(podcastLocal.title), + child: Material( + color: Colors.transparent, + child: InkWell( + onTap: () { + Navigator.push( + context, + SlideLeftRoute( + page: PodcastDetail( + podcastLocal: podcastLocal, + )), + ); + }, + child: PodcastPreview( + podcastLocal: podcastLocal, + ), + ))); + }).toList(), + ), + ), + ), + ], + ), + ); + }, + ); + } +} + +class PodcastPreview extends StatefulWidget { + final PodcastLocal podcastLocal; + + PodcastPreview({this.podcastLocal, Key key}) : super(key: key); + + @override + _PodcastPreviewState createState() => _PodcastPreviewState(); +} + +class _PodcastPreviewState extends State { + Future _getRssItem; + + Future> _getRssItemTop(PodcastLocal podcastLocal) async { + var dbHelper = DBHelper(); + var episodes = await dbHelper.getRssItemTop(podcastLocal.id); + return episodes; + } + + @override + void initState() { + super.initState(); + _getRssItem = _getRssItemTop(widget.podcastLocal); + } + + @override + Widget build(BuildContext context) { + final c = widget.podcastLocal.backgroudColor(context); + return Column( + children: [ + Expanded( + child: Selector( + selector: (_, worker) => worker.created, + builder: (context, created, child) { + return FutureBuilder>( + future: _getRssItem, + builder: (context, snapshot) { + return (snapshot.hasData) + ? ShowEpisode( + episodes: snapshot.data, + podcastLocal: widget.podcastLocal, + ) + : Padding( + padding: const EdgeInsets.all(5.0), + ); + }, + ); + }), + ), + Container( + height: 40, + padding: EdgeInsets.only(left: 10.0), + alignment: Alignment.center, + child: Row( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + Expanded( + flex: 4, + child: Text(widget.podcastLocal.title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontWeight: FontWeight.bold, color: c)), + ), + Expanded( + flex: 1, + child: Align( + alignment: Alignment.centerRight, + child: Padding( + padding: const EdgeInsets.only(right: 8.0), + child: Icon(Icons.arrow_forward), + )), + ), + ], + ), + ), + ], + ); + } +} + +class ShowEpisode extends StatelessWidget { + final List episodes; + final PodcastLocal podcastLocal; + final DBHelper _dbHelper = DBHelper(); + ShowEpisode({Key key, this.episodes, this.podcastLocal}) : super(key: key); + + Future>> _initData( + EpisodeBrief episode) async { + final menuList = await _getEpisodeMenu(); + final tapToOpen = await _getTapToOpenPopupMenu(); + final listened = await _isListened(episode); + final liked = await _isLiked(episode); + final downloaded = await _isDownloaded(episode); + + return Tuple5(listened, liked, downloaded, tapToOpen, menuList); + } + + Future _isListened(EpisodeBrief episode) async { + return await _dbHelper.isListened(episode.enclosureUrl); + } + + Future _isLiked(EpisodeBrief episode) async { + return await _dbHelper.isLiked(episode.enclosureUrl); + } + + Future> _getEpisodeMenu() async { + var popupMenuStorage = KeyValueStorage(episodePopupMenuKey); + var list = await popupMenuStorage.getMenu(); + return list; + } + + Future _isDownloaded(EpisodeBrief episode) async { + return await _dbHelper.isDownloaded(episode.enclosureUrl); + } + + Future _getTapToOpenPopupMenu() async { + final tapToOpenPopupMenuStorage = KeyValueStorage(tapToOpenPopupMenuKey); + var boo = await tapToOpenPopupMenuStorage.getInt(defaultValue: 0); + return boo == 1; + } + + Future _markListened(EpisodeBrief episode) async { + var marked = await _dbHelper.checkMarked(episode); + if (!marked) { + final history = PlayHistory(episode.title, episode.enclosureUrl, 0, 1); + await _dbHelper.saveHistory(history); + } + } + + Future _saveLiked(String url) async { + await _dbHelper.setLiked(url); + } + + Future _setUnliked(String url) async { + await _dbHelper.setUniked(url); + } + + Future _requestDownload(BuildContext context, + {EpisodeBrief episode}) async { + final permissionReady = await _checkPermmison(); + final downloadUsingData = await KeyValueStorage(downloadUsingDataKey) + .getBool(defaultValue: true, reverse: true); + final result = await Connectivity().checkConnectivity(); + final usingData = result == ConnectivityResult.mobile; + var dataConfirm = true; + if (permissionReady) { + if (downloadUsingData && usingData) { + dataConfirm = await _useDataConfirm(context); + } + if (dataConfirm) { + Provider.of(context, listen: false).startTask(episode); + } + } + } + + Future _checkPermmison() async { + var permission = await Permission.storage.status; + if (permission != PermissionStatus.granted) { + var permissions = await [Permission.storage].request(); + if (permissions[Permission.storage] == PermissionStatus.granted) { + return true; + } else { + return false; + } + } else { + return true; + } + } + + Future _useDataConfirm(BuildContext context) async { + var ifUseData = false; + final s = context.s; + await generalDialog( + context, + title: Text(s.cellularConfirm), + content: Text(s.cellularConfirmDes), + actions: [ + FlatButton( + onPressed: () { + Navigator.of(context).pop(); + }, + child: Text( + s.cancel, + style: TextStyle(color: Colors.grey[600]), + ), + ), + FlatButton( + onPressed: () { + ifUseData = true; + Navigator.of(context).pop(); + }, + child: Text( + s.confirm, + style: TextStyle(color: Colors.red), + ), + ) + ], + ); + return ifUseData; + } + + @override + Widget build(BuildContext context) { + final width = context.width; + final s = context.s; + final audio = Provider.of(context, listen: false); + return CustomScrollView( + physics: NeverScrollableScrollPhysics(), + primary: false, + slivers: [ + SliverPadding( + padding: const EdgeInsets.all(5.0), + sliver: SliverGrid( + gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( + childAspectRatio: 1.5, + crossAxisCount: 2, + mainAxisSpacing: 6.0, + crossAxisSpacing: 6.0, + ), + delegate: SliverChildBuilderDelegate( + (context, index) { + final c = podcastLocal.backgroudColor(context); + return Selector>>( + selector: (_, audio) => Tuple2( + audio?.episode, + audio.queue.playlist + .map((e) => e.enclosureUrl) + .toList(), + ), + builder: (_, data, __) => FutureBuilder< + Tuple5>>( + future: _initData(episodes[index]), + initialData: Tuple5(0, false, false, false, []), + builder: (context, snapshot) { + final isListened = snapshot.data.item1; + final isLiked = snapshot.data.item2; + final isDownloaded = snapshot.data.item3; + final tapToOpen = snapshot.data.item4; + final menuList = snapshot.data.item5; + return Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(5.0), + color: context.scaffoldBackgroundColor, + ), + alignment: Alignment.center, + child: FocusedMenuHolder( + blurSize: 0.0, + menuItemExtent: 45, + menuBoxDecoration: BoxDecoration( + color: Colors.transparent, + borderRadius: + BorderRadius.all(Radius.circular(15.0))), + duration: Duration(milliseconds: 100), + tapMode: tapToOpen + ? TapMode.onTap + : TapMode.onLongPress, + animateMenuItems: false, + blurBackgroundColor: + context.brightness == Brightness.light + ? Colors.white38 + : Colors.black38, + bottomOffsetHeight: 10, + menuOffset: 6, + menuItems: [ + FocusedMenuItem( + backgroundColor: + context.brightness == Brightness.light + ? context.primaryColor + : context.dialogBackgroundColor, + title: Text(data.item1 != episodes[index] + ? s.play + : s.playing), + trailingIcon: Icon( + LineIcons.play_circle_solid, + color: context.accentColor, + ), + onPressed: () { + if (data != episodes[index]) { + audio.episodeLoad(episodes[index]); + } + }), + menuList.contains(1) + ? FocusedMenuItem( + backgroundColor: context.brightness == + Brightness.light + ? context.primaryColor + : context.dialogBackgroundColor, + title: data.item2.contains( + episodes[index].enclosureUrl) + ? Text(s.remove) + : Text(s.later), + trailingIcon: Icon( + LineIcons.clock_solid, + color: Colors.cyan, + ), + onPressed: () { + if (!data.item2.contains( + episodes[index].enclosureUrl)) { + audio + .addToPlaylist(episodes[index]); + Fluttertoast.showToast( + msg: s.toastAddPlaylist, + gravity: ToastGravity.BOTTOM, + ); + } else { + audio.delFromPlaylist( + episodes[index]); + Fluttertoast.showToast( + msg: s.toastRemovePlaylist, + gravity: ToastGravity.BOTTOM, + ); + } + }) + : null, + menuList.contains(2) + ? FocusedMenuItem( + backgroundColor: context.brightness == + Brightness.light + ? context.primaryColor + : context.dialogBackgroundColor, + title: isLiked + ? Text(s.unlike) + : Text(s.like), + trailingIcon: Icon(LineIcons.heart, + color: Colors.red, size: 21), + onPressed: () async { + if (isLiked) { + await _setUnliked( + episodes[index].enclosureUrl); + audio.setEpisodeState = true; + Fluttertoast.showToast( + msg: s.unliked, + gravity: ToastGravity.BOTTOM, + ); + } else { + await _saveLiked( + episodes[index].enclosureUrl); + audio.setEpisodeState = true; + Fluttertoast.showToast( + msg: s.liked, + gravity: ToastGravity.BOTTOM, + ); + } + }) + : null, + menuList.contains(3) + ? FocusedMenuItem( + backgroundColor: context.brightness == + Brightness.light + ? context.primaryColor + : context.dialogBackgroundColor, + title: isListened > 0 + ? Text(s.listened, + style: TextStyle( + color: context.textColor + .withOpacity(0.5))) + : Text( + s.markListened, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + trailingIcon: SizedBox( + width: 23, + height: 23, + child: CustomPaint( + painter: ListenedAllPainter( + Colors.blue, + stroke: 1.5)), + ), + onPressed: () async { + if (isListened < 1) { + await _markListened( + episodes[index]); + audio.setEpisodeState = true; + Fluttertoast.showToast( + msg: s.markListened, + gravity: ToastGravity.BOTTOM, + ); + } + }) + : null, + menuList.contains(4) + ? FocusedMenuItem( + backgroundColor: context.brightness == + Brightness.light + ? context.primaryColor + : context.dialogBackgroundColor, + title: isDownloaded + ? Text(s.downloaded, + style: TextStyle( + color: context.textColor + .withOpacity(0.5))) + : Text(s.download), + trailingIcon: Icon( + LineIcons.download_solid, + color: Colors.green), + onPressed: () { + if (!isDownloaded) { + _requestDownload(context, + episode: episodes[index]); + // downloader + // .startTask(episodes[index]); + } + }) + : null + ], + action: () => Navigator.push( + context, + ScaleRoute( + page: EpisodeDetail( + episodeItem: episodes[index], + heroTag: 'scroll', + //unique hero tag + )), + ), + child: Container( + padding: EdgeInsets.all(10.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Expanded( + flex: 2, + child: Row( + mainAxisAlignment: + MainAxisAlignment.start, + children: [ + Hero( + tag: + '${episodes[index].enclosureUrl}scroll', + child: Container( + height: width / 18, + width: width / 18, + child: CircleAvatar( + backgroundImage: + podcastLocal.avatarImage, + ), + ), + ), + Spacer(), + Selector>( + selector: (_, audio) => Tuple2( + audio.episode, + audio.playerRunning), + builder: (_, data, __) { + return (episodes[index] + .enclosureUrl == + data.item1 + ?.enclosureUrl && + data.item2) + ? Container( + height: 20, + width: 20, + margin: EdgeInsets + .symmetric( + horizontal: 2), + decoration: + BoxDecoration( + shape: + BoxShape.circle, + ), + child: WaveLoader( + color: context + .accentColor)) + : Center(); + }), + episodes[index].isNew == 1 + ? Text( + 'New', + style: TextStyle( + color: Colors.red, + fontStyle: + FontStyle.italic), + ) + : Center(), + ], + ), + ), + Expanded( + flex: 5, + child: Container( + padding: EdgeInsets.only(top: 2.0), + alignment: Alignment.topLeft, + child: Text( + episodes[index].title, + style: TextStyle( + //fontSize: _width / 32, + ), + maxLines: 4, + overflow: TextOverflow.fade, + ), + ), + ), + Expanded( + flex: 1, + child: Row( + crossAxisAlignment: + CrossAxisAlignment.center, + children: [ + Text( + episodes[index] + .pubDate + .toDate(context), + overflow: TextOverflow.visible, + style: TextStyle( + height: 1, + fontSize: width / 35, + color: c, + fontStyle: FontStyle.italic, + ), + ), + Spacer(), + if (episodes[index].duration != 0) + Align( + alignment: Alignment.center, + child: Text( + episodes[index] + .duration + .toTime, + style: TextStyle( + fontSize: width / 35, + // color: _c, + // fontStyle: FontStyle.italic, + ), + ), + ), + episodes[index].duration == 0 || + episodes[index] + .enclosureLength == + null || + episodes[index] + .enclosureLength == + 0 + ? Center() + : Text( + '|', + style: TextStyle( + fontSize: width / 35, + ), + ), + if (episodes[index] + .enclosureLength != + null && + episodes[index] + .enclosureLength != + 0) + Container( + alignment: Alignment.center, + child: Text( + '${(episodes[index].enclosureLength) ~/ 1000000}MB', + style: TextStyle( + fontSize: width / 35), + ), + ), + ], + )), + ], + ), + ), + ), + ); + })); + }, + childCount: math.min(episodes.length, 2), + ), + ), + ), + ], + ); + } +} + +//Circle Indicator +class CircleTabIndicator extends Decoration { + final BoxPainter _painter; + CircleTabIndicator({@required Color color, @required double radius}) + : _painter = _CirclePainter(color, radius); + @override + BoxPainter createBoxPainter([onChanged]) => _painter; +} + +class _CirclePainter extends BoxPainter { + final Paint _paint; + final double radius; + + _CirclePainter(Color color, this.radius) + : _paint = Paint() + ..color = color + ..isAntiAlias = true; + + @override + void paint(Canvas canvas, Offset offset, ImageConfiguration cfg) { + final circleOffset = + offset + Offset(cfg.size.width / 2, cfg.size.height - radius); + canvas.drawCircle(circleOffset, radius, _paint); + } +} diff --git a/lib/home/home_menu.dart b/lib/home/home_menu.dart index 8ea3a0c..5c68db0 100644 --- a/lib/home/home_menu.dart +++ b/lib/home/home_menu.dart @@ -1,216 +1,202 @@ -import 'dart:async'; -import 'dart:developer' as developer; -import 'dart:io'; - -import 'package:file_picker/file_picker.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:fluttertoast/fluttertoast.dart'; -import 'package:line_icons/line_icons.dart'; -import 'package:provider/provider.dart'; - -import '../local_storage/key_value_storage.dart'; -import '../service/opml_build.dart'; -import '../settings/settting.dart'; -import '../state/podcast_group.dart'; -import '../state/refresh_podcast.dart'; -import '../util/extension_helper.dart'; -import 'about.dart'; - -class PopupMenu extends StatefulWidget { - @override - _PopupMenuState createState() => _PopupMenuState(); -} - -class _PopupMenuState extends State { - Future _getRefreshDate(BuildContext context) async { - int refreshDate; - var refreshstorage = KeyValueStorage('refreshdate'); - var i = await refreshstorage.getInt(); - if (i == 0) { - var refreshstorage = KeyValueStorage('refreshdate'); - await refreshstorage.saveInt(DateTime.now().millisecondsSinceEpoch); - refreshDate = DateTime.now().millisecondsSinceEpoch; - } else { - refreshDate = i; - } - return refreshDate.toDate(context); - // var date = DateTime.fromMillisecondsSinceEpoch(refreshDate); - // var difference = DateTime.now().difference(date); - // if (difference.inSeconds < 60) { - // return s.secondsAgo(difference.inSeconds); - // } else if (difference.inMinutes < 60) { - // return s.minsAgo(difference.inMinutes); - // } else if (difference.inHours < 24) { - // return s.hoursAgo(difference.inHours); - // } else if (difference.inDays < 7) { - // return s.daysAgo(difference.inDays); - // } else { - // return DateFormat.yMMMd() - // .format(DateTime.fromMillisecondsSinceEpoch(refreshDate)); - // } - } - - void _saveOmpl(String path) async { - var subscribeWorker = Provider.of(context, listen: false); - var rssExp = RegExp(r'^(https?):\/\/(.*)'); - final s = context.s; - var file = File(path); - try { - final opml = file.readAsStringSync(); - Map> data = PodcastsBackup.parseOPML(opml); - for (var entry in data.entries) { - var title = entry.key; - var list = entry.value.reversed; - for (var rss in list) { - var rssLink = rssExp.stringMatch(rss.xmlUrl); - if (rssLink != null) { - var item = SubscribeItem(rssLink, rss.text, group: title); - await subscribeWorker.setSubscribeItem(item); - await Future.delayed(Duration(milliseconds: 200)); - } - } - } - } catch (e) { - developer.log(e, name: 'OMPL parse error'); - Fluttertoast.showToast( - msg: s.toastFileError, - gravity: ToastGravity.TOP, - ); - } - } - - void _getFilePath() async { - final s = context.s; - try { - var filePickResult = - await FilePicker.platform.pickFiles(type: FileType.any); - if (filePickResult == null) { - return; - } - Fluttertoast.showToast( - msg: s.toastReadFile, - gravity: ToastGravity.TOP, - ); - final filePath = filePickResult.files.first.path; - _saveOmpl(filePath); - } on PlatformException catch (e) { - developer.log(e.toString(), name: 'Get OMPL file'); - } - } - - @override - Widget build(BuildContext context) { - var refreshWorker = Provider.of(context, listen: false); - final s = context.s; - return Material( - color: Colors.transparent, - borderRadius: BorderRadius.circular(100), - clipBehavior: Clip.hardEdge, - child: PopupMenuButton( - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(10))), - elevation: 1, - tooltip: s.menu, - itemBuilder: (context) => [ - PopupMenuItem( - value: 1, - child: Container( - padding: EdgeInsets.only(left: 10), - child: Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Icon(LineIcons.cloud_download_alt_solid), - Padding( - padding: EdgeInsets.symmetric(horizontal: 5.0), - ), - Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - s.homeToprightMenuRefreshAll, - ), - FutureBuilder( - future: _getRefreshDate(context), - builder: (_, snapshot) { - if (snapshot.hasData) { - return Text( - snapshot.data, - style: - TextStyle(color: Colors.red, fontSize: 12), - ); - } else { - return Center(); - } - }) - ], - ), - ], - ), - ), - ), - PopupMenuItem( - value: 2, - child: Container( - padding: EdgeInsets.only(left: 10), - child: Row( - children: [ - Icon(LineIcons.paperclip_solid), - Padding( - padding: EdgeInsets.symmetric(horizontal: 5.0), - ), - Text(s.homeToprightMenuImportOMPL), - ], - ), - ), - ), - PopupMenuItem( - value: 4, - child: Container( - padding: EdgeInsets.only(left: 10), - child: Row( - children: [ - Icon(LineIcons.cog_solid), - Padding( - padding: EdgeInsets.symmetric(horizontal: 5.0), - ), - Text(s.settings), - ], - ), - ), - ), - PopupMenuItem( - value: 5, - child: Container( - padding: EdgeInsets.only(left: 10), - child: Row( - children: [ - Icon(LineIcons.info_circle_solid), - Padding( - padding: EdgeInsets.symmetric(horizontal: 5.0), - ), - Text(s.homeToprightMenuAbout), - ], - ), - ), - ), - ], - onSelected: (value) { - if (value == 5) { - Navigator.push( - context, MaterialPageRoute(builder: (context) => AboutApp())); - } else if (value == 2) { - _getFilePath(); - } else if (value == 1) { - refreshWorker.start([]); - } else if (value == 3) { - // setting.theme != 2 ? setting.setTheme(2) : setting.setTheme(1); - } else if (value == 4) { - Navigator.push( - context, MaterialPageRoute(builder: (context) => Settings())); - } - }, - ), - ); - } -} +import 'dart:async'; +import 'dart:developer' as developer; +import 'dart:io'; + +import 'package:file_picker/file_picker.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:line_icons/line_icons.dart'; +import 'package:provider/provider.dart'; + +import '../local_storage/key_value_storage.dart'; +import '../service/opml_build.dart'; +import '../settings/settting.dart'; +import '../state/podcast_group.dart'; +import '../state/refresh_podcast.dart'; +import '../util/extension_helper.dart'; +import 'about.dart'; + +class PopupMenu extends StatefulWidget { + @override + _PopupMenuState createState() => _PopupMenuState(); +} + +class _PopupMenuState extends State { + Future _getRefreshDate(BuildContext context) async { + int refreshDate; + var refreshstorage = KeyValueStorage('refreshdate'); + var i = await refreshstorage.getInt(); + if (i == 0) { + var refreshstorage = KeyValueStorage('refreshdate'); + await refreshstorage.saveInt(DateTime.now().millisecondsSinceEpoch); + refreshDate = DateTime.now().millisecondsSinceEpoch; + } else { + refreshDate = i; + } + return refreshDate.toDate(context); + } + + void _saveOmpl(String path) async { + var subscribeWorker = Provider.of(context, listen: false); + var rssExp = RegExp(r'^(https?):\/\/(.*)'); + final s = context.s; + var file = File(path); + try { + final opml = file.readAsStringSync(); + Map> data = PodcastsBackup.parseOPML(opml); + for (var entry in data.entries) { + var title = entry.key; + var list = entry.value.reversed; + for (var rss in list) { + var rssLink = rssExp.stringMatch(rss.xmlUrl); + if (rssLink != null) { + var item = SubscribeItem(rssLink, rss.text, group: title); + await subscribeWorker.setSubscribeItem(item); + await Future.delayed(Duration(milliseconds: 200)); + } + } + } + } catch (e) { + developer.log(e, name: 'OMPL parse error'); + Fluttertoast.showToast( + msg: s.toastFileError, + gravity: ToastGravity.TOP, + ); + } + } + + void _getFilePath() async { + final s = context.s; + try { + var filePickResult = + await FilePicker.platform.pickFiles(type: FileType.any); + if (filePickResult == null) { + return; + } + Fluttertoast.showToast( + msg: s.toastReadFile, + gravity: ToastGravity.TOP, + ); + final filePath = filePickResult.files.first.path; + _saveOmpl(filePath); + } on PlatformException catch (e) { + developer.log(e.toString(), name: 'Get OMPL file'); + } + } + + @override + Widget build(BuildContext context) { + var refreshWorker = Provider.of(context, listen: false); + final s = context.s; + return Material( + color: Colors.transparent, + borderRadius: BorderRadius.circular(100), + clipBehavior: Clip.hardEdge, + child: PopupMenuButton( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(10))), + elevation: 1, + tooltip: s.menu, + itemBuilder: (context) => [ + PopupMenuItem( + value: 1, + child: Container( + padding: EdgeInsets.only(left: 10), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(LineIcons.cloud_download_alt_solid), + Padding( + padding: EdgeInsets.symmetric(horizontal: 5.0), + ), + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + s.homeToprightMenuRefreshAll, + ), + FutureBuilder( + future: _getRefreshDate(context), + builder: (_, snapshot) { + if (snapshot.hasData) { + return Text( + snapshot.data, + style: + TextStyle(color: Colors.red, fontSize: 12), + ); + } else { + return Center(); + } + }) + ], + ), + ], + ), + ), + ), + PopupMenuItem( + value: 2, + child: Container( + padding: EdgeInsets.only(left: 10), + child: Row( + children: [ + Icon(LineIcons.paperclip_solid), + Padding( + padding: EdgeInsets.symmetric(horizontal: 5.0), + ), + Text(s.homeToprightMenuImportOMPL), + ], + ), + ), + ), + PopupMenuItem( + value: 4, + child: Container( + padding: EdgeInsets.only(left: 10), + child: Row( + children: [ + Icon(LineIcons.cog_solid), + Padding( + padding: EdgeInsets.symmetric(horizontal: 5.0), + ), + Text(s.settings), + ], + ), + ), + ), + PopupMenuItem( + value: 5, + child: Container( + padding: EdgeInsets.only(left: 10), + child: Row( + children: [ + Icon(LineIcons.info_circle_solid), + Padding( + padding: EdgeInsets.symmetric(horizontal: 5.0), + ), + Text(s.homeToprightMenuAbout), + ], + ), + ), + ), + ], + onSelected: (value) { + if (value == 5) { + Navigator.push( + context, MaterialPageRoute(builder: (context) => AboutApp())); + } else if (value == 2) { + _getFilePath(); + } else if (value == 1) { + refreshWorker.start([]); + } else if (value == 3) { + // setting.theme != 2 ? setting.setTheme(2) : setting.setTheme(1); + } else if (value == 4) { + Navigator.push( + context, MaterialPageRoute(builder: (context) => Settings())); + } + }, + ), + ); + } +} diff --git a/lib/home/import_ompl.dart b/lib/home/import_ompl.dart index 0e4aeac..533f134 100644 --- a/lib/home/import_ompl.dart +++ b/lib/home/import_ompl.dart @@ -1,105 +1,105 @@ -import 'package:connectivity/connectivity.dart'; -import 'package:flutter/material.dart'; -import 'package:provider/provider.dart'; - -import '../local_storage/key_value_storage.dart'; -import '../local_storage/sqflite_localpodcast.dart'; -import '../state/download_state.dart'; -import '../state/podcast_group.dart'; -import '../state/refresh_podcast.dart'; -import '../util/extension_helper.dart'; - -class Import extends StatelessWidget { - Widget importColumn(String text, BuildContext context) { - return Container( - color: context.primaryColorDark, - child: Column( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - SizedBox(height: 2.0, child: LinearProgressIndicator()), - Container( - padding: EdgeInsets.symmetric(horizontal: 20.0), - height: 20.0, - alignment: Alignment.centerLeft, - child: Text(text), - ), - ]), - ); - } - - _autoDownloadNew(BuildContext context) async { - final dbHelper = DBHelper(); - var downloader = Provider.of(context, listen: false); - var result = await Connectivity().checkConnectivity(); - var autoDownloadStorage = KeyValueStorage(autoDownloadNetworkKey); - var autoDownloadNetwork = await autoDownloadStorage.getInt(); - if (autoDownloadNetwork == 1) { - var episodes = await dbHelper.getNewEpisodes('all'); - // For safety - if (episodes.length < 100 && episodes.length > 0) { - for (var episode in episodes) { - await downloader.startTask(episode, showNotification: true); - } - } - } else if (result == ConnectivityResult.wifi) { - var episodes = await dbHelper.getNewEpisodes('all'); - //For safety - if (episodes.length < 100 && episodes.length > 0) { - for (var episode in episodes) { - await downloader.startTask(episode, showNotification: true); - } - } - } - } - - @override - Widget build(BuildContext context) { - final s = context.s; - var groupList = Provider.of(context, listen: false); - return Column( - children: [ - Consumer( - builder: (_, subscribeWorker, __) { - var item = subscribeWorker.currentSubscribeItem; - switch (item.subscribeState) { - case SubscribeState.start: - return importColumn( - s.notificationSubscribe(item.title), context); - case SubscribeState.subscribe: - return importColumn(s.notificaitonFatch(item.title), context); - case SubscribeState.fetch: - return importColumn(s.notificationSuccess(item.title), context); - case SubscribeState.exist: - return importColumn( - s.notificationSubscribeExisted(item.title), context); - case SubscribeState.error: - return importColumn( - s.notificationNetworkError(item.title), context); - default: - return Center(); - } - }, - ), - Consumer( - builder: (context, refreshWorker, child) { - var item = refreshWorker.currentRefreshItem; - if (refreshWorker.complete) { - groupList.updateGroups(); - _autoDownloadNew(context); - } - switch (item.refreshState) { - case RefreshState.fetch: - return importColumn(s.notificationUpdate(item.title), context); - case RefreshState.error: - return importColumn( - s.notificationUpdateError(item.title), context); - default: - return Center(); - } - }, - ) - ], - ); - } -} +import 'package:connectivity/connectivity.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../local_storage/key_value_storage.dart'; +import '../local_storage/sqflite_localpodcast.dart'; +import '../state/download_state.dart'; +import '../state/podcast_group.dart'; +import '../state/refresh_podcast.dart'; +import '../util/extension_helper.dart'; + +class Import extends StatelessWidget { + Widget importColumn(String text, BuildContext context) { + return Container( + color: context.primaryColorDark, + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + SizedBox(height: 2.0, child: LinearProgressIndicator()), + Container( + padding: EdgeInsets.symmetric(horizontal: 20.0), + height: 20.0, + alignment: Alignment.centerLeft, + child: Text(text), + ), + ]), + ); + } + + _autoDownloadNew(BuildContext context) async { + final dbHelper = DBHelper(); + var downloader = Provider.of(context, listen: false); + var result = await Connectivity().checkConnectivity(); + var autoDownloadStorage = KeyValueStorage(autoDownloadNetworkKey); + var autoDownloadNetwork = await autoDownloadStorage.getInt(); + if (autoDownloadNetwork == 1) { + var episodes = await dbHelper.getNewEpisodes('all'); + // For safety + if (episodes.length < 100 && episodes.length > 0) { + for (var episode in episodes) { + await downloader.startTask(episode, showNotification: true); + } + } + } else if (result == ConnectivityResult.wifi) { + var episodes = await dbHelper.getNewEpisodes('all'); + //For safety + if (episodes.length < 100 && episodes.length > 0) { + for (var episode in episodes) { + await downloader.startTask(episode, showNotification: true); + } + } + } + } + + @override + Widget build(BuildContext context) { + final s = context.s; + var groupList = Provider.of(context, listen: false); + return Column( + children: [ + Consumer( + builder: (_, subscribeWorker, __) { + var item = subscribeWorker.currentSubscribeItem; + switch (item.subscribeState) { + case SubscribeState.start: + return importColumn( + s.notificationSubscribe(item.title), context); + case SubscribeState.subscribe: + return importColumn(s.notificaitonFatch(item.title), context); + case SubscribeState.fetch: + return importColumn(s.notificationSuccess(item.title), context); + case SubscribeState.exist: + return importColumn( + s.notificationSubscribeExisted(item.title), context); + case SubscribeState.error: + return importColumn( + s.notificationNetworkError(item.title), context); + default: + return Center(); + } + }, + ), + Consumer( + builder: (context, refreshWorker, child) { + var item = refreshWorker.currentRefreshItem; + if (refreshWorker.complete) { + groupList.updateGroups(); + _autoDownloadNew(context); + } + switch (item.refreshState) { + case RefreshState.fetch: + return importColumn(s.notificationUpdate(item.title), context); + case RefreshState.error: + return importColumn( + s.notificationUpdateError(item.title), context); + default: + return Center(); + } + }, + ) + ], + ); + } +} diff --git a/lib/home/playlist.dart b/lib/home/playlist.dart index 32379a9..b75d7a6 100644 --- a/lib/home/playlist.dart +++ b/lib/home/playlist.dart @@ -1,794 +1,794 @@ -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:fluttertoast/fluttertoast.dart'; -import 'package:google_fonts/google_fonts.dart'; -import 'package:line_icons/line_icons.dart'; -import 'package:provider/provider.dart'; -import 'package:tuple/tuple.dart'; - -import '../local_storage/sqflite_localpodcast.dart'; -import '../state/audio_state.dart'; -import '../type/episodebrief.dart'; -import '../type/play_histroy.dart'; -import '../type/playlist.dart'; -import '../util/custom_widget.dart'; -import '../util/extension_helper.dart'; - -enum InitPage { playlist, history } - -class PlaylistPage extends StatefulWidget { - final InitPage initPage; - PlaylistPage({this.initPage, Key key}) : super(key: key); - @override - _PlaylistPageState createState() => _PlaylistPageState(); -} - -class _PlaylistPageState extends State { - final textstyle = TextStyle(fontSize: 15.0, color: Colors.black); - var _loadList; - int _sumPlaylistLength(List episodes) { - var sum = 0; - if (episodes.length == 0) { - return sum; - } else { - for (var episode in episodes) { - sum += episode.duration ~/ 60; - } - return sum; - } - } - - Future _getListenTime() async { - var dbHelper = DBHelper(); - var listenTime = await dbHelper.listenMins(0); - return listenTime; - } - - bool _loadHistory = false; - - @override - void initState() { - super.initState(); - if (widget.initPage == InitPage.playlist) { - _loadList = _ReorderablePlaylist(); - } else { - _loadHistory = true; - _loadList = _HistoryList(); - } - } - - @override - Widget build(BuildContext context) { - final s = context.s; - var audio = Provider.of(context, listen: false); - return AnnotatedRegion( - value: SystemUiOverlayStyle( - systemNavigationBarIconBrightness: - Theme.of(context).accentColorBrightness, - statusBarIconBrightness: Theme.of(context).accentColorBrightness, - systemNavigationBarColor: Theme.of(context).primaryColor, - ), - child: Scaffold( - backgroundColor: context.primaryColor, - appBar: AppBar( - elevation: 0, - backgroundColor: context.accentColor.withAlpha(70), - leading: CustomBackButton(), - ), - body: SafeArea( - child: Selector>( - selector: (_, audio) => Tuple4(audio.queue, audio.playerRunning, - audio.queueUpdate, audio.episode), - builder: (_, data, __) { - var episodes = data.item1.playlist; - return Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisAlignment: MainAxisAlignment.start, - children: [ - Container( - color: context.accentColor.withAlpha(70), - child: Row( - children: [ - Expanded( - flex: 2, - child: Container( - height: 100, - padding: EdgeInsets.only( - left: 60, - ), - alignment: Alignment.centerLeft, - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - Text( - _loadHistory - ? s.settingsHistory - : s.homeMenuPlaylist, - style: TextStyle( - color: context.textColor, - fontSize: 30, - ), - ), - SizedBox(width: 5), - IconButton( - icon: _loadHistory - ? Icon(Icons.playlist_play) - : Icon(Icons.history), - onPressed: () => setState(() { - _loadHistory = !_loadHistory; - if (_loadHistory) { - _loadList = _HistoryList(); - } else { - _loadList = - _ReorderablePlaylist(); - } - })) - ], - ), - _loadHistory - ? FutureBuilder( - future: _getListenTime(), - initialData: 0.0, - builder: (context, snapshot) => - RichText( - text: TextSpan( - text: 'Today ', - style: GoogleFonts.cairo( - textStyle: TextStyle( - color: context.accentColor, - fontSize: 20, - ), - ), - children: [ - TextSpan( - text: - '${snapshot.data.toStringAsFixed(0)} ', - style: GoogleFonts.cairo( - textStyle: TextStyle( - color: context.accentColor, - fontSize: 25, - )), - ), - TextSpan( - text: 'mins', - style: TextStyle( - color: context.accentColor, - fontSize: 15, - )), - ], - ), - ), - ) - : RichText( - text: TextSpan( - text: episodes.length.toString(), - style: GoogleFonts.cairo( - textStyle: TextStyle( - color: - Theme.of(context).accentColor, - fontSize: 25, - ), - ), - children: [ - TextSpan( - text: episodes.length < 2 - ? 'episode' - : 'episodes', - style: TextStyle( - color: context.accentColor, - fontSize: 15, - )), - TextSpan( - text: _sumPlaylistLength(episodes) - .toString(), - style: GoogleFonts.cairo( - textStyle: TextStyle( - color: context.accentColor, - fontSize: 25, - )), - ), - TextSpan( - text: 'mins', - style: TextStyle( - color: context.accentColor, - fontSize: 15, - )), - ], - ), - ), - ], - ), - ), - ), - Expanded( - flex: 1, - child: Container( - alignment: Alignment.center, - padding: EdgeInsets.all(5.0), - margin: EdgeInsets.only(right: 20.0, bottom: 5.0), - decoration: data.item2 - ? BoxDecoration( - color: context.brightness == Brightness.dark - ? Colors.grey[800] - : Colors.grey[200], - borderRadius: BorderRadius.circular(10.0), - ) - : BoxDecoration(color: Colors.transparent), - child: data.item2 - ? Column( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: - CrossAxisAlignment.center, - children: [ - CircleAvatar( - radius: 15, - backgroundImage: - data.item4.avatarImage), - Container( - width: 150, - alignment: Alignment.center, - child: Text( - data.item4.title, - maxLines: 1, - overflow: TextOverflow.fade, - textAlign: TextAlign.center, - ), - ), - Padding( - padding: EdgeInsets.symmetric( - horizontal: 15), - child: SizedBox( - width: 20, - height: 15, - child: WaveLoader( - color: context.accentColor, - )), - ), - ], - ) - : IconButton( - icon: Icon(Icons.play_circle_filled, - size: 40, color: context.accentColor), - onPressed: () { - audio.playlistLoad(); - // setState(() {}); - }), - ), - ), - ], - ), - ), - Expanded( - child: Container( - color: context.primaryColor, - child: AnimatedSwitcher( - duration: Duration(milliseconds: 300), - child: _loadList), - )), - ], - ); - }, - ), - ), - ), - ); - } -} - -class _ReorderablePlaylist extends StatefulWidget { - _ReorderablePlaylist({Key key}) : super(key: key); - - @override - __ReorderablePlaylistState createState() => __ReorderablePlaylistState(); -} - -class __ReorderablePlaylistState extends State<_ReorderablePlaylist> { - @override - Widget build(BuildContext context) { - var audio = Provider.of(context, listen: false); - return Selector>( - selector: (_, audio) => Tuple2(audio.queue, audio.playerRunning), - builder: (_, data, __) { - var episodes = data.item1.playlist; - return ReorderableListView( - onReorder: (oldIndex, newIndex) { - if (newIndex > oldIndex) { - newIndex -= 1; - } - audio.reorderPlaylist(oldIndex, newIndex); - setState(() {}); - }, - scrollDirection: Axis.vertical, - children: data.item2 - ? episodes.map((episode) { - if (episode.enclosureUrl != episodes.first.enclosureUrl) { - return _DismissibleContainer( - episode: episode, - onRemove: (value) => setState(() {}), - key: ValueKey(episode.enclosureUrl), - ); - } else { - return Container( - key: ValueKey('sd'), - ); - } - }).toList() - : episodes - .map((episode) => _DismissibleContainer( - episode: episode, - onRemove: (value) => setState(() {}), - key: ValueKey(episode.enclosureUrl), - )) - .toList()); - }); - } -} - -class _DismissibleContainer extends StatefulWidget { - final EpisodeBrief episode; - final ValueChanged onRemove; - _DismissibleContainer({this.episode, this.onRemove, Key key}) - : super(key: key); - - @override - __DismissibleContainerState createState() => __DismissibleContainerState(); -} - -class __DismissibleContainerState extends State<_DismissibleContainer> { - bool _delete; - Widget _episodeTag(String text, Color color) { - if (text == '') { - return Center(); - } - return Container( - decoration: BoxDecoration( - color: color, borderRadius: BorderRadius.circular(15.0)), - height: 25.0, - margin: EdgeInsets.only(right: 10.0), - padding: EdgeInsets.symmetric(horizontal: 8.0), - alignment: Alignment.center, - child: Text(text, style: TextStyle(fontSize: 14.0, color: Colors.black)), - ); - } - - @override - void initState() { - _delete = false; - super.initState(); - } - - @override - Widget build(BuildContext context) { - final audio = Provider.of(context, listen: false); - final s = context.s; - final c = widget.episode.backgroudColor(context); - return AnimatedContainer( - duration: Duration(milliseconds: 300), - curve: Curves.easeInSine, - alignment: Alignment.center, - height: _delete ? 0 : 90.0, - child: _delete - ? Container( - color: Colors.transparent, - ) - : Dismissible( - key: ValueKey('${widget.episode.enclosureUrl}t'), - background: Container( - padding: EdgeInsets.symmetric(horizontal: 20.0), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Container( - decoration: BoxDecoration( - shape: BoxShape.circle, color: Colors.red), - padding: EdgeInsets.all(5), - alignment: Alignment.center, - child: Icon( - LineIcons.trash_alt_solid, - color: Colors.white, - size: 15, - ), - ), - Container( - decoration: BoxDecoration( - shape: BoxShape.circle, color: Colors.red), - padding: EdgeInsets.all(5), - alignment: Alignment.center, - child: Icon( - LineIcons.trash_alt_solid, - color: Colors.white, - size: 15, - ), - ), - ], - ), - height: 30, - color: context.accentColor, - ), - onDismissed: (direction) async { - setState(() { - _delete = true; - }); - var index = await audio.delFromPlaylist(widget.episode); - widget.onRemove(true); - final episodeRemove = widget.episode; - Scaffold.of(context).removeCurrentSnackBar(); - Scaffold.of(context).showSnackBar(SnackBar( - behavior: SnackBarBehavior.floating, - backgroundColor: Colors.grey[800], - content: Text(s.toastRemovePlaylist, - style: TextStyle(color: Colors.white)), - action: SnackBarAction( - textColor: context.accentColor, - label: s.undo, - onPressed: () async { - await audio.addToPlaylistAt(episodeRemove, index); - widget.onRemove(false); - }), - )); - }, - child: SizedBox( - height: 90.0, - child: Column( - mainAxisAlignment: MainAxisAlignment.spaceAround, - children: [ - Expanded( - child: ListTile( - contentPadding: EdgeInsets.symmetric(vertical: 8), - onTap: () async { - await audio.episodeLoad(widget.episode); - widget.onRemove(true); - }, - title: Container( - padding: EdgeInsets.fromLTRB(0, 5.0, 20.0, 5.0), - child: Text( - widget.episode.title, - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - ), - leading: Row( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.center, - mainAxisSize: MainAxisSize.min, - children: [ - Icon(Icons.unfold_more, color: c), - CircleAvatar( - backgroundColor: c.withOpacity(0.5), - backgroundImage: widget.episode.avatarImage), - ], - ), - subtitle: Container( - padding: EdgeInsets.only(top: 5, bottom: 5), - height: 35, - child: Row( - children: [ - if (widget.episode.explicit == 1) - Container( - decoration: BoxDecoration( - color: Colors.red[800], - shape: BoxShape.circle), - height: 25.0, - width: 25.0, - margin: EdgeInsets.only(right: 10.0), - alignment: Alignment.center, - child: Text('E', - style: TextStyle(color: Colors.white))), - if (widget.episode.duration != 0) - _episodeTag( - widget.episode.duration == 0 - ? '' - : s.minsCount( - widget.episode.duration ~/ 60), - Colors.cyan[300]), - if (widget.episode.enclosureLength != null) - _episodeTag( - widget.episode.enclosureLength == 0 - ? '' - : '${(widget.episode.enclosureLength) ~/ 1000000}MB', - Colors.lightBlue[300]), - ], - ), - ), - //trailing: Icon(Icons.menu), - ), - ), - Divider( - height: 2, - ), - ], - ), - ), - ), - ); - } -} - -class _HistoryList extends StatefulWidget { - _HistoryList({Key key}) : super(key: key); - - @override - __HistoryListState createState() => __HistoryListState(); -} - -class __HistoryListState extends State<_HistoryList> { - var dbHelper = DBHelper(); - bool _loadMore = false; - Future _getData; - - Future> getPlayRecords(int top) async { - List playHistory; - playHistory = await dbHelper.getPlayRecords(top); - for (var record in playHistory) { - await record.getEpisode(); - } - return playHistory; - } - - Future _loadMoreData() async { - if (mounted) { - setState(() { - _loadMore = true; - }); - } - await Future.delayed(Duration(milliseconds: 500)); - _top = _top + 20; - if (mounted) { - setState(() { - _getData = getPlayRecords(_top); - _loadMore = false; - }); - } - } - - int _top; - @override - void initState() { - super.initState(); - _top = 20; - _getData = getPlayRecords(_top); - } - - @override - Widget build(BuildContext context) { - final s = context.s; - final audio = context.watch(); - return FutureBuilder>( - future: _getData, - builder: (context, snapshot) { - return snapshot.hasData - ? NotificationListener( - onNotification: (scrollInfo) { - if (scrollInfo.metrics.pixels == - scrollInfo.metrics.maxScrollExtent && - snapshot.data.length == _top) { - if (!_loadMore) { - _loadMoreData(); - } - } - return true; - }, - child: ListView.builder( - scrollDirection: Axis.vertical, - itemCount: snapshot.data.length + 1, - itemBuilder: (context, index) { - if (index == snapshot.data.length) { - return SizedBox( - height: 2, - child: _loadMore - ? LinearProgressIndicator() - : Center()); - } else { - final seekValue = snapshot.data[index].seekValue; - final seconds = snapshot.data[index].seconds; - final date = snapshot - .data[index].playdate.millisecondsSinceEpoch; - final episode = snapshot.data[index].episode; - final c = episode?.backgroudColor(context); - return episode == null - ? Center() - : SizedBox( - height: 90.0, - child: Column( - mainAxisAlignment: - MainAxisAlignment.spaceAround, - children: [ - Expanded( - child: Center( - child: ListTile( - contentPadding: EdgeInsets.fromLTRB( - 24, 8, 20, 8), - onTap: () => audio.episodeLoad( - episode, - startPosition: seekValue < 0.9 - ? (seconds * 1000).toInt() - : 0), - leading: CircleAvatar( - backgroundColor: - c?.withOpacity(0.5), - backgroundImage: - episode.avatarImage), - title: Padding( - padding: EdgeInsets.symmetric( - vertical: 5.0), - child: Text( - snapshot.data[index].title, - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - ), - subtitle: SizedBox( - height: 40, - child: Row( - mainAxisAlignment: - MainAxisAlignment.start, - crossAxisAlignment: - CrossAxisAlignment.center, - children: [ - if (seekValue < 0.9) - Padding( - padding: - EdgeInsets.symmetric( - vertical: 5.0), - child: Material( - color: - Colors.transparent, - child: InkWell( - onTap: () { - audio.episodeLoad( - episode, - startPosition: - (seconds * - 1000) - .toInt()); - }, - borderRadius: - BorderRadius - .circular(20), - child: Stack( - children: [ - ShaderMask( - shaderCallback: - (bounds) { - return LinearGradient( - begin: Alignment - .centerLeft, - colors: < - Color>[ - Colors - .cyan[600] - .withOpacity(0.8), - Colors - .white70 - ], - stops: [ - seekValue, - seekValue - ], - tileMode: - TileMode - .mirror, - ).createShader( - bounds); - }, - child: - Container( - height: 25, - alignment: - Alignment - .center, - padding: EdgeInsets.symmetric( - horizontal: - 20), - decoration: - BoxDecoration( - borderRadius: - BorderRadius.circular( - 20.0), - color: context - .accentColor, - ), - child: Text( - seconds - .toTime, - style: TextStyle( - color: - Colors.white), - ), - ), - ), - ]), - ), - ), - ), - SizedBox( - child: Selector< - AudioPlayerNotifier, - Tuple2< - List, - bool>>( - selector: (_, audio) => - Tuple2( - audio.queue - .playlist, - audio - .queueUpdate), - builder: (_, data, __) { - return data.item1 - .contains( - episode) - ? IconButton( - icon: Icon( - Icons - .playlist_add_check, - color: context - .accentColor), - onPressed: - () async { - audio.delFromPlaylist( - episode); - Fluttertoast - .showToast( - msg: s - .toastRemovePlaylist, - gravity: - ToastGravity - .BOTTOM, - ); - }) - : IconButton( - icon: Icon( - Icons - .playlist_add, - color: Colors - .grey[ - 700]), - onPressed: - () async { - audio.addToPlaylist( - episode); - Fluttertoast - .showToast( - msg: s - .toastAddPlaylist, - gravity: - ToastGravity - .BOTTOM, - ); - }); - }, - ), - ), - Spacer(), - Text( - date.toDate(context), - style: TextStyle( - fontSize: 15, - ), - ), - ], - ), - ), - ), - ), - ), - Divider(height: 1) - ], - ), - ); - } - }), - ) - : Center( - child: SizedBox( - height: 25, - width: 25, - child: CircularProgressIndicator()), - ); - }); - } -} +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:line_icons/line_icons.dart'; +import 'package:provider/provider.dart'; +import 'package:tuple/tuple.dart'; + +import '../local_storage/sqflite_localpodcast.dart'; +import '../state/audio_state.dart'; +import '../type/episodebrief.dart'; +import '../type/play_histroy.dart'; +import '../type/playlist.dart'; +import '../util/custom_widget.dart'; +import '../util/extension_helper.dart'; + +enum InitPage { playlist, history } + +class PlaylistPage extends StatefulWidget { + final InitPage initPage; + PlaylistPage({this.initPage, Key key}) : super(key: key); + @override + _PlaylistPageState createState() => _PlaylistPageState(); +} + +class _PlaylistPageState extends State { + final textstyle = TextStyle(fontSize: 15.0, color: Colors.black); + var _loadList; + int _sumPlaylistLength(List episodes) { + var sum = 0; + if (episodes.length == 0) { + return sum; + } else { + for (var episode in episodes) { + sum += episode.duration ~/ 60; + } + return sum; + } + } + + Future _getListenTime() async { + var dbHelper = DBHelper(); + var listenTime = await dbHelper.listenMins(0); + return listenTime; + } + + bool _loadHistory = false; + + @override + void initState() { + super.initState(); + if (widget.initPage == InitPage.playlist) { + _loadList = _ReorderablePlaylist(); + } else { + _loadHistory = true; + _loadList = _HistoryList(); + } + } + + @override + Widget build(BuildContext context) { + final s = context.s; + var audio = Provider.of(context, listen: false); + return AnnotatedRegion( + value: SystemUiOverlayStyle( + systemNavigationBarIconBrightness: + Theme.of(context).accentColorBrightness, + statusBarIconBrightness: Theme.of(context).accentColorBrightness, + systemNavigationBarColor: Theme.of(context).primaryColor, + ), + child: Scaffold( + backgroundColor: context.primaryColor, + appBar: AppBar( + elevation: 0, + backgroundColor: context.accentColor.withAlpha(70), + leading: CustomBackButton(), + ), + body: SafeArea( + child: Selector>( + selector: (_, audio) => Tuple4(audio.queue, audio.playerRunning, + audio.queueUpdate, audio.episode), + builder: (_, data, __) { + var episodes = data.item1.playlist; + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.start, + children: [ + Container( + color: context.accentColor.withAlpha(70), + child: Row( + children: [ + Expanded( + flex: 2, + child: Container( + height: 100, + padding: EdgeInsets.only( + left: 60, + ), + alignment: Alignment.centerLeft, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Text( + _loadHistory + ? s.settingsHistory + : s.homeMenuPlaylist, + style: TextStyle( + color: context.textColor, + fontSize: 30, + ), + ), + SizedBox(width: 5), + IconButton( + icon: _loadHistory + ? Icon(Icons.playlist_play) + : Icon(Icons.history), + onPressed: () => setState(() { + _loadHistory = !_loadHistory; + if (_loadHistory) { + _loadList = _HistoryList(); + } else { + _loadList = + _ReorderablePlaylist(); + } + })) + ], + ), + _loadHistory + ? FutureBuilder( + future: _getListenTime(), + initialData: 0.0, + builder: (context, snapshot) => + RichText( + text: TextSpan( + text: 'Today ', + style: GoogleFonts.cairo( + textStyle: TextStyle( + color: context.accentColor, + fontSize: 20, + ), + ), + children: [ + TextSpan( + text: + '${snapshot.data.toStringAsFixed(0)} ', + style: GoogleFonts.cairo( + textStyle: TextStyle( + color: context.accentColor, + fontSize: 25, + )), + ), + TextSpan( + text: 'mins', + style: TextStyle( + color: context.accentColor, + fontSize: 15, + )), + ], + ), + ), + ) + : RichText( + text: TextSpan( + text: episodes.length.toString(), + style: GoogleFonts.cairo( + textStyle: TextStyle( + color: + Theme.of(context).accentColor, + fontSize: 25, + ), + ), + children: [ + TextSpan( + text: episodes.length < 2 + ? 'episode' + : 'episodes', + style: TextStyle( + color: context.accentColor, + fontSize: 15, + )), + TextSpan( + text: _sumPlaylistLength(episodes) + .toString(), + style: GoogleFonts.cairo( + textStyle: TextStyle( + color: context.accentColor, + fontSize: 25, + )), + ), + TextSpan( + text: 'mins', + style: TextStyle( + color: context.accentColor, + fontSize: 15, + )), + ], + ), + ), + ], + ), + ), + ), + Expanded( + flex: 1, + child: Container( + alignment: Alignment.center, + padding: EdgeInsets.all(5.0), + margin: EdgeInsets.only(right: 20.0, bottom: 5.0), + decoration: data.item2 + ? BoxDecoration( + color: context.brightness == Brightness.dark + ? Colors.grey[800] + : Colors.grey[200], + borderRadius: BorderRadius.circular(10.0), + ) + : BoxDecoration(color: Colors.transparent), + child: data.item2 + ? Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: + CrossAxisAlignment.center, + children: [ + CircleAvatar( + radius: 15, + backgroundImage: + data.item4.avatarImage), + Container( + width: 150, + alignment: Alignment.center, + child: Text( + data.item4.title, + maxLines: 1, + overflow: TextOverflow.fade, + textAlign: TextAlign.center, + ), + ), + Padding( + padding: EdgeInsets.symmetric( + horizontal: 15), + child: SizedBox( + width: 20, + height: 15, + child: WaveLoader( + color: context.accentColor, + )), + ), + ], + ) + : IconButton( + icon: Icon(Icons.play_circle_filled, + size: 40, color: context.accentColor), + onPressed: () { + audio.playlistLoad(); + // setState(() {}); + }), + ), + ), + ], + ), + ), + Expanded( + child: Container( + color: context.primaryColor, + child: AnimatedSwitcher( + duration: Duration(milliseconds: 300), + child: _loadList), + )), + ], + ); + }, + ), + ), + ), + ); + } +} + +class _ReorderablePlaylist extends StatefulWidget { + _ReorderablePlaylist({Key key}) : super(key: key); + + @override + __ReorderablePlaylistState createState() => __ReorderablePlaylistState(); +} + +class __ReorderablePlaylistState extends State<_ReorderablePlaylist> { + @override + Widget build(BuildContext context) { + var audio = Provider.of(context, listen: false); + return Selector>( + selector: (_, audio) => Tuple2(audio.queue, audio.playerRunning), + builder: (_, data, __) { + var episodes = data.item1.playlist; + return ReorderableListView( + onReorder: (oldIndex, newIndex) { + if (newIndex > oldIndex) { + newIndex -= 1; + } + audio.reorderPlaylist(oldIndex, newIndex); + setState(() {}); + }, + scrollDirection: Axis.vertical, + children: data.item2 + ? episodes.map((episode) { + if (episode.enclosureUrl != episodes.first.enclosureUrl) { + return _DismissibleContainer( + episode: episode, + onRemove: (value) => setState(() {}), + key: ValueKey(episode.enclosureUrl), + ); + } else { + return Container( + key: ValueKey('sd'), + ); + } + }).toList() + : episodes + .map((episode) => _DismissibleContainer( + episode: episode, + onRemove: (value) => setState(() {}), + key: ValueKey(episode.enclosureUrl), + )) + .toList()); + }); + } +} + +class _DismissibleContainer extends StatefulWidget { + final EpisodeBrief episode; + final ValueChanged onRemove; + _DismissibleContainer({this.episode, this.onRemove, Key key}) + : super(key: key); + + @override + __DismissibleContainerState createState() => __DismissibleContainerState(); +} + +class __DismissibleContainerState extends State<_DismissibleContainer> { + bool _delete; + Widget _episodeTag(String text, Color color) { + if (text == '') { + return Center(); + } + return Container( + decoration: BoxDecoration( + color: color, borderRadius: BorderRadius.circular(15.0)), + height: 25.0, + margin: EdgeInsets.only(right: 10.0), + padding: EdgeInsets.symmetric(horizontal: 8.0), + alignment: Alignment.center, + child: Text(text, style: TextStyle(fontSize: 14.0, color: Colors.black)), + ); + } + + @override + void initState() { + _delete = false; + super.initState(); + } + + @override + Widget build(BuildContext context) { + final audio = Provider.of(context, listen: false); + final s = context.s; + final c = widget.episode.backgroudColor(context); + return AnimatedContainer( + duration: Duration(milliseconds: 300), + curve: Curves.easeInSine, + alignment: Alignment.center, + height: _delete ? 0 : 90.0, + child: _delete + ? Container( + color: Colors.transparent, + ) + : Dismissible( + key: ValueKey('${widget.episode.enclosureUrl}t'), + background: Container( + padding: EdgeInsets.symmetric(horizontal: 20.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Container( + decoration: BoxDecoration( + shape: BoxShape.circle, color: Colors.red), + padding: EdgeInsets.all(5), + alignment: Alignment.center, + child: Icon( + LineIcons.trash_alt_solid, + color: Colors.white, + size: 15, + ), + ), + Container( + decoration: BoxDecoration( + shape: BoxShape.circle, color: Colors.red), + padding: EdgeInsets.all(5), + alignment: Alignment.center, + child: Icon( + LineIcons.trash_alt_solid, + color: Colors.white, + size: 15, + ), + ), + ], + ), + height: 30, + color: context.accentColor, + ), + onDismissed: (direction) async { + setState(() { + _delete = true; + }); + var index = await audio.delFromPlaylist(widget.episode); + widget.onRemove(true); + final episodeRemove = widget.episode; + Scaffold.of(context).removeCurrentSnackBar(); + Scaffold.of(context).showSnackBar(SnackBar( + behavior: SnackBarBehavior.floating, + backgroundColor: Colors.grey[800], + content: Text(s.toastRemovePlaylist, + style: TextStyle(color: Colors.white)), + action: SnackBarAction( + textColor: context.accentColor, + label: s.undo, + onPressed: () async { + await audio.addToPlaylistAt(episodeRemove, index); + widget.onRemove(false); + }), + )); + }, + child: SizedBox( + height: 90.0, + child: Column( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + Expanded( + child: ListTile( + contentPadding: EdgeInsets.symmetric(vertical: 8), + onTap: () async { + await audio.episodeLoad(widget.episode); + widget.onRemove(true); + }, + title: Container( + padding: EdgeInsets.fromLTRB(0, 5.0, 20.0, 5.0), + child: Text( + widget.episode.title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + leading: Row( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.center, + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.unfold_more, color: c), + CircleAvatar( + backgroundColor: c.withOpacity(0.5), + backgroundImage: widget.episode.avatarImage), + ], + ), + subtitle: Container( + padding: EdgeInsets.only(top: 5, bottom: 5), + height: 35, + child: Row( + children: [ + if (widget.episode.explicit == 1) + Container( + decoration: BoxDecoration( + color: Colors.red[800], + shape: BoxShape.circle), + height: 25.0, + width: 25.0, + margin: EdgeInsets.only(right: 10.0), + alignment: Alignment.center, + child: Text('E', + style: TextStyle(color: Colors.white))), + if (widget.episode.duration != 0) + _episodeTag( + widget.episode.duration == 0 + ? '' + : s.minsCount( + widget.episode.duration ~/ 60), + Colors.cyan[300]), + if (widget.episode.enclosureLength != null) + _episodeTag( + widget.episode.enclosureLength == 0 + ? '' + : '${(widget.episode.enclosureLength) ~/ 1000000}MB', + Colors.lightBlue[300]), + ], + ), + ), + //trailing: Icon(Icons.menu), + ), + ), + Divider( + height: 2, + ), + ], + ), + ), + ), + ); + } +} + +class _HistoryList extends StatefulWidget { + _HistoryList({Key key}) : super(key: key); + + @override + __HistoryListState createState() => __HistoryListState(); +} + +class __HistoryListState extends State<_HistoryList> { + var dbHelper = DBHelper(); + bool _loadMore = false; + Future _getData; + + Future> getPlayRecords(int top) async { + List playHistory; + playHistory = await dbHelper.getPlayRecords(top); + for (var record in playHistory) { + await record.getEpisode(); + } + return playHistory; + } + + Future _loadMoreData() async { + if (mounted) { + setState(() { + _loadMore = true; + }); + } + await Future.delayed(Duration(milliseconds: 500)); + _top = _top + 20; + if (mounted) { + setState(() { + _getData = getPlayRecords(_top); + _loadMore = false; + }); + } + } + + int _top; + @override + void initState() { + super.initState(); + _top = 20; + _getData = getPlayRecords(_top); + } + + @override + Widget build(BuildContext context) { + final s = context.s; + final audio = context.watch(); + return FutureBuilder>( + future: _getData, + builder: (context, snapshot) { + return snapshot.hasData + ? NotificationListener( + onNotification: (scrollInfo) { + if (scrollInfo.metrics.pixels == + scrollInfo.metrics.maxScrollExtent && + snapshot.data.length == _top) { + if (!_loadMore) { + _loadMoreData(); + } + } + return true; + }, + child: ListView.builder( + scrollDirection: Axis.vertical, + itemCount: snapshot.data.length + 1, + itemBuilder: (context, index) { + if (index == snapshot.data.length) { + return SizedBox( + height: 2, + child: _loadMore + ? LinearProgressIndicator() + : Center()); + } else { + final seekValue = snapshot.data[index].seekValue; + final seconds = snapshot.data[index].seconds; + final date = snapshot + .data[index].playdate.millisecondsSinceEpoch; + final episode = snapshot.data[index].episode; + final c = episode?.backgroudColor(context); + return episode == null + ? Center() + : SizedBox( + height: 90.0, + child: Column( + mainAxisAlignment: + MainAxisAlignment.spaceAround, + children: [ + Expanded( + child: Center( + child: ListTile( + contentPadding: EdgeInsets.fromLTRB( + 24, 8, 20, 8), + onTap: () => audio.episodeLoad( + episode, + startPosition: seekValue < 0.9 + ? (seconds * 1000).toInt() + : 0), + leading: CircleAvatar( + backgroundColor: + c?.withOpacity(0.5), + backgroundImage: + episode.avatarImage), + title: Padding( + padding: EdgeInsets.symmetric( + vertical: 5.0), + child: Text( + snapshot.data[index].title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + subtitle: SizedBox( + height: 40, + child: Row( + mainAxisAlignment: + MainAxisAlignment.start, + crossAxisAlignment: + CrossAxisAlignment.center, + children: [ + if (seekValue < 0.9) + Padding( + padding: + EdgeInsets.symmetric( + vertical: 5.0), + child: Material( + color: + Colors.transparent, + child: InkWell( + onTap: () { + audio.episodeLoad( + episode, + startPosition: + (seconds * + 1000) + .toInt()); + }, + borderRadius: + BorderRadius + .circular(20), + child: Stack( + children: [ + ShaderMask( + shaderCallback: + (bounds) { + return LinearGradient( + begin: Alignment + .centerLeft, + colors: < + Color>[ + Colors + .cyan[600] + .withOpacity(0.8), + Colors + .white70 + ], + stops: [ + seekValue, + seekValue + ], + tileMode: + TileMode + .mirror, + ).createShader( + bounds); + }, + child: + Container( + height: 25, + alignment: + Alignment + .center, + padding: EdgeInsets.symmetric( + horizontal: + 20), + decoration: + BoxDecoration( + borderRadius: + BorderRadius.circular( + 20.0), + color: context + .accentColor, + ), + child: Text( + seconds + .toTime, + style: TextStyle( + color: + Colors.white), + ), + ), + ), + ]), + ), + ), + ), + SizedBox( + child: Selector< + AudioPlayerNotifier, + Tuple2< + List, + bool>>( + selector: (_, audio) => + Tuple2( + audio.queue + .playlist, + audio + .queueUpdate), + builder: (_, data, __) { + return data.item1 + .contains( + episode) + ? IconButton( + icon: Icon( + Icons + .playlist_add_check, + color: context + .accentColor), + onPressed: + () async { + audio.delFromPlaylist( + episode); + Fluttertoast + .showToast( + msg: s + .toastRemovePlaylist, + gravity: + ToastGravity + .BOTTOM, + ); + }) + : IconButton( + icon: Icon( + Icons + .playlist_add, + color: Colors + .grey[ + 700]), + onPressed: + () async { + audio.addToPlaylist( + episode); + Fluttertoast + .showToast( + msg: s + .toastAddPlaylist, + gravity: + ToastGravity + .BOTTOM, + ); + }); + }, + ), + ), + Spacer(), + Text( + date.toDate(context), + style: TextStyle( + fontSize: 15, + ), + ), + ], + ), + ), + ), + ), + ), + Divider(height: 1) + ], + ), + ); + } + }), + ) + : Center( + child: SizedBox( + height: 25, + width: 25, + child: CircularProgressIndicator()), + ); + }); + } +} diff --git a/lib/home/pocast_discovery.dart b/lib/home/pocast_discovery.dart index ad10f11..3df7e1c 100644 --- a/lib/home/pocast_discovery.dart +++ b/lib/home/pocast_discovery.dart @@ -1,483 +1,483 @@ -import 'package:flutter/material.dart'; -import 'package:line_icons/line_icons.dart'; -import 'package:provider/provider.dart'; - -import '../local_storage/key_value_storage.dart'; -import '../service/search_api.dart'; -import '../state/search_state.dart'; -import '../type/search_api/search_genre.dart'; -import '../type/search_api/searchpodcast.dart'; -import '../util/custom_widget.dart'; -import '../util/extension_helper.dart'; -import 'search_podcast.dart'; - -class DiscoveryPage extends StatefulWidget { - DiscoveryPage({this.onTap, Key key}) : super(key: key); - final ValueChanged onTap; - @override - DiscoveryPageState createState() => DiscoveryPageState(); -} - -class DiscoveryPageState extends State { - Genre _selectedGenre; - Genre get selectedGenre => _selectedGenre; - final List _podcastList = []; - Future _searchTopPodcast; - Future> _getSearchHistory() { - final storage = KeyValueStorage(searchHistoryKey); - final history = storage.getStringList(); - return history; - } - - void backToHome() { - setState(() { - _selectedGenre = null; - }); - } - - @override - void initState() { - super.initState(); - _searchTopPodcast = _getTopPodcasts(page: 1); - } - - Widget _loadTopPodcasts() => Container( - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(10), color: context.primaryColor), - width: 120, - margin: EdgeInsets.fromLTRB(10, 10, 0, 10), - padding: EdgeInsets.all(4), - alignment: Alignment.topCenter, - child: Column( - children: [ - Expanded( - flex: 2, - child: Center( - child: Container( - height: 50, - width: 50, - decoration: BoxDecoration( - shape: BoxShape.circle, - color: context.primaryColorDark, - ), - alignment: Alignment.center, - child: SizedBox( - width: 20, - height: 2, - child: LinearProgressIndicator(value: 0), - ), - ), - ), - ), - Expanded( - flex: 1, - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Container( - width: 80, - height: context.textTheme.bodyText1.fontSize, - decoration: BoxDecoration( - color: context.primaryColorDark, - borderRadius: BorderRadius.circular(4)), - ), - SizedBox(height: 10), - Container( - width: 40, - height: context.textTheme.bodyText1.fontSize, - decoration: BoxDecoration( - color: context.primaryColorDark, - borderRadius: BorderRadius.circular(4)), - ), - ], - ), - ), - Expanded( - flex: 1, - child: Center( - child: SizedBox( - height: 32, - child: OutlineButton( - color: context.accentColor.withOpacity(0.5), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(100.0), - side: BorderSide(color: Colors.grey[500])), - highlightedBorderColor: Colors.grey[500], - disabledTextColor: Colors.grey[500], - child: Text(context.s.subscribe), - disabledBorderColor: Colors.grey[500], - onPressed: () {}), - ), - ), - ), - ], - )); - - Widget _historyList() => FutureBuilder>( - future: _getSearchHistory(), - initialData: [], - builder: (context, snapshot) { - if (snapshot.hasData && snapshot.data.isNotEmpty) { - final history = snapshot.data; - return SizedBox( - child: Wrap( - direction: Axis.horizontal, - children: history - .map((e) => Padding( - padding: const EdgeInsets.fromLTRB(8, 2, 0, 0), - child: FlatButton.icon( - color: - Colors.accents[history.indexOf(e)].withAlpha(70), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(100.0), - ), - onPressed: () => widget.onTap(e), - label: Text(e), - icon: Icon( - Icons.search, - size: 20, - ), - ), - )) - .toList(), - ), - ); - } - return SizedBox( - height: 0, - ); - }); - - Future> _getTopPodcasts({int page}) async { - final searchEngine = ListenNotesSearch(); - var searchResult = await searchEngine.fetchBestPodcast( - genre: '', - page: page, - ); - final podcastTopList = - searchResult.podcasts.map((e) => e?.toOnlinePodcast).toList(); - _podcastList.addAll(podcastTopList.cast()); - return _podcastList; - } - - Future _getHideDiscovery() async { - final storage = KeyValueStorage(hidePodcastDiscoveryKey); - return await storage.getBool(defaultValue: false); - } - - @override - Widget build(BuildContext context) { - final searchState = context.watch(); - return FutureBuilder( - future: _getHideDiscovery(), - initialData: true, - builder: (context, snapshot) => snapshot.data - ? ScrollConfiguration( - behavior: NoGrowBehavior(), - child: SingleChildScrollView( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - _historyList(), - SizedBox( - height: 150, - child: Center( - child: Icon( - Icons.search, - size: 80, - color: Colors.grey[400], - ), - ), - ), - SizedBox( - height: 50, - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Icon( - LineIcons.microphone_solid, - size: 30, - color: Colors.lightBlue, - ), - SizedBox(width: 50), - Icon( - LineIcons.broadcast_tower_solid, - size: 30, - color: Colors.deepPurple, - ), - SizedBox(width: 50), - Icon( - LineIcons.rss_square_solid, - size: 30, - color: Colors.blueGrey, - ), - ], - ), - ), - Padding( - padding: EdgeInsets.fromLTRB(50, 20, 50, 20), - child: Center( - child: Text( - context.s.searchHelper, - textAlign: TextAlign.center, - style: context.textTheme.headline6 - .copyWith(color: Colors.grey[400]), - ), - ), - ), - ], - ), - ), - ) - : PodcastSlideup( - searchEngine: SearchEngine.listenNotes, - child: _selectedGenre == null - ? SingleChildScrollView( - child: Column( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - _historyList(), - Padding( - padding: EdgeInsets.fromLTRB(20, 10, 10, 4), - child: Text('Popular', - style: context.textTheme.headline6 - .copyWith(color: context.accentColor)), - ), - SizedBox( - height: 200, - child: FutureBuilder>( - future: _searchTopPodcast, - builder: (context, snapshot) { - return ScrollConfiguration( - behavior: NoGrowBehavior(), - child: ListView( - scrollDirection: Axis.horizontal, - children: snapshot.hasData - ? snapshot.data - .map((podcast) { - return Container( - decoration: BoxDecoration( - borderRadius: - BorderRadius.circular( - 10), - color: - context.primaryColor), - width: 120, - margin: EdgeInsets.fromLTRB( - 10, 10, 0, 10), - child: Material( - color: Colors.transparent, - borderRadius: - BorderRadius.circular( - 10), - clipBehavior: Clip.hardEdge, - child: InkWell( - onTap: () { - searchState - .selectedPodcast = - podcast; - widget.onTap(''); - }, - child: Padding( - padding: - EdgeInsets.all(4.0), - child: Column( - children: [ - Expanded( - flex: 2, - child: Center( - child: PodcastAvatar( - podcast)), - ), - Expanded( - flex: 1, - child: Text( - podcast.title, - textAlign: - TextAlign - .center, - maxLines: 2, - overflow: - TextOverflow - .fade, - style: TextStyle( - fontWeight: - FontWeight - .bold), - ), - ), - Expanded( - flex: 1, - child: Center( - child: SizedBox( - height: 32, - child: SubscribeButton( - podcast)), - ), - ), - ], - ), - ), - ), - ), - ); - }).toList() - : [ - _loadTopPodcasts(), - _loadTopPodcasts(), - _loadTopPodcasts(), - _loadTopPodcasts(), - ]), - ); - }), - ), - Padding( - padding: EdgeInsets.fromLTRB(20, 10, 10, 4), - child: Text('Categories', - style: context.textTheme.headline6 - .copyWith(color: context.accentColor)), - ), - ListView( - shrinkWrap: true, - physics: NeverScrollableScrollPhysics(), - children: genres - .map((e) => ListTile( - contentPadding: - EdgeInsets.fromLTRB(20, 0, 20, 0), - onTap: () { - widget.onTap(''); - setState(() => _selectedGenre = e); - }, - title: Text(e.name), - )) - .toList(), - ), - SizedBox( - height: 40, - child: Center( - child: Image( - image: context.brightness == Brightness.light - ? AssetImage('assets/listennotes.png') - : AssetImage( - 'assets/listennotes_light.png'), - height: 15, - ), - ), - ) - ], - ), - ) - : _TopPodcastList(genre: _selectedGenre), - ), - ); - } -} - -class _TopPodcastList extends StatefulWidget { - final Genre genre; - _TopPodcastList({this.genre, Key key}) : super(key: key); - - @override - __TopPodcastListState createState() => __TopPodcastListState(); -} - -class __TopPodcastListState extends State<_TopPodcastList> { - final List _podcastList = []; - Future _searchFuture; - bool _loading; - int _page; - Future> _getTopPodcasts({Genre genre, int page}) async { - final searchEngine = ListenNotesSearch(); - var searchResult = await searchEngine.fetchBestPodcast( - genre: genre.id, - page: page, - ); - final podcastTopList = - searchResult.podcasts.map((e) => e?.toOnlinePodcast).toList(); - _podcastList.addAll(podcastTopList.cast()); - _loading = false; - return _podcastList; - } - - @override - void initState() { - _page = 1; - _searchFuture = _getTopPodcasts(genre: widget.genre, page: _page); - super.initState(); - } - - @override - Widget build(BuildContext context) { - return FutureBuilder( - future: _searchFuture, - builder: (context, snapshot) { - if (!snapshot.hasData) { - return Container( - padding: EdgeInsets.only(top: 200), - alignment: Alignment.topCenter, - child: CircularProgressIndicator(), - ); - } - final content = snapshot.data; - return CustomScrollView( - slivers: [ - SliverToBoxAdapter( - child: Padding( - padding: EdgeInsets.fromLTRB(20, 10, 10, 4), - child: Text(widget.genre.name, - style: context.textTheme.headline6 - .copyWith(color: context.accentColor)), - ), - ), - SliverList( - delegate: SliverChildBuilderDelegate( - (context, index) { - return SearchResult( - onlinePodcast: content[index], - ); - }, - childCount: content.length, - ), - ), - SliverToBoxAdapter( - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - mainAxisSize: MainAxisSize.min, - children: [ - Padding( - padding: const EdgeInsets.only(top: 10.0, bottom: 20.0), - child: OutlineButton( - highlightedBorderColor: context.accentColor, - splashColor: context.accentColor.withOpacity(0.5), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(100))), - child: _loading - ? SizedBox( - height: 20, - width: 20, - child: CircularProgressIndicator( - strokeWidth: 2, - )) - : Text(context.s.loadMore), - onPressed: () => _loading - ? null - : setState( - () { - _loading = true; - _page++; - _searchFuture = _getTopPodcasts( - genre: widget.genre, page: _page); - }, - ), - ), - ) - ], - ), - ) - ], - ); - }, - ); - } -} +import 'package:flutter/material.dart'; +import 'package:line_icons/line_icons.dart'; +import 'package:provider/provider.dart'; + +import '../local_storage/key_value_storage.dart'; +import '../service/search_api.dart'; +import '../state/search_state.dart'; +import '../type/search_api/search_genre.dart'; +import '../type/search_api/searchpodcast.dart'; +import '../util/custom_widget.dart'; +import '../util/extension_helper.dart'; +import 'search_podcast.dart'; + +class DiscoveryPage extends StatefulWidget { + DiscoveryPage({this.onTap, Key key}) : super(key: key); + final ValueChanged onTap; + @override + DiscoveryPageState createState() => DiscoveryPageState(); +} + +class DiscoveryPageState extends State { + Genre _selectedGenre; + Genre get selectedGenre => _selectedGenre; + final List _podcastList = []; + Future _searchTopPodcast; + Future> _getSearchHistory() { + final storage = KeyValueStorage(searchHistoryKey); + final history = storage.getStringList(); + return history; + } + + void backToHome() { + setState(() { + _selectedGenre = null; + }); + } + + @override + void initState() { + super.initState(); + _searchTopPodcast = _getTopPodcasts(page: 1); + } + + Widget _loadTopPodcasts() => Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(10), color: context.primaryColor), + width: 120, + margin: EdgeInsets.fromLTRB(10, 10, 0, 10), + padding: EdgeInsets.all(4), + alignment: Alignment.topCenter, + child: Column( + children: [ + Expanded( + flex: 2, + child: Center( + child: Container( + height: 50, + width: 50, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: context.primaryColorDark, + ), + alignment: Alignment.center, + child: SizedBox( + width: 20, + height: 2, + child: LinearProgressIndicator(value: 0), + ), + ), + ), + ), + Expanded( + flex: 1, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Container( + width: 80, + height: context.textTheme.bodyText1.fontSize, + decoration: BoxDecoration( + color: context.primaryColorDark, + borderRadius: BorderRadius.circular(4)), + ), + SizedBox(height: 10), + Container( + width: 40, + height: context.textTheme.bodyText1.fontSize, + decoration: BoxDecoration( + color: context.primaryColorDark, + borderRadius: BorderRadius.circular(4)), + ), + ], + ), + ), + Expanded( + flex: 1, + child: Center( + child: SizedBox( + height: 32, + child: OutlineButton( + color: context.accentColor.withOpacity(0.5), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(100.0), + side: BorderSide(color: Colors.grey[500])), + highlightedBorderColor: Colors.grey[500], + disabledTextColor: Colors.grey[500], + child: Text(context.s.subscribe), + disabledBorderColor: Colors.grey[500], + onPressed: () {}), + ), + ), + ), + ], + )); + + Widget _historyList() => FutureBuilder>( + future: _getSearchHistory(), + initialData: [], + builder: (context, snapshot) { + if (snapshot.hasData && snapshot.data.isNotEmpty) { + final history = snapshot.data; + return SizedBox( + child: Wrap( + direction: Axis.horizontal, + children: history + .map((e) => Padding( + padding: const EdgeInsets.fromLTRB(8, 2, 0, 0), + child: FlatButton.icon( + color: + Colors.accents[history.indexOf(e)].withAlpha(70), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(100.0), + ), + onPressed: () => widget.onTap(e), + label: Text(e), + icon: Icon( + Icons.search, + size: 20, + ), + ), + )) + .toList(), + ), + ); + } + return SizedBox( + height: 0, + ); + }); + + Future> _getTopPodcasts({int page}) async { + final searchEngine = ListenNotesSearch(); + var searchResult = await searchEngine.fetchBestPodcast( + genre: '', + page: page, + ); + final podcastTopList = + searchResult.podcasts.map((e) => e?.toOnlinePodcast).toList(); + _podcastList.addAll(podcastTopList.cast()); + return _podcastList; + } + + Future _getHideDiscovery() async { + final storage = KeyValueStorage(hidePodcastDiscoveryKey); + return await storage.getBool(defaultValue: false); + } + + @override + Widget build(BuildContext context) { + final searchState = context.watch(); + return FutureBuilder( + future: _getHideDiscovery(), + initialData: true, + builder: (context, snapshot) => snapshot.data + ? ScrollConfiguration( + behavior: NoGrowBehavior(), + child: SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _historyList(), + SizedBox( + height: 150, + child: Center( + child: Icon( + Icons.search, + size: 80, + color: Colors.grey[400], + ), + ), + ), + SizedBox( + height: 50, + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + LineIcons.microphone_solid, + size: 30, + color: Colors.lightBlue, + ), + SizedBox(width: 50), + Icon( + LineIcons.broadcast_tower_solid, + size: 30, + color: Colors.deepPurple, + ), + SizedBox(width: 50), + Icon( + LineIcons.rss_square_solid, + size: 30, + color: Colors.blueGrey, + ), + ], + ), + ), + Padding( + padding: EdgeInsets.fromLTRB(50, 20, 50, 20), + child: Center( + child: Text( + context.s.searchHelper, + textAlign: TextAlign.center, + style: context.textTheme.headline6 + .copyWith(color: Colors.grey[400]), + ), + ), + ), + ], + ), + ), + ) + : PodcastSlideup( + searchEngine: SearchEngine.listenNotes, + child: _selectedGenre == null + ? SingleChildScrollView( + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _historyList(), + Padding( + padding: EdgeInsets.fromLTRB(20, 10, 10, 4), + child: Text('Popular', + style: context.textTheme.headline6 + .copyWith(color: context.accentColor)), + ), + SizedBox( + height: 200, + child: FutureBuilder>( + future: _searchTopPodcast, + builder: (context, snapshot) { + return ScrollConfiguration( + behavior: NoGrowBehavior(), + child: ListView( + scrollDirection: Axis.horizontal, + children: snapshot.hasData + ? snapshot.data + .map((podcast) { + return Container( + decoration: BoxDecoration( + borderRadius: + BorderRadius.circular( + 10), + color: + context.primaryColor), + width: 120, + margin: EdgeInsets.fromLTRB( + 10, 10, 0, 10), + child: Material( + color: Colors.transparent, + borderRadius: + BorderRadius.circular( + 10), + clipBehavior: Clip.hardEdge, + child: InkWell( + onTap: () { + searchState + .selectedPodcast = + podcast; + widget.onTap(''); + }, + child: Padding( + padding: + EdgeInsets.all(4.0), + child: Column( + children: [ + Expanded( + flex: 2, + child: Center( + child: PodcastAvatar( + podcast)), + ), + Expanded( + flex: 1, + child: Text( + podcast.title, + textAlign: + TextAlign + .center, + maxLines: 2, + overflow: + TextOverflow + .fade, + style: TextStyle( + fontWeight: + FontWeight + .bold), + ), + ), + Expanded( + flex: 1, + child: Center( + child: SizedBox( + height: 32, + child: SubscribeButton( + podcast)), + ), + ), + ], + ), + ), + ), + ), + ); + }).toList() + : [ + _loadTopPodcasts(), + _loadTopPodcasts(), + _loadTopPodcasts(), + _loadTopPodcasts(), + ]), + ); + }), + ), + Padding( + padding: EdgeInsets.fromLTRB(20, 10, 10, 4), + child: Text('Categories', + style: context.textTheme.headline6 + .copyWith(color: context.accentColor)), + ), + ListView( + shrinkWrap: true, + physics: NeverScrollableScrollPhysics(), + children: genres + .map((e) => ListTile( + contentPadding: + EdgeInsets.fromLTRB(20, 0, 20, 0), + onTap: () { + widget.onTap(''); + setState(() => _selectedGenre = e); + }, + title: Text(e.name), + )) + .toList(), + ), + SizedBox( + height: 40, + child: Center( + child: Image( + image: context.brightness == Brightness.light + ? AssetImage('assets/listennotes.png') + : AssetImage( + 'assets/listennotes_light.png'), + height: 15, + ), + ), + ) + ], + ), + ) + : _TopPodcastList(genre: _selectedGenre), + ), + ); + } +} + +class _TopPodcastList extends StatefulWidget { + final Genre genre; + _TopPodcastList({this.genre, Key key}) : super(key: key); + + @override + __TopPodcastListState createState() => __TopPodcastListState(); +} + +class __TopPodcastListState extends State<_TopPodcastList> { + final List _podcastList = []; + Future _searchFuture; + bool _loading; + int _page; + Future> _getTopPodcasts({Genre genre, int page}) async { + final searchEngine = ListenNotesSearch(); + var searchResult = await searchEngine.fetchBestPodcast( + genre: genre.id, + page: page, + ); + final podcastTopList = + searchResult.podcasts.map((e) => e?.toOnlinePodcast).toList(); + _podcastList.addAll(podcastTopList.cast()); + _loading = false; + return _podcastList; + } + + @override + void initState() { + _page = 1; + _searchFuture = _getTopPodcasts(genre: widget.genre, page: _page); + super.initState(); + } + + @override + Widget build(BuildContext context) { + return FutureBuilder( + future: _searchFuture, + builder: (context, snapshot) { + if (!snapshot.hasData) { + return Container( + padding: EdgeInsets.only(top: 200), + alignment: Alignment.topCenter, + child: CircularProgressIndicator(), + ); + } + final content = snapshot.data; + return CustomScrollView( + slivers: [ + SliverToBoxAdapter( + child: Padding( + padding: EdgeInsets.fromLTRB(20, 10, 10, 4), + child: Text(widget.genre.name, + style: context.textTheme.headline6 + .copyWith(color: context.accentColor)), + ), + ), + SliverList( + delegate: SliverChildBuilderDelegate( + (context, index) { + return SearchResult( + onlinePodcast: content[index], + ); + }, + childCount: content.length, + ), + ), + SliverToBoxAdapter( + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + mainAxisSize: MainAxisSize.min, + children: [ + Padding( + padding: const EdgeInsets.only(top: 10.0, bottom: 20.0), + child: OutlineButton( + highlightedBorderColor: context.accentColor, + splashColor: context.accentColor.withOpacity(0.5), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(100))), + child: _loading + ? SizedBox( + height: 20, + width: 20, + child: CircularProgressIndicator( + strokeWidth: 2, + )) + : Text(context.s.loadMore), + onPressed: () => _loading + ? null + : setState( + () { + _loading = true; + _page++; + _searchFuture = _getTopPodcasts( + genre: widget.genre, page: _page); + }, + ), + ), + ) + ], + ), + ) + ], + ); + }, + ); + } +} diff --git a/lib/home/search_podcast.dart b/lib/home/search_podcast.dart index 90b8a10..c179f4b 100644 --- a/lib/home/search_podcast.dart +++ b/lib/home/search_podcast.dart @@ -1,1295 +1,1294 @@ -import 'dart:async'; -import 'dart:math' as math; - -import 'package:cached_network_image/cached_network_image.dart'; -import 'package:dio/dio.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:flutter_html/flutter_html.dart'; -import 'package:fluttertoast/fluttertoast.dart'; -import 'package:provider/provider.dart'; -import 'package:webfeed/webfeed.dart'; - -import '../local_storage/key_value_storage.dart'; -import '../service/search_api.dart'; -import '../state/podcast_group.dart'; -import '../state/search_state.dart'; -import '../type/search_api/searchepisodes.dart'; -import '../type/search_api/searchpodcast.dart'; -import '../util/custom_widget.dart'; -import '../util/extension_helper.dart'; -import 'pocast_discovery.dart'; - -class MyHomePageDelegate extends SearchDelegate { - final String searchFieldLabel; - final GlobalKey _discoveryKey = - GlobalKey(); - MyHomePageDelegate({this.searchFieldLabel}) - : super( - searchFieldLabel: searchFieldLabel, - ); - var _searchEngine; - static Future _getRss(String url) async { - try { - final options = BaseOptions( - connectTimeout: 30000, - receiveTimeout: 90000, - ); - var response = await Dio(options).get(url); - return RssFeed.parse(response.data); - } catch (e) { - rethrow; - } - } - - Future _getSearchEngine() async { - final storage = KeyValueStorage(searchEngineKey); - final index = await storage.getInt(); - if (_searchEngine == null) { - _searchEngine = SearchEngine.values[index]; - } - return _searchEngine; - } - - RegExp rssExp = RegExp(r'^(https?):\/\/(.*)'); - - Widget invalidRss(BuildContext context) => Container( - height: 50, - alignment: Alignment.center, - child: Text(context.s.searchInvalidRss), - ); - - @override - void close(BuildContext context, int result) { - final selectedPodcast = context.read().selectedPodcast; - if (selectedPodcast != null) { - context.read().clearSelect(); - } else { - if (_discoveryKey.currentState?.selectedGenre != null) { - _discoveryKey.currentState.backToHome(); - } else { - context.read().clearList(); - super.close(context, result); - } - } - } - - @override - ThemeData appBarTheme(BuildContext context) => Theme.of(context); - - @override - Widget buildLeading(BuildContext context) { - return WillPopScope( - onWillPop: () async { - close(context, null); - return false; - }, - child: IconButton( - tooltip: context.s.back, - splashRadius: 25, - icon: AnimatedIcon( - icon: AnimatedIcons.menu_arrow, - progress: transitionAnimation, - ), - onPressed: () { - close(context, 1); - }, - ), - ); - } - - @override - Widget buildSuggestions(BuildContext context) { - return DiscoveryPage( - key: _discoveryKey, - onTap: (history) { - query = history; - showResults(context); - }, - ); - } - - @override - List buildActions(BuildContext context) { - return [ - if (query.isNotEmpty) - IconButton( - tooltip: context.s.clear, - splashRadius: 25, - icon: const Icon(Icons.clear), - onPressed: () { - query = ''; - showResults(context); - }, - ), - FutureBuilder( - future: _getSearchEngine(), - initialData: SearchEngine.podcastIndex, - builder: (context, snapshot) => PopupMenuButton( - shape: - RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), - elevation: 1, - icon: SizedBox( - height: 30, - width: 30, - child: CircleAvatar( - backgroundImage: snapshot.data == SearchEngine.podcastIndex - ? AssetImage('assets/podcastindex_logo.png') - : AssetImage('assets/listennotes_logo.png'), - maxRadius: 25, - ), - ), - onSelected: (value) { - _searchEngine = value; - showSuggestions(context); - if (query != '') { - showResults(context); - } - }, - itemBuilder: (context) => [ - PopupMenuItem( - value: SearchEngine.podcastIndex, - child: Container( - padding: EdgeInsets.only(left: 10), - child: Row( - children: [ - Text('Podcastindex'), - Spacer(), - if (_searchEngine == SearchEngine.podcastIndex) - DotIndicator() - ], - ), - ), - ), - PopupMenuItem( - value: SearchEngine.listenNotes, - child: Container( - padding: EdgeInsets.only(left: 10), - child: Row( - children: [ - Text('ListenNotes'), - Spacer(), - if (_searchEngine == SearchEngine.listenNotes) - DotIndicator() - ], - ), - ), - ), - ], - ), - ), - SizedBox(width: 10), - ]; - } - - @override - Widget buildResults(BuildContext context) { - if (query.isEmpty) { - return DiscoveryPage( - key: _discoveryKey, - onTap: (history) { - query = history; - showResults(context); - }); - } else if (rssExp.stringMatch(query) != null) { - return FutureBuilder( - future: _getRss(rssExp.stringMatch(query)), - builder: (context, snapshot) { - if (snapshot.hasError) { - return invalidRss(context); - } else if (snapshot.hasData) { - return RssResult( - url: rssExp.stringMatch(query), - rssFeed: snapshot.data, - ); - } else { - return Container( - padding: EdgeInsets.only(top: 200), - alignment: Alignment.topCenter, - child: CircularProgressIndicator(), - ); - } - }, - ); - } else { - switch (_searchEngine) { - case SearchEngine.listenNotes: - return _ListenNotesSearch(query: query); - break; - case SearchEngine.podcastIndex: - return _PodcastIndexSearch(query: query); - default: - return Center(); - break; - } - } - } -} - -class RssResult extends StatefulWidget { - RssResult({this.url, this.rssFeed, Key key}) : super(key: key); - final RssFeed rssFeed; - final String url; - @override - _RssResultState createState() => _RssResultState(); -} - -class _RssResultState extends State { - OnlinePodcast _onlinePodcast; - int _loadItems; - - @override - void initState() { - var p = widget.rssFeed; - _loadItems = 10; - _onlinePodcast = OnlinePodcast( - rss: widget.url, - title: p.title, - publisher: p.author, - description: p.description, - image: p.itunes.image.href, - count: p.items.length); - super.initState(); - } - - @override - Widget build(BuildContext context) { - final s = context.s; - var items = widget.rssFeed.items; - return DefaultTabController( - length: 2, - child: Column( - children: [ - SizedBox( - height: 140, - child: Row( - children: [ - Expanded( - child: Padding( - padding: const EdgeInsets.only(left: 20), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Padding( - padding: const EdgeInsets.symmetric(vertical: 8), - child: Text(_onlinePodcast.title, - maxLines: 2, - overflow: TextOverflow.ellipsis, - style: context.textTheme.headline5), - ), - SubscribeButton(_onlinePodcast), - ], - ), - ), - ), - CachedNetworkImage( - height: 120.0, - width: 120.0, - fit: BoxFit.fitWidth, - alignment: Alignment.center, - imageUrl: _onlinePodcast.image, - progressIndicatorBuilder: (context, url, downloadProgress) => - Container( - height: 120, - width: 120, - alignment: Alignment.center, - color: context.primaryColorDark, - child: SizedBox( - width: 40, - height: 2, - child: LinearProgressIndicator( - value: downloadProgress.progress), - ), - ), - errorWidget: (context, url, error) => Container( - width: 120, - height: 120, - alignment: Alignment.center, - color: context.primaryColorDark, - child: Icon(Icons.error)), - ), - ], - ), - ), - Container( - height: 50, - color: context.scaffoldBackgroundColor, - child: TabBar( - indicatorColor: context.accentColor, - labelColor: context.textColor, - indicatorWeight: 3, - indicatorSize: TabBarIndicatorSize.label, - tabs: [ - Text(s.homeToprightMenuAbout), - Row( - mainAxisSize: MainAxisSize.min, - children: [ - Text(s.episode(2)), - SizedBox(width: 2), - Container( - padding: const EdgeInsets.only( - left: 5, right: 5, top: 2, bottom: 2), - decoration: BoxDecoration( - color: context.accentColor, - borderRadius: BorderRadius.circular(100)), - child: Text(_onlinePodcast.count.toString(), - style: TextStyle(color: Colors.white))) - ], - ) - ]), - ), - Expanded( - child: TabBarView(children: [ - ListView( - children: [ - Align( - alignment: Alignment.topLeft, - child: Html( - onLinkTap: (url) { - url.launchUrl; - }, - linkStyle: TextStyle( - color: context.accentColor, - // decoration: TextDecoration.underline, - textBaseline: TextBaseline.ideographic), - shrinkToFit: true, - data: _onlinePodcast.description, - padding: - EdgeInsets.only(left: 20.0, right: 20, bottom: 20), - defaultTextStyle: TextStyle( - height: 1.8, - ), - ), - ), - ], - ), - ListView.builder( - itemCount: math.min(_loadItems + 1, items.length), - itemBuilder: (context, index) { - if (index == _loadItems) { - return Container( - padding: const EdgeInsets.only(top: 10.0, bottom: 20.0), - alignment: Alignment.center, - child: OutlineButton( - highlightedBorderColor: context.accentColor, - splashColor: context.accentColor.withOpacity(0.5), - shape: RoundedRectangleBorder( - borderRadius: - BorderRadius.all(Radius.circular(100))), - child: Text(context.s.loadMore), - onPressed: () => setState( - () => _loadItems += 10, - ), - ), - ); - } - return ListTile( - title: Text(items[index].title), - subtitle: Text('${items[index].pubDate}', - style: TextStyle(color: context.accentColor)), - ); - }) - ]), - ) - ], - ), - ); - } -} - -class _ListenNotesSearch extends StatefulWidget { - final String query; - _ListenNotesSearch({this.query, Key key}) : super(key: key); - - @override - __ListenNotesSearchState createState() => __ListenNotesSearchState(); -} - -class __ListenNotesSearchState extends State<_ListenNotesSearch> { - int _nextOffset = 0; - final List _podcastList = []; - int _offset; - bool _loading = false; - bool _loadError = false; - Future _searchFuture; - - @override - void initState() { - super.initState(); - _searchFuture = _getListenNotesList(widget.query, _nextOffset); - } - - Future _saveHistory(String query) async { - final storage = KeyValueStorage(searchHistoryKey); - final history = await storage.getStringList(); - if (!history.contains(query)) { - if (history.length >= 6) { - history.removeLast(); - } - history.insert(0, query); - await storage.saveStringList(history); - } - } - - Future> _getListenNotesList( - String searchText, int nextOffset) async { - if (nextOffset == 0) _saveHistory(searchText); - final searchEngine = ListenNotesSearch(); - var searchResult; - try { - searchResult = await searchEngine.searchPodcasts( - searchText: searchText, nextOffset: nextOffset); - } catch (e) { - _loadError = true; - _loading = false; - return []; - } - _offset = searchResult.nextOffset; - _podcastList.addAll(searchResult.results.cast()); - _loading = false; - return _podcastList; - } - - @override - Widget build(BuildContext context) { - return PodcastSlideup( - searchEngine: SearchEngine.listenNotes, - child: FutureBuilder( - future: _searchFuture, - builder: (context, snapshot) { - if (!snapshot.hasData && widget.query != null) { - return Container( - padding: EdgeInsets.only(top: 200), - alignment: Alignment.topCenter, - child: CircularProgressIndicator(), - ); - } - if (snapshot.data.isEmpty) { - if (_loadError) { - return Container( - padding: EdgeInsets.only(top: 200), - alignment: Alignment.topCenter, - child: Text('Network error.', - style: context.textTheme.headline6 - .copyWith(color: Colors.red)), - ); - } else { - return Container( - padding: EdgeInsets.only(top: 200), - alignment: Alignment.topCenter, - child: Text('No result.', - style: context.textTheme.headline6 - .copyWith(color: context.accentColor)), - ); - } - } - var content = snapshot.data; - return CustomScrollView( - slivers: [ - SliverList( - delegate: SliverChildBuilderDelegate( - (context, index) { - return SearchResult(onlinePodcast: content[index]); - }, - childCount: content.length, - ), - ), - SliverToBoxAdapter( - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - mainAxisSize: MainAxisSize.min, - children: [ - Padding( - padding: const EdgeInsets.only(top: 10.0, bottom: 20.0), - child: OutlineButton( - highlightedBorderColor: context.accentColor, - splashColor: context.accentColor.withOpacity(0.5), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(100)), - child: _loading - ? SizedBox( - height: 20, - width: 20, - child: CircularProgressIndicator( - strokeWidth: 2, - )) - : Text(context.s.loadMore), - onPressed: () => _loading - ? null - : setState( - () { - _loading = true; - _nextOffset = _offset; - _searchFuture = _getListenNotesList( - widget.query, _nextOffset); - }, - ), - ), - ) - ], - ), - ), - SliverToBoxAdapter( - child: SizedBox( - height: 20, - child: Center( - child: Image( - image: context.brightness == Brightness.light - ? AssetImage('assets/listennotes.png') - : AssetImage('assets/listennotes_light.png'), - height: 15, - ), - ), - )) - ], - ); - }, - ), - ); - } -} - -class _PodcastIndexSearch extends StatefulWidget { - final String query; - _PodcastIndexSearch({this.query, Key key}) : super(key: key); - - @override - __PodcastIndexSearchState createState() => __PodcastIndexSearchState(); -} - -class __PodcastIndexSearchState extends State<_PodcastIndexSearch> { - int _limit; - bool _loading; - bool _loadError; - Future _searchFuture; - List _podcastList = []; - final _searchEngine = PodcastsIndexSearch(); - - Future _saveHistory(String query) async { - final storage = KeyValueStorage(searchHistoryKey); - final history = await storage.getStringList(); - if (!history.contains(query)) { - if (history.length >= 6) { - history.removeLast(); - } - history.insert(0, query); - await storage.saveStringList(history); - } - } - - @override - void initState() { - super.initState(); - _loading = false; - _loadError = false; - _limit = 10; - _searchFuture = _getPodcatsIndexList(widget.query, limit: _limit); - } - - Future> _getPodcatsIndexList(String searchText, - {int limit}) async { - if (_limit == 10) _saveHistory(searchText); - var searchResult; - try { - searchResult = await _searchEngine.searchPodcasts( - searchText: searchText, limit: limit); - } catch (e) { - _loadError = true; - _loading = false; - return []; - } - var list = searchResult.feeds.cast(); - _podcastList = [ - for (var podcast in list) podcast.toOnlinePodcast - ]; - _loading = false; - return _podcastList; - } - - @override - Widget build(BuildContext context) { - return PodcastSlideup( - searchEngine: SearchEngine.podcastIndex, - child: FutureBuilder( - future: _searchFuture, - builder: (context, snapshot) { - if (!snapshot.hasData && widget.query != null) { - return Container( - padding: EdgeInsets.only(top: 200), - alignment: Alignment.topCenter, - child: CircularProgressIndicator(), - ); - } - if (snapshot.data.isEmpty) { - if (_loadError) { - return Container( - padding: EdgeInsets.only(top: 200), - alignment: Alignment.topCenter, - child: Text('Network error.', - style: context.textTheme.headline6 - .copyWith(color: Colors.red)), - ); - } else { - return Container( - padding: EdgeInsets.only(top: 200), - alignment: Alignment.topCenter, - child: Text('No result found.', - style: context.textTheme.headline6 - .copyWith(color: context.accentColor)), - ); - } - } - var content = snapshot.data; - return CustomScrollView( - slivers: [ - SliverList( - delegate: SliverChildBuilderDelegate( - (context, index) { - return SearchResult(onlinePodcast: content[index]); - }, - childCount: content.length, - ), - ), - SliverToBoxAdapter( - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - mainAxisSize: MainAxisSize.min, - children: [ - Padding( - padding: const EdgeInsets.only(top: 10.0, bottom: 20.0), - child: OutlineButton( - highlightedBorderColor: context.accentColor, - splashColor: context.accentColor.withOpacity(0.5), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(100)), - child: _loading - ? SizedBox( - height: 20, - width: 20, - child: CircularProgressIndicator( - strokeWidth: 2, - )) - : Text(context.s.loadMore), - onPressed: () => _loading - ? null - : setState( - () { - _loading = true; - _limit += 10; - _searchFuture = _getPodcatsIndexList( - widget.query, - limit: _limit); - }, - ), - ), - ) - ], - ), - ), - SliverToBoxAdapter( - child: SizedBox( - height: 20, - child: Center( - child: Image( - image: AssetImage('assets/podcastindex.png'), - height: 15, - ), - ), - )) - ], - ); - }), - ); - } -} - -class SearchResult extends StatelessWidget { - final OnlinePodcast onlinePodcast; - SearchResult({this.onlinePodcast, Key key}) : super(key: key); - - @override - Widget build(BuildContext context) { - var searchState = context.watch(); - return Column( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - ListTile( - contentPadding: EdgeInsets.fromLTRB(20, 10, 20, 10), - onTap: () { - searchState.selectedPodcast = onlinePodcast; - }, - leading: ClipRRect( - borderRadius: BorderRadius.circular(25.0), - child: CachedNetworkImage( - height: 50.0, - width: 50.0, - fit: BoxFit.fitWidth, - alignment: Alignment.center, - imageUrl: onlinePodcast.image, - progressIndicatorBuilder: (context, url, downloadProgress) => - Container( - height: 50, - width: 50, - alignment: Alignment.center, - color: context.primaryColorDark, - child: SizedBox( - width: 20, - height: 2, - child: LinearProgressIndicator( - value: downloadProgress.progress), - ), - ), - errorWidget: (context, url, error) => Container( - width: 50, - height: 50, - alignment: Alignment.center, - color: context.primaryColorDark, - child: Icon(Icons.error)), - ), - ), - title: Text(onlinePodcast.title), - subtitle: Text( - onlinePodcast.publisher ?? '', - maxLines: 3, - overflow: TextOverflow.ellipsis, - ), - trailing: SubscribeButton(onlinePodcast)), - ], - ); - } -} - -/// Search podcast detail widget -class SearchResultDetail extends StatefulWidget { - SearchResultDetail(this.onlinePodcast, - {this.maxHeight, this.isSubscribed, this.searchEngine, Key key}) - : super(key: key); - final OnlinePodcast onlinePodcast; - final double maxHeight; - final bool isSubscribed; - final SearchEngine searchEngine; - @override - _SearchResultDetailState createState() => _SearchResultDetailState(); -} - -enum SlideDirection { up, down } - -class _SearchResultDetailState extends State - with SingleTickerProviderStateMixin { - /// Animation value. - double _initSize; - - /// Gesture tap start position. - double _startdy; - - /// Height of first open. - double _minHeight; - - /// Gesture move. - double _move = 0; - - AnimationController _controller; - Animation _animation; - - /// Gesture scroll direction. - SlideDirection _slideDirection; - - /// Search offset. - int _nextEpisdoeDate = DateTime.now().millisecondsSinceEpoch; - - /// Search result. - final List _episodeList = []; - - Future _searchFuture; - - /// Episodes list load more. - bool _loading = false; - - @override - void initState() { - super.initState(); - - _searchFuture = widget.searchEngine == SearchEngine.listenNotes - ? _getListenNotesEpisodes( - id: widget.onlinePodcast.id, nextEpisodeDate: _nextEpisdoeDate) - : _getIndexEpisodes(id: widget.onlinePodcast.rss); - _minHeight = widget.maxHeight / 2; - _initSize = _minHeight; - _slideDirection = SlideDirection.up; - _controller = - AnimationController(vsync: this, duration: Duration(milliseconds: 200)) - ..addListener(() { - if (mounted) setState(() {}); - }); - _animation = - Tween(begin: 170, end: _minHeight).animate(_controller); - _controller.forward(); - } - - @override - void dispose() { - _controller.dispose(); - super.dispose(); - } - - Future> _getListenNotesEpisodes( - {String id, int nextEpisodeDate}) async { - var searchEngine = ListenNotesSearch(); - var searchResult = await searchEngine.fetchEpisode( - id: id, nextEpisodeDate: nextEpisodeDate); - _nextEpisdoeDate = searchResult.nextEpisodeDate; - _episodeList.addAll(searchResult.episodes.cast()); - _loading = false; - return _episodeList; - } - - Future> _getIndexEpisodes( - {String id, int nextEpisodeDate}) async { - var searchEngine = PodcastsIndexSearch(); - var searchResult = await searchEngine.fetchEpisode(rssUrl: id); - var episodes = searchResult.items.cast(); - for (var episode in episodes) { - _episodeList.add(episode.toOnlineWEpisode); - } - _loading = false; - return _episodeList; - } - - void _start(DragStartDetails event) { - setState(() { - _startdy = event.localPosition.dy; - _animation = - Tween(begin: _initSize, end: _initSize).animate(_controller); - }); - _controller.forward(); - } - - void _update(DragUpdateDetails event) { - setState(() { - _move = _startdy - event.localPosition.dy; - _animation = Tween(begin: _initSize, end: _initSize + _move) - .animate(_controller); - _slideDirection = _move > 0 ? SlideDirection.up : SlideDirection.down; - }); - _controller.forward(); - } - - void _end() { - if (_slideDirection == SlideDirection.up) { - if (_move > 20) { - setState(() { - _animation = - Tween(begin: _animation.value, end: widget.maxHeight) - .animate(_controller); - _initSize = widget.maxHeight; - }); - _controller.forward(); - } else { - setState(() { - _animation = Tween(begin: _animation.value, end: _minHeight) - .animate(_controller); - _initSize = _minHeight; - }); - _controller.forward(); - } - } else if (_slideDirection == SlideDirection.down) { - if (_move > -50) { - setState(() { - _animation = Tween( - begin: _animation.value, - end: _animation.value > _minHeight - ? widget.maxHeight - : _minHeight) - .animate(_controller); - _initSize = - _animation.value > _minHeight ? widget.maxHeight : _minHeight; - }); - _controller.forward(); - } else { - setState(() { - _animation = Tween( - begin: _animation.value, - end: _animation.value > _minHeight - 50 ? _minHeight : 1) - .animate(_controller); - _initSize = _animation.value > _minHeight - 50 ? _minHeight : 100; - }); - _controller.forward(); - if (_animation.value < _minHeight - 50) { - context.read().clearSelect(); - } - } - } - } - - @override - Widget build(BuildContext context) { - final s = context.s; - return GestureDetector( - onVerticalDragStart: _start, - onVerticalDragUpdate: _update, - onVerticalDragEnd: (event) => _end(), - child: Container( - decoration: BoxDecoration( - color: context.primaryColor, - boxShadow: [ - BoxShadow( - offset: Offset(0, -0.5), - blurRadius: 1, - color: Theme.of(context).brightness == Brightness.light - ? Colors.grey[400].withOpacity(0.5) - : Colors.grey[800], - ), - ], - ), - height: _animation.value, - child: DefaultTabController( - length: 2, - child: Column( - children: [ - SizedBox( - height: math.min(_animation.value, 120), - child: SingleChildScrollView( - physics: const NeverScrollableScrollPhysics(), - child: SizedBox( - height: 120, - child: Row( - children: [ - Expanded( - child: Padding( - padding: const EdgeInsets.only(left: 20), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Padding( - padding: - const EdgeInsets.symmetric(vertical: 8), - child: Text(widget.onlinePodcast.title, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: context.textTheme.headline5), - ), - Text( - widget.onlinePodcast.interval - .toInterval(context) != - '' - ? '${widget.onlinePodcast.interval.toInterval(context)} | ' - '${widget.onlinePodcast.latestPubDate.toDate(context)}' - : '${widget.onlinePodcast.latestPubDate.toDate(context)}', - maxLines: 1, - overflow: TextOverflow.fade, - style: TextStyle(color: context.accentColor), - ), - SubscribeButton(widget.onlinePodcast), - ], - ), - ), - ), - CachedNetworkImage( - height: 120.0, - width: 120.0, - fit: BoxFit.fitWidth, - alignment: Alignment.center, - imageUrl: widget.onlinePodcast.image, - progressIndicatorBuilder: - (context, url, downloadProgress) => Container( - height: 120, - width: 120, - alignment: Alignment.center, - color: context.primaryColorDark, - child: SizedBox( - width: 40, - height: 2, - child: LinearProgressIndicator( - value: downloadProgress.progress), - ), - ), - errorWidget: (context, url, error) => Container( - width: 120, - height: 120, - alignment: Alignment.center, - color: context.primaryColorDark, - child: Icon(Icons.error)), - ), - ], - ), - ), - ), - ), - if (_animation.value > 120) - SizedBox( - height: math.min(_animation.value - 120, 50), - child: SingleChildScrollView( - physics: const NeverScrollableScrollPhysics(), - child: SizedBox( - height: 50, - child: TabBar( - indicatorColor: context.accentColor, - labelColor: context.textColor, - indicatorWeight: 3, - indicatorSize: TabBarIndicatorSize.label, - tabs: [ - Text(s.homeToprightMenuAbout), - Row( - mainAxisSize: MainAxisSize.min, - children: [ - Text(s.episode(2)), - SizedBox(width: 2), - if (widget.onlinePodcast.count > 0) - Container( - padding: const EdgeInsets.only( - left: 5, right: 5, top: 2, bottom: 2), - decoration: BoxDecoration( - color: context.accentColor, - borderRadius: - BorderRadius.circular(100)), - child: Text( - widget.onlinePodcast.count.toString(), - style: - TextStyle(color: Colors.white))) - ], - ) - ]), - ), - ), - ), - Expanded( - child: TabBarView(children: [ - ListView( - physics: _animation.value != widget.maxHeight - ? NeverScrollableScrollPhysics() - : null, - children: [ - Html( - onLinkTap: (url) { - url.launchUrl; - }, - linkStyle: TextStyle( - color: context.accentColor, - textBaseline: TextBaseline.ideographic), - shrinkToFit: true, - data: widget.onlinePodcast.description, - padding: const EdgeInsets.only( - left: 20.0, right: 20, bottom: 20), - defaultTextStyle: TextStyle( - height: 1.8, - ), - ), - ], - ), - FutureBuilder>( - future: _searchFuture, - builder: (context, snapshot) { - if (snapshot.hasData) { - var content = snapshot.data; - return ListView.builder( - physics: _animation.value != widget.maxHeight - ? NeverScrollableScrollPhysics() - : null, - itemCount: content.length + 1, - itemBuilder: (context, index) { - if (index == content.length) { - return Container( - padding: const EdgeInsets.only( - top: 10.0, bottom: 20.0), - alignment: Alignment.center, - child: SizedBox( - child: OutlineButton( - highlightedBorderColor: - context.accentColor, - splashColor: context.accentColor - .withOpacity(0.5), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.all( - Radius.circular(100))), - child: _loading - ? SizedBox( - height: 20, - width: 20, - child: - CircularProgressIndicator( - strokeWidth: 2, - )) - : Text(context.s.loadMore), - onPressed: () { - if (widget.searchEngine == - SearchEngine.listenNotes) { - _loading - ? null - : setState( - () { - _loading = true; - _searchFuture = - _getListenNotesEpisodes( - id: widget - .onlinePodcast - .id, - nextEpisodeDate: - _nextEpisdoeDate); - }, - ); - } - }), - ), - ); - } - return ListTile( - title: Text(content[index].title), - subtitle: Text( - content[index].length == 0 - ? '${content[index].pubDate.toDate(context)}' - : '${content[index].length.toTime} | ' - '${content[index].pubDate.toDate(context)}', - style: - TextStyle(color: context.accentColor)), - ); - }, - ); - } - return Center( - child: CircularProgressIndicator(), - ); - }) - ]), - ) - ], - ), - ), - ), - ); - } -} - -class SubscribeButton extends StatelessWidget { - SubscribeButton(this.onlinePodcast, {Key key}) : super(key: key); - final OnlinePodcast onlinePodcast; - - @override - Widget build(BuildContext context) { - final subscribeWorker = context.watch(); - final searchState = context.watch(); - final s = context.s; - void subscribePodcast(OnlinePodcast podcast) { - var item = SubscribeItem(podcast.rss, podcast.title, - imgUrl: podcast.image, group: 'Home'); - subscribeWorker.setSubscribeItem(item); - searchState.addPodcast(podcast); - } - - return Consumer(builder: (_, searchState, __) { - final subscribed = searchState.isSubscribed(onlinePodcast); - return !subscribed - ? ButtonTheme( - height: 32, - child: OutlineButton( - highlightedBorderColor: context.accentColor, - borderSide: BorderSide(color: context.accentColor), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(100.0), - side: BorderSide(color: context.accentColor)), - splashColor: context.accentColor.withOpacity(0.5), - child: Text(s.subscribe, - style: TextStyle(color: context.accentColor)), - onPressed: () { - Fluttertoast.showToast( - msg: s.podcastSubscribed, - gravity: ToastGravity.BOTTOM, - ); - subscribePodcast(onlinePodcast); - searchState.addPodcast(onlinePodcast); - }), - ) - : ButtonTheme( - height: 32, - child: OutlineButton( - color: context.accentColor.withOpacity(0.5), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(100.0), - side: BorderSide(color: Colors.grey[500])), - highlightedBorderColor: Colors.grey[500], - disabledTextColor: Colors.grey[500], - child: Text(s.subscribe), - disabledBorderColor: Colors.grey[500], - onPressed: () {}), - ); - }); - } -} - -class PodcastSlideup extends StatelessWidget { - const PodcastSlideup({this.child, this.searchEngine, Key key}) - : super(key: key); - final Widget child; - final SearchEngine searchEngine; - - @override - Widget build(BuildContext context) { - return Consumer(builder: (_, searchState, __) { - final selectedPodcast = searchState.selectedPodcast; - final subscribed = searchState.subscribedList; - return Stack( - alignment: Alignment.bottomCenter, - children: [ - child, - if (selectedPodcast != null) - Positioned.fill( - child: GestureDetector( - onTap: searchState.clearSelect, - child: Container( - color: context.scaffoldBackgroundColor.withOpacity(0.9), - ), - ), - ), - if (selectedPodcast != null) - LayoutBuilder( - builder: (context, constrants) => SearchResultDetail( - selectedPodcast, - maxHeight: constrants.maxHeight, - isSubscribed: subscribed.contains(selectedPodcast), - ), - ), - ], - ); - }); - } -} - -class PodcastAvatar extends StatelessWidget { - const PodcastAvatar(this.podcast, {Key key}) : super(key: key); - final OnlinePodcast podcast; - @override - Widget build(BuildContext context) { - return SizedBox( - height: 50, - child: ClipRRect( - borderRadius: BorderRadius.circular(25.0), - child: CachedNetworkImage( - height: 50.0, - width: 50.0, - fit: BoxFit.fitWidth, - alignment: Alignment.center, - imageUrl: podcast.image, - progressIndicatorBuilder: (context, url, downloadProgress) => - Container( - height: 50, - width: 50, - alignment: Alignment.center, - color: context.primaryColorDark, - child: SizedBox( - width: 20, - height: 2, - child: LinearProgressIndicator(value: downloadProgress.progress), - ), - ), - errorWidget: (context, url, error) => Container( - width: 50, - height: 50, - alignment: Alignment.center, - color: context.primaryColorDark, - child: Icon(Icons.error)), - ), - ), - ); - } -} +import 'dart:async'; +import 'dart:math' as math; + +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:dio/dio.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_html/flutter_html.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:provider/provider.dart'; +import 'package:webfeed/webfeed.dart'; + +import '../local_storage/key_value_storage.dart'; +import '../service/search_api.dart'; +import '../state/podcast_group.dart'; +import '../state/search_state.dart'; +import '../type/search_api/searchepisodes.dart'; +import '../type/search_api/searchpodcast.dart'; +import '../util/custom_widget.dart'; +import '../util/extension_helper.dart'; +import 'pocast_discovery.dart'; + +class MyHomePageDelegate extends SearchDelegate { + final String searchFieldLabel; + final GlobalKey _discoveryKey = + GlobalKey(); + MyHomePageDelegate({this.searchFieldLabel}) + : super( + searchFieldLabel: searchFieldLabel, + ); + var _searchEngine; + static Future _getRss(String url) async { + try { + final options = BaseOptions( + connectTimeout: 30000, + receiveTimeout: 90000, + ); + var response = await Dio(options).get(url); + return RssFeed.parse(response.data); + } catch (e) { + rethrow; + } + } + + Future _getSearchEngine() async { + final storage = KeyValueStorage(searchEngineKey); + final index = await storage.getInt(); + if (_searchEngine == null) { + _searchEngine = SearchEngine.values[index]; + } + return _searchEngine; + } + + RegExp rssExp = RegExp(r'^(https?):\/\/(.*)'); + + Widget invalidRss(BuildContext context) => Container( + height: 50, + alignment: Alignment.center, + child: Text(context.s.searchInvalidRss), + ); + + @override + void close(BuildContext context, int result) { + final selectedPodcast = context.read().selectedPodcast; + if (selectedPodcast != null) { + context.read().clearSelect(); + } else { + if (_discoveryKey.currentState?.selectedGenre != null) { + _discoveryKey.currentState.backToHome(); + } else { + context.read().clearList(); + super.close(context, result); + } + } + } + + @override + ThemeData appBarTheme(BuildContext context) => Theme.of(context); + + @override + Widget buildLeading(BuildContext context) { + return WillPopScope( + onWillPop: () async { + close(context, null); + return false; + }, + child: IconButton( + tooltip: context.s.back, + splashRadius: 25, + icon: AnimatedIcon( + icon: AnimatedIcons.menu_arrow, + progress: transitionAnimation, + ), + onPressed: () { + close(context, 1); + }, + ), + ); + } + + @override + Widget buildSuggestions(BuildContext context) { + return DiscoveryPage( + key: _discoveryKey, + onTap: (history) { + query = history; + showResults(context); + }, + ); + } + + @override + List buildActions(BuildContext context) { + return [ + if (query.isNotEmpty) + IconButton( + tooltip: context.s.clear, + splashRadius: 25, + icon: const Icon(Icons.clear), + onPressed: () { + query = ''; + showResults(context); + }, + ), + FutureBuilder( + future: _getSearchEngine(), + initialData: SearchEngine.podcastIndex, + builder: (context, snapshot) => PopupMenuButton( + shape: + RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), + elevation: 1, + icon: SizedBox( + height: 30, + width: 30, + child: CircleAvatar( + backgroundImage: snapshot.data == SearchEngine.podcastIndex + ? AssetImage('assets/podcastindex_logo.png') + : AssetImage('assets/listennotes_logo.png'), + maxRadius: 25, + ), + ), + onSelected: (value) { + _searchEngine = value; + showSuggestions(context); + if (query != '') { + showResults(context); + } + }, + itemBuilder: (context) => [ + PopupMenuItem( + value: SearchEngine.podcastIndex, + child: Container( + padding: EdgeInsets.only(left: 10), + child: Row( + children: [ + Text('Podcastindex'), + Spacer(), + if (_searchEngine == SearchEngine.podcastIndex) + DotIndicator() + ], + ), + ), + ), + PopupMenuItem( + value: SearchEngine.listenNotes, + child: Container( + padding: EdgeInsets.only(left: 10), + child: Row( + children: [ + Text('ListenNotes'), + Spacer(), + if (_searchEngine == SearchEngine.listenNotes) + DotIndicator() + ], + ), + ), + ), + ], + ), + ), + SizedBox(width: 10), + ]; + } + + @override + Widget buildResults(BuildContext context) { + if (query.isEmpty) { + return DiscoveryPage( + key: _discoveryKey, + onTap: (history) { + query = history; + showResults(context); + }); + } else if (rssExp.stringMatch(query) != null) { + return FutureBuilder( + future: _getRss(rssExp.stringMatch(query)), + builder: (context, snapshot) { + if (snapshot.hasError) { + return invalidRss(context); + } else if (snapshot.hasData) { + return RssResult( + url: rssExp.stringMatch(query), + rssFeed: snapshot.data, + ); + } else { + return Container( + padding: EdgeInsets.only(top: 200), + alignment: Alignment.topCenter, + child: CircularProgressIndicator(), + ); + } + }, + ); + } else { + switch (_searchEngine) { + case SearchEngine.listenNotes: + return _ListenNotesSearch(query: query); + break; + case SearchEngine.podcastIndex: + return _PodcastIndexSearch(query: query); + default: + return Center(); + break; + } + } + } +} + +class RssResult extends StatefulWidget { + RssResult({this.url, this.rssFeed, Key key}) : super(key: key); + final RssFeed rssFeed; + final String url; + @override + _RssResultState createState() => _RssResultState(); +} + +class _RssResultState extends State { + OnlinePodcast _onlinePodcast; + int _loadItems; + + @override + void initState() { + var p = widget.rssFeed; + _loadItems = 10; + _onlinePodcast = OnlinePodcast( + rss: widget.url, + title: p.title, + publisher: p.author, + description: p.description, + image: p.itunes.image.href, + count: p.items.length); + super.initState(); + } + + @override + Widget build(BuildContext context) { + final s = context.s; + var items = widget.rssFeed.items; + return DefaultTabController( + length: 2, + child: Column( + children: [ + SizedBox( + height: 140, + child: Row( + children: [ + Expanded( + child: Padding( + padding: const EdgeInsets.only(left: 20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Padding( + padding: const EdgeInsets.symmetric(vertical: 8), + child: Text(_onlinePodcast.title, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: context.textTheme.headline5), + ), + SubscribeButton(_onlinePodcast), + ], + ), + ), + ), + CachedNetworkImage( + height: 120.0, + width: 120.0, + fit: BoxFit.fitWidth, + alignment: Alignment.center, + imageUrl: _onlinePodcast.image, + progressIndicatorBuilder: (context, url, downloadProgress) => + Container( + height: 120, + width: 120, + alignment: Alignment.center, + color: context.primaryColorDark, + child: SizedBox( + width: 40, + height: 2, + child: LinearProgressIndicator( + value: downloadProgress.progress), + ), + ), + errorWidget: (context, url, error) => Container( + width: 120, + height: 120, + alignment: Alignment.center, + color: context.primaryColorDark, + child: Icon(Icons.error)), + ), + ], + ), + ), + Container( + height: 50, + color: context.scaffoldBackgroundColor, + child: TabBar( + indicatorColor: context.accentColor, + labelColor: context.textColor, + indicatorWeight: 3, + indicatorSize: TabBarIndicatorSize.label, + tabs: [ + Text(s.homeToprightMenuAbout), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text(s.episode(2)), + SizedBox(width: 2), + Container( + padding: const EdgeInsets.only( + left: 5, right: 5, top: 2, bottom: 2), + decoration: BoxDecoration( + color: context.accentColor, + borderRadius: BorderRadius.circular(100)), + child: Text(_onlinePodcast.count.toString(), + style: TextStyle(color: Colors.white))) + ], + ) + ]), + ), + Expanded( + child: TabBarView(children: [ + ListView( + children: [ + Align( + alignment: Alignment.topLeft, + child: Html( + onLinkTap: (url) { + url.launchUrl; + }, + linkStyle: TextStyle( + color: context.accentColor, + // decoration: TextDecoration.underline, + textBaseline: TextBaseline.ideographic), + shrinkToFit: true, + data: _onlinePodcast.description, + padding: + EdgeInsets.only(left: 20.0, right: 20, bottom: 20), + defaultTextStyle: TextStyle( + height: 1.8, + ), + ), + ), + ], + ), + ListView.builder( + itemCount: math.min(_loadItems + 1, items.length), + itemBuilder: (context, index) { + if (index == _loadItems) { + return Container( + padding: const EdgeInsets.only(top: 10.0, bottom: 20.0), + alignment: Alignment.center, + child: OutlineButton( + highlightedBorderColor: context.accentColor, + splashColor: context.accentColor.withOpacity(0.5), + shape: RoundedRectangleBorder( + borderRadius: + BorderRadius.all(Radius.circular(100))), + child: Text(context.s.loadMore), + onPressed: () => setState( + () => _loadItems += 10, + ), + ), + ); + } + return ListTile( + title: Text(items[index].title), + subtitle: Text('${items[index].pubDate}', + style: TextStyle(color: context.accentColor)), + ); + }) + ]), + ) + ], + ), + ); + } +} + +class _ListenNotesSearch extends StatefulWidget { + final String query; + _ListenNotesSearch({this.query, Key key}) : super(key: key); + + @override + __ListenNotesSearchState createState() => __ListenNotesSearchState(); +} + +class __ListenNotesSearchState extends State<_ListenNotesSearch> { + int _nextOffset = 0; + final List _podcastList = []; + int _offset; + bool _loading = false; + bool _loadError = false; + Future _searchFuture; + + @override + void initState() { + super.initState(); + _searchFuture = _getListenNotesList(widget.query, _nextOffset); + } + + Future _saveHistory(String query) async { + final storage = KeyValueStorage(searchHistoryKey); + final history = await storage.getStringList(); + if (!history.contains(query)) { + if (history.length >= 6) { + history.removeLast(); + } + history.insert(0, query); + await storage.saveStringList(history); + } + } + + Future> _getListenNotesList( + String searchText, int nextOffset) async { + if (nextOffset == 0) _saveHistory(searchText); + final searchEngine = ListenNotesSearch(); + var searchResult; + try { + searchResult = await searchEngine.searchPodcasts( + searchText: searchText, nextOffset: nextOffset); + } catch (e) { + _loadError = true; + _loading = false; + return []; + } + _offset = searchResult.nextOffset; + _podcastList.addAll(searchResult.results.cast()); + _loading = false; + return _podcastList; + } + + @override + Widget build(BuildContext context) { + return PodcastSlideup( + searchEngine: SearchEngine.listenNotes, + child: FutureBuilder( + future: _searchFuture, + builder: (context, snapshot) { + if (!snapshot.hasData && widget.query != null) { + return Container( + padding: EdgeInsets.only(top: 200), + alignment: Alignment.topCenter, + child: CircularProgressIndicator(), + ); + } + if (snapshot.data.isEmpty) { + if (_loadError) { + return Container( + padding: EdgeInsets.only(top: 200), + alignment: Alignment.topCenter, + child: Text('Network error.', + style: context.textTheme.headline6 + .copyWith(color: Colors.red)), + ); + } else { + return Container( + padding: EdgeInsets.only(top: 200), + alignment: Alignment.topCenter, + child: Text('No result.', + style: context.textTheme.headline6 + .copyWith(color: context.accentColor)), + ); + } + } + var content = snapshot.data; + return CustomScrollView( + slivers: [ + SliverList( + delegate: SliverChildBuilderDelegate( + (context, index) { + return SearchResult(onlinePodcast: content[index]); + }, + childCount: content.length, + ), + ), + SliverToBoxAdapter( + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + mainAxisSize: MainAxisSize.min, + children: [ + Padding( + padding: const EdgeInsets.only(top: 10.0, bottom: 20.0), + child: OutlineButton( + highlightedBorderColor: context.accentColor, + splashColor: context.accentColor.withOpacity(0.5), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(100)), + child: _loading + ? SizedBox( + height: 20, + width: 20, + child: CircularProgressIndicator( + strokeWidth: 2, + )) + : Text(context.s.loadMore), + onPressed: () => _loading + ? null + : setState( + () { + _loading = true; + _nextOffset = _offset; + _searchFuture = _getListenNotesList( + widget.query, _nextOffset); + }, + ), + ), + ) + ], + ), + ), + SliverToBoxAdapter( + child: SizedBox( + height: 20, + child: Center( + child: Image( + image: context.brightness == Brightness.light + ? AssetImage('assets/listennotes.png') + : AssetImage('assets/listennotes_light.png'), + height: 15, + ), + ), + )) + ], + ); + }, + ), + ); + } +} + +class _PodcastIndexSearch extends StatefulWidget { + final String query; + _PodcastIndexSearch({this.query, Key key}) : super(key: key); + + @override + __PodcastIndexSearchState createState() => __PodcastIndexSearchState(); +} + +class __PodcastIndexSearchState extends State<_PodcastIndexSearch> { + int _limit; + bool _loading; + bool _loadError; + Future _searchFuture; + List _podcastList = []; + final _searchEngine = PodcastsIndexSearch(); + + Future _saveHistory(String query) async { + final storage = KeyValueStorage(searchHistoryKey); + final history = await storage.getStringList(); + if (!history.contains(query)) { + if (history.length >= 6) { + history.removeLast(); + } + history.insert(0, query); + await storage.saveStringList(history); + } + } + + @override + void initState() { + super.initState(); + _loading = false; + _loadError = false; + _limit = 10; + _searchFuture = _getPodcatsIndexList(widget.query, limit: _limit); + } + + Future> _getPodcatsIndexList(String searchText, + {int limit}) async { + if (_limit == 10) _saveHistory(searchText); + var searchResult; + try { + searchResult = await _searchEngine.searchPodcasts( + searchText: searchText, limit: limit); + } catch (e) { + _loadError = true; + _loading = false; + return []; + } + var list = searchResult.feeds.cast(); + _podcastList = [ + for (var podcast in list) podcast.toOnlinePodcast + ]; + _loading = false; + return _podcastList; + } + + @override + Widget build(BuildContext context) { + return PodcastSlideup( + searchEngine: SearchEngine.podcastIndex, + child: FutureBuilder( + future: _searchFuture, + builder: (context, snapshot) { + if (!snapshot.hasData && widget.query != null) { + return Container( + padding: EdgeInsets.only(top: 200), + alignment: Alignment.topCenter, + child: CircularProgressIndicator(), + ); + } + if (snapshot.data.isEmpty) { + if (_loadError) { + return Container( + padding: EdgeInsets.only(top: 200), + alignment: Alignment.topCenter, + child: Text('Network error.', + style: context.textTheme.headline6 + .copyWith(color: Colors.red)), + ); + } else { + return Container( + padding: EdgeInsets.only(top: 200), + alignment: Alignment.topCenter, + child: Text('No result found.', + style: context.textTheme.headline6 + .copyWith(color: context.accentColor)), + ); + } + } + var content = snapshot.data; + return CustomScrollView( + slivers: [ + SliverList( + delegate: SliverChildBuilderDelegate( + (context, index) { + return SearchResult(onlinePodcast: content[index]); + }, + childCount: content.length, + ), + ), + SliverToBoxAdapter( + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + mainAxisSize: MainAxisSize.min, + children: [ + Padding( + padding: const EdgeInsets.only(top: 10.0, bottom: 20.0), + child: OutlineButton( + highlightedBorderColor: context.accentColor, + splashColor: context.accentColor.withOpacity(0.5), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(100)), + child: _loading + ? SizedBox( + height: 20, + width: 20, + child: CircularProgressIndicator( + strokeWidth: 2, + )) + : Text(context.s.loadMore), + onPressed: () => _loading + ? null + : setState( + () { + _loading = true; + _limit += 10; + _searchFuture = _getPodcatsIndexList( + widget.query, + limit: _limit); + }, + ), + ), + ) + ], + ), + ), + SliverToBoxAdapter( + child: SizedBox( + height: 20, + child: Center( + child: Image( + image: AssetImage('assets/podcastindex.png'), + height: 15, + ), + ), + )) + ], + ); + }), + ); + } +} + +class SearchResult extends StatelessWidget { + final OnlinePodcast onlinePodcast; + SearchResult({this.onlinePodcast, Key key}) : super(key: key); + + @override + Widget build(BuildContext context) { + var searchState = context.watch(); + return Column( + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + ListTile( + contentPadding: EdgeInsets.fromLTRB(20, 10, 20, 10), + onTap: () { + searchState.selectedPodcast = onlinePodcast; + }, + leading: ClipRRect( + borderRadius: BorderRadius.circular(25.0), + child: CachedNetworkImage( + height: 50.0, + width: 50.0, + fit: BoxFit.fitWidth, + alignment: Alignment.center, + imageUrl: onlinePodcast.image, + progressIndicatorBuilder: (context, url, downloadProgress) => + Container( + height: 50, + width: 50, + alignment: Alignment.center, + color: context.primaryColorDark, + child: SizedBox( + width: 20, + height: 2, + child: LinearProgressIndicator( + value: downloadProgress.progress), + ), + ), + errorWidget: (context, url, error) => Container( + width: 50, + height: 50, + alignment: Alignment.center, + color: context.primaryColorDark, + child: Icon(Icons.error)), + ), + ), + title: Text(onlinePodcast.title), + subtitle: Text( + onlinePodcast.publisher ?? '', + maxLines: 3, + overflow: TextOverflow.ellipsis, + ), + trailing: SubscribeButton(onlinePodcast)), + ], + ); + } +} + +/// Search podcast detail widget +class SearchResultDetail extends StatefulWidget { + SearchResultDetail(this.onlinePodcast, + {this.maxHeight, this.isSubscribed, this.searchEngine, Key key}) + : super(key: key); + final OnlinePodcast onlinePodcast; + final double maxHeight; + final bool isSubscribed; + final SearchEngine searchEngine; + @override + _SearchResultDetailState createState() => _SearchResultDetailState(); +} + +enum SlideDirection { up, down } + +class _SearchResultDetailState extends State + with SingleTickerProviderStateMixin { + /// Animation value. + double _initSize; + + /// Gesture tap start position. + double _startdy; + + /// Height of first open. + double _minHeight; + + /// Gesture move. + double _move = 0; + + AnimationController _controller; + Animation _animation; + + /// Gesture scroll direction. + SlideDirection _slideDirection; + + /// Search offset. + int _nextEpisdoeDate = DateTime.now().millisecondsSinceEpoch; + + /// Search result. + final List _episodeList = []; + + Future _searchFuture; + + /// Episodes list load more. + bool _loading = false; + + @override + void initState() { + super.initState(); + + _searchFuture = widget.searchEngine == SearchEngine.listenNotes + ? _getListenNotesEpisodes( + id: widget.onlinePodcast.id, nextEpisodeDate: _nextEpisdoeDate) + : _getIndexEpisodes(id: widget.onlinePodcast.rss); + _minHeight = widget.maxHeight / 2; + _initSize = _minHeight; + _slideDirection = SlideDirection.up; + _controller = + AnimationController(vsync: this, duration: Duration(milliseconds: 200)) + ..addListener(() { + if (mounted) setState(() {}); + }); + _animation = + Tween(begin: 170, end: _minHeight).animate(_controller); + _controller.forward(); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + Future> _getListenNotesEpisodes( + {String id, int nextEpisodeDate}) async { + var searchEngine = ListenNotesSearch(); + var searchResult = await searchEngine.fetchEpisode( + id: id, nextEpisodeDate: nextEpisodeDate); + _nextEpisdoeDate = searchResult.nextEpisodeDate; + _episodeList.addAll(searchResult.episodes.cast()); + _loading = false; + return _episodeList; + } + + Future> _getIndexEpisodes({String id}) async { + var searchEngine = PodcastsIndexSearch(); + var searchResult = await searchEngine.fetchEpisode(rssUrl: id); + var episodes = searchResult.items.cast(); + for (var episode in episodes) { + _episodeList.add(episode.toOnlineWEpisode); + } + _loading = false; + return _episodeList; + } + + void _start(DragStartDetails event) { + setState(() { + _startdy = event.localPosition.dy; + _animation = + Tween(begin: _initSize, end: _initSize).animate(_controller); + }); + _controller.forward(); + } + + void _update(DragUpdateDetails event) { + setState(() { + _move = _startdy - event.localPosition.dy; + _animation = Tween(begin: _initSize, end: _initSize + _move) + .animate(_controller); + _slideDirection = _move > 0 ? SlideDirection.up : SlideDirection.down; + }); + _controller.forward(); + } + + void _end() { + if (_slideDirection == SlideDirection.up) { + if (_move > 20) { + setState(() { + _animation = + Tween(begin: _animation.value, end: widget.maxHeight) + .animate(_controller); + _initSize = widget.maxHeight; + }); + _controller.forward(); + } else { + setState(() { + _animation = Tween(begin: _animation.value, end: _minHeight) + .animate(_controller); + _initSize = _minHeight; + }); + _controller.forward(); + } + } else if (_slideDirection == SlideDirection.down) { + if (_move > -50) { + setState(() { + _animation = Tween( + begin: _animation.value, + end: _animation.value > _minHeight + ? widget.maxHeight + : _minHeight) + .animate(_controller); + _initSize = + _animation.value > _minHeight ? widget.maxHeight : _minHeight; + }); + _controller.forward(); + } else { + setState(() { + _animation = Tween( + begin: _animation.value, + end: _animation.value > _minHeight - 50 ? _minHeight : 1) + .animate(_controller); + _initSize = _animation.value > _minHeight - 50 ? _minHeight : 100; + }); + _controller.forward(); + if (_animation.value < _minHeight - 50) { + context.read().clearSelect(); + } + } + } + } + + @override + Widget build(BuildContext context) { + final s = context.s; + return GestureDetector( + onVerticalDragStart: _start, + onVerticalDragUpdate: _update, + onVerticalDragEnd: (event) => _end(), + child: Container( + decoration: BoxDecoration( + color: context.primaryColor, + boxShadow: [ + BoxShadow( + offset: Offset(0, -0.5), + blurRadius: 1, + color: Theme.of(context).brightness == Brightness.light + ? Colors.grey[400].withOpacity(0.5) + : Colors.grey[800], + ), + ], + ), + height: _animation.value, + child: DefaultTabController( + length: 2, + child: Column( + children: [ + SizedBox( + height: math.min(_animation.value, 120), + child: SingleChildScrollView( + physics: const NeverScrollableScrollPhysics(), + child: SizedBox( + height: 120, + child: Row( + children: [ + Expanded( + child: Padding( + padding: const EdgeInsets.only(left: 20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: + const EdgeInsets.symmetric(vertical: 8), + child: Text(widget.onlinePodcast.title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: context.textTheme.headline5), + ), + Text( + widget.onlinePodcast.interval + .toInterval(context) != + '' + ? '${widget.onlinePodcast.interval.toInterval(context)} | ' + '${widget.onlinePodcast.latestPubDate.toDate(context)}' + : '${widget.onlinePodcast.latestPubDate.toDate(context)}', + maxLines: 1, + overflow: TextOverflow.fade, + style: TextStyle(color: context.accentColor), + ), + SubscribeButton(widget.onlinePodcast), + ], + ), + ), + ), + CachedNetworkImage( + height: 120.0, + width: 120.0, + fit: BoxFit.fitWidth, + alignment: Alignment.center, + imageUrl: widget.onlinePodcast.image, + progressIndicatorBuilder: + (context, url, downloadProgress) => Container( + height: 120, + width: 120, + alignment: Alignment.center, + color: context.primaryColorDark, + child: SizedBox( + width: 40, + height: 2, + child: LinearProgressIndicator( + value: downloadProgress.progress), + ), + ), + errorWidget: (context, url, error) => Container( + width: 120, + height: 120, + alignment: Alignment.center, + color: context.primaryColorDark, + child: Icon(Icons.error)), + ), + ], + ), + ), + ), + ), + if (_animation.value > 120) + SizedBox( + height: math.min(_animation.value - 120, 50), + child: SingleChildScrollView( + physics: const NeverScrollableScrollPhysics(), + child: SizedBox( + height: 50, + child: TabBar( + indicatorColor: context.accentColor, + labelColor: context.textColor, + indicatorWeight: 3, + indicatorSize: TabBarIndicatorSize.label, + tabs: [ + Text(s.homeToprightMenuAbout), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text(s.episode(2)), + SizedBox(width: 2), + if (widget.onlinePodcast.count > 0) + Container( + padding: const EdgeInsets.only( + left: 5, right: 5, top: 2, bottom: 2), + decoration: BoxDecoration( + color: context.accentColor, + borderRadius: + BorderRadius.circular(100)), + child: Text( + widget.onlinePodcast.count.toString(), + style: + TextStyle(color: Colors.white))) + ], + ) + ]), + ), + ), + ), + Expanded( + child: TabBarView(children: [ + ListView( + physics: _animation.value != widget.maxHeight + ? NeverScrollableScrollPhysics() + : null, + children: [ + Html( + onLinkTap: (url) { + url.launchUrl; + }, + linkStyle: TextStyle( + color: context.accentColor, + textBaseline: TextBaseline.ideographic), + shrinkToFit: true, + data: widget.onlinePodcast.description, + padding: const EdgeInsets.only( + left: 20.0, right: 20, bottom: 20), + defaultTextStyle: TextStyle( + height: 1.8, + ), + ), + ], + ), + FutureBuilder>( + future: _searchFuture, + builder: (context, snapshot) { + if (snapshot.hasData) { + var content = snapshot.data; + return ListView.builder( + physics: _animation.value != widget.maxHeight + ? NeverScrollableScrollPhysics() + : null, + itemCount: content.length + 1, + itemBuilder: (context, index) { + if (index == content.length) { + return Container( + padding: const EdgeInsets.only( + top: 10.0, bottom: 20.0), + alignment: Alignment.center, + child: SizedBox( + child: OutlineButton( + highlightedBorderColor: + context.accentColor, + splashColor: context.accentColor + .withOpacity(0.5), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.all( + Radius.circular(100))), + child: _loading + ? SizedBox( + height: 20, + width: 20, + child: + CircularProgressIndicator( + strokeWidth: 2, + )) + : Text(context.s.loadMore), + onPressed: () { + if (widget.searchEngine == + SearchEngine.listenNotes) { + _loading + ? null + : setState( + () { + _loading = true; + _searchFuture = + _getListenNotesEpisodes( + id: widget + .onlinePodcast + .id, + nextEpisodeDate: + _nextEpisdoeDate); + }, + ); + } + }), + ), + ); + } + return ListTile( + title: Text(content[index].title), + subtitle: Text( + content[index].length == 0 + ? '${content[index].pubDate.toDate(context)}' + : '${content[index].length.toTime} | ' + '${content[index].pubDate.toDate(context)}', + style: + TextStyle(color: context.accentColor)), + ); + }, + ); + } + return Center( + child: CircularProgressIndicator(), + ); + }) + ]), + ) + ], + ), + ), + ), + ); + } +} + +class SubscribeButton extends StatelessWidget { + SubscribeButton(this.onlinePodcast, {Key key}) : super(key: key); + final OnlinePodcast onlinePodcast; + + @override + Widget build(BuildContext context) { + final subscribeWorker = context.watch(); + final searchState = context.watch(); + final s = context.s; + void subscribePodcast(OnlinePodcast podcast) { + var item = SubscribeItem(podcast.rss, podcast.title, + imgUrl: podcast.image, group: 'Home'); + subscribeWorker.setSubscribeItem(item); + searchState.addPodcast(podcast); + } + + return Consumer(builder: (_, searchState, __) { + final subscribed = searchState.isSubscribed(onlinePodcast); + return !subscribed + ? ButtonTheme( + height: 32, + child: OutlineButton( + highlightedBorderColor: context.accentColor, + borderSide: BorderSide(color: context.accentColor), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(100.0), + side: BorderSide(color: context.accentColor)), + splashColor: context.accentColor.withOpacity(0.5), + child: Text(s.subscribe, + style: TextStyle(color: context.accentColor)), + onPressed: () { + Fluttertoast.showToast( + msg: s.podcastSubscribed, + gravity: ToastGravity.BOTTOM, + ); + subscribePodcast(onlinePodcast); + searchState.addPodcast(onlinePodcast); + }), + ) + : ButtonTheme( + height: 32, + child: OutlineButton( + color: context.accentColor.withOpacity(0.5), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(100.0), + side: BorderSide(color: Colors.grey[500])), + highlightedBorderColor: Colors.grey[500], + disabledTextColor: Colors.grey[500], + child: Text(s.subscribe), + disabledBorderColor: Colors.grey[500], + onPressed: () {}), + ); + }); + } +} + +class PodcastSlideup extends StatelessWidget { + const PodcastSlideup({this.child, this.searchEngine, Key key}) + : super(key: key); + final Widget child; + final SearchEngine searchEngine; + + @override + Widget build(BuildContext context) { + return Consumer(builder: (_, searchState, __) { + final selectedPodcast = searchState.selectedPodcast; + final subscribed = searchState.subscribedList; + return Stack( + alignment: Alignment.bottomCenter, + children: [ + child, + if (selectedPodcast != null) + Positioned.fill( + child: GestureDetector( + onTap: searchState.clearSelect, + child: Container( + color: context.scaffoldBackgroundColor.withOpacity(0.9), + ), + ), + ), + if (selectedPodcast != null) + LayoutBuilder( + builder: (context, constrants) => SearchResultDetail( + selectedPodcast, + maxHeight: constrants.maxHeight, + isSubscribed: subscribed.contains(selectedPodcast), + ), + ), + ], + ); + }); + } +} + +class PodcastAvatar extends StatelessWidget { + const PodcastAvatar(this.podcast, {Key key}) : super(key: key); + final OnlinePodcast podcast; + @override + Widget build(BuildContext context) { + return SizedBox( + height: 50, + child: ClipRRect( + borderRadius: BorderRadius.circular(25.0), + child: CachedNetworkImage( + height: 50.0, + width: 50.0, + fit: BoxFit.fitWidth, + alignment: Alignment.center, + imageUrl: podcast.image, + progressIndicatorBuilder: (context, url, downloadProgress) => + Container( + height: 50, + width: 50, + alignment: Alignment.center, + color: context.primaryColorDark, + child: SizedBox( + width: 20, + height: 2, + child: LinearProgressIndicator(value: downloadProgress.progress), + ), + ), + errorWidget: (context, url, error) => Container( + width: 50, + height: 50, + alignment: Alignment.center, + color: context.primaryColorDark, + child: Icon(Icons.error)), + ), + ), + ); + } +} diff --git a/lib/intro_slider/app_intro.dart b/lib/intro_slider/app_intro.dart index 57fa149..c4790db 100644 --- a/lib/intro_slider/app_intro.dart +++ b/lib/intro_slider/app_intro.dart @@ -1,241 +1,241 @@ -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:provider/provider.dart'; - -import '../home/home.dart'; -import '../state/setting_state.dart'; -import '../util/extension_helper.dart'; -import '../util/pageroute.dart'; -import 'firstpage.dart'; -import 'fourthpage.dart'; -import 'secondpage.dart'; -import 'thirdpage.dart'; - -enum Goto { home, settings } - -class SlideIntro extends StatefulWidget { - final Goto goto; - SlideIntro({this.goto, Key key}) : super(key: key); - - @override - _SlideIntroState createState() => _SlideIntroState(); -} - -class _SlideIntroState extends State { - final List _customShadow = [ - BoxShadow(blurRadius: 2, offset: Offset(-2, -2), color: Colors.white54), - BoxShadow( - blurRadius: 8, - offset: Offset(2, 2), - color: Colors.grey[600].withOpacity(0.4)) - ]; - PageController _controller; - double _position; - @override - void initState() { - super.initState(); - _position = 0; - _controller = PageController() - ..addListener(() { - setState(() { - _position = _controller.page; - }); - }); - } - - @override - void dispose() { - _controller.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - return AnnotatedRegion( - value: SystemUiOverlayStyle( - statusBarBrightness: Brightness.light, - systemNavigationBarIconBrightness: Brightness.dark), - child: Scaffold( - backgroundColor: Colors.grey[100], - body: Container( - child: Stack( - children: [ - PageView( - physics: const PageScrollPhysics(), - controller: _controller, - scrollDirection: Axis.horizontal, - children: [ - FirstPage(), - SecondPage(), - ThirdPage(), - FourthPage(), - ], - ), - Positioned( - bottom: 0, - left: 0, - child: Container( - color: Colors.grey[100].withOpacity(0.5), - width: MediaQuery.of(context).size.width, - // alignment: Alignment.center, - padding: - EdgeInsets.only(left: 40, right: 20, bottom: 30, top: 20), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Expanded( - child: Container( - alignment: Alignment.centerLeft, - child: Row( - crossAxisAlignment: CrossAxisAlignment.center, - mainAxisAlignment: MainAxisAlignment.start, - children: [ - Container( - alignment: Alignment.center, - child: _position < 0.2 - ? Text( - '1', - style: TextStyle( - color: Color.fromRGBO( - 35, 204, 198, 1)), - ) - : Center(), - margin: EdgeInsets.symmetric(horizontal: 10), - height: _position > 1 - ? 10 - : (1 - _position) * 10 + 10, - width: _position > 1 - ? 10 - : (1 - _position) * 10 + 10, - decoration: BoxDecoration( - shape: BoxShape.circle, - color: Colors.white, - boxShadow: _customShadow), - ), - Container( - child: _position < 1.2 && _position > 0.8 - ? Text('2', - style: TextStyle( - color: Color.fromRGBO( - 77, 145, 190, 1))) - : Center(), - alignment: Alignment.center, - margin: EdgeInsets.symmetric(horizontal: 10), - height: _position > 2 - ? 10 - : 20 - (_position - 1).abs() * 10, - width: _position > 2 - ? 10 - : 20 - (_position - 1).abs() * 10, - decoration: BoxDecoration( - shape: BoxShape.circle, - color: Colors.white, - boxShadow: _customShadow), - ), - Container( - child: _position < 2.2 && _position > 1.8 - ? Text('3', - style: TextStyle( - color: Color.fromRGBO( - 35, 204, 198, 1))) - : Center(), - alignment: Alignment.center, - margin: EdgeInsets.symmetric(horizontal: 10), - height: _position < 1 - ? 10 - : 20 - (_position - 2).abs() * 10, - width: _position < 1 - ? 10 - : 20 - (_position - 2).abs() * 10, - decoration: BoxDecoration( - shape: BoxShape.circle, - color: Colors.white, - boxShadow: _customShadow), - ), - Container( - child: _position > 2.8 - ? Text( - '4', - style: TextStyle( - color: Color.fromRGBO( - 77, 145, 190, 1)), - ) - : Center(), - alignment: Alignment.center, - margin: EdgeInsets.symmetric(horizontal: 10), - height: _position < 2 - ? 10 - : 20 - (3 - _position) * 10, - width: _position < 2 - ? 10 - : 20 - (3 - _position) * 10, - decoration: BoxDecoration( - shape: BoxShape.circle, - color: Colors.white, - boxShadow: _customShadow), - ), - ], - ), - ), - ), - Container( - alignment: Alignment.center, - height: 40, - width: 80, - decoration: BoxDecoration( - border: Border.all(width: 1, color: Colors.white), - borderRadius: BorderRadius.all(Radius.circular(20)), - color: Colors.white, - boxShadow: _customShadow, - ), - child: Material( - color: Colors.transparent, - child: _position < 2.5 - ? InkWell( - borderRadius: - BorderRadius.all(Radius.circular(20)), - onTap: () => _controller.animateToPage( - _position.toInt() + 1, - duration: Duration(milliseconds: 200), - curve: Curves.linear), - child: SizedBox( - height: 40, - width: 80, - child: Center( - child: Text(context.s.next, - style: TextStyle( - color: Colors.black))))) - : InkWell( - borderRadius: - BorderRadius.all(Radius.circular(20)), - onTap: () { - if (widget.goto == Goto.home) { - Navigator.push(context, - SlideLeftRoute(page: Home())); - Provider.of(context, - listen: false) - .saveShowIntro(1); - } else if (widget.goto == Goto.settings) { - Navigator.pop(context); - } - }, - child: SizedBox( - height: 40, - width: 80, - child: Center( - child: Text(context.s.done, - style: TextStyle( - color: Colors.black))))), - ), - ), - ], - ), - ), - ), - ], - ), - ), - ), - ); - } -} +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; + +import '../home/home.dart'; +import '../state/setting_state.dart'; +import '../util/extension_helper.dart'; +import '../util/pageroute.dart'; +import 'firstpage.dart'; +import 'fourthpage.dart'; +import 'secondpage.dart'; +import 'thirdpage.dart'; + +enum Goto { home, settings } + +class SlideIntro extends StatefulWidget { + final Goto goto; + SlideIntro({this.goto, Key key}) : super(key: key); + + @override + _SlideIntroState createState() => _SlideIntroState(); +} + +class _SlideIntroState extends State { + final List _customShadow = [ + BoxShadow(blurRadius: 2, offset: Offset(-2, -2), color: Colors.white54), + BoxShadow( + blurRadius: 8, + offset: Offset(2, 2), + color: Colors.grey[600].withOpacity(0.4)) + ]; + PageController _controller; + double _position; + @override + void initState() { + super.initState(); + _position = 0; + _controller = PageController() + ..addListener(() { + setState(() { + _position = _controller.page; + }); + }); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return AnnotatedRegion( + value: SystemUiOverlayStyle( + statusBarBrightness: Brightness.light, + systemNavigationBarIconBrightness: Brightness.dark), + child: Scaffold( + backgroundColor: Colors.grey[100], + body: Container( + child: Stack( + children: [ + PageView( + physics: const PageScrollPhysics(), + controller: _controller, + scrollDirection: Axis.horizontal, + children: [ + FirstPage(), + SecondPage(), + ThirdPage(), + FourthPage(), + ], + ), + Positioned( + bottom: 0, + left: 0, + child: Container( + color: Colors.grey[100].withOpacity(0.5), + width: MediaQuery.of(context).size.width, + // alignment: Alignment.center, + padding: + EdgeInsets.only(left: 40, right: 20, bottom: 30, top: 20), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Expanded( + child: Container( + alignment: Alignment.centerLeft, + child: Row( + crossAxisAlignment: CrossAxisAlignment.center, + mainAxisAlignment: MainAxisAlignment.start, + children: [ + Container( + alignment: Alignment.center, + child: _position < 0.2 + ? Text( + '1', + style: TextStyle( + color: Color.fromRGBO( + 35, 204, 198, 1)), + ) + : Center(), + margin: EdgeInsets.symmetric(horizontal: 10), + height: _position > 1 + ? 10 + : (1 - _position) * 10 + 10, + width: _position > 1 + ? 10 + : (1 - _position) * 10 + 10, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: Colors.white, + boxShadow: _customShadow), + ), + Container( + child: _position < 1.2 && _position > 0.8 + ? Text('2', + style: TextStyle( + color: Color.fromRGBO( + 77, 145, 190, 1))) + : Center(), + alignment: Alignment.center, + margin: EdgeInsets.symmetric(horizontal: 10), + height: _position > 2 + ? 10 + : 20 - (_position - 1).abs() * 10, + width: _position > 2 + ? 10 + : 20 - (_position - 1).abs() * 10, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: Colors.white, + boxShadow: _customShadow), + ), + Container( + child: _position < 2.2 && _position > 1.8 + ? Text('3', + style: TextStyle( + color: Color.fromRGBO( + 35, 204, 198, 1))) + : Center(), + alignment: Alignment.center, + margin: EdgeInsets.symmetric(horizontal: 10), + height: _position < 1 + ? 10 + : 20 - (_position - 2).abs() * 10, + width: _position < 1 + ? 10 + : 20 - (_position - 2).abs() * 10, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: Colors.white, + boxShadow: _customShadow), + ), + Container( + child: _position > 2.8 + ? Text( + '4', + style: TextStyle( + color: Color.fromRGBO( + 77, 145, 190, 1)), + ) + : Center(), + alignment: Alignment.center, + margin: EdgeInsets.symmetric(horizontal: 10), + height: _position < 2 + ? 10 + : 20 - (3 - _position) * 10, + width: _position < 2 + ? 10 + : 20 - (3 - _position) * 10, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: Colors.white, + boxShadow: _customShadow), + ), + ], + ), + ), + ), + Container( + alignment: Alignment.center, + height: 40, + width: 80, + decoration: BoxDecoration( + border: Border.all(width: 1, color: Colors.white), + borderRadius: BorderRadius.all(Radius.circular(20)), + color: Colors.white, + boxShadow: _customShadow, + ), + child: Material( + color: Colors.transparent, + child: _position < 2.5 + ? InkWell( + borderRadius: + BorderRadius.all(Radius.circular(20)), + onTap: () => _controller.animateToPage( + _position.toInt() + 1, + duration: Duration(milliseconds: 200), + curve: Curves.linear), + child: SizedBox( + height: 40, + width: 80, + child: Center( + child: Text(context.s.next, + style: TextStyle( + color: Colors.black))))) + : InkWell( + borderRadius: + BorderRadius.all(Radius.circular(20)), + onTap: () { + if (widget.goto == Goto.home) { + Navigator.push(context, + SlideLeftRoute(page: Home())); + Provider.of(context, + listen: false) + .saveShowIntro(1); + } else if (widget.goto == Goto.settings) { + Navigator.pop(context); + } + }, + child: SizedBox( + height: 40, + width: 80, + child: Center( + child: Text(context.s.done, + style: TextStyle( + color: Colors.black))))), + ), + ), + ], + ), + ), + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/intro_slider/firstpage.dart b/lib/intro_slider/firstpage.dart index e2da493..5f7f1ca 100644 --- a/lib/intro_slider/firstpage.dart +++ b/lib/intro_slider/firstpage.dart @@ -1,42 +1,42 @@ -import 'package:flutter/material.dart'; -import 'package:flare_flutter/flare_actor.dart'; -import '../util/extension_helper.dart'; - -class FirstPage extends StatefulWidget { - FirstPage({Key key}) : super(key: key); - - @override - _FirstPageState createState() => _FirstPageState(); -} - -class _FirstPageState extends State { - @override - Widget build(BuildContext context) { - return Scaffold( - body: Container( - color: Color.fromRGBO(35, 204, 198, 1), - child: Center( - child: Column( - crossAxisAlignment: CrossAxisAlignment.center, - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Padding( - padding: EdgeInsets.symmetric(vertical: 100), - ), - Container( - height: context.width * 3 / 4, - // color: Colors.red, - child: FlareActor( - 'assets/splash.flr', - alignment: Alignment.center, - animation: 'logo', - fit: BoxFit.cover, - )), - Spacer(), - ], - ), - ), - ), - ); - } -} +import 'package:flutter/material.dart'; +import 'package:flare_flutter/flare_actor.dart'; +import '../util/extension_helper.dart'; + +class FirstPage extends StatefulWidget { + FirstPage({Key key}) : super(key: key); + + @override + _FirstPageState createState() => _FirstPageState(); +} + +class _FirstPageState extends State { + @override + Widget build(BuildContext context) { + return Scaffold( + body: Container( + color: Color.fromRGBO(35, 204, 198, 1), + child: Center( + child: Column( + crossAxisAlignment: CrossAxisAlignment.center, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Padding( + padding: EdgeInsets.symmetric(vertical: 100), + ), + Container( + height: context.width * 3 / 4, + // color: Colors.red, + child: FlareActor( + 'assets/splash.flr', + alignment: Alignment.center, + animation: 'logo', + fit: BoxFit.cover, + )), + Spacer(), + ], + ), + ), + ), + ); + } +} diff --git a/lib/intro_slider/fourthpage.dart b/lib/intro_slider/fourthpage.dart index c822c47..c5fe77c 100644 --- a/lib/intro_slider/fourthpage.dart +++ b/lib/intro_slider/fourthpage.dart @@ -1,46 +1,46 @@ -import 'package:flutter/material.dart'; -import 'package:flare_flutter/flare_actor.dart'; -import '../util/extension_helper.dart'; - -class FourthPage extends StatefulWidget { - FourthPage({Key key}) : super(key: key); - - @override - _FourthPageState createState() => _FourthPageState(); -} - -class _FourthPageState extends State { - @override - Widget build(BuildContext context) { - return Container( - color: Color.fromRGBO(77, 145, 190, 1), - child: Center( - child: Column( - crossAxisAlignment: CrossAxisAlignment.center, - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Container( - height: 200, - alignment: Alignment.center, - padding: EdgeInsets.all(40), - child: Text( - context.s.introFourthPage, - style: TextStyle(fontSize: 30, color: Colors.white), - ), - ), - Container( - height: context.width * 3 / 4, - // color: Colors.red, - child: FlareActor( - 'assets/longtap.flr', - alignment: Alignment.center, - animation: 'longtap', - fit: BoxFit.cover, - )), - Spacer(), - ], - ), - ), - ); - } -} +import 'package:flutter/material.dart'; +import 'package:flare_flutter/flare_actor.dart'; +import '../util/extension_helper.dart'; + +class FourthPage extends StatefulWidget { + FourthPage({Key key}) : super(key: key); + + @override + _FourthPageState createState() => _FourthPageState(); +} + +class _FourthPageState extends State { + @override + Widget build(BuildContext context) { + return Container( + color: Color.fromRGBO(77, 145, 190, 1), + child: Center( + child: Column( + crossAxisAlignment: CrossAxisAlignment.center, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Container( + height: 200, + alignment: Alignment.center, + padding: EdgeInsets.all(40), + child: Text( + context.s.introFourthPage, + style: TextStyle(fontSize: 30, color: Colors.white), + ), + ), + Container( + height: context.width * 3 / 4, + // color: Colors.red, + child: FlareActor( + 'assets/longtap.flr', + alignment: Alignment.center, + animation: 'longtap', + fit: BoxFit.cover, + )), + Spacer(), + ], + ), + ), + ); + } +} diff --git a/lib/intro_slider/secondpage.dart b/lib/intro_slider/secondpage.dart index 52c7b86..026aa01 100644 --- a/lib/intro_slider/secondpage.dart +++ b/lib/intro_slider/secondpage.dart @@ -1,48 +1,48 @@ -import 'package:flutter/material.dart'; -import 'package:flare_flutter/flare_actor.dart'; -import '../util/extension_helper.dart'; - -class SecondPage extends StatefulWidget { - SecondPage({Key key}) : super(key: key); - - @override - _SecondPageState createState() => _SecondPageState(); -} - -class _SecondPageState extends State { - @override - Widget build(BuildContext context) { - return Container( - color: Color.fromRGBO(77, 145, 190, 1), - child: Center( - child: Column( - crossAxisAlignment: CrossAxisAlignment.center, - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Container( - height: 200, - alignment: Alignment.center, - padding: - EdgeInsets.only(top: 20, bottom: 20, left: 40, right: 40), - child: Text( - context.s.introSecondPage, - style: TextStyle(fontSize: 30, color: Colors.white), - ), - ), - Container( - height: context.width * 3 / 4, - // color: Colors.red, - child: FlareActor( - 'assets/add.flr', - isPaused: false, - alignment: Alignment.center, - animation: 'add', - fit: BoxFit.cover, - )), - Spacer(), - ], - ), - ), - ); - } -} +import 'package:flutter/material.dart'; +import 'package:flare_flutter/flare_actor.dart'; +import '../util/extension_helper.dart'; + +class SecondPage extends StatefulWidget { + SecondPage({Key key}) : super(key: key); + + @override + _SecondPageState createState() => _SecondPageState(); +} + +class _SecondPageState extends State { + @override + Widget build(BuildContext context) { + return Container( + color: Color.fromRGBO(77, 145, 190, 1), + child: Center( + child: Column( + crossAxisAlignment: CrossAxisAlignment.center, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Container( + height: 200, + alignment: Alignment.center, + padding: + EdgeInsets.only(top: 20, bottom: 20, left: 40, right: 40), + child: Text( + context.s.introSecondPage, + style: TextStyle(fontSize: 30, color: Colors.white), + ), + ), + Container( + height: context.width * 3 / 4, + // color: Colors.red, + child: FlareActor( + 'assets/add.flr', + isPaused: false, + alignment: Alignment.center, + animation: 'add', + fit: BoxFit.cover, + )), + Spacer(), + ], + ), + ), + ); + } +} diff --git a/lib/intro_slider/thirdpage.dart b/lib/intro_slider/thirdpage.dart index fe31f25..1d247e2 100644 --- a/lib/intro_slider/thirdpage.dart +++ b/lib/intro_slider/thirdpage.dart @@ -1,46 +1,46 @@ -import 'package:flutter/material.dart'; -import 'package:flare_flutter/flare_actor.dart'; -import '../util/extension_helper.dart'; - -class ThirdPage extends StatefulWidget { - ThirdPage({Key key}) : super(key: key); - - @override - _ThirdPageState createState() => _ThirdPageState(); -} - -class _ThirdPageState extends State { - @override - Widget build(BuildContext context) { - return Container( - color: Color.fromRGBO(35, 204, 198, 1), - child: Center( - child: Column( - crossAxisAlignment: CrossAxisAlignment.center, - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Container( - height: 200, - alignment: Alignment.center, - padding: EdgeInsets.all(40), - child: Text( - context.s.introThirdPage, - style: TextStyle(fontSize: 30, color: Colors.white), - ), - ), - Container( - height: context.width * 3 / 4, - // color: Colors.red, - child: FlareActor( - 'assets/swipe.flr', - alignment: Alignment.center, - animation: 'swipe', - fit: BoxFit.cover, - )), - Spacer(), - ], - ), - ), - ); - } -} +import 'package:flutter/material.dart'; +import 'package:flare_flutter/flare_actor.dart'; +import '../util/extension_helper.dart'; + +class ThirdPage extends StatefulWidget { + ThirdPage({Key key}) : super(key: key); + + @override + _ThirdPageState createState() => _ThirdPageState(); +} + +class _ThirdPageState extends State { + @override + Widget build(BuildContext context) { + return Container( + color: Color.fromRGBO(35, 204, 198, 1), + child: Center( + child: Column( + crossAxisAlignment: CrossAxisAlignment.center, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Container( + height: 200, + alignment: Alignment.center, + padding: EdgeInsets.all(40), + child: Text( + context.s.introThirdPage, + style: TextStyle(fontSize: 30, color: Colors.white), + ), + ), + Container( + height: context.width * 3 / 4, + // color: Colors.red, + child: FlareActor( + 'assets/swipe.flr', + alignment: Alignment.center, + animation: 'swipe', + fit: BoxFit.cover, + )), + Spacer(), + ], + ), + ), + ); + } +} diff --git a/lib/local_storage/key_value_storage.dart b/lib/local_storage/key_value_storage.dart index 73d9221..cdf6984 100644 --- a/lib/local_storage/key_value_storage.dart +++ b/lib/local_storage/key_value_storage.dart @@ -1,202 +1,201 @@ -import 'dart:async'; -import 'dart:convert'; - -import 'package:flutter/foundation.dart'; -import 'package:shared_preferences/shared_preferences.dart'; - -import '../state/podcast_group.dart'; - -const String groupsKey = 'groups'; -const String playlistKey = 'playlist'; -const String autoPlayKey = 'autoPlay'; -const String audioPositionKey = 'audioposition'; -const String lastWorkKey = 'lastWork'; -const String refreshdateKey = 'refreshdate'; -const String themesKey = 'themes'; -const String accentsKey = 'accents'; -const String autoUpdateKey = 'autoAdd'; -const String updateIntervalKey = 'updateInterval'; -const String downloadUsingDataKey = 'downloadUsingData'; -const String introKey = 'intro'; -const String realDarkKey = 'realDark'; -const String cacheMaxKey = 'cacheMax'; -const String podcastLayoutKey = 'podcastLayoutKey'; -const String recentLayoutKey = 'recentLayoutKey'; -const String favLayoutKey = 'favLayoutKey'; -const String downloadLayoutKey = 'downloadLayoutKey'; -const String autoDownloadNetworkKey = 'autoDownloadNetwork'; -const String episodePopupMenuKey = 'episodePopupMenuKey'; -const String autoDeleteKey = 'autoDeleteKey'; -const String autoSleepTimerKey = 'autoSleepTimerKey'; -const String autoSleepTimerStartKey = 'autoSleepTimerStartKey'; -const String autoSleepTimerEndKey = 'autoSleepTimerEndKey'; -const String defaultSleepTimerKey = 'defaultSleepTimerKey'; -const String autoSleepTimerModeKey = 'autoSleepTimerModeKey'; -const String tapToOpenPopupMenuKey = 'tapToOpenPopupMenuKey'; -const String fastForwardSecondsKey = 'fastForwardSecondsKey'; -const String rewindSecondsKey = 'rewindSecondsKey'; -const String playerHeightKey = 'playerHeightKey'; -const String speedKey = 'speedKey'; -const String skipSilenceKey = 'skipSilenceKey'; -const String localeKey = 'localeKey'; -const String boostVolumeKey = 'boostVolumeKey'; -const String volumeGainKey = 'volumeGainKey'; -const String hideListenedKey = 'hideListenedKey'; -const String notificationLayoutKey = 'notificationLayoutKey'; -const String showNotesFontKey = 'showNotesFontKey'; -const String speedListKey = 'speedListKey'; -const String searchHistoryKey = 'searchHistoryKey'; -const String gpodderApiKey = 'gpodderApiKey'; -const String gpodderAddKey = 'gpodderAddKey'; -const String gpodderRemoveKey = 'gpodderRemoveKey'; -const String gpodderSyncStatusKey = 'gpodderSyncStatusKey'; -const String gpodderSyncDateTimeKey = 'gpodderSyncDateTimeKey'; -const String gpodderRemoteAddKey = 'gpodderRemoteAddKey'; -const String gpodderRemoteRemoveKey = 'gpodderRemoteRemoveKey'; -const String hidePodcastDiscoveryKey = 'hidePodcastDiscoveryKey'; -const String searchEngineKey = 'searchEngineKey'; -const String markListenedAfterSkipKey = 'markListenedAfterSkipKey'; -const String downloadPositionKey = 'downloadPositionKey'; -const String deleteAfterPlayedKey = 'removeAfterPlayedKey'; - -class KeyValueStorage { - final String key; - KeyValueStorage(this.key); - Future> getGroups() async { - var prefs = await SharedPreferences.getInstance(); - if (prefs.getString(key) == null) { - var home = PodcastGroup('Home'); - await prefs.setString( - key, - json.encode({ - 'groups': [home.toEntity().toJson()] - })); - } - return json - .decode(prefs.getString(key))['groups'] - .cast>() - .map(GroupEntity.fromJson) - .toList(growable: false); - } - - Future saveGroup(List groupList) async { - var prefs = await SharedPreferences.getInstance(); - return prefs.setString( - key, - json.encode( - {'groups': groupList.map((group) => group.toJson()).toList()})); - } - - Future saveInt(int setting) async { - var prefs = await SharedPreferences.getInstance(); - return prefs.setInt(key, setting); - } - - Future getInt({int defaultValue = 0}) async { - var prefs = await SharedPreferences.getInstance(); - if (prefs.getInt(key) == null) await prefs.setInt(key, defaultValue); - return prefs.getInt(key); - } - - Future saveStringList(List playList) async { - var prefs = await SharedPreferences.getInstance(); - return prefs.setStringList(key, playList); - } - - Future> getStringList() async { - var prefs = await SharedPreferences.getInstance(); - if (prefs.getStringList(key) == null) { - await prefs.setStringList(key, []); - } - return prefs.getStringList(key); - } - - Future saveString(String string) async { - var prefs = await SharedPreferences.getInstance(); - return prefs.setString(key, string); - } - - Future getString() async { - var prefs = await SharedPreferences.getInstance(); - if (prefs.getString(key) == null) { - await prefs.setString(key, ''); - } - return prefs.getString(key); - } - - Future saveMenu(List list) async { - var prefs = await SharedPreferences.getInstance(); - return await prefs.setStringList( - key, list.map((e) => e.toString()).toList()); - } - - Future> getMenu() async { - var prefs = await SharedPreferences.getInstance(); - if (prefs.getStringList(key) == null || prefs.getStringList(key).isEmpty) { - await prefs.setStringList(key, ['0', '1', '2', '13', '14']); - } - var list = prefs.getStringList(key); - return list.map(int.parse).toList(); - } - - /// For player speed settings. - Future saveSpeedList(List list) async { - var prefs = await SharedPreferences.getInstance(); - list.sort(); - return await prefs.setStringList( - key, list.map((e) => e.toStringAsFixed(1)).toList()); - } - - Future> getSpeedList() async { - var prefs = await SharedPreferences.getInstance(); - if (prefs.getStringList(key) == null || prefs.getStringList(key).isEmpty) { - await prefs.setStringList( - key, ['0.5', '0.6', '0.8', '1.0', '1.1', '1.2', '1.5', '2.0']); - } - var list = prefs.getStringList(key); - return list.map(double.parse).toList(); - } - - /// Rreverse is used for compatite bool value save before which set true = 0, false = 1 - Future getBool( - {@required bool defaultValue, bool reverse = false}) async { - var prefs = await SharedPreferences.getInstance(); - if (prefs.getInt(key) == null) { - reverse - ? await prefs.setInt(key, defaultValue ? 0 : 1) - : await prefs.setInt(key, defaultValue ? 1 : 0); - } - var i = prefs.getInt(key); - return reverse ? i == 0 : i == 1; - } - - /// Rreverse is used for compatite bool value save before which set true = 0, false = 1 - Future saveBool(boo, {reverse = false}) async { - var prefs = await SharedPreferences.getInstance(); - return reverse - ? prefs.setInt(key, boo ? 0 : 1) - : prefs.setInt(key, boo ? 1 : 0); - } - - Future saveDouble(double data) async { - var prefs = await SharedPreferences.getInstance(); - return prefs.setDouble(key, data); - } - - Future getDoubel({double defaultValue = 0.0}) async { - var prefs = await SharedPreferences.getInstance(); - if (prefs.getDouble(key) == null) { - await prefs.setDouble(key, defaultValue); - } - return prefs.getDouble(key); - } - - Future addList(List addList) async { - final list = await getStringList(); - await saveStringList(list..addAll(addList)); - } - - Future clearList() async { - await saveStringList([]); - } -} +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../state/podcast_group.dart'; + +const String groupsKey = 'groups'; +const String playlistKey = 'playlist'; +const String autoPlayKey = 'autoPlay'; +const String audioPositionKey = 'audioposition'; +const String lastWorkKey = 'lastWork'; +const String refreshdateKey = 'refreshdate'; +const String themesKey = 'themes'; +const String accentsKey = 'accents'; +const String autoUpdateKey = 'autoAdd'; +const String updateIntervalKey = 'updateInterval'; +const String downloadUsingDataKey = 'downloadUsingData'; +const String introKey = 'intro'; +const String realDarkKey = 'realDark'; +const String cacheMaxKey = 'cacheMax'; +const String podcastLayoutKey = 'podcastLayoutKey'; +const String recentLayoutKey = 'recentLayoutKey'; +const String favLayoutKey = 'favLayoutKey'; +const String downloadLayoutKey = 'downloadLayoutKey'; +const String autoDownloadNetworkKey = 'autoDownloadNetwork'; +const String episodePopupMenuKey = 'episodePopupMenuKey'; +const String autoDeleteKey = 'autoDeleteKey'; +const String autoSleepTimerKey = 'autoSleepTimerKey'; +const String autoSleepTimerStartKey = 'autoSleepTimerStartKey'; +const String autoSleepTimerEndKey = 'autoSleepTimerEndKey'; +const String defaultSleepTimerKey = 'defaultSleepTimerKey'; +const String autoSleepTimerModeKey = 'autoSleepTimerModeKey'; +const String tapToOpenPopupMenuKey = 'tapToOpenPopupMenuKey'; +const String fastForwardSecondsKey = 'fastForwardSecondsKey'; +const String rewindSecondsKey = 'rewindSecondsKey'; +const String playerHeightKey = 'playerHeightKey'; +const String speedKey = 'speedKey'; +const String skipSilenceKey = 'skipSilenceKey'; +const String localeKey = 'localeKey'; +const String boostVolumeKey = 'boostVolumeKey'; +const String volumeGainKey = 'volumeGainKey'; +const String hideListenedKey = 'hideListenedKey'; +const String notificationLayoutKey = 'notificationLayoutKey'; +const String showNotesFontKey = 'showNotesFontKey'; +const String speedListKey = 'speedListKey'; +const String searchHistoryKey = 'searchHistoryKey'; +const String gpodderApiKey = 'gpodderApiKey'; +const String gpodderAddKey = 'gpodderAddKey'; +const String gpodderRemoveKey = 'gpodderRemoveKey'; +const String gpodderSyncStatusKey = 'gpodderSyncStatusKey'; +const String gpodderSyncDateTimeKey = 'gpodderSyncDateTimeKey'; +const String gpodderRemoteAddKey = 'gpodderRemoteAddKey'; +const String gpodderRemoteRemoveKey = 'gpodderRemoteRemoveKey'; +const String hidePodcastDiscoveryKey = 'hidePodcastDiscoveryKey'; +const String searchEngineKey = 'searchEngineKey'; +const String markListenedAfterSkipKey = 'markListenedAfterSkipKey'; +const String downloadPositionKey = 'downloadPositionKey'; +const String deleteAfterPlayedKey = 'removeAfterPlayedKey'; + +class KeyValueStorage { + final String key; + KeyValueStorage(this.key); + Future> getGroups() async { + var prefs = await SharedPreferences.getInstance(); + if (prefs.getString(key) == null) { + var home = PodcastGroup('Home'); + await prefs.setString( + key, + json.encode({ + 'groups': [home.toEntity().toJson()] + })); + } + return json + .decode(prefs.getString(key))['groups'] + .cast>() + .map(GroupEntity.fromJson) + .toList(growable: false); + } + + Future saveGroup(List groupList) async { + var prefs = await SharedPreferences.getInstance(); + return prefs.setString( + key, + json.encode( + {'groups': groupList.map((group) => group.toJson()).toList()})); + } + + Future saveInt(int setting) async { + var prefs = await SharedPreferences.getInstance(); + return prefs.setInt(key, setting); + } + + Future getInt({int defaultValue = 0}) async { + var prefs = await SharedPreferences.getInstance(); + if (prefs.getInt(key) == null) await prefs.setInt(key, defaultValue); + return prefs.getInt(key); + } + + Future saveStringList(List playList) async { + var prefs = await SharedPreferences.getInstance(); + return prefs.setStringList(key, playList); + } + + Future> getStringList() async { + var prefs = await SharedPreferences.getInstance(); + if (prefs.getStringList(key) == null) { + await prefs.setStringList(key, []); + } + return prefs.getStringList(key); + } + + Future saveString(String string) async { + var prefs = await SharedPreferences.getInstance(); + return prefs.setString(key, string); + } + + Future getString() async { + var prefs = await SharedPreferences.getInstance(); + if (prefs.getString(key) == null) { + await prefs.setString(key, ''); + } + return prefs.getString(key); + } + + Future saveMenu(List list) async { + var prefs = await SharedPreferences.getInstance(); + return await prefs.setStringList( + key, list.map((e) => e.toString()).toList()); + } + + Future> getMenu() async { + var prefs = await SharedPreferences.getInstance(); + if (prefs.getStringList(key) == null || prefs.getStringList(key).isEmpty) { + await prefs.setStringList(key, ['0', '1', '2', '13', '14']); + } + var list = prefs.getStringList(key); + return list.map(int.parse).toList(); + } + + /// For player speed settings. + Future saveSpeedList(List list) async { + var prefs = await SharedPreferences.getInstance(); + list.sort(); + return await prefs.setStringList( + key, list.map((e) => e.toStringAsFixed(1)).toList()); + } + + Future> getSpeedList() async { + var prefs = await SharedPreferences.getInstance(); + if (prefs.getStringList(key) == null || prefs.getStringList(key).isEmpty) { + await prefs.setStringList( + key, ['0.5', '0.6', '0.8', '1.0', '1.1', '1.2', '1.5', '2.0']); + } + var list = prefs.getStringList(key); + return list.map(double.parse).toList(); + } + + /// Rreverse is used for compatite bool value save before which set true = 0, false = 1 + Future getBool( + {@required bool defaultValue, bool reverse = false}) async { + var prefs = await SharedPreferences.getInstance(); + if (prefs.getInt(key) == null) { + reverse + ? await prefs.setInt(key, defaultValue ? 0 : 1) + : await prefs.setInt(key, defaultValue ? 1 : 0); + } + var i = prefs.getInt(key); + return reverse ? i == 0 : i == 1; + } + + /// Rreverse is used for compatite bool value save before which set true = 0, false = 1 + Future saveBool(boo, {reverse = false}) async { + var prefs = await SharedPreferences.getInstance(); + return reverse + ? prefs.setInt(key, boo ? 0 : 1) + : prefs.setInt(key, boo ? 1 : 0); + } + + Future saveDouble(double data) async { + var prefs = await SharedPreferences.getInstance(); + return prefs.setDouble(key, data); + } + + Future getDoubel({double defaultValue = 0.0}) async { + var prefs = await SharedPreferences.getInstance(); + if (prefs.getDouble(key) == null) { + await prefs.setDouble(key, defaultValue); + } + return prefs.getDouble(key); + } + + Future addList(List addList) async { + final list = await getStringList(); + await saveStringList(list..addAll(addList)); + } + + Future clearList() async { + await saveStringList([]); + } +} diff --git a/lib/local_storage/sqflite_localpodcast.dart b/lib/local_storage/sqflite_localpodcast.dart index be128c7..6fdfb59 100644 --- a/lib/local_storage/sqflite_localpodcast.dart +++ b/lib/local_storage/sqflite_localpodcast.dart @@ -1,1580 +1,1580 @@ -import 'dart:async'; -import 'dart:developer' as developer; - -import 'package:dio/dio.dart'; -import 'package:flutter_downloader/flutter_downloader.dart'; -import 'package:intl/intl.dart'; -import 'package:path/path.dart'; -import 'package:sqflite/sqflite.dart'; -import 'package:webfeed/webfeed.dart'; - -import '../type/episodebrief.dart'; -import '../type/play_histroy.dart'; -import '../type/podcastlocal.dart'; -import '../type/sub_history.dart'; - -enum Filter { downloaded, liked, search, all } - -class DBHelper { - static Database _db; - Future get database async { - if (_db != null) return _db; - _db = await initDb(); - return _db; - } - - initDb() async { - var documentsDirectory = await getDatabasesPath(); - var path = join(documentsDirectory, "podcasts.db"); - var theDb = await openDatabase(path, - version: 4, onCreate: _onCreate, onUpgrade: _onUpgrade); - return theDb; - } - - void _onCreate(Database db, int version) async { - await db - .execute("""CREATE TABLE PodcastLocal(id TEXT PRIMARY KEY,title TEXT, - imageUrl TEXT,rssUrl TEXT UNIQUE, primaryColor TEXT, author TEXT, - description TEXT, add_date INTEGER, imagePath TEXT, provider TEXT, link TEXT, - background_image TEXT DEFAULT '', hosts TEXT DEFAULT '',update_count INTEGER DEFAULT 0, - episode_count INTEGER DEFAULT 0, skip_seconds INTEGER DEFAULT 0, - auto_download INTEGER DEFAULT 0, skip_seconds_end INTEGER DEFAULT 0, - never_update INTEGER DEFAULT 0)"""); - await db - .execute("""CREATE TABLE Episodes(id INTEGER PRIMARY KEY,title TEXT, - enclosure_url TEXT UNIQUE, enclosure_length INTEGER, pubDate TEXT, - description TEXT, feed_id TEXT, feed_link TEXT, milliseconds INTEGER, - duration INTEGER DEFAULT 0, explicit INTEGER DEFAULT 0, liked INTEGER DEFAULT 0, - liked_date INTEGER DEFAULT 0, downloaded TEXT DEFAULT 'ND', - download_date INTEGER DEFAULT 0, media_id TEXT, is_new INTEGER DEFAULT 0)"""); - await db.execute( - """CREATE TABLE PlayHistory(id INTEGER PRIMARY KEY, title TEXT, enclosure_url TEXT, - seconds REAL, seek_value REAL, add_date INTEGER, listen_time INTEGER DEFAULT 0)"""); - await db.execute( - """CREATE TABLE SubscribeHistory(id TEXT PRIMARY KEY, title TEXT, rss_url TEXT UNIQUE, - add_date INTEGER, remove_date INTEGER DEFAULT 0, status INTEGER DEFAULT 0)"""); - } - - void _onUpgrade(Database db, int oldVersion, int newVersion) async { - if (oldVersion == 1) { - await db.execute( - "ALTER TABLE PodcastLocal ADD skip_seconds INTEGER DEFAULT 0 "); - await db.execute( - "ALTER TABLE PodcastLocal ADD auto_download INTEGER DEFAULT 0"); - await db.execute( - "ALTER TABLE PodcastLocal ADD skip_seconds_end INTEGER DEFAULT 0 "); - await db.execute( - "ALTER TABLE PodcastLocal ADD never_update INTEGER DEFAULT 0 "); - } else if (oldVersion == 2) { - await db.execute( - "ALTER TABLE PodcastLocal ADD auto_download INTEGER DEFAULT 0"); - await db.execute( - "ALTER TABLE PodcastLocal ADD skip_seconds_end INTEGER DEFAULT 0 "); - await db.execute( - "ALTER TABLE PodcastLocal ADD never_update INTEGER DEFAULT 0 "); - } else if (oldVersion == 3) { - await db.execute( - "ALTER TABLE PodcastLocal ADD skip_seconds_end INTEGER DEFAULT 0"); - await db.execute( - "ALTER TABLE PodcastLocal ADD never_update INTEGER DEFAULT 0 "); - } - } - - Future> getPodcastLocal(List podcasts, - {bool updateOnly = false}) async { - var dbClient = await database; - var podcastLocal = []; - - for (var s in podcasts) { - List list; - if (updateOnly) { - list = await dbClient.rawQuery( - """SELECT id, title, imageUrl, rssUrl, primaryColor, author, imagePath , provider, - link ,update_count, episode_count FROM PodcastLocal WHERE id = ? AND - never_update = 0""", [s]); - } else { - list = await dbClient.rawQuery( - """SELECT id, title, imageUrl, rssUrl, primaryColor, author, imagePath , provider, - link ,update_count, episode_count FROM PodcastLocal WHERE id = ?""", - [s]); - } - if (list.length > 0) { - podcastLocal.add(PodcastLocal( - list.first['title'], - list.first['imageUrl'], - list.first['rssUrl'], - list.first['primaryColor'], - list.first['author'], - list.first['id'], - list.first['imagePath'], - list.first['provider'], - list.first['link'], - upateCount: list.first['update_count'], - episodeCount: list.first['episode_count'])); - } - } - return podcastLocal; - } - - Future> getPodcastLocalAll( - {bool updateOnly = false}) async { - var dbClient = await database; - - List list; - if (updateOnly) { - list = await dbClient.rawQuery( - """SELECT id, title, imageUrl, rssUrl, primaryColor, author, imagePath, - provider, link FROM PodcastLocal WHERE never_update = 0 ORDER BY - add_date DESC"""); - } else { - list = await dbClient.rawQuery( - """SELECT id, title, imageUrl, rssUrl, primaryColor, author, imagePath, - provider, link FROM PodcastLocal ORDER BY add_date DESC"""); - } - - var podcastLocal = []; - - for (var i in list) { - podcastLocal.add(PodcastLocal( - i['title'], - i['imageUrl'], - i['rssUrl'], - i['primaryColor'], - i['author'], - i['id'], - i['imagePath'], - list.first['provider'], - list.first['link'])); - } - return podcastLocal; - } - - Future getPodcastCounts(String id) async { - var dbClient = await database; - List list = await dbClient - .rawQuery('SELECT episode_count FROM PodcastLocal WHERE id = ?', [id]); - if (list.isNotEmpty) return list.first['episode_count']; - return 0; - } - - Future getNeverUpdate(String id) async { - var dbClient = await database; - List list = await dbClient - .rawQuery('SELECT never_update FROM PodcastLocal WHERE id = ?', [id]); - if (list.isNotEmpty) return list.first['never_update'] == 1; - return false; - } - - Future saveNeverUpdate(String id, {bool boo}) async { - var dbClient = await database; - return await dbClient.rawUpdate( - "UPDATE PodcastLocal SET never_update = ? WHERE id = ?", - [boo ? 1 : 0, id]); - } - - Future getPodcastUpdateCounts(String id) async { - var dbClient = await database; - List list = await dbClient.rawQuery( - 'SELECt count(*) as count FROM Episodes WHERE feed_id = ? AND is_new = 1', - [id]); - if (list.isNotEmpty) return list.first['count']; - return 0; - } - - Future getSkipSecondsStart(String id) async { - var dbClient = await database; - List list = await dbClient - .rawQuery('SELECT skip_seconds FROM PodcastLocal WHERE id = ?', [id]); - if (list.isNotEmpty) return list.first['skip_seconds']; - return 0; - } - - Future saveSkipSecondsStart(String id, int seconds) async { - var dbClient = await database; - return await dbClient.rawUpdate( - "UPDATE PodcastLocal SET skip_seconds = ? WHERE id = ?", [seconds, id]); - } - - Future getSkipSecondsEnd(String id) async { - var dbClient = await database; - List list = await dbClient.rawQuery( - 'SELECT skip_seconds_end FROM PodcastLocal WHERE id = ?', [id]); - if (list.isNotEmpty) return list.first['skip_seconds_end']; - return 0; - } - - Future saveSkipSecondsEnd(String id, int seconds) async { - var dbClient = await database; - return await dbClient.rawUpdate( - "UPDATE PodcastLocal SET skip_seconds_end = ? WHERE id = ?", - [seconds, id]); - } - - Future getAutoDownload(String id) async { - var dbClient = await database; - List list = await dbClient - .rawQuery('SELECT auto_download FROM PodcastLocal WHERE id = ?', [id]); - if (list.isNotEmpty) return list.first['auto_download'] == 1; - return false; - } - - Future saveAutoDownload(String id, {bool boo}) async { - var dbClient = await database; - return await dbClient.rawUpdate( - "UPDATE PodcastLocal SET auto_download = ? WHERE id = ?", - [boo ? 1 : 0, id]); - } - - Future checkPodcast(String url) async { - var dbClient = await database; - List list = await dbClient - .rawQuery('SELECT id FROM PodcastLocal WHERE rssUrl = ?', [url]); - if (list.isEmpty) return ''; - return list.first['id']; - } - - Future savePodcastLocal(PodcastLocal podcastLocal) async { - var _milliseconds = DateTime.now().millisecondsSinceEpoch; - var dbClient = await database; - await dbClient.transaction((txn) async { - await txn.rawInsert( - """INSERT OR IGNORE INTO PodcastLocal (id, title, imageUrl, rssUrl, - primaryColor, author, description, add_date, imagePath, provider, link) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", - [ - podcastLocal.id, - podcastLocal.title, - podcastLocal.imageUrl, - podcastLocal.rssUrl, - podcastLocal.primaryColor, - podcastLocal.author, - podcastLocal.description, - _milliseconds, - podcastLocal.imagePath, - podcastLocal.provider, - podcastLocal.link - ]); - await txn.rawInsert( - """REPLACE INTO SubscribeHistory(id, title, rss_url, add_date) VALUES (?, ?, ?, ?)""", - [ - podcastLocal.id, - podcastLocal.title, - podcastLocal.rssUrl, - _milliseconds - ]); - }); - } - - Future saveFiresideData(List list) async { - var dbClient = await database; - var result = await dbClient.rawUpdate( - 'UPDATE PodcastLocal SET background_image = ? , hosts = ? WHERE id = ?', - [list[1], list[2], list[0]]); - return result; - } - - Future> getFiresideData(String id) async { - var dbClient = await database; - List list = await dbClient.rawQuery( - 'SELECT background_image, hosts FROM PodcastLocal WHERE id = ?', [id]); - if (list.isNotEmpty) { - var data = [list.first['background_image'], list.first['hosts']]; - return data; - } - return ['', '']; - } - - Future delPodcastLocal(String id) async { - var dbClient = await database; - await dbClient.rawDelete('DELETE FROM PodcastLocal WHERE id =?', [id]); - List list = await dbClient.rawQuery( - """SELECT downloaded FROM Episodes WHERE downloaded != 'ND' AND feed_id = ?""", - [id]); - for (var i in list) { - if (i != null) { - await FlutterDownloader.remove( - taskId: i['downloaded'], shouldDeleteContent: true); - } - } - await dbClient.rawDelete('DELETE FROM Episodes WHERE feed_id=?', [id]); - var milliseconds = DateTime.now().millisecondsSinceEpoch; - await dbClient.rawUpdate( - """UPDATE SubscribeHistory SET remove_date = ? , status = ? WHERE id = ?""", - [milliseconds, 1, id]); - } - - Future saveHistory(PlayHistory history) async { - var dbClient = await database; - final milliseconds = DateTime.now().millisecondsSinceEpoch; - var recent = await getPlayHistory(1); - if (recent.isNotEmpty && recent.first.title == history.title) { - await dbClient.rawDelete("DELETE FROM PlayHistory WHERE add_date = ?", - [recent.first.playdate.millisecondsSinceEpoch]); - } - await dbClient.transaction((txn) async { - return await txn.rawInsert( - """INSERT INTO PlayHistory (title, enclosure_url, seconds, seek_value, add_date, listen_time) - VALUES (?, ?, ?, ?, ?, ?) """, - [ - history.title, - history.url, - history.seconds, - history.seekValue, - milliseconds, - history.seekValue > 0.95 ? 1 : 0 - ]); - }); - } - - Future> getPlayHistory(int top) async { - var dbClient = await database; - List list = await dbClient.rawQuery( - """SELECT title, enclosure_url, seconds, seek_value, add_date FROM PlayHistory - ORDER BY add_date DESC LIMIT ? - """, [top]); - var playHistory = []; - for (var record in list) { - playHistory.add(PlayHistory(record['title'], record['enclosure_url'], - (record['seconds']).toInt(), record['seek_value'], - playdate: DateTime.fromMillisecondsSinceEpoch(record['add_date']))); - } - return playHistory; - } - - /// History list in playlist page, not include marked episdoes. - Future> getPlayRecords(int top) async { - var dbClient = await database; - List list = await dbClient.rawQuery( - """SELECT title, enclosure_url, seconds, seek_value, add_date FROM PlayHistory - WHERE seconds != 0 ORDER BY add_date DESC LIMIT ? - """, [top]); - var playHistory = []; - for (var record in list) { - playHistory.add(PlayHistory(record['title'], record['enclosure_url'], - (record['seconds']).toInt(), record['seek_value'], - playdate: DateTime.fromMillisecondsSinceEpoch(record['add_date']))); - } - return playHistory; - } - - Future isListened(String url) async { - var dbClient = await database; - var i = 0; - List list = await dbClient.rawQuery( - "SELECT SUM(listen_time) FROM PlayHistory WHERE enclosure_url = ?", - [url]); - if (list.isNotEmpty) { - i = list.first['SUM(listen_time)']; - return i ?? 0; - } - return 0; - } - - Future markNotListened(String url) async { - var dbClient = await database; - int count; - await dbClient.transaction((txn) async { - count = await txn.rawUpdate( - "UPDATE OR IGNORE PlayHistory SET listen_time = 0 WHERE enclosure_url = ?", - [url]); - }); - await dbClient.rawDelete( - 'DELETE FROM PlayHistory WHERE enclosure_url=? ' - 'AND listen_time = 0 AND seconds = 0', - [url]); - return count; - } - - Future> getSubHistory() async { - var dbClient = await database; - List list = await dbClient.rawQuery( - """SELECT title, rss_url, add_date, remove_date, status FROM SubscribeHistory - ORDER BY add_date DESC"""); - return list - .map((record) => SubHistory( - record['status'] == 0 ? true : false, - DateTime.fromMillisecondsSinceEpoch(record['remove_date']), - DateTime.fromMillisecondsSinceEpoch(record['add_date']), - record['rss_url'], - record['title'])) - .toList(); - } - - Future listenMins(int day) async { - var dbClient = await database; - var now = DateTime.now(); - var start = DateTime(now.year, now.month, now.day) - .subtract(Duration(days: day)) - .millisecondsSinceEpoch; - var end = DateTime(now.year, now.month, now.day) - .subtract(Duration(days: (day - 1))) - .millisecondsSinceEpoch; - List list = await dbClient.rawQuery( - "SELECT seconds FROM PlayHistory WHERE add_date > ? AND add_date < ?", - [start, end]); - var sum = 0.0; - if (list.isEmpty) { - sum = 0.0; - } else { - for (var record in list) { - sum += record['seconds']; - } - } - return (sum ~/ 60).toDouble(); - } - - Future getPosition(EpisodeBrief episodeBrief) async { - var dbClient = await database; - List list = await dbClient.rawQuery( - """SELECT title, enclosure_url, seconds, seek_value, add_date FROM PlayHistory - WHERE enclosure_url = ? ORDER BY add_date DESC LIMIT 1""", - [episodeBrief.enclosureUrl]); - return list.isNotEmpty - ? PlayHistory(list.first['title'], list.first['enclosure_url'], - (list.first['seconds']).toInt(), list.first['seek_value'], - playdate: - DateTime.fromMillisecondsSinceEpoch(list.first['add_date'])) - : PlayHistory(episodeBrief.title, episodeBrief.enclosureUrl, 0, 0); - } - - /// Check if episode was marked listend. - Future checkMarked(EpisodeBrief episodeBrief) async { - var dbClient = await database; - List list = await dbClient.rawQuery( - """SELECT title, enclosure_url, seconds, seek_value, add_date FROM PlayHistory - WHERE enclosure_url = ? AND seek_value = 1 ORDER BY add_date DESC LIMIT 1""", - [episodeBrief.enclosureUrl]); - return list.isNotEmpty; - } - - DateTime _parsePubDate(String pubDate) { - if (pubDate == null) return DateTime.now(); - DateTime date; - var yyyy = RegExp(r'[1-2][0-9]{3}'); - var hhmm = RegExp(r'[0-2][0-9]\:[0-5][0-9]'); - var ddmmm = RegExp(r'[0-3][0-9]\s[A-Z][a-z]{2}'); - var mmDd = RegExp(r'([1-2][0-9]{3}\-[0-1]|\s)[0-9]\-[0-3][0-9]'); - // RegExp timezone - var z = RegExp(r'(\+|\-)[0-1][0-9]00'); - var timezone = z.stringMatch(pubDate); - var timezoneInt = 0; - if (timezone != null) { - if (timezone.substring(0, 1) == '-') { - timezoneInt = int.parse(timezone.substring(1, 2)); - } else { - timezoneInt = -int.parse(timezone.substring(1, 2)); - } - } - try { - date = DateFormat('EEE, dd MMM yyyy HH:mm:ss Z', 'en_US').parse(pubDate); - } catch (e) { - try { - date = DateFormat('dd MMM yyyy HH:mm:ss Z', 'en_US').parse(pubDate); - } catch (e) { - try { - date = DateFormat('EEE, dd MMM yyyy HH:mm Z', 'en_US').parse(pubDate); - } catch (e) { - var year = yyyy.stringMatch(pubDate); - var time = hhmm.stringMatch(pubDate); - var month = ddmmm.stringMatch(pubDate); - if (year != null && time != null && month != null) { - try { - date = DateFormat('dd MMM yyyy HH:mm', 'en_US') - .parse('$month $year $time'); - } catch (e) { - date = DateTime.now(); - } - } else if (year != null && time != null && month == null) { - var month = mmDd.stringMatch(pubDate); - try { - date = - DateFormat('yyyy-MM-dd HH:mm', 'en_US').parse('$month $time'); - } catch (e) { - date = DateTime.now(); - } - } else { - date = DateTime.now(); - } - } - } - } - date.add(Duration(hours: timezoneInt)).add(DateTime.now().timeZoneOffset); - developer.log(date.toString()); - return date; - } - - int _getExplicit(bool b) { - int result; - if (b == true) { - result = 1; - return result; - } else { - result = 0; - return result; - } - } - - bool _isXimalaya(String input) { - var ximalaya = RegExp(r"ximalaya.com"); - return ximalaya.hasMatch(input); - } - - String _getDescription(String content, String description, String summary) { - if (content.length >= description.length) { - if (content.length >= summary.length) { - return content; - } else { - return summary; - } - } else if (description.length >= summary.length) { - return description; - } else { - return summary; - } - } - - Future savePodcastRss(RssFeed feed, String id) async { - feed.items.removeWhere((item) => item == null); - var result = feed.items.length; - var dbClient = await database; - String description, url; - for (var i = 0; i < result; i++) { - developer.log(feed.items[i].title); - description = _getDescription(feed.items[i]?.content?.value ?? '', - feed.items[i].description ?? '', feed.items[i].itunes.summary ?? ''); - if (feed.items[i].enclosure != null) { - _isXimalaya(feed.items[i].enclosure.url) - ? url = feed.items[i].enclosure.url.split('=').last - : url = feed.items[i].enclosure.url; - } - - final title = feed.items[i].itunes.title ?? feed.items[i].title; - final length = feed.items[i]?.enclosure?.length; - final pubDate = feed.items[i].pubDate; - final date = _parsePubDate(pubDate); - final milliseconds = date.millisecondsSinceEpoch; - final duration = feed.items[i].itunes.duration?.inSeconds ?? 0; - final explicit = _getExplicit(feed.items[i].itunes.explicit); - - if (url != null) { - await dbClient.transaction((txn) { - return txn.rawInsert( - """INSERT OR REPLACE INTO Episodes(title, enclosure_url, enclosure_length, pubDate, - description, feed_id, milliseconds, duration, explicit, media_id) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", - [ - title, - url, - length, - pubDate, - description, - id, - milliseconds, - duration, - explicit, - url - ]); - }); - } - } - var countUpdate = Sqflite.firstIntValue(await dbClient - .rawQuery('SELECT COUNT(*) FROM Episodes WHERE feed_id = ?', [id])); - - await dbClient.rawUpdate( - """UPDATE PodcastLocal SET episode_count = ? WHERE id = ?""", - [countUpdate, id]); - return result; - } - - Future updatePodcastRss(PodcastLocal podcastLocal, - {int removeMark = 0}) async { - var options = BaseOptions( - connectTimeout: 20000, - receiveTimeout: 20000, - ); - try { - var response = await Dio(options).get(podcastLocal.rssUrl); - if (response.statusCode == 200) { - var feed = RssFeed.parse(response.data); - String url, description; - feed.items.removeWhere((item) => item == null); - - var dbClient = await database; - var count = Sqflite.firstIntValue(await dbClient.rawQuery( - 'SELECT COUNT(*) FROM Episodes WHERE feed_id = ?', - [podcastLocal.id])); - if (removeMark == 0) { - await dbClient.rawUpdate( - "UPDATE Episodes SET is_new = 0 WHERE feed_id = ?", - [podcastLocal.id]); - } - for (var item in feed.items) { - developer.log(item.title); - description = _getDescription(item.content.value ?? '', - item.description ?? '', item.itunes.summary ?? ''); - - if (item.enclosure?.url != null) { - _isXimalaya(item.enclosure.url) - ? url = item.enclosure.url.split('=').last - : url = item.enclosure.url; - } - - final title = item.itunes.title ?? item.title; - final length = item?.enclosure?.length ?? 0; - final pubDate = item.pubDate; - final date = _parsePubDate(pubDate); - final milliseconds = date.millisecondsSinceEpoch; - final duration = item.itunes.duration?.inSeconds ?? 0; - final explicit = _getExplicit(item.itunes.explicit); - - if (url != null) { - await dbClient.transaction((txn) async { - await txn.rawInsert( - """INSERT OR IGNORE INTO Episodes(title, enclosure_url, enclosure_length, pubDate, - description, feed_id, milliseconds, duration, explicit, media_id, is_new) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)""", - [ - title, - url, - length, - pubDate, - description, - podcastLocal.id, - milliseconds, - duration, - explicit, - url, - ]); - }); - } - } - var countUpdate = Sqflite.firstIntValue(await dbClient.rawQuery( - 'SELECT COUNT(*) FROM Episodes WHERE feed_id = ?', - [podcastLocal.id])); - - await dbClient.rawUpdate( - """UPDATE PodcastLocal SET update_count = ?, episode_count = ? WHERE id = ?""", - [countUpdate - count, countUpdate, podcastLocal.id]); - return countUpdate - count; - } - return 0; - } catch (e) { - developer.log(e.toString(), name: 'Update podcast error'); - return -1; - } - } - - Future> getRssItem(String id, int count, - {bool reverse, - Filter filter = Filter.all, - String query = '', - bool hideListened = false}) async { - var dbClient = await database; - var episodes = []; - var list = []; - if (hideListened) { - if (count == -1) { - if (reverse) { - switch (filter) { - case Filter.all: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url - WHERE P.id = ? GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null - OR SUM(H.listen_time) = 0 ORDER BY E.milliseconds ASC""", [id]); - break; - case Filter.liked: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE P.id = ? AND E.liked = 1 ORDER BY E.milliseconds ASC""", [id]); - break; - case Filter.downloaded: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE P.id = ? AND E.media_id != E.enclosure_url ORDER BY E.milliseconds ASC""", - [id]); - break; - case Filter.search: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE P.id = ? AND E.title LIKE ? ORDER BY E.milliseconds ASC""", - [id, '%$query%']); - break; - default: - } - } else { - switch (filter) { - case Filter.all: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url - WHERE P.id = ? GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null - OR SUM(H.listen_time) = 0 ORDER BY E.milliseconds DESC""", [id]); - break; - case Filter.liked: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE P.id = ? AND E.liked = 1 ORDER BY E.milliseconds DESC""", [id]); - break; - case Filter.downloaded: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE P.id = ? AND E.media_id != E.enclosure_url ORDER BY E.milliseconds DESC""", - [id]); - break; - case Filter.search: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE P.id = ? AND E.title LIKE ? ORDER BY E.milliseconds DESC""", - [id, '%$query%']); - break; - default: - } - } - } else if (reverse) { - switch (filter) { - case Filter.all: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url - WHERE P.id = ? GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null - OR SUM(H.listen_time) = 0 ORDER BY E.milliseconds ASC LIMIT ?""", - [id, count]); - break; - case Filter.liked: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url - WHERE P.id = ? AND E.liked = 1 GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null - OR SUM(H.listen_time) = 0 ORDER BY E.milliseconds ASC LIMIT ?""", - [id, count]); - break; - case Filter.downloaded: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url - WHERE P.id = ? AND E.enclosure_url != E.media_id - GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null - OR SUM(H.listen_time) = 0 ORDER BY E.milliseconds ASC LIMIT ?""", - [id, count]); - break; - case Filter.search: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url - WHERE P.id = ? AND E.title LIKE ? GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null - OR SUM(H.listen_time) = 0 ORDER BY E.milliseconds ASC LIMIT ?""", - [id, '%$query%', count]); - break; - default: - } - } else { - switch (filter) { - case Filter.all: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url - WHERE P.id = ? GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null - OR SUM(H.listen_time) = 0 ORDER BY E.milliseconds DESC LIMIT ?""", - [id, count]); - break; - case Filter.liked: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url - WHERE P.id = ? AND E.liked = 1 GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null - OR SUM(H.listen_time) = 0 ORDER BY E.milliseconds DESC LIMIT ?""", - [id, count]); - break; - case Filter.downloaded: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url - WHERE P.id = ? AND E.enclosure_url != E.media_id GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null - OR SUM(H.listen_time) = 0 ORDER BY E.milliseconds DESC LIMIT ?""", - [id, count]); - break; - case Filter.search: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url - WHERE P.id = ? AND E.title LIKE ? GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null - OR SUM(H.listen_time) = 0 ORDER BY E.milliseconds DESC LIMIT ?""", - [id, '%$query%', count]); - break; - default: - } - } - } else { - if (count == -1) { - if (reverse) { - switch (filter) { - case Filter.all: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE P.id = ? ORDER BY E.milliseconds ASC""", [id]); - break; - case Filter.liked: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE P.id = ? AND E.liked = 1 ORDER BY E.milliseconds ASC""", [id]); - break; - case Filter.downloaded: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE P.id = ? AND E.media_id != E.enclosure_url ORDER BY E.milliseconds ASC""", - [id]); - break; - case Filter.search: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE P.id = ? AND E.title LIKE ? ORDER BY E.milliseconds ASC""", - [id, '%$query%']); - break; - default: - } - } else { - switch (filter) { - case Filter.all: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE P.id = ? ORDER BY E.milliseconds DESC""", [id]); - break; - case Filter.liked: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE P.id = ? AND E.liked = 1 ORDER BY E.milliseconds DESC""", [id]); - break; - case Filter.downloaded: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE P.id = ? AND E.media_id != E.enclosure_url ORDER BY E.milliseconds DESC""", - [id]); - break; - case Filter.search: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE P.id = ? AND E.title LIKE ? ORDER BY E.milliseconds DESC""", - [id, '%$query%']); - break; - default: - } - } - } else if (reverse) { - switch (filter) { - case Filter.all: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE P.id = ? ORDER BY E.milliseconds ASC LIMIT ?""", [id, count]); - break; - case Filter.liked: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE P.id = ? AND E.liked = 1 ORDER BY E.milliseconds ASC LIMIT ?""", - [id, count]); - break; - case Filter.downloaded: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE P.id = ? AND E.enclosure_url != E.media_id ORDER BY E.milliseconds ASC LIMIT ?""", - [id, count]); - break; - case Filter.search: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE P.id = ? AND E.title LIKE ? ORDER BY E.milliseconds ASC LIMIT ?""", - [id, '%$query%', count]); - break; - default: - } - } else { - switch (filter) { - case Filter.all: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE P.id = ? ORDER BY E.milliseconds DESC LIMIT ?""", [id, count]); - break; - case Filter.liked: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE P.id = ? AND E.liked = 1 ORDER BY E.milliseconds DESC LIMIT ?""", - [id, count]); - break; - case Filter.downloaded: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE P.id = ? AND E.enclosure_url != E.media_id ORDER BY E.milliseconds DESC LIMIT ?""", - [id, count]); - break; - case Filter.search: - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE P.id = ? AND E.title LIKE ? ORDER BY E.milliseconds DESC LIMIT ?""", - [id, '%$query%', count]); - break; - default: - } - } - } - - if (list.isNotEmpty) { - for (var i in list) { - episodes.add(EpisodeBrief( - i['title'], - i['enclosure_url'], - i['enclosure_length'], - i['milliseconds'], - i['feed_title'], - i['primaryColor'], - i['duration'], - i['explicit'], - i['imagePath'], - i['is_new'])); - } - } - return episodes; - } - - Future> getNewEpisodes(String id) async { - var dbClient = await database; - var episodes = []; - List list; - if (id == 'all') { - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE E.is_new = 1 AND E.downloaded = 'ND' AND P.auto_download = 1 ORDER BY E.milliseconds ASC""", - ); - } else { - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE E.is_new = 1 AND E.downloaded = 'ND' AND E.feed_id = ? ORDER BY E.milliseconds ASC""", - [id]); - } - if (list.isNotEmpty) { - for (var i in list) { - episodes.add(EpisodeBrief( - i['title'], - i['enclosure_url'], - i['enclosure_length'], - i['milliseconds'], - i['feed_title'], - i['primaryColor'], - i['duration'], - i['explicit'], - i['imagePath'], - i['is_new'])); - } - } - return episodes; - } - - Future> getRssItemTop(String id) async { - var dbClient = await database; - var episodes = []; - List list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, - E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, - P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - where E.feed_id = ? ORDER BY E.milliseconds DESC LIMIT 2""", [id]); - for (var i in list) { - episodes.add(EpisodeBrief( - i['title'], - i['enclosure_url'], - i['enclosure_length'], - i['milliseconds'], - i['feed_title'], - i['primaryColor'], - i['duration'], - i['explicit'], - i['imagePath'], - i['is_new'])); - } - return episodes; - } - - Future> getRecentRssItem(int top, - {bool hideListened = false}) async { - var dbClient = await database; - var episodes = []; - var list = []; - if (hideListened) { - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, - E.milliseconds, P.title as feed_title, E.duration, E.explicit, - P.imagePath, P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url - GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null - OR SUM(H.listen_time) = 0 ORDER BY E.milliseconds DESC LIMIT ? """, - [top]); - } else { - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, - E.milliseconds, P.title as feed_title, E.duration, E.explicit, - P.imagePath, P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - ORDER BY E.milliseconds DESC LIMIT ? """, [top]); - } - if (list.isNotEmpty) { - for (var i in list) { - episodes.add(EpisodeBrief( - i['title'], - i['enclosure_url'], - i['enclosure_length'], - i['milliseconds'], - i['feed_title'], - i['primaryColor'], - i['duration'], - i['explicit'], - i['imagePath'], - i['is_new'])); - } - } - return episodes; - } - - Future> getGroupRssItem(int top, List group, - {bool hideListened = false}) async { - var dbClient = await database; - var episodes = []; - if (group.length > 0) { - var s = group.map((e) => "'$e'").toList(); - var list = []; - if (hideListened) { - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, - E.milliseconds, P.title as feed_title, E.duration, E.explicit, - P.imagePath, P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url - WHERE P.id in (${s.join(',')}) GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null - OR SUM(H.listen_time) = 0 ORDER BY E.milliseconds DESC LIMIT ? """, - [top]); - } else { - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, - E.milliseconds, P.title as feed_title, E.duration, E.explicit, - P.imagePath, P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE P.id in (${s.join(',')}) - ORDER BY E.milliseconds DESC LIMIT ? """, [top]); - } - if (list.isNotEmpty) { - for (var i in list) { - episodes.add(EpisodeBrief( - i['title'], - i['enclosure_url'], - i['enclosure_length'], - i['milliseconds'], - i['feed_title'], - i['primaryColor'], - i['duration'], - i['explicit'], - i['imagePath'], - i['is_new'])); - } - } - } - return episodes; - } - - Future> getRecentNewRssItem() async { - var dbClient = await database; - var episodes = []; - List list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, E.media_id, - E.milliseconds, P.title as feed_title, E.duration, E.explicit, - P.imagePath, P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE is_new = 1 ORDER BY E.milliseconds DESC """, - ); - for (var i in list) { - episodes.add(EpisodeBrief( - i['title'], - i['enclosure_url'], - i['enclosure_length'], - i['milliseconds'], - i['feed_title'], - i['primaryColor'], - i['duration'], - i['explicit'], - i['imagePath'], - i['is_new'], - mediaId: i['media_id'])); - } - return episodes; - } - - Future> getOutdatedEpisode(int deadline, - {bool deletePlayed}) async { - var dbClient = await database; - var episodes = []; - List list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, - E.milliseconds, P.title as feed_title, E.duration, E.explicit, - P.imagePath, P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE E.download_date < ? AND E.enclosure_url != E.media_id - ORDER BY E.milliseconds DESC""", [deadline]); - if (list.isNotEmpty) { - for (var i in list) { - episodes.add(EpisodeBrief( - i['title'], - i['enclosure_url'], - i['enclosure_length'], - i['milliseconds'], - i['feed_title'], - i['primaryColor'], - i['duration'], - i['explicit'], - i['imagePath'], - i['is_new'])); - } - } - if (deletePlayed) { - List results = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, - E.milliseconds, P.title as feed_title, E.duration, E.explicit, - P.imagePath, P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P - ON E.feed_id = P.id LEFT JOIN PlayHistory H ON E.enclosure_url = - H.enclosure_url WHERE E.enclosure_url != E.media_id - GROUP BY E.enclosure_url HAVING SUM(H.listen_time) > 0 ORDER BY - E.milliseconds DESC"""); - if (results.isNotEmpty) { - for (var i in results) { - episodes.add(EpisodeBrief( - i['title'], - i['enclosure_url'], - i['enclosure_length'], - i['milliseconds'], - i['feed_title'], - i['primaryColor'], - i['duration'], - i['explicit'], - i['imagePath'], - i['is_new'])); - } - } - } - return episodes.toSet().toList(); - } - - Future> getDownloadedEpisode(int mode, - {bool hideListened = false}) async { - var dbClient = await database; - var episodes = []; - List list; - if (hideListened) { - if (mode == 0) { - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, E.download_date, E.is_new, - E.milliseconds, P.title as feed_title, E.duration, E.explicit, - P.imagePath, P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url - WHERE E.enclosure_url != E.media_id GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null - OR SUM(H.listen_time) = 0 ORDER BY E.download_date DESC""", - ); - } else if (mode == 1) { - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, E.download_date,E.is_new, - E.milliseconds, P.title as feed_title, E.duration, E.explicit, - P.imagePath, P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url - WHERE E.enclosure_url != E.media_id GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null - OR SUM(H.listen_time) = 0 ORDER BY E.download_date ASC""", - ); - } else if (mode == 2) { - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, E.download_date,E.is_new, - E.milliseconds, P.title as feed_title, E.duration, E.explicit, - P.imagePath, P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url - WHERE E.enclosure_url != E.media_id GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null - OR SUM(H.listen_time) = 0 ORDER BY E.enclosure_length DESC""", - ); - } - } else //Ordered by date - { - if (mode == 0) { - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, E.download_date, E.is_new, - E.milliseconds, P.title as feed_title, E.duration, E.explicit, - P.imagePath, P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE E.enclosure_url != E.media_id - ORDER BY E.download_date DESC""", - ); - } else if (mode == 1) { - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, E.download_date,E.is_new, - E.milliseconds, P.title as feed_title, E.duration, E.explicit, - P.imagePath, P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE E.enclosure_url != E.media_id - ORDER BY E.download_date ASC""", - ); - } else if (mode == 2) { - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, E.download_date,E.is_new, - E.milliseconds, P.title as feed_title, E.duration, E.explicit, - P.imagePath, P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE E.enclosure_url != E.media_id - ORDER BY E.enclosure_length DESC""", - ); - } - } - if (list.isNotEmpty) { - for (var i in list) { - episodes.add(EpisodeBrief( - i['title'], - i['enclosure_url'], - i['enclosure_length'], - i['milliseconds'], - i['feed_title'], - i['primaryColor'], - i['duration'], - i['explicit'], - i['imagePath'], - i['is_new'], - downloadDate: i['download_date'])); - } - } - return episodes; - } - - Future removeAllNewMark() async { - var dbClient = await database; - await dbClient.transaction((txn) async { - await txn.rawUpdate("UPDATE Episodes SET is_new = 0 "); - }); - } - - Future> getGroupNewRssItem(List group) async { - var dbClient = await database; - var episodes = []; - if (group.length > 0) { - var s = group.map((e) => "'$e'").toList(); - List list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, E.media_id, - E.milliseconds, P.title as feed_title, E.duration, E.explicit, - P.imagePath, P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE P.id in (${s.join(',')}) AND is_new = 1 - ORDER BY E.milliseconds DESC""", - ); - for (var i in list) { - episodes.add(EpisodeBrief( - i['title'], - i['enclosure_url'], - i['enclosure_length'], - i['milliseconds'], - i['feed_title'], - i['primaryColor'], - i['duration'], - i['explicit'], - i['imagePath'], - i['is_new'], - mediaId: i['media_id'])); - } - } - return episodes; - } - - Future removeGroupNewMark(List group) async { - var dbClient = await database; - if (group.length > 0) { - var s = group.map((e) => "'$e'").toList(); - await dbClient.transaction((txn) async { - await txn.rawUpdate( - "UPDATE Episodes SET is_new = 0 WHERE feed_id in (${s.join(',')})"); - }); - } - } - - Future removeEpisodeNewMark(String url) async { - var dbClient = await database; - await dbClient.transaction((txn) async { - await txn.rawUpdate( - "UPDATE Episodes SET is_new = 0 WHERE enclosure_url = ?", [url]); - }); - developer.log('remove new episode $url'); - } - - Future> getLikedRssItem(int i, int sortBy, - {bool hideListened = false}) async { - var dbClient = await database; - var episodes = []; - var list = []; - if (hideListened) { - if (sortBy == 0) { - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, E.milliseconds, P.imagePath, - P.title as feed_title, E.duration, E.explicit, P.primaryColor, E.is_new - FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url - WHERE E.liked = 1 GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null - OR SUM(H.listen_time) = 0 ORDER BY E.milliseconds DESC LIMIT ?""", [i]); - } else { - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, E.milliseconds, P.imagePath, - P.title as feed_title, E.duration, E.explicit, P.primaryColor, E.is_new - FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url - WHERE E.liked = 1 GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null - OR SUM(H.listen_time) = 0 ORDER BY E.liked_date DESC LIMIT ?""", [i]); - } - } else { - if (sortBy == 0) { - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, E.milliseconds, P.imagePath, - P.title as feed_title, E.duration, E.explicit, P.primaryColor, E.is_new - FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE E.liked = 1 ORDER BY E.milliseconds DESC LIMIT ?""", [i]); - } else { - list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, E.milliseconds, P.imagePath, - P.title as feed_title, E.duration, E.explicit, P.primaryColor, E.is_new - FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE E.liked = 1 ORDER BY E.liked_date DESC LIMIT ?""", [i]); - } - } - if (list.isNotEmpty) { - for (var i in list) { - episodes.add(EpisodeBrief( - i['title'], - i['enclosure_url'], - i['enclosure_length'], - i['milliseconds'], - i['feed_title'], - i['primaryColor'], - i['duration'], - i['explicit'], - i['imagePath'], - i['is_new'])); - } - } - - return episodes; - } - - Future setLiked(String url) async { - var dbClient = await database; - var milliseconds = DateTime.now().millisecondsSinceEpoch; - await dbClient.transaction((txn) async { - await txn.rawUpdate( - "UPDATE Episodes SET liked = 1, liked_date = ? WHERE enclosure_url= ?", - [milliseconds, url]); - }); - } - - Future setUniked(String url) async { - var dbClient = await database; - await dbClient.transaction((txn) async { - await txn.rawUpdate( - "UPDATE Episodes SET liked = 0 WHERE enclosure_url = ?", [url]); - }); - } - - Future isLiked(String url) async { - var dbClient = await database; - var list = []; - list = await dbClient - .rawQuery("SELECT liked FROM Episodes WHERE enclosure_url = ?", [url]); - if (list.isNotEmpty) { - return list.first['liked'] == 0 ? false : true; - } - return false; - } - - Future isDownloaded(String url) async { - var dbClient = await database; - List list = await dbClient.rawQuery( - "SELECT id FROM Episodes WHERE enclosure_url = ? AND enclosure_url != media_id", - [url]); - return list.isNotEmpty; - } - - Future saveDownloaded(String url, String id) async { - var dbClient = await database; - var milliseconds = DateTime.now().millisecondsSinceEpoch; - int count; - await dbClient.transaction((txn) async { - count = await txn.rawUpdate( - "UPDATE Episodes SET downloaded = ?, download_date = ? WHERE enclosure_url = ?", - [id, milliseconds, url]); - }); - return count; - } - - Future saveMediaId(String url, String path, String id, int size) async { - var dbClient = await database; - var milliseconds = DateTime.now().millisecondsSinceEpoch; - int count; - await dbClient.transaction((txn) async { - count = await txn.rawUpdate( - "UPDATE Episodes SET enclosure_length = ?, media_id = ?, download_date = ?, downloaded = ? WHERE enclosure_url = ?", - [size, path, milliseconds, id, url]); - }); - return count; - } - - Future delDownloaded(String url) async { - var dbClient = await database; - int count; - await dbClient.transaction((txn) async { - count = await txn.rawUpdate( - "UPDATE Episodes SET downloaded = 'ND', media_id = ? WHERE enclosure_url = ?", - [url, url]); - }); - developer.log('Deleted $url'); - return count; - } - - Future getDescription(String url) async { - var dbClient = await database; - List list = await dbClient.rawQuery( - 'SELECT description FROM Episodes WHERE enclosure_url = ?', [url]); - String description = list[0]['description']; - return description; - } - - Future saveEpisodeDes(String url, {String description}) async { - var dbClient = await database; - await dbClient.transaction((txn) async { - await txn.rawUpdate( - "UPDATE Episodes SET description = ? WHERE enclosure_url = ?", - [description, url]); - }); - } - - Future getFeedDescription(String id) async { - var dbClient = await database; - List list = await dbClient - .rawQuery('SELECT description FROM PodcastLocal WHERE id = ?', [id]); - String description = list[0]['description']; - return description; - } - - Future getRssItemWithUrl(String url) async { - var dbClient = await database; - EpisodeBrief episode; - List list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, E.milliseconds, P.imagePath, - P.title as feed_title, E.duration, E.explicit, P.skip_seconds, P.skip_seconds_end, - E.is_new, P.primaryColor, E.media_id FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE E.enclosure_url = ?""", [url]); - if (list.isEmpty) { - return null; - } else { - episode = EpisodeBrief( - list.first['title'], - list.first['enclosure_url'], - list.first['enclosure_length'], - list.first['milliseconds'], - list.first['feed_title'], - list.first['primaryColor'], - list.first['duration'], - list.first['explicit'], - list.first['imagePath'], - list.first['is_new'], - mediaId: list.first['media_id'], - skipSecondsStart: list.first['skip_seconds'], - skipSecondsEnd: list.first['skip_seconds_end']); - return episode; - } - } - - Future getRssItemWithMediaId(String id) async { - var dbClient = await database; - EpisodeBrief episode; - List list = await dbClient.rawQuery( - """SELECT E.title, E.enclosure_url, E.enclosure_length, E.milliseconds, P.imagePath, - P.title as feed_title, E.duration, E.explicit, P.skip_seconds, P.skip_seconds_end, - E.is_new, P.primaryColor, E.media_id FROM Episodes E INNER JOIN - PodcastLocal P ON E.feed_id = P.id WHERE E.media_id = ?""", [id]); - if (list.isEmpty) { - return null; - } else { - episode = EpisodeBrief( - list.first['title'], - list.first['enclosure_url'], - list.first['enclosure_length'], - list.first['milliseconds'], - list.first['feed_title'], - list.first['primaryColor'], - list.first['duration'], - list.first['explicit'], - list.first['imagePath'], - list.first['is_new'], - mediaId: list.first['media_id'], - skipSecondsStart: list.first['skip_seconds'], - skipSecondsEnd: list.first['skip_seconds_end']); - return episode; - } - } - - Future getImageUrl(String url) async { - var dbClient = await database; - List list = await dbClient.rawQuery( - """SELECT P.imageUrl FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id - WHERE E.enclosure_url = ?""", [url]); - if (list.isEmpty) return null; - return list.first["imageUrl"]; - } -} +import 'dart:async'; +import 'dart:developer' as developer; + +import 'package:dio/dio.dart'; +import 'package:flutter_downloader/flutter_downloader.dart'; +import 'package:intl/intl.dart'; +import 'package:path/path.dart'; +import 'package:sqflite/sqflite.dart'; +import 'package:webfeed/webfeed.dart'; + +import '../type/episodebrief.dart'; +import '../type/play_histroy.dart'; +import '../type/podcastlocal.dart'; +import '../type/sub_history.dart'; + +enum Filter { downloaded, liked, search, all } + +class DBHelper { + static Database _db; + Future get database async { + if (_db != null) return _db; + _db = await initDb(); + return _db; + } + + initDb() async { + var documentsDirectory = await getDatabasesPath(); + var path = join(documentsDirectory, "podcasts.db"); + var theDb = await openDatabase(path, + version: 4, onCreate: _onCreate, onUpgrade: _onUpgrade); + return theDb; + } + + void _onCreate(Database db, int version) async { + await db + .execute("""CREATE TABLE PodcastLocal(id TEXT PRIMARY KEY,title TEXT, + imageUrl TEXT,rssUrl TEXT UNIQUE, primaryColor TEXT, author TEXT, + description TEXT, add_date INTEGER, imagePath TEXT, provider TEXT, link TEXT, + background_image TEXT DEFAULT '', hosts TEXT DEFAULT '',update_count INTEGER DEFAULT 0, + episode_count INTEGER DEFAULT 0, skip_seconds INTEGER DEFAULT 0, + auto_download INTEGER DEFAULT 0, skip_seconds_end INTEGER DEFAULT 0, + never_update INTEGER DEFAULT 0)"""); + await db + .execute("""CREATE TABLE Episodes(id INTEGER PRIMARY KEY,title TEXT, + enclosure_url TEXT UNIQUE, enclosure_length INTEGER, pubDate TEXT, + description TEXT, feed_id TEXT, feed_link TEXT, milliseconds INTEGER, + duration INTEGER DEFAULT 0, explicit INTEGER DEFAULT 0, liked INTEGER DEFAULT 0, + liked_date INTEGER DEFAULT 0, downloaded TEXT DEFAULT 'ND', + download_date INTEGER DEFAULT 0, media_id TEXT, is_new INTEGER DEFAULT 0)"""); + await db.execute( + """CREATE TABLE PlayHistory(id INTEGER PRIMARY KEY, title TEXT, enclosure_url TEXT, + seconds REAL, seek_value REAL, add_date INTEGER, listen_time INTEGER DEFAULT 0)"""); + await db.execute( + """CREATE TABLE SubscribeHistory(id TEXT PRIMARY KEY, title TEXT, rss_url TEXT UNIQUE, + add_date INTEGER, remove_date INTEGER DEFAULT 0, status INTEGER DEFAULT 0)"""); + } + + void _onUpgrade(Database db, int oldVersion, int newVersion) async { + if (oldVersion == 1) { + await db.execute( + "ALTER TABLE PodcastLocal ADD skip_seconds INTEGER DEFAULT 0 "); + await db.execute( + "ALTER TABLE PodcastLocal ADD auto_download INTEGER DEFAULT 0"); + await db.execute( + "ALTER TABLE PodcastLocal ADD skip_seconds_end INTEGER DEFAULT 0 "); + await db.execute( + "ALTER TABLE PodcastLocal ADD never_update INTEGER DEFAULT 0 "); + } else if (oldVersion == 2) { + await db.execute( + "ALTER TABLE PodcastLocal ADD auto_download INTEGER DEFAULT 0"); + await db.execute( + "ALTER TABLE PodcastLocal ADD skip_seconds_end INTEGER DEFAULT 0 "); + await db.execute( + "ALTER TABLE PodcastLocal ADD never_update INTEGER DEFAULT 0 "); + } else if (oldVersion == 3) { + await db.execute( + "ALTER TABLE PodcastLocal ADD skip_seconds_end INTEGER DEFAULT 0"); + await db.execute( + "ALTER TABLE PodcastLocal ADD never_update INTEGER DEFAULT 0 "); + } + } + + Future> getPodcastLocal(List podcasts, + {bool updateOnly = false}) async { + var dbClient = await database; + var podcastLocal = []; + + for (var s in podcasts) { + List list; + if (updateOnly) { + list = await dbClient.rawQuery( + """SELECT id, title, imageUrl, rssUrl, primaryColor, author, imagePath , provider, + link ,update_count, episode_count FROM PodcastLocal WHERE id = ? AND + never_update = 0""", [s]); + } else { + list = await dbClient.rawQuery( + """SELECT id, title, imageUrl, rssUrl, primaryColor, author, imagePath , provider, + link ,update_count, episode_count FROM PodcastLocal WHERE id = ?""", + [s]); + } + if (list.length > 0) { + podcastLocal.add(PodcastLocal( + list.first['title'], + list.first['imageUrl'], + list.first['rssUrl'], + list.first['primaryColor'], + list.first['author'], + list.first['id'], + list.first['imagePath'], + list.first['provider'], + list.first['link'], + upateCount: list.first['update_count'], + episodeCount: list.first['episode_count'])); + } + } + return podcastLocal; + } + + Future> getPodcastLocalAll( + {bool updateOnly = false}) async { + var dbClient = await database; + + List list; + if (updateOnly) { + list = await dbClient.rawQuery( + """SELECT id, title, imageUrl, rssUrl, primaryColor, author, imagePath, + provider, link FROM PodcastLocal WHERE never_update = 0 ORDER BY + add_date DESC"""); + } else { + list = await dbClient.rawQuery( + """SELECT id, title, imageUrl, rssUrl, primaryColor, author, imagePath, + provider, link FROM PodcastLocal ORDER BY add_date DESC"""); + } + + var podcastLocal = []; + + for (var i in list) { + podcastLocal.add(PodcastLocal( + i['title'], + i['imageUrl'], + i['rssUrl'], + i['primaryColor'], + i['author'], + i['id'], + i['imagePath'], + list.first['provider'], + list.first['link'])); + } + return podcastLocal; + } + + Future getPodcastCounts(String id) async { + var dbClient = await database; + List list = await dbClient + .rawQuery('SELECT episode_count FROM PodcastLocal WHERE id = ?', [id]); + if (list.isNotEmpty) return list.first['episode_count']; + return 0; + } + + Future getNeverUpdate(String id) async { + var dbClient = await database; + List list = await dbClient + .rawQuery('SELECT never_update FROM PodcastLocal WHERE id = ?', [id]); + if (list.isNotEmpty) return list.first['never_update'] == 1; + return false; + } + + Future saveNeverUpdate(String id, {bool boo}) async { + var dbClient = await database; + return await dbClient.rawUpdate( + "UPDATE PodcastLocal SET never_update = ? WHERE id = ?", + [boo ? 1 : 0, id]); + } + + Future getPodcastUpdateCounts(String id) async { + var dbClient = await database; + List list = await dbClient.rawQuery( + 'SELECt count(*) as count FROM Episodes WHERE feed_id = ? AND is_new = 1', + [id]); + if (list.isNotEmpty) return list.first['count']; + return 0; + } + + Future getSkipSecondsStart(String id) async { + var dbClient = await database; + List list = await dbClient + .rawQuery('SELECT skip_seconds FROM PodcastLocal WHERE id = ?', [id]); + if (list.isNotEmpty) return list.first['skip_seconds']; + return 0; + } + + Future saveSkipSecondsStart(String id, int seconds) async { + var dbClient = await database; + return await dbClient.rawUpdate( + "UPDATE PodcastLocal SET skip_seconds = ? WHERE id = ?", [seconds, id]); + } + + Future getSkipSecondsEnd(String id) async { + var dbClient = await database; + List list = await dbClient.rawQuery( + 'SELECT skip_seconds_end FROM PodcastLocal WHERE id = ?', [id]); + if (list.isNotEmpty) return list.first['skip_seconds_end']; + return 0; + } + + Future saveSkipSecondsEnd(String id, int seconds) async { + var dbClient = await database; + return await dbClient.rawUpdate( + "UPDATE PodcastLocal SET skip_seconds_end = ? WHERE id = ?", + [seconds, id]); + } + + Future getAutoDownload(String id) async { + var dbClient = await database; + List list = await dbClient + .rawQuery('SELECT auto_download FROM PodcastLocal WHERE id = ?', [id]); + if (list.isNotEmpty) return list.first['auto_download'] == 1; + return false; + } + + Future saveAutoDownload(String id, {bool boo}) async { + var dbClient = await database; + return await dbClient.rawUpdate( + "UPDATE PodcastLocal SET auto_download = ? WHERE id = ?", + [boo ? 1 : 0, id]); + } + + Future checkPodcast(String url) async { + var dbClient = await database; + List list = await dbClient + .rawQuery('SELECT id FROM PodcastLocal WHERE rssUrl = ?', [url]); + if (list.isEmpty) return ''; + return list.first['id']; + } + + Future savePodcastLocal(PodcastLocal podcastLocal) async { + var _milliseconds = DateTime.now().millisecondsSinceEpoch; + var dbClient = await database; + await dbClient.transaction((txn) async { + await txn.rawInsert( + """INSERT OR IGNORE INTO PodcastLocal (id, title, imageUrl, rssUrl, + primaryColor, author, description, add_date, imagePath, provider, link) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", + [ + podcastLocal.id, + podcastLocal.title, + podcastLocal.imageUrl, + podcastLocal.rssUrl, + podcastLocal.primaryColor, + podcastLocal.author, + podcastLocal.description, + _milliseconds, + podcastLocal.imagePath, + podcastLocal.provider, + podcastLocal.link + ]); + await txn.rawInsert( + """REPLACE INTO SubscribeHistory(id, title, rss_url, add_date) VALUES (?, ?, ?, ?)""", + [ + podcastLocal.id, + podcastLocal.title, + podcastLocal.rssUrl, + _milliseconds + ]); + }); + } + + Future saveFiresideData(List list) async { + var dbClient = await database; + var result = await dbClient.rawUpdate( + 'UPDATE PodcastLocal SET background_image = ? , hosts = ? WHERE id = ?', + [list[1], list[2], list[0]]); + return result; + } + + Future> getFiresideData(String id) async { + var dbClient = await database; + List list = await dbClient.rawQuery( + 'SELECT background_image, hosts FROM PodcastLocal WHERE id = ?', [id]); + if (list.isNotEmpty) { + var data = [list.first['background_image'], list.first['hosts']]; + return data; + } + return ['', '']; + } + + Future delPodcastLocal(String id) async { + var dbClient = await database; + await dbClient.rawDelete('DELETE FROM PodcastLocal WHERE id =?', [id]); + List list = await dbClient.rawQuery( + """SELECT downloaded FROM Episodes WHERE downloaded != 'ND' AND feed_id = ?""", + [id]); + for (var i in list) { + if (i != null) { + await FlutterDownloader.remove( + taskId: i['downloaded'], shouldDeleteContent: true); + } + } + await dbClient.rawDelete('DELETE FROM Episodes WHERE feed_id=?', [id]); + var milliseconds = DateTime.now().millisecondsSinceEpoch; + await dbClient.rawUpdate( + """UPDATE SubscribeHistory SET remove_date = ? , status = ? WHERE id = ?""", + [milliseconds, 1, id]); + } + + Future saveHistory(PlayHistory history) async { + var dbClient = await database; + final milliseconds = DateTime.now().millisecondsSinceEpoch; + var recent = await getPlayHistory(1); + if (recent.isNotEmpty && recent.first.title == history.title) { + await dbClient.rawDelete("DELETE FROM PlayHistory WHERE add_date = ?", + [recent.first.playdate.millisecondsSinceEpoch]); + } + await dbClient.transaction((txn) async { + return await txn.rawInsert( + """INSERT INTO PlayHistory (title, enclosure_url, seconds, seek_value, add_date, listen_time) + VALUES (?, ?, ?, ?, ?, ?) """, + [ + history.title, + history.url, + history.seconds, + history.seekValue, + milliseconds, + history.seekValue > 0.95 ? 1 : 0 + ]); + }); + } + + Future> getPlayHistory(int top) async { + var dbClient = await database; + List list = await dbClient.rawQuery( + """SELECT title, enclosure_url, seconds, seek_value, add_date FROM PlayHistory + ORDER BY add_date DESC LIMIT ? + """, [top]); + var playHistory = []; + for (var record in list) { + playHistory.add(PlayHistory(record['title'], record['enclosure_url'], + (record['seconds']).toInt(), record['seek_value'], + playdate: DateTime.fromMillisecondsSinceEpoch(record['add_date']))); + } + return playHistory; + } + + /// History list in playlist page, not include marked episdoes. + Future> getPlayRecords(int top) async { + var dbClient = await database; + List list = await dbClient.rawQuery( + """SELECT title, enclosure_url, seconds, seek_value, add_date FROM PlayHistory + WHERE seconds != 0 ORDER BY add_date DESC LIMIT ? + """, [top]); + var playHistory = []; + for (var record in list) { + playHistory.add(PlayHistory(record['title'], record['enclosure_url'], + (record['seconds']).toInt(), record['seek_value'], + playdate: DateTime.fromMillisecondsSinceEpoch(record['add_date']))); + } + return playHistory; + } + + Future isListened(String url) async { + var dbClient = await database; + var i = 0; + List list = await dbClient.rawQuery( + "SELECT SUM(listen_time) FROM PlayHistory WHERE enclosure_url = ?", + [url]); + if (list.isNotEmpty) { + i = list.first['SUM(listen_time)']; + return i ?? 0; + } + return 0; + } + + Future markNotListened(String url) async { + var dbClient = await database; + int count; + await dbClient.transaction((txn) async { + count = await txn.rawUpdate( + "UPDATE OR IGNORE PlayHistory SET listen_time = 0 WHERE enclosure_url = ?", + [url]); + }); + await dbClient.rawDelete( + 'DELETE FROM PlayHistory WHERE enclosure_url=? ' + 'AND listen_time = 0 AND seconds = 0', + [url]); + return count; + } + + Future> getSubHistory() async { + var dbClient = await database; + List list = await dbClient.rawQuery( + """SELECT title, rss_url, add_date, remove_date, status FROM SubscribeHistory + ORDER BY add_date DESC"""); + return list + .map((record) => SubHistory( + record['status'] == 0 ? true : false, + DateTime.fromMillisecondsSinceEpoch(record['remove_date']), + DateTime.fromMillisecondsSinceEpoch(record['add_date']), + record['rss_url'], + record['title'])) + .toList(); + } + + Future listenMins(int day) async { + var dbClient = await database; + var now = DateTime.now(); + var start = DateTime(now.year, now.month, now.day) + .subtract(Duration(days: day)) + .millisecondsSinceEpoch; + var end = DateTime(now.year, now.month, now.day) + .subtract(Duration(days: (day - 1))) + .millisecondsSinceEpoch; + List list = await dbClient.rawQuery( + "SELECT seconds FROM PlayHistory WHERE add_date > ? AND add_date < ?", + [start, end]); + var sum = 0.0; + if (list.isEmpty) { + sum = 0.0; + } else { + for (var record in list) { + sum += record['seconds']; + } + } + return (sum ~/ 60).toDouble(); + } + + Future getPosition(EpisodeBrief episodeBrief) async { + var dbClient = await database; + List list = await dbClient.rawQuery( + """SELECT title, enclosure_url, seconds, seek_value, add_date FROM PlayHistory + WHERE enclosure_url = ? ORDER BY add_date DESC LIMIT 1""", + [episodeBrief.enclosureUrl]); + return list.isNotEmpty + ? PlayHistory(list.first['title'], list.first['enclosure_url'], + (list.first['seconds']).toInt(), list.first['seek_value'], + playdate: + DateTime.fromMillisecondsSinceEpoch(list.first['add_date'])) + : PlayHistory(episodeBrief.title, episodeBrief.enclosureUrl, 0, 0); + } + + /// Check if episode was marked listend. + Future checkMarked(EpisodeBrief episodeBrief) async { + var dbClient = await database; + List list = await dbClient.rawQuery( + """SELECT title, enclosure_url, seconds, seek_value, add_date FROM PlayHistory + WHERE enclosure_url = ? AND seek_value = 1 ORDER BY add_date DESC LIMIT 1""", + [episodeBrief.enclosureUrl]); + return list.isNotEmpty; + } + + DateTime _parsePubDate(String pubDate) { + if (pubDate == null) return DateTime.now(); + DateTime date; + var yyyy = RegExp(r'[1-2][0-9]{3}'); + var hhmm = RegExp(r'[0-2][0-9]\:[0-5][0-9]'); + var ddmmm = RegExp(r'[0-3][0-9]\s[A-Z][a-z]{2}'); + var mmDd = RegExp(r'([1-2][0-9]{3}\-[0-1]|\s)[0-9]\-[0-3][0-9]'); + // RegExp timezone + var z = RegExp(r'(\+|\-)[0-1][0-9]00'); + var timezone = z.stringMatch(pubDate); + var timezoneInt = 0; + if (timezone != null) { + if (timezone.substring(0, 1) == '-') { + timezoneInt = int.parse(timezone.substring(1, 2)); + } else { + timezoneInt = -int.parse(timezone.substring(1, 2)); + } + } + try { + date = DateFormat('EEE, dd MMM yyyy HH:mm:ss Z', 'en_US').parse(pubDate); + } catch (e) { + try { + date = DateFormat('dd MMM yyyy HH:mm:ss Z', 'en_US').parse(pubDate); + } catch (e) { + try { + date = DateFormat('EEE, dd MMM yyyy HH:mm Z', 'en_US').parse(pubDate); + } catch (e) { + var year = yyyy.stringMatch(pubDate); + var time = hhmm.stringMatch(pubDate); + var month = ddmmm.stringMatch(pubDate); + if (year != null && time != null && month != null) { + try { + date = DateFormat('dd MMM yyyy HH:mm', 'en_US') + .parse('$month $year $time'); + } catch (e) { + date = DateTime.now(); + } + } else if (year != null && time != null && month == null) { + var month = mmDd.stringMatch(pubDate); + try { + date = + DateFormat('yyyy-MM-dd HH:mm', 'en_US').parse('$month $time'); + } catch (e) { + date = DateTime.now(); + } + } else { + date = DateTime.now(); + } + } + } + } + date.add(Duration(hours: timezoneInt)).add(DateTime.now().timeZoneOffset); + developer.log(date.toString()); + return date; + } + + int _getExplicit(bool b) { + int result; + if (b == true) { + result = 1; + return result; + } else { + result = 0; + return result; + } + } + + bool _isXimalaya(String input) { + var ximalaya = RegExp(r"ximalaya.com"); + return ximalaya.hasMatch(input); + } + + String _getDescription(String content, String description, String summary) { + if (content.length >= description.length) { + if (content.length >= summary.length) { + return content; + } else { + return summary; + } + } else if (description.length >= summary.length) { + return description; + } else { + return summary; + } + } + + Future savePodcastRss(RssFeed feed, String id) async { + feed.items.removeWhere((item) => item == null); + var result = feed.items.length; + var dbClient = await database; + String description, url; + for (var i = 0; i < result; i++) { + developer.log(feed.items[i].title); + description = _getDescription(feed.items[i]?.content?.value ?? '', + feed.items[i].description ?? '', feed.items[i].itunes.summary ?? ''); + if (feed.items[i].enclosure != null) { + _isXimalaya(feed.items[i].enclosure.url) + ? url = feed.items[i].enclosure.url.split('=').last + : url = feed.items[i].enclosure.url; + } + + final title = feed.items[i].itunes.title ?? feed.items[i].title; + final length = feed.items[i]?.enclosure?.length; + final pubDate = feed.items[i].pubDate; + final date = _parsePubDate(pubDate); + final milliseconds = date.millisecondsSinceEpoch; + final duration = feed.items[i].itunes.duration?.inSeconds ?? 0; + final explicit = _getExplicit(feed.items[i].itunes.explicit); + + if (url != null) { + await dbClient.transaction((txn) { + return txn.rawInsert( + """INSERT OR REPLACE INTO Episodes(title, enclosure_url, enclosure_length, pubDate, + description, feed_id, milliseconds, duration, explicit, media_id) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", + [ + title, + url, + length, + pubDate, + description, + id, + milliseconds, + duration, + explicit, + url + ]); + }); + } + } + var countUpdate = Sqflite.firstIntValue(await dbClient + .rawQuery('SELECT COUNT(*) FROM Episodes WHERE feed_id = ?', [id])); + + await dbClient.rawUpdate( + """UPDATE PodcastLocal SET episode_count = ? WHERE id = ?""", + [countUpdate, id]); + return result; + } + + Future updatePodcastRss(PodcastLocal podcastLocal, + {int removeMark = 0}) async { + var options = BaseOptions( + connectTimeout: 20000, + receiveTimeout: 20000, + ); + try { + var response = await Dio(options).get(podcastLocal.rssUrl); + if (response.statusCode == 200) { + var feed = RssFeed.parse(response.data); + String url, description; + feed.items.removeWhere((item) => item == null); + + var dbClient = await database; + var count = Sqflite.firstIntValue(await dbClient.rawQuery( + 'SELECT COUNT(*) FROM Episodes WHERE feed_id = ?', + [podcastLocal.id])); + if (removeMark == 0) { + await dbClient.rawUpdate( + "UPDATE Episodes SET is_new = 0 WHERE feed_id = ?", + [podcastLocal.id]); + } + for (var item in feed.items) { + developer.log(item.title); + description = _getDescription(item.content.value ?? '', + item.description ?? '', item.itunes.summary ?? ''); + + if (item.enclosure?.url != null) { + _isXimalaya(item.enclosure.url) + ? url = item.enclosure.url.split('=').last + : url = item.enclosure.url; + } + + final title = item.itunes.title ?? item.title; + final length = item?.enclosure?.length ?? 0; + final pubDate = item.pubDate; + final date = _parsePubDate(pubDate); + final milliseconds = date.millisecondsSinceEpoch; + final duration = item.itunes.duration?.inSeconds ?? 0; + final explicit = _getExplicit(item.itunes.explicit); + + if (url != null) { + await dbClient.transaction((txn) async { + await txn.rawInsert( + """INSERT OR IGNORE INTO Episodes(title, enclosure_url, enclosure_length, pubDate, + description, feed_id, milliseconds, duration, explicit, media_id, is_new) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)""", + [ + title, + url, + length, + pubDate, + description, + podcastLocal.id, + milliseconds, + duration, + explicit, + url, + ]); + }); + } + } + var countUpdate = Sqflite.firstIntValue(await dbClient.rawQuery( + 'SELECT COUNT(*) FROM Episodes WHERE feed_id = ?', + [podcastLocal.id])); + + await dbClient.rawUpdate( + """UPDATE PodcastLocal SET update_count = ?, episode_count = ? WHERE id = ?""", + [countUpdate - count, countUpdate, podcastLocal.id]); + return countUpdate - count; + } + return 0; + } catch (e) { + developer.log(e.toString(), name: 'Update podcast error'); + return -1; + } + } + + Future> getRssItem(String id, int count, + {bool reverse, + Filter filter = Filter.all, + String query = '', + bool hideListened = false}) async { + var dbClient = await database; + var episodes = []; + var list = []; + if (hideListened) { + if (count == -1) { + if (reverse) { + switch (filter) { + case Filter.all: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url + WHERE P.id = ? GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null + OR SUM(H.listen_time) = 0 ORDER BY E.milliseconds ASC""", [id]); + break; + case Filter.liked: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE P.id = ? AND E.liked = 1 ORDER BY E.milliseconds ASC""", [id]); + break; + case Filter.downloaded: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE P.id = ? AND E.media_id != E.enclosure_url ORDER BY E.milliseconds ASC""", + [id]); + break; + case Filter.search: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE P.id = ? AND E.title LIKE ? ORDER BY E.milliseconds ASC""", + [id, '%$query%']); + break; + default: + } + } else { + switch (filter) { + case Filter.all: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url + WHERE P.id = ? GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null + OR SUM(H.listen_time) = 0 ORDER BY E.milliseconds DESC""", [id]); + break; + case Filter.liked: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE P.id = ? AND E.liked = 1 ORDER BY E.milliseconds DESC""", [id]); + break; + case Filter.downloaded: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE P.id = ? AND E.media_id != E.enclosure_url ORDER BY E.milliseconds DESC""", + [id]); + break; + case Filter.search: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE P.id = ? AND E.title LIKE ? ORDER BY E.milliseconds DESC""", + [id, '%$query%']); + break; + default: + } + } + } else if (reverse) { + switch (filter) { + case Filter.all: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url + WHERE P.id = ? GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null + OR SUM(H.listen_time) = 0 ORDER BY E.milliseconds ASC LIMIT ?""", + [id, count]); + break; + case Filter.liked: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url + WHERE P.id = ? AND E.liked = 1 GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null + OR SUM(H.listen_time) = 0 ORDER BY E.milliseconds ASC LIMIT ?""", + [id, count]); + break; + case Filter.downloaded: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url + WHERE P.id = ? AND E.enclosure_url != E.media_id + GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null + OR SUM(H.listen_time) = 0 ORDER BY E.milliseconds ASC LIMIT ?""", + [id, count]); + break; + case Filter.search: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url + WHERE P.id = ? AND E.title LIKE ? GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null + OR SUM(H.listen_time) = 0 ORDER BY E.milliseconds ASC LIMIT ?""", + [id, '%$query%', count]); + break; + default: + } + } else { + switch (filter) { + case Filter.all: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url + WHERE P.id = ? GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null + OR SUM(H.listen_time) = 0 ORDER BY E.milliseconds DESC LIMIT ?""", + [id, count]); + break; + case Filter.liked: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url + WHERE P.id = ? AND E.liked = 1 GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null + OR SUM(H.listen_time) = 0 ORDER BY E.milliseconds DESC LIMIT ?""", + [id, count]); + break; + case Filter.downloaded: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url + WHERE P.id = ? AND E.enclosure_url != E.media_id GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null + OR SUM(H.listen_time) = 0 ORDER BY E.milliseconds DESC LIMIT ?""", + [id, count]); + break; + case Filter.search: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url + WHERE P.id = ? AND E.title LIKE ? GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null + OR SUM(H.listen_time) = 0 ORDER BY E.milliseconds DESC LIMIT ?""", + [id, '%$query%', count]); + break; + default: + } + } + } else { + if (count == -1) { + if (reverse) { + switch (filter) { + case Filter.all: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE P.id = ? ORDER BY E.milliseconds ASC""", [id]); + break; + case Filter.liked: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE P.id = ? AND E.liked = 1 ORDER BY E.milliseconds ASC""", [id]); + break; + case Filter.downloaded: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE P.id = ? AND E.media_id != E.enclosure_url ORDER BY E.milliseconds ASC""", + [id]); + break; + case Filter.search: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE P.id = ? AND E.title LIKE ? ORDER BY E.milliseconds ASC""", + [id, '%$query%']); + break; + default: + } + } else { + switch (filter) { + case Filter.all: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE P.id = ? ORDER BY E.milliseconds DESC""", [id]); + break; + case Filter.liked: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE P.id = ? AND E.liked = 1 ORDER BY E.milliseconds DESC""", [id]); + break; + case Filter.downloaded: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE P.id = ? AND E.media_id != E.enclosure_url ORDER BY E.milliseconds DESC""", + [id]); + break; + case Filter.search: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE P.id = ? AND E.title LIKE ? ORDER BY E.milliseconds DESC""", + [id, '%$query%']); + break; + default: + } + } + } else if (reverse) { + switch (filter) { + case Filter.all: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE P.id = ? ORDER BY E.milliseconds ASC LIMIT ?""", [id, count]); + break; + case Filter.liked: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE P.id = ? AND E.liked = 1 ORDER BY E.milliseconds ASC LIMIT ?""", + [id, count]); + break; + case Filter.downloaded: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE P.id = ? AND E.enclosure_url != E.media_id ORDER BY E.milliseconds ASC LIMIT ?""", + [id, count]); + break; + case Filter.search: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE P.id = ? AND E.title LIKE ? ORDER BY E.milliseconds ASC LIMIT ?""", + [id, '%$query%', count]); + break; + default: + } + } else { + switch (filter) { + case Filter.all: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE P.id = ? ORDER BY E.milliseconds DESC LIMIT ?""", [id, count]); + break; + case Filter.liked: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE P.id = ? AND E.liked = 1 ORDER BY E.milliseconds DESC LIMIT ?""", + [id, count]); + break; + case Filter.downloaded: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE P.id = ? AND E.enclosure_url != E.media_id ORDER BY E.milliseconds DESC LIMIT ?""", + [id, count]); + break; + case Filter.search: + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE P.id = ? AND E.title LIKE ? ORDER BY E.milliseconds DESC LIMIT ?""", + [id, '%$query%', count]); + break; + default: + } + } + } + + if (list.isNotEmpty) { + for (var i in list) { + episodes.add(EpisodeBrief( + i['title'], + i['enclosure_url'], + i['enclosure_length'], + i['milliseconds'], + i['feed_title'], + i['primaryColor'], + i['duration'], + i['explicit'], + i['imagePath'], + i['is_new'])); + } + } + return episodes; + } + + Future> getNewEpisodes(String id) async { + var dbClient = await database; + var episodes = []; + List list; + if (id == 'all') { + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE E.is_new = 1 AND E.downloaded = 'ND' AND P.auto_download = 1 ORDER BY E.milliseconds ASC""", + ); + } else { + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE E.is_new = 1 AND E.downloaded = 'ND' AND E.feed_id = ? ORDER BY E.milliseconds ASC""", + [id]); + } + if (list.isNotEmpty) { + for (var i in list) { + episodes.add(EpisodeBrief( + i['title'], + i['enclosure_url'], + i['enclosure_length'], + i['milliseconds'], + i['feed_title'], + i['primaryColor'], + i['duration'], + i['explicit'], + i['imagePath'], + i['is_new'])); + } + } + return episodes; + } + + Future> getRssItemTop(String id) async { + var dbClient = await database; + var episodes = []; + List list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, + E.milliseconds, P.imagePath, P.title as feed_title, E.duration, E.explicit, + P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + where E.feed_id = ? ORDER BY E.milliseconds DESC LIMIT 2""", [id]); + for (var i in list) { + episodes.add(EpisodeBrief( + i['title'], + i['enclosure_url'], + i['enclosure_length'], + i['milliseconds'], + i['feed_title'], + i['primaryColor'], + i['duration'], + i['explicit'], + i['imagePath'], + i['is_new'])); + } + return episodes; + } + + Future> getRecentRssItem(int top, + {bool hideListened = false}) async { + var dbClient = await database; + var episodes = []; + var list = []; + if (hideListened) { + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, + E.milliseconds, P.title as feed_title, E.duration, E.explicit, + P.imagePath, P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url + GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null + OR SUM(H.listen_time) = 0 ORDER BY E.milliseconds DESC LIMIT ? """, + [top]); + } else { + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, + E.milliseconds, P.title as feed_title, E.duration, E.explicit, + P.imagePath, P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + ORDER BY E.milliseconds DESC LIMIT ? """, [top]); + } + if (list.isNotEmpty) { + for (var i in list) { + episodes.add(EpisodeBrief( + i['title'], + i['enclosure_url'], + i['enclosure_length'], + i['milliseconds'], + i['feed_title'], + i['primaryColor'], + i['duration'], + i['explicit'], + i['imagePath'], + i['is_new'])); + } + } + return episodes; + } + + Future> getGroupRssItem(int top, List group, + {bool hideListened = false}) async { + var dbClient = await database; + var episodes = []; + if (group.length > 0) { + var s = group.map((e) => "'$e'").toList(); + var list = []; + if (hideListened) { + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, + E.milliseconds, P.title as feed_title, E.duration, E.explicit, + P.imagePath, P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url + WHERE P.id in (${s.join(',')}) GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null + OR SUM(H.listen_time) = 0 ORDER BY E.milliseconds DESC LIMIT ? """, + [top]); + } else { + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, + E.milliseconds, P.title as feed_title, E.duration, E.explicit, + P.imagePath, P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE P.id in (${s.join(',')}) + ORDER BY E.milliseconds DESC LIMIT ? """, [top]); + } + if (list.isNotEmpty) { + for (var i in list) { + episodes.add(EpisodeBrief( + i['title'], + i['enclosure_url'], + i['enclosure_length'], + i['milliseconds'], + i['feed_title'], + i['primaryColor'], + i['duration'], + i['explicit'], + i['imagePath'], + i['is_new'])); + } + } + } + return episodes; + } + + Future> getRecentNewRssItem() async { + var dbClient = await database; + var episodes = []; + List list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, E.media_id, + E.milliseconds, P.title as feed_title, E.duration, E.explicit, + P.imagePath, P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE is_new = 1 ORDER BY E.milliseconds DESC """, + ); + for (var i in list) { + episodes.add(EpisodeBrief( + i['title'], + i['enclosure_url'], + i['enclosure_length'], + i['milliseconds'], + i['feed_title'], + i['primaryColor'], + i['duration'], + i['explicit'], + i['imagePath'], + i['is_new'], + mediaId: i['media_id'])); + } + return episodes; + } + + Future> getOutdatedEpisode(int deadline, + {bool deletePlayed}) async { + var dbClient = await database; + var episodes = []; + List list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, + E.milliseconds, P.title as feed_title, E.duration, E.explicit, + P.imagePath, P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE E.download_date < ? AND E.enclosure_url != E.media_id + ORDER BY E.milliseconds DESC""", [deadline]); + if (list.isNotEmpty) { + for (var i in list) { + episodes.add(EpisodeBrief( + i['title'], + i['enclosure_url'], + i['enclosure_length'], + i['milliseconds'], + i['feed_title'], + i['primaryColor'], + i['duration'], + i['explicit'], + i['imagePath'], + i['is_new'])); + } + } + if (deletePlayed) { + List results = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, + E.milliseconds, P.title as feed_title, E.duration, E.explicit, + P.imagePath, P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P + ON E.feed_id = P.id LEFT JOIN PlayHistory H ON E.enclosure_url = + H.enclosure_url WHERE E.enclosure_url != E.media_id + GROUP BY E.enclosure_url HAVING SUM(H.listen_time) > 0 ORDER BY + E.milliseconds DESC"""); + if (results.isNotEmpty) { + for (var i in results) { + episodes.add(EpisodeBrief( + i['title'], + i['enclosure_url'], + i['enclosure_length'], + i['milliseconds'], + i['feed_title'], + i['primaryColor'], + i['duration'], + i['explicit'], + i['imagePath'], + i['is_new'])); + } + } + } + return episodes.toSet().toList(); + } + + Future> getDownloadedEpisode(int mode, + {bool hideListened = false}) async { + var dbClient = await database; + var episodes = []; + List list; + if (hideListened) { + if (mode == 0) { + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, E.download_date, E.is_new, + E.milliseconds, P.title as feed_title, E.duration, E.explicit, + P.imagePath, P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url + WHERE E.enclosure_url != E.media_id GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null + OR SUM(H.listen_time) = 0 ORDER BY E.download_date DESC""", + ); + } else if (mode == 1) { + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, E.download_date,E.is_new, + E.milliseconds, P.title as feed_title, E.duration, E.explicit, + P.imagePath, P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url + WHERE E.enclosure_url != E.media_id GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null + OR SUM(H.listen_time) = 0 ORDER BY E.download_date ASC""", + ); + } else if (mode == 2) { + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, E.download_date,E.is_new, + E.milliseconds, P.title as feed_title, E.duration, E.explicit, + P.imagePath, P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url + WHERE E.enclosure_url != E.media_id GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null + OR SUM(H.listen_time) = 0 ORDER BY E.enclosure_length DESC""", + ); + } + } else //Ordered by date + { + if (mode == 0) { + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, E.download_date, E.is_new, + E.milliseconds, P.title as feed_title, E.duration, E.explicit, + P.imagePath, P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE E.enclosure_url != E.media_id + ORDER BY E.download_date DESC""", + ); + } else if (mode == 1) { + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, E.download_date,E.is_new, + E.milliseconds, P.title as feed_title, E.duration, E.explicit, + P.imagePath, P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE E.enclosure_url != E.media_id + ORDER BY E.download_date ASC""", + ); + } else if (mode == 2) { + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, E.download_date,E.is_new, + E.milliseconds, P.title as feed_title, E.duration, E.explicit, + P.imagePath, P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE E.enclosure_url != E.media_id + ORDER BY E.enclosure_length DESC""", + ); + } + } + if (list.isNotEmpty) { + for (var i in list) { + episodes.add(EpisodeBrief( + i['title'], + i['enclosure_url'], + i['enclosure_length'], + i['milliseconds'], + i['feed_title'], + i['primaryColor'], + i['duration'], + i['explicit'], + i['imagePath'], + i['is_new'], + downloadDate: i['download_date'])); + } + } + return episodes; + } + + Future removeAllNewMark() async { + var dbClient = await database; + await dbClient.transaction((txn) async { + await txn.rawUpdate("UPDATE Episodes SET is_new = 0 "); + }); + } + + Future> getGroupNewRssItem(List group) async { + var dbClient = await database; + var episodes = []; + if (group.length > 0) { + var s = group.map((e) => "'$e'").toList(); + List list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, E.is_new, E.media_id, + E.milliseconds, P.title as feed_title, E.duration, E.explicit, + P.imagePath, P.primaryColor FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE P.id in (${s.join(',')}) AND is_new = 1 + ORDER BY E.milliseconds DESC""", + ); + for (var i in list) { + episodes.add(EpisodeBrief( + i['title'], + i['enclosure_url'], + i['enclosure_length'], + i['milliseconds'], + i['feed_title'], + i['primaryColor'], + i['duration'], + i['explicit'], + i['imagePath'], + i['is_new'], + mediaId: i['media_id'])); + } + } + return episodes; + } + + Future removeGroupNewMark(List group) async { + var dbClient = await database; + if (group.length > 0) { + var s = group.map((e) => "'$e'").toList(); + await dbClient.transaction((txn) async { + await txn.rawUpdate( + "UPDATE Episodes SET is_new = 0 WHERE feed_id in (${s.join(',')})"); + }); + } + } + + Future removeEpisodeNewMark(String url) async { + var dbClient = await database; + await dbClient.transaction((txn) async { + await txn.rawUpdate( + "UPDATE Episodes SET is_new = 0 WHERE enclosure_url = ?", [url]); + }); + developer.log('remove new episode $url'); + } + + Future> getLikedRssItem(int i, int sortBy, + {bool hideListened = false}) async { + var dbClient = await database; + var episodes = []; + var list = []; + if (hideListened) { + if (sortBy == 0) { + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, E.milliseconds, P.imagePath, + P.title as feed_title, E.duration, E.explicit, P.primaryColor, E.is_new + FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url + WHERE E.liked = 1 GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null + OR SUM(H.listen_time) = 0 ORDER BY E.milliseconds DESC LIMIT ?""", [i]); + } else { + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, E.milliseconds, P.imagePath, + P.title as feed_title, E.duration, E.explicit, P.primaryColor, E.is_new + FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + LEFT JOIN PlayHistory H ON E.enclosure_url = H.enclosure_url + WHERE E.liked = 1 GROUP BY E.enclosure_url HAVING SUM(H.listen_time) is null + OR SUM(H.listen_time) = 0 ORDER BY E.liked_date DESC LIMIT ?""", [i]); + } + } else { + if (sortBy == 0) { + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, E.milliseconds, P.imagePath, + P.title as feed_title, E.duration, E.explicit, P.primaryColor, E.is_new + FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE E.liked = 1 ORDER BY E.milliseconds DESC LIMIT ?""", [i]); + } else { + list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, E.milliseconds, P.imagePath, + P.title as feed_title, E.duration, E.explicit, P.primaryColor, E.is_new + FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE E.liked = 1 ORDER BY E.liked_date DESC LIMIT ?""", [i]); + } + } + if (list.isNotEmpty) { + for (var i in list) { + episodes.add(EpisodeBrief( + i['title'], + i['enclosure_url'], + i['enclosure_length'], + i['milliseconds'], + i['feed_title'], + i['primaryColor'], + i['duration'], + i['explicit'], + i['imagePath'], + i['is_new'])); + } + } + + return episodes; + } + + Future setLiked(String url) async { + var dbClient = await database; + var milliseconds = DateTime.now().millisecondsSinceEpoch; + await dbClient.transaction((txn) async { + await txn.rawUpdate( + "UPDATE Episodes SET liked = 1, liked_date = ? WHERE enclosure_url= ?", + [milliseconds, url]); + }); + } + + Future setUniked(String url) async { + var dbClient = await database; + await dbClient.transaction((txn) async { + await txn.rawUpdate( + "UPDATE Episodes SET liked = 0 WHERE enclosure_url = ?", [url]); + }); + } + + Future isLiked(String url) async { + var dbClient = await database; + var list = []; + list = await dbClient + .rawQuery("SELECT liked FROM Episodes WHERE enclosure_url = ?", [url]); + if (list.isNotEmpty) { + return list.first['liked'] == 0 ? false : true; + } + return false; + } + + Future isDownloaded(String url) async { + var dbClient = await database; + List list = await dbClient.rawQuery( + "SELECT id FROM Episodes WHERE enclosure_url = ? AND enclosure_url != media_id", + [url]); + return list.isNotEmpty; + } + + Future saveDownloaded(String url, String id) async { + var dbClient = await database; + var milliseconds = DateTime.now().millisecondsSinceEpoch; + int count; + await dbClient.transaction((txn) async { + count = await txn.rawUpdate( + "UPDATE Episodes SET downloaded = ?, download_date = ? WHERE enclosure_url = ?", + [id, milliseconds, url]); + }); + return count; + } + + Future saveMediaId(String url, String path, String id, int size) async { + var dbClient = await database; + var milliseconds = DateTime.now().millisecondsSinceEpoch; + int count; + await dbClient.transaction((txn) async { + count = await txn.rawUpdate( + "UPDATE Episodes SET enclosure_length = ?, media_id = ?, download_date = ?, downloaded = ? WHERE enclosure_url = ?", + [size, path, milliseconds, id, url]); + }); + return count; + } + + Future delDownloaded(String url) async { + var dbClient = await database; + int count; + await dbClient.transaction((txn) async { + count = await txn.rawUpdate( + "UPDATE Episodes SET downloaded = 'ND', media_id = ? WHERE enclosure_url = ?", + [url, url]); + }); + developer.log('Deleted $url'); + return count; + } + + Future getDescription(String url) async { + var dbClient = await database; + List list = await dbClient.rawQuery( + 'SELECT description FROM Episodes WHERE enclosure_url = ?', [url]); + String description = list[0]['description']; + return description; + } + + Future saveEpisodeDes(String url, {String description}) async { + var dbClient = await database; + await dbClient.transaction((txn) async { + await txn.rawUpdate( + "UPDATE Episodes SET description = ? WHERE enclosure_url = ?", + [description, url]); + }); + } + + Future getFeedDescription(String id) async { + var dbClient = await database; + List list = await dbClient + .rawQuery('SELECT description FROM PodcastLocal WHERE id = ?', [id]); + String description = list[0]['description']; + return description; + } + + Future getRssItemWithUrl(String url) async { + var dbClient = await database; + EpisodeBrief episode; + List list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, E.milliseconds, P.imagePath, + P.title as feed_title, E.duration, E.explicit, P.skip_seconds, P.skip_seconds_end, + E.is_new, P.primaryColor, E.media_id FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE E.enclosure_url = ?""", [url]); + if (list.isEmpty) { + return null; + } else { + episode = EpisodeBrief( + list.first['title'], + list.first['enclosure_url'], + list.first['enclosure_length'], + list.first['milliseconds'], + list.first['feed_title'], + list.first['primaryColor'], + list.first['duration'], + list.first['explicit'], + list.first['imagePath'], + list.first['is_new'], + mediaId: list.first['media_id'], + skipSecondsStart: list.first['skip_seconds'], + skipSecondsEnd: list.first['skip_seconds_end']); + return episode; + } + } + + Future getRssItemWithMediaId(String id) async { + var dbClient = await database; + EpisodeBrief episode; + List list = await dbClient.rawQuery( + """SELECT E.title, E.enclosure_url, E.enclosure_length, E.milliseconds, P.imagePath, + P.title as feed_title, E.duration, E.explicit, P.skip_seconds, P.skip_seconds_end, + E.is_new, P.primaryColor, E.media_id FROM Episodes E INNER JOIN + PodcastLocal P ON E.feed_id = P.id WHERE E.media_id = ?""", [id]); + if (list.isEmpty) { + return null; + } else { + episode = EpisodeBrief( + list.first['title'], + list.first['enclosure_url'], + list.first['enclosure_length'], + list.first['milliseconds'], + list.first['feed_title'], + list.first['primaryColor'], + list.first['duration'], + list.first['explicit'], + list.first['imagePath'], + list.first['is_new'], + mediaId: list.first['media_id'], + skipSecondsStart: list.first['skip_seconds'], + skipSecondsEnd: list.first['skip_seconds_end']); + return episode; + } + } + + Future getImageUrl(String url) async { + var dbClient = await database; + List list = await dbClient.rawQuery( + """SELECT P.imageUrl FROM Episodes E INNER JOIN PodcastLocal P ON E.feed_id = P.id + WHERE E.enclosure_url = ?""", [url]); + if (list.isEmpty) return null; + return list.first["imageUrl"]; + } +} diff --git a/lib/podcasts/custom_tabview.dart b/lib/podcasts/custom_tabview.dart index 8ba248a..8c68ff0 100644 --- a/lib/podcasts/custom_tabview.dart +++ b/lib/podcasts/custom_tabview.dart @@ -1,146 +1,146 @@ -import 'package:flutter/material.dart'; - -class CustomTabView extends StatefulWidget { - final int itemCount; - final IndexedWidgetBuilder tabBuilder; - final IndexedWidgetBuilder pageBuilder; - final ValueChanged onPositionChange; - final ValueChanged onScroll; - final int initPosition; - - CustomTabView({ - @required this.itemCount, - @required this.tabBuilder, - @required this.pageBuilder, - this.onPositionChange, - this.onScroll, - this.initPosition, - }); - - @override - _CustomTabsState createState() => _CustomTabsState(); -} - -class _CustomTabsState extends State - with TickerProviderStateMixin { - TabController controller; - int _currentCount; - int _currentPosition; - - @override - void initState() { - _currentPosition = widget.initPosition ?? 0; - controller = TabController( - length: widget.itemCount, - vsync: this, - initialIndex: _currentPosition, - ); - controller.addListener(onPositionChange); - controller.animation.addListener(onScroll); - _currentCount = widget.itemCount; - super.initState(); - } - - @override - void didUpdateWidget(CustomTabView oldWidget) { - if (_currentCount != widget.itemCount) { - controller.animation.removeListener(onScroll); - controller.removeListener(onPositionChange); - controller.dispose(); - - if (widget.initPosition != null) { - _currentPosition = widget.initPosition; - } - - if (_currentPosition > widget.itemCount - 1) { - _currentPosition = widget.itemCount - 1; - _currentPosition = _currentPosition < 0 ? 0 : _currentPosition; - if (widget.onPositionChange is ValueChanged) { - WidgetsBinding.instance.addPostFrameCallback((_) { - if (mounted) { - widget.onPositionChange(_currentPosition); - } - }); - } - } - - _currentCount = widget.itemCount; - setState(() { - controller = TabController( - length: widget.itemCount, - vsync: this, - initialIndex: _currentPosition, - ); - controller.addListener(onPositionChange); - controller.animation.addListener(onScroll); - }); - } else if (widget.initPosition != null) { - controller.animateTo(widget.initPosition); - } - - super.didUpdateWidget(oldWidget); - } - - @override - void dispose() { - controller.animation.removeListener(onScroll); - controller.removeListener(onPositionChange); - controller.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Container( - alignment: Alignment.centerLeft, - height: 50.0, - padding: EdgeInsets.all(10.0), - child: TabBar( - indicatorSize: TabBarIndicatorSize.label, - labelPadding: EdgeInsets.symmetric(horizontal: 5.0), - indicatorPadding: EdgeInsets.symmetric(horizontal: 5.0), - isScrollable: true, - controller: controller, - labelColor: Colors.white, - unselectedLabelColor: Colors.grey[700], - indicator: BoxDecoration( - borderRadius: BorderRadius.all(Radius.circular(15)), - color: Theme.of(context).accentColor, - ), - tabs: List.generate( - widget.itemCount, - (index) => widget.tabBuilder(context, index), - ), - ), - ), - Expanded( - child: TabBarView( - controller: controller, - children: List.generate( - widget.itemCount, - (index) => widget.pageBuilder(context, index), - ), - ), - ), - ], - ); - } - - onPositionChange() { - if (!controller.indexIsChanging) { - _currentPosition = controller.index; - if (widget.onPositionChange is ValueChanged) { - widget.onPositionChange(_currentPosition); - } - } - } - - onScroll() { - if (widget.onScroll is ValueChanged) { - widget.onScroll(controller.animation.value); - } - } -} +import 'package:flutter/material.dart'; + +class CustomTabView extends StatefulWidget { + final int itemCount; + final IndexedWidgetBuilder tabBuilder; + final IndexedWidgetBuilder pageBuilder; + final ValueChanged onPositionChange; + final ValueChanged onScroll; + final int initPosition; + + CustomTabView({ + @required this.itemCount, + @required this.tabBuilder, + @required this.pageBuilder, + this.onPositionChange, + this.onScroll, + this.initPosition, + }); + + @override + _CustomTabsState createState() => _CustomTabsState(); +} + +class _CustomTabsState extends State + with TickerProviderStateMixin { + TabController controller; + int _currentCount; + int _currentPosition; + + @override + void initState() { + _currentPosition = widget.initPosition ?? 0; + controller = TabController( + length: widget.itemCount, + vsync: this, + initialIndex: _currentPosition, + ); + controller.addListener(onPositionChange); + controller.animation.addListener(onScroll); + _currentCount = widget.itemCount; + super.initState(); + } + + @override + void didUpdateWidget(CustomTabView oldWidget) { + if (_currentCount != widget.itemCount) { + controller.animation.removeListener(onScroll); + controller.removeListener(onPositionChange); + controller.dispose(); + + if (widget.initPosition != null) { + _currentPosition = widget.initPosition; + } + + if (_currentPosition > widget.itemCount - 1) { + _currentPosition = widget.itemCount - 1; + _currentPosition = _currentPosition < 0 ? 0 : _currentPosition; + if (widget.onPositionChange is ValueChanged) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { + widget.onPositionChange(_currentPosition); + } + }); + } + } + + _currentCount = widget.itemCount; + setState(() { + controller = TabController( + length: widget.itemCount, + vsync: this, + initialIndex: _currentPosition, + ); + controller.addListener(onPositionChange); + controller.animation.addListener(onScroll); + }); + } else if (widget.initPosition != null) { + controller.animateTo(widget.initPosition); + } + + super.didUpdateWidget(oldWidget); + } + + @override + void dispose() { + controller.animation.removeListener(onScroll); + controller.removeListener(onPositionChange); + controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Container( + alignment: Alignment.centerLeft, + height: 50.0, + padding: EdgeInsets.all(10.0), + child: TabBar( + indicatorSize: TabBarIndicatorSize.label, + labelPadding: EdgeInsets.symmetric(horizontal: 5.0), + indicatorPadding: EdgeInsets.symmetric(horizontal: 5.0), + isScrollable: true, + controller: controller, + labelColor: Colors.white, + unselectedLabelColor: Colors.grey[700], + indicator: BoxDecoration( + borderRadius: BorderRadius.all(Radius.circular(15)), + color: Theme.of(context).accentColor, + ), + tabs: List.generate( + widget.itemCount, + (index) => widget.tabBuilder(context, index), + ), + ), + ), + Expanded( + child: TabBarView( + controller: controller, + children: List.generate( + widget.itemCount, + (index) => widget.pageBuilder(context, index), + ), + ), + ), + ], + ); + } + + onPositionChange() { + if (!controller.indexIsChanging) { + _currentPosition = controller.index; + if (widget.onPositionChange is ValueChanged) { + widget.onPositionChange(_currentPosition); + } + } + } + + onScroll() { + if (widget.onScroll is ValueChanged) { + widget.onScroll(controller.animation.value); + } + } +} diff --git a/lib/podcasts/podcast_detail.dart b/lib/podcasts/podcast_detail.dart index 436dd4d..649144f 100644 --- a/lib/podcasts/podcast_detail.dart +++ b/lib/podcasts/podcast_detail.dart @@ -1,1145 +1,1145 @@ -import 'dart:async'; -import 'dart:io'; -import 'dart:math' as math; - -import 'package:cached_network_image/cached_network_image.dart'; -import 'package:connectivity/connectivity.dart'; -import 'package:flutter/foundation.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:flutter_linkify/flutter_linkify.dart'; -import 'package:fluttertoast/fluttertoast.dart'; -import 'package:html/parser.dart'; -import 'package:line_icons/line_icons.dart'; -import 'package:provider/provider.dart'; -import 'package:tuple/tuple.dart'; - -import '../home/audioplayer.dart'; -import '../local_storage/key_value_storage.dart'; -import '../local_storage/sqflite_localpodcast.dart'; -import '../state/audio_state.dart'; -import '../state/download_state.dart'; -import '../type/episodebrief.dart'; -import '../type/fireside_data.dart'; -import '../type/podcastlocal.dart'; -import '../util/audiopanel.dart'; -import '../util/custom_widget.dart'; -import '../util/episodegrid.dart'; -import '../util/extension_helper.dart'; -import '../util/general_dialog.dart'; -import '../util/muiliselect_bar.dart'; -import 'podcast_settings.dart'; - -class PodcastDetail extends StatefulWidget { - PodcastDetail({Key key, @required this.podcastLocal, this.hide = false}) - : super(key: key); - final PodcastLocal podcastLocal; - final bool hide; - @override - _PodcastDetailState createState() => _PodcastDetailState(); -} - -class _PodcastDetailState extends State { - final GlobalKey _refreshIndicatorKey = - GlobalKey(); - - final GlobalKey _playerKey = GlobalKey(); - final _dbHelper = DBHelper(); - - /// Episodes total count. - int _episodeCount; - - /// Default layout. - Layout _layout; - - /// If true, stop grid load animation. - bool _scroll = false; - - double _topHeight = 0; - - ScrollController _controller; - - /// Episodes num load first time. - int _top = 96; - int _dataCount = 0; - - /// Load more episodes when scroll to bottom. - bool _loadMore = false; - - /// Change sort by. - bool _reverse = false; - - /// Filter type. - Filter _filter = Filter.all; - - /// Query string - String _query = ''; - - ///Hide listened. - bool _hideListened; - - ///Selected episode list. - List _selectedEpisodes; - - ///Toggle for multi-select. - bool _multiSelect; - bool _selectAll; - bool _selectBefore; - bool _selectAfter; - bool _loadEpisodes = false; - - @override - void initState() { - super.initState(); - _loadMore = false; - _reverse = false; - _controller = ScrollController(); - _scroll = false; - _multiSelect = false; - _selectAll = false; - _selectAfter = false; - _selectBefore = false; - Future.delayed(Duration(milliseconds: 200)) - .then((value) => setState(() => _loadEpisodes = true)); - } - - @override - void dispose() { - _controller.dispose(); - super.dispose(); - } - - Future _updateRssItem(BuildContext context, PodcastLocal podcastLocal) async { - final result = await _dbHelper.updatePodcastRss(podcastLocal); - if (result >= 0) { - Fluttertoast.showToast( - msg: context.s.updateEpisodesCount(result), - gravity: ToastGravity.TOP, - ); - } - if (result > 0) { - var autoDownload = await _dbHelper.getAutoDownload(podcastLocal.id); - if (autoDownload) { - var downloader = Provider.of(context, listen: false); - var result = await Connectivity().checkConnectivity(); - var autoDownloadStorage = KeyValueStorage(autoDownloadNetworkKey); - var autoDownloadNetwork = await autoDownloadStorage.getInt(); - if (autoDownloadNetwork == 1) { - var episodes = await _dbHelper.getNewEpisodes(podcastLocal.id); - // For safety - if (episodes.length < 100) { - for (var episode in episodes) { - downloader.startTask(episode, showNotification: false); - } - } - } else if (result == ConnectivityResult.wifi) { - var episodes = await _dbHelper.getNewEpisodes(podcastLocal.id); - //For safety - if (episodes.length < 100) { - for (var episode in episodes) { - downloader.startTask(episode, showNotification: false); - } - } - } - } - } else if (result != 0) { - Fluttertoast.showToast( - msg: context.s.updateFailed, - gravity: ToastGravity.TOP, - ); - } - if (mounted && result > 0) setState(() {}); - } - - Future> _getRssItem(PodcastLocal podcastLocal, - {int count, bool reverse, Filter filter, String query}) async { - var episodes = []; - _episodeCount = await _dbHelper.getPodcastCounts(podcastLocal.id); - final layoutStorage = KeyValueStorage(podcastLayoutKey); - final hideListenedStorage = KeyValueStorage(hideListenedKey); - final index = await layoutStorage.getInt(defaultValue: 1); - if (_layout == null) _layout = Layout.values[index]; - if (_hideListened == null) { - _hideListened = await hideListenedStorage.getBool(defaultValue: false); - } - episodes = await _dbHelper.getRssItem(podcastLocal.id, count, - reverse: reverse, - filter: filter, - query: query, - hideListened: _hideListened); - _dataCount = episodes.length; - return episodes; - } - - Future>> _getHosts( - PodcastLocal podcastLocal) async { - var data = FiresideData(podcastLocal.id, podcastLocal.link); - await data.getData(); - var backgroundImage = data.background; - var hosts = data.hosts; - return Tuple2(backgroundImage, hosts); - } - - Future _getLayout() async { - var storage = KeyValueStorage(podcastLayoutKey); - var index = await storage.getInt(defaultValue: 1); - return index; - } - - Future _getHideListened() async { - var hideListenedStorage = KeyValueStorage(hideListenedKey); - var hideListened = await hideListenedStorage.getBool(defaultValue: false); - return hideListened; - } - - Future _checkPodcast() async { - final exist = await _dbHelper.checkPodcast(widget.podcastLocal.rssUrl); - if (exist == '') { - Navigator.of(context).pop(); - } - } - - Widget _podcastInfo(BuildContext context) { - return Container( - height: 170, - padding: EdgeInsets.only(top: 40, left: 80, right: 130), - alignment: Alignment.topLeft, - child: Container( - padding: EdgeInsets.symmetric(vertical: 10), - child: Text( - widget.podcastLocal.title, - maxLines: 2, - overflow: TextOverflow.ellipsis, - style: context.textTheme.headline5.copyWith(color: Colors.white), - ), - ), - ); - } - - Widget _hostsList(BuildContext context, PodcastLocal podcastLocal) { - return Column( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - if (podcastLocal.provider.contains('fireside')) - FutureBuilder( - future: _getHosts(podcastLocal), - builder: (context, snapshot) { - if (snapshot.hasData) { - var hosts = snapshot.data.item2; - var backgroundImage = snapshot.data.item1; - return CachedNetworkImage( - imageUrl: backgroundImage, - errorWidget: (context, url, error) => Center(), - imageBuilder: (context, backgroundImageProvider) => - Container( - decoration: BoxDecoration( - image: DecorationImage( - image: backgroundImageProvider, - fit: BoxFit.cover)), - alignment: Alignment.centerRight, - child: Container( - color: Colors.black26, - padding: EdgeInsets.symmetric(vertical: 5.0), - width: MediaQuery.of(context).size.width, - alignment: Alignment.centerRight, - child: SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - children: hosts - .map((host) { - final image = host.image == - "http://xuanmei.us/assets/default/avatar_small-" - "170afdc2be97fc6148b283083942d82c101d4c1061f6b28f87c8958b52664af9.jpg" - ? "https://fireside.fm/assets/default/avatar_small" - "-170afdc2be97fc6148b283083942d82c101d4c1061f6b28f87c8958b52664af9.jpg" - : host.image; - return Container( - padding: EdgeInsets.all(5.0), - width: 80.0, - child: Column( - mainAxisAlignment: - MainAxisAlignment.center, - mainAxisSize: MainAxisSize.min, - children: [ - CachedNetworkImage( - imageUrl: image, - progressIndicatorBuilder: - (context, url, - downloadProgress) => - SizedBox( - width: 40, - height: 2, - child: LinearProgressIndicator( - value: - downloadProgress - .progress), - ), - errorWidget: - (context, url, error) => - CircleAvatar( - backgroundColor: - Colors.grey[400], - backgroundImage: AssetImage( - 'assets/fireside.jpg'), - ), - imageBuilder: (context, - hostImage) => - CircleAvatar( - backgroundColor: - Colors - .grey[400], - backgroundImage: - hostImage), - ), - Padding( - padding: EdgeInsets.all(2), - ), - Text( - host.name, - style: TextStyle( - backgroundColor: Colors - .black - .withOpacity(0.5), - color: Colors.white, - ), - textAlign: TextAlign.center, - maxLines: 2, - overflow: TextOverflow.fade, - ), - ], - )); - }) - .toList() - .cast()), - ), - )), - ); - } else { - return Center(); - } - }), - Padding(padding: EdgeInsets.all(10.0)), - Container( - padding: EdgeInsets.only(left: 15.0, right: 15.0, bottom: 10.0), - alignment: Alignment.topLeft, - color: context.scaffoldBackgroundColor, - child: AboutPodcast(podcastLocal: widget.podcastLocal), - ), - ], - ); - } - - Widget _customPopupMenu( - {Widget child, - String tooltip, - List> itemBuilder, - Function(int) onSelected, - bool clip = true}) => - Material( - key: UniqueKey(), - color: Colors.transparent, - borderRadius: BorderRadius.circular(100), - clipBehavior: clip ? Clip.hardEdge : Clip.none, - child: PopupMenuButton( - shape: - RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), - elevation: 1, - tooltip: tooltip, - child: child, - itemBuilder: (context) => itemBuilder, - onSelected: (value) => onSelected(value), - ), - ); - - Widget _rightTopMenu(BuildContext context) { - final s = context.s; - return _customPopupMenu( - tooltip: s.menu, - // clip: false, - onSelected: (value) { - switch (value) { - case 0: - widget.podcastLocal.link.launchUrl; - break; - case 1: - widget.podcastLocal.rssUrl.launchUrl; - break; - case 2: - generalSheet( - context, - title: widget.podcastLocal.title, - child: PodcastSetting(podcastLocal: widget.podcastLocal), - ).then((value) { - _checkPodcast(); - setState(() {}); - }); - break; - } - }, - itemBuilder: [ - if (widget.podcastLocal.link != null) - PopupMenuItem( - value: 0, - child: Container( - padding: EdgeInsets.only(left: 10), - child: Row( - children: [ - Icon(Icons.link, color: context.textColor), - Padding( - padding: EdgeInsets.symmetric(horizontal: 5.0), - ), - Text(s.menuVisitSite), - ], - ), - ), - ), - PopupMenuItem( - value: 1, - child: Padding( - padding: EdgeInsets.only(left: 10), - child: Row( - children: [ - Icon( - LineIcons.rss_square_solid, - color: context.textColor, - ), - Padding( - padding: EdgeInsets.symmetric(horizontal: 5.0), - ), - Text(s.menuViewRSS), - ], - ), - ), - ), - PopupMenuItem( - value: 2, - child: Padding( - padding: const EdgeInsets.only(left: 10), - child: Row( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Icon(LineIcons.cog_solid, color: context.textColor), - Padding( - padding: EdgeInsets.symmetric(horizontal: 5.0), - ), - Text(s.settings), - ], - ), - ), - ) - ]); - } - - Widget _actionBar(BuildContext context) { - final s = context.s; - return Container( - height: 30, - child: Row( - children: [ - SizedBox(width: 15), - _customPopupMenu( - tooltip: s.filter, - child: Container( - height: 30, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(100), - border: Border.all(color: context.primaryColorDark)), - padding: EdgeInsets.symmetric(horizontal: 10), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Text(s.filter), - SizedBox(width: 5), - Icon( - LineIcons.filter_solid, - color: - _filter != Filter.all ? context.accentColor : null, - size: 18, - ) - ], - ), - ), - itemBuilder: [ - PopupMenuItem( - value: 0, - child: Row( - children: [ - Text(s.all), - Spacer(), - if (_filter == Filter.all) DotIndicator(), - ], - ), - ), - PopupMenuItem( - value: 1, - child: Row( - children: [ - Text(s.homeTabMenuFavotite), - Spacer(), - if (_filter == Filter.liked) DotIndicator() - ], - ), - ), - PopupMenuItem( - value: 2, - child: Row( - children: [ - Text(s.downloaded), - Spacer(), - if (_filter == Filter.downloaded) DotIndicator() - ], - ), - ), - PopupMenuItem( - value: 3, - child: Container( - padding: - EdgeInsets.only(top: 5, bottom: 5, left: 2, right: 2), - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(5), - border: Border.all( - width: 2, - color: context.textColor.withOpacity(0.2))), - child: _query == '' - ? Row( - children: [ - Text(s.search, - style: TextStyle( - color: context.textColor - .withOpacity(0.4))), - Spacer() - ], - ) - : Row( - children: [ - Expanded( - child: Text(_query, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle( - color: context.accentColor)), - ), - ], - ), - ), - ), - ], - onSelected: (value) { - switch (value) { - case 0: - if (_filter != Filter.all) { - setState(() { - _filter = Filter.all; - _query = ''; - }); - } - break; - case 1: - if (_filter != Filter.liked) { - setState(() { - _query = ''; - _filter = Filter.liked; - }); - } - break; - case 2: - if (_filter != Filter.downloaded) { - setState(() { - _query = ''; - _filter = Filter.downloaded; - }); - } - break; - case 3: - showGeneralDialog( - context: context, - barrierDismissible: true, - barrierLabel: MaterialLocalizations.of(context) - .modalBarrierDismissLabel, - barrierColor: Colors.black54, - transitionDuration: const Duration(milliseconds: 200), - pageBuilder: - (context, animaiton, secondaryAnimation) => - SearchEpisode( - onSearch: (query) { - setState(() { - _query = query; - _filter = Filter.search; - }); - }, - )); - break; - default: - } - }), - Spacer(), - Material( - color: Colors.transparent, - clipBehavior: Clip.hardEdge, - borderRadius: BorderRadius.circular(100), - child: TweenAnimationBuilder( - duration: Duration(milliseconds: 500), - curve: Curves.easeInOutQuart, - tween: Tween(begin: 0.0, end: 1.0), - builder: (context, angle, child) => Transform.rotate( - angle: math.pi * 2 * angle, - child: SizedBox( - width: 30, - child: IconButton( - padding: EdgeInsets.zero, - tooltip: s.homeSubMenuSortBy, - icon: Icon( - _reverse - ? LineIcons.hourglass_start_solid - : LineIcons.hourglass_end_solid, - color: _reverse ? context.accentColor : null, - ), - iconSize: 18, - onPressed: () { - setState(() => _reverse = !_reverse); - }, - ), - ), - ), - )), - FutureBuilder( - future: _getHideListened(), - builder: (context, snapshot) { - if (_hideListened == null) { - _hideListened = snapshot.data; - } - return Material( - color: Colors.transparent, - clipBehavior: Clip.hardEdge, - borderRadius: BorderRadius.circular(100), - child: IconButton( - icon: SizedBox( - width: 30, - height: 30, - child: HideListened( - hideListened: _hideListened ?? false, - ), - ), - onPressed: () { - setState(() => _hideListened = !_hideListened); - }, - )); - }), - FutureBuilder( - future: _getLayout(), - builder: (context, snapshot) { - if (_layout == null && snapshot.data != null) { - _layout = Layout.values[snapshot.data]; - } - return Material( - color: Colors.transparent, - clipBehavior: Clip.hardEdge, - borderRadius: BorderRadius.circular(100), - child: LayoutButton( - layout: _layout ?? Layout.two, - onPressed: (layout) => setState(() { - _layout = layout; - }), - ), - ); - }), - Material( - color: Colors.transparent, - clipBehavior: Clip.hardEdge, - borderRadius: BorderRadius.circular(100), - child: IconButton( - icon: SizedBox( - width: 20, - height: 10, - child: CustomPaint( - painter: - MultiSelectPainter(color: context.accentColor)), - ), - onPressed: () { - setState(() { - _top = -1; - _selectedEpisodes = []; - _multiSelect = true; - }); - }, - )), - SizedBox(width: 10) - ], - )); - } - - @override - Widget build(BuildContext context) { - final color = widget.podcastLocal.primaryColor.colorizedark(); - final s = context.s; - return AnnotatedRegion( - value: SystemUiOverlayStyle( - statusBarIconBrightness: Brightness.dark, - systemNavigationBarColor: Theme.of(context).primaryColor, - systemNavigationBarIconBrightness: - Theme.of(context).accentColorBrightness, - ), - child: WillPopScope( - onWillPop: () { - if (_playerKey.currentState != null && - _playerKey.currentState.initSize > 100) { - _playerKey.currentState.backToMini(); - return Future.value(false); - } else { - return Future.value(true); - } - }, - child: Scaffold( - body: SafeArea( - top: false, - child: RefreshIndicator( - key: _refreshIndicatorKey, - color: context.accentColor, - onRefresh: () async { - await _updateRssItem(context, widget.podcastLocal); - }, - child: Stack( - children: [ - Column( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Expanded( - child: ScrollConfiguration( - behavior: NoGrowBehavior(), - child: CustomScrollView( - controller: _controller - ..addListener(() async { - if (_controller.offset == - _controller.position.maxScrollExtent && - _dataCount == _top) { - if (mounted) { - setState(() => _loadMore = true); - } - await Future.delayed(Duration(seconds: 3)); - if (mounted && _loadMore) { - setState(() { - _top = _top + 36; - _loadMore = false; - }); - } - } - if (_controller.offset > 0 && - mounted && - !_scroll) { - setState(() => _scroll = true); - } - }), - physics: const AlwaysScrollableScrollPhysics(), - slivers: [ - SliverAppBar( - brightness: Brightness.dark, - actions: [_rightTopMenu(context)], - elevation: 0, - iconTheme: IconThemeData( - color: Colors.white, - ), - expandedHeight: 150 + context.paddingTop, - backgroundColor: color, - floating: true, - pinned: true, - leading: CustomBackButton(), - flexibleSpace: LayoutBuilder( - builder: (context, constraints) { - _topHeight = constraints.biggest.height; - return FlexibleSpaceBar( - background: Stack( - children: [ - Container( - margin: EdgeInsets.only( - top: 120 + context.paddingTop), - padding: EdgeInsets.only( - left: 80, right: 120), - color: Colors.white10, - alignment: Alignment.centerLeft, - child: Column( - mainAxisAlignment: - MainAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: - CrossAxisAlignment.start, - children: [ - Text( - widget.podcastLocal.author ?? - '', - maxLines: 1, - overflow: - TextOverflow.ellipsis, - style: TextStyle( - color: Colors.white)), - if (widget.podcastLocal.provider - .isNotEmpty) - Text( - s.hostedOn(widget - .podcastLocal.provider), - maxLines: 1, - style: TextStyle( - color: Colors.white), - ), - ], - ), - ), - Container( - alignment: Alignment.centerRight, - padding: EdgeInsets.only(right: 10), - child: SizedBox( - height: 120, - child: Image.file(File( - "${widget.podcastLocal.imagePath}")), - ), - ), - Align( - alignment: Alignment.center, - child: _podcastInfo(context), - ), - ], - ), - title: _topHeight < 70 + context.paddingTop - ? Text(widget.podcastLocal.title, - maxLines: 1, - overflow: TextOverflow.clip, - style: - TextStyle(color: Colors.white)) - : Center(), - ); - }), - ), - SliverToBoxAdapter( - child: _hostsList(context, widget.podcastLocal), - ), - SliverToBoxAdapter( - child: _multiSelect - ? Center() - : _actionBar(context)), - if (_loadEpisodes) - FutureBuilder>( - future: _getRssItem(widget.podcastLocal, - count: _top, - reverse: _reverse, - filter: _filter, - query: _query), - builder: (context, snapshot) { - if (snapshot.hasData) { - if (_selectAll) { - _selectedEpisodes = snapshot.data; - } - if (_selectBefore) { - final index = snapshot.data - .indexOf(_selectedEpisodes.first); - if (index != 0) { - _selectedEpisodes = snapshot.data - .sublist(0, index + 1); - } - } - if (_selectAfter) { - final index = snapshot.data - .indexOf(_selectedEpisodes.first); - _selectedEpisodes = - snapshot.data.sublist(index); - } - return EpisodeGrid( - episodes: snapshot.data, - showFavorite: true, - showNumber: _filter == Filter.all && - !_hideListened - ? true - : false, - layout: _layout, - reverse: _reverse, - episodeCount: _episodeCount, - initNum: _scroll ? 0 : 12, - multiSelect: _multiSelect, - selectedList: _selectedEpisodes ?? [], - onSelect: (value) => setState(() { - _selectAll = false; - _selectBefore = false; - _selectAfter = false; - _selectedEpisodes = value; - }), - ); - } - return SliverToBoxAdapter( - child: Center()); - }), - SliverList( - delegate: SliverChildBuilderDelegate( - (context, index) { - return _loadMore - ? Container( - height: 2, - child: LinearProgressIndicator()) - : Center(); - }, - childCount: 1, - ), - ), - ], - ), - ), - ), - Selector>( - selector: (_, audio) => - Tuple2(audio.playerRunning, audio.playerHeight), - builder: (_, data, __) { - var height = kMinPlayerHeight[data.item2.index]; - return Column( - children: [ - if (_multiSelect) - MultiSelectMenuBar( - selectedList: _selectedEpisodes, - selectAll: _selectAll, - onSelectAll: (value) { - setState(() { - _selectAll = value; - _selectAfter = false; - _selectBefore = false; - if (!value) { - _selectedEpisodes = []; - } - }); - }, - onSelectAfter: (value) { - setState(() { - _selectBefore = false; - _selectAfter = true; - }); - }, - onSelectBefore: (value) { - setState(() { - _selectAfter = false; - _selectBefore = true; - }); - }, - onClose: (value) { - setState(() { - if (value) { - _multiSelect = false; - _selectAll = false; - _selectAfter = false; - _selectBefore = false; - } - }); - }, - ), - SizedBox( - height: data.item1 ? height : 0, - ), - ], - ); - }), - ], - ), - Container( - child: PlayerWidget( - playerKey: _playerKey, - )), - ], - ), - ), - ), - ), - ), - ); - } -} - -class AboutPodcast extends StatefulWidget { - final PodcastLocal podcastLocal; - AboutPodcast({this.podcastLocal, Key key}) : super(key: key); - - @override - _AboutPodcastState createState() => _AboutPodcastState(); -} - -class _AboutPodcastState extends State { - String _description; - bool _load; - bool _expand; - void getDescription(String id) async { - var dbHelper = DBHelper(); - var description = await dbHelper.getFeedDescription(id); - if (description == null || description.isEmpty) { - _description = ''; - } else { - var doc = parse(description); - _description = parse(doc.body.text).documentElement.text; - } - if (mounted) setState(() => _load = true); - } - - @override - void initState() { - super.initState(); - _load = false; - _expand = false; - getDescription(widget.podcastLocal.id); - } - - @override - Widget build(BuildContext context) { - return !_load - ? Center() - : LayoutBuilder( - builder: (context, size) { - final span = TextSpan(text: _description); - final tp = TextPainter( - text: span, maxLines: 3, textDirection: TextDirection.ltr); - tp.layout(maxWidth: size.maxWidth); - - if (tp.didExceedMaxLines) { - return GestureDetector( - onTap: () { - setState(() => _expand = !_expand); - }, - child: !_expand - ? Column( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Linkify( - onOpen: (link) { - link.url.launchUrl; - }, - text: _description, - linkStyle: TextStyle( - color: Theme.of(context).accentColor, - decoration: TextDecoration.underline, - textBaseline: TextBaseline.ideographic), - maxLines: 3, - overflow: TextOverflow.ellipsis, - ), - ], - ) - : Linkify( - onOpen: (link) { - link.url.launchUrl; - }, - text: _description, - linkStyle: TextStyle( - color: Theme.of(context).accentColor, - decoration: TextDecoration.underline, - textBaseline: TextBaseline.ideographic), - ), - ); - } else { - return Linkify( - text: _description, - onOpen: (link) { - link.url.launchUrl; - }, - linkStyle: TextStyle( - color: Theme.of(context).accentColor, - decoration: TextDecoration.underline, - textBaseline: TextBaseline.ideographic), - ); - } - }, - ); - } -} - -class SearchEpisode extends StatefulWidget { - SearchEpisode({this.onSearch, Key key}) : super(key: key); - final ValueChanged onSearch; - @override - _SearchEpisodeState createState() => _SearchEpisodeState(); -} - -class _SearchEpisodeState extends State { - TextEditingController _controller; - String _query; - - @override - void initState() { - super.initState(); - _controller = TextEditingController(); - } - - @override - void dispose() { - _controller.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - final s = context.s; - return AnnotatedRegion( - value: SystemUiOverlayStyle( - statusBarIconBrightness: Brightness.light, - systemNavigationBarColor: - Theme.of(context).brightness == Brightness.light - ? Color.fromRGBO(113, 113, 113, 1) - : Color.fromRGBO(5, 5, 5, 1), - ), - child: AlertDialog( - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(10))), - elevation: 1, - contentPadding: const EdgeInsets.symmetric(horizontal: 20), - titlePadding: const EdgeInsets.all(20), - actionsPadding: EdgeInsets.zero, - actions: [ - FlatButton( - splashColor: context.accentColor.withAlpha(70), - onPressed: () => Navigator.of(context).pop(), - child: Text( - s.cancel, - textAlign: TextAlign.end, - style: TextStyle(color: Colors.grey[600]), - ), - ), - FlatButton( - splashColor: context.accentColor.withAlpha(70), - onPressed: () { - if ((_query ?? '').isNotEmpty) { - widget.onSearch(_query); - Navigator.of(context).pop(); - } - }, - child: - Text(s.confirm, style: TextStyle(color: context.accentColor)), - ) - ], - title: SizedBox(width: context.width - 160, child: Text(s.search)), - content: Column( - mainAxisSize: MainAxisSize.min, - children: [ - TextField( - decoration: InputDecoration( - contentPadding: EdgeInsets.symmetric(horizontal: 10), - hintText: s.searchEpisode, - hintStyle: TextStyle(fontSize: 18), - filled: true, - focusedBorder: UnderlineInputBorder( - borderSide: - BorderSide(color: context.accentColor, width: 2.0), - ), - enabledBorder: UnderlineInputBorder( - borderSide: - BorderSide(color: context.accentColor, width: 2.0), - ), - ), - cursorRadius: Radius.circular(2), - autofocus: true, - maxLines: 1, - controller: _controller, - onChanged: (value) { - setState(() => _query = value); - }, - ), - ], - ), - ), - ); - } -} +import 'dart:async'; +import 'dart:io'; +import 'dart:math' as math; + +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:connectivity/connectivity.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_linkify/flutter_linkify.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:html/parser.dart'; +import 'package:line_icons/line_icons.dart'; +import 'package:provider/provider.dart'; +import 'package:tuple/tuple.dart'; + +import '../home/audioplayer.dart'; +import '../local_storage/key_value_storage.dart'; +import '../local_storage/sqflite_localpodcast.dart'; +import '../state/audio_state.dart'; +import '../state/download_state.dart'; +import '../type/episodebrief.dart'; +import '../type/fireside_data.dart'; +import '../type/podcastlocal.dart'; +import '../util/audiopanel.dart'; +import '../util/custom_widget.dart'; +import '../util/episodegrid.dart'; +import '../util/extension_helper.dart'; +import '../util/general_dialog.dart'; +import '../util/muiliselect_bar.dart'; +import 'podcast_settings.dart'; + +class PodcastDetail extends StatefulWidget { + PodcastDetail({Key key, @required this.podcastLocal, this.hide = false}) + : super(key: key); + final PodcastLocal podcastLocal; + final bool hide; + @override + _PodcastDetailState createState() => _PodcastDetailState(); +} + +class _PodcastDetailState extends State { + final GlobalKey _refreshIndicatorKey = + GlobalKey(); + + final GlobalKey _playerKey = GlobalKey(); + final _dbHelper = DBHelper(); + + /// Episodes total count. + int _episodeCount; + + /// Default layout. + Layout _layout; + + /// If true, stop grid load animation. + bool _scroll = false; + + double _topHeight = 0; + + ScrollController _controller; + + /// Episodes num load first time. + int _top = 96; + int _dataCount = 0; + + /// Load more episodes when scroll to bottom. + bool _loadMore = false; + + /// Change sort by. + bool _reverse = false; + + /// Filter type. + Filter _filter = Filter.all; + + /// Query string + String _query = ''; + + ///Hide listened. + bool _hideListened; + + ///Selected episode list. + List _selectedEpisodes; + + ///Toggle for multi-select. + bool _multiSelect; + bool _selectAll; + bool _selectBefore; + bool _selectAfter; + bool _loadEpisodes = false; + + @override + void initState() { + super.initState(); + _loadMore = false; + _reverse = false; + _controller = ScrollController(); + _scroll = false; + _multiSelect = false; + _selectAll = false; + _selectAfter = false; + _selectBefore = false; + Future.delayed(Duration(milliseconds: 200)) + .then((value) => setState(() => _loadEpisodes = true)); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + Future _updateRssItem(BuildContext context, PodcastLocal podcastLocal) async { + final result = await _dbHelper.updatePodcastRss(podcastLocal); + if (result >= 0) { + Fluttertoast.showToast( + msg: context.s.updateEpisodesCount(result), + gravity: ToastGravity.TOP, + ); + } + if (result > 0) { + var autoDownload = await _dbHelper.getAutoDownload(podcastLocal.id); + if (autoDownload) { + var downloader = Provider.of(context, listen: false); + var result = await Connectivity().checkConnectivity(); + var autoDownloadStorage = KeyValueStorage(autoDownloadNetworkKey); + var autoDownloadNetwork = await autoDownloadStorage.getInt(); + if (autoDownloadNetwork == 1) { + var episodes = await _dbHelper.getNewEpisodes(podcastLocal.id); + // For safety + if (episodes.length < 100) { + for (var episode in episodes) { + downloader.startTask(episode, showNotification: false); + } + } + } else if (result == ConnectivityResult.wifi) { + var episodes = await _dbHelper.getNewEpisodes(podcastLocal.id); + //For safety + if (episodes.length < 100) { + for (var episode in episodes) { + downloader.startTask(episode, showNotification: false); + } + } + } + } + } else if (result != 0) { + Fluttertoast.showToast( + msg: context.s.updateFailed, + gravity: ToastGravity.TOP, + ); + } + if (mounted && result > 0) setState(() {}); + } + + Future> _getRssItem(PodcastLocal podcastLocal, + {int count, bool reverse, Filter filter, String query}) async { + var episodes = []; + _episodeCount = await _dbHelper.getPodcastCounts(podcastLocal.id); + final layoutStorage = KeyValueStorage(podcastLayoutKey); + final hideListenedStorage = KeyValueStorage(hideListenedKey); + final index = await layoutStorage.getInt(defaultValue: 1); + if (_layout == null) _layout = Layout.values[index]; + if (_hideListened == null) { + _hideListened = await hideListenedStorage.getBool(defaultValue: false); + } + episodes = await _dbHelper.getRssItem(podcastLocal.id, count, + reverse: reverse, + filter: filter, + query: query, + hideListened: _hideListened); + _dataCount = episodes.length; + return episodes; + } + + Future>> _getHosts( + PodcastLocal podcastLocal) async { + var data = FiresideData(podcastLocal.id, podcastLocal.link); + await data.getData(); + var backgroundImage = data.background; + var hosts = data.hosts; + return Tuple2(backgroundImage, hosts); + } + + Future _getLayout() async { + var storage = KeyValueStorage(podcastLayoutKey); + var index = await storage.getInt(defaultValue: 1); + return index; + } + + Future _getHideListened() async { + var hideListenedStorage = KeyValueStorage(hideListenedKey); + var hideListened = await hideListenedStorage.getBool(defaultValue: false); + return hideListened; + } + + Future _checkPodcast() async { + final exist = await _dbHelper.checkPodcast(widget.podcastLocal.rssUrl); + if (exist == '') { + Navigator.of(context).pop(); + } + } + + Widget _podcastInfo(BuildContext context) { + return Container( + height: 170, + padding: EdgeInsets.only(top: 40, left: 80, right: 130), + alignment: Alignment.topLeft, + child: Container( + padding: EdgeInsets.symmetric(vertical: 10), + child: Text( + widget.podcastLocal.title, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: context.textTheme.headline5.copyWith(color: Colors.white), + ), + ), + ); + } + + Widget _hostsList(BuildContext context, PodcastLocal podcastLocal) { + return Column( + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + if (podcastLocal.provider.contains('fireside')) + FutureBuilder( + future: _getHosts(podcastLocal), + builder: (context, snapshot) { + if (snapshot.hasData) { + var hosts = snapshot.data.item2; + var backgroundImage = snapshot.data.item1; + return CachedNetworkImage( + imageUrl: backgroundImage, + errorWidget: (context, url, error) => Center(), + imageBuilder: (context, backgroundImageProvider) => + Container( + decoration: BoxDecoration( + image: DecorationImage( + image: backgroundImageProvider, + fit: BoxFit.cover)), + alignment: Alignment.centerRight, + child: Container( + color: Colors.black26, + padding: EdgeInsets.symmetric(vertical: 5.0), + width: MediaQuery.of(context).size.width, + alignment: Alignment.centerRight, + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: hosts + .map((host) { + final image = host.image == + "http://xuanmei.us/assets/default/avatar_small-" + "170afdc2be97fc6148b283083942d82c101d4c1061f6b28f87c8958b52664af9.jpg" + ? "https://fireside.fm/assets/default/avatar_small" + "-170afdc2be97fc6148b283083942d82c101d4c1061f6b28f87c8958b52664af9.jpg" + : host.image; + return Container( + padding: EdgeInsets.all(5.0), + width: 80.0, + child: Column( + mainAxisAlignment: + MainAxisAlignment.center, + mainAxisSize: MainAxisSize.min, + children: [ + CachedNetworkImage( + imageUrl: image, + progressIndicatorBuilder: + (context, url, + downloadProgress) => + SizedBox( + width: 40, + height: 2, + child: LinearProgressIndicator( + value: + downloadProgress + .progress), + ), + errorWidget: + (context, url, error) => + CircleAvatar( + backgroundColor: + Colors.grey[400], + backgroundImage: AssetImage( + 'assets/fireside.jpg'), + ), + imageBuilder: (context, + hostImage) => + CircleAvatar( + backgroundColor: + Colors + .grey[400], + backgroundImage: + hostImage), + ), + Padding( + padding: EdgeInsets.all(2), + ), + Text( + host.name, + style: TextStyle( + backgroundColor: Colors + .black + .withOpacity(0.5), + color: Colors.white, + ), + textAlign: TextAlign.center, + maxLines: 2, + overflow: TextOverflow.fade, + ), + ], + )); + }) + .toList() + .cast()), + ), + )), + ); + } else { + return Center(); + } + }), + Padding(padding: EdgeInsets.all(10.0)), + Container( + padding: EdgeInsets.only(left: 15.0, right: 15.0, bottom: 10.0), + alignment: Alignment.topLeft, + color: context.scaffoldBackgroundColor, + child: AboutPodcast(podcastLocal: widget.podcastLocal), + ), + ], + ); + } + + Widget _customPopupMenu( + {Widget child, + String tooltip, + List> itemBuilder, + Function(int) onSelected, + bool clip = true}) => + Material( + key: UniqueKey(), + color: Colors.transparent, + borderRadius: BorderRadius.circular(100), + clipBehavior: clip ? Clip.hardEdge : Clip.none, + child: PopupMenuButton( + shape: + RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), + elevation: 1, + tooltip: tooltip, + child: child, + itemBuilder: (context) => itemBuilder, + onSelected: (value) => onSelected(value), + ), + ); + + Widget _rightTopMenu(BuildContext context) { + final s = context.s; + return _customPopupMenu( + tooltip: s.menu, + // clip: false, + onSelected: (value) { + switch (value) { + case 0: + widget.podcastLocal.link.launchUrl; + break; + case 1: + widget.podcastLocal.rssUrl.launchUrl; + break; + case 2: + generalSheet( + context, + title: widget.podcastLocal.title, + child: PodcastSetting(podcastLocal: widget.podcastLocal), + ).then((value) { + _checkPodcast(); + setState(() {}); + }); + break; + } + }, + itemBuilder: [ + if (widget.podcastLocal.link != null) + PopupMenuItem( + value: 0, + child: Container( + padding: EdgeInsets.only(left: 10), + child: Row( + children: [ + Icon(Icons.link, color: context.textColor), + Padding( + padding: EdgeInsets.symmetric(horizontal: 5.0), + ), + Text(s.menuVisitSite), + ], + ), + ), + ), + PopupMenuItem( + value: 1, + child: Padding( + padding: EdgeInsets.only(left: 10), + child: Row( + children: [ + Icon( + LineIcons.rss_square_solid, + color: context.textColor, + ), + Padding( + padding: EdgeInsets.symmetric(horizontal: 5.0), + ), + Text(s.menuViewRSS), + ], + ), + ), + ), + PopupMenuItem( + value: 2, + child: Padding( + padding: const EdgeInsets.only(left: 10), + child: Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Icon(LineIcons.cog_solid, color: context.textColor), + Padding( + padding: EdgeInsets.symmetric(horizontal: 5.0), + ), + Text(s.settings), + ], + ), + ), + ) + ]); + } + + Widget _actionBar(BuildContext context) { + final s = context.s; + return Container( + height: 30, + child: Row( + children: [ + SizedBox(width: 15), + _customPopupMenu( + tooltip: s.filter, + child: Container( + height: 30, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(100), + border: Border.all(color: context.primaryColorDark)), + padding: EdgeInsets.symmetric(horizontal: 10), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text(s.filter), + SizedBox(width: 5), + Icon( + LineIcons.filter_solid, + color: + _filter != Filter.all ? context.accentColor : null, + size: 18, + ) + ], + ), + ), + itemBuilder: [ + PopupMenuItem( + value: 0, + child: Row( + children: [ + Text(s.all), + Spacer(), + if (_filter == Filter.all) DotIndicator(), + ], + ), + ), + PopupMenuItem( + value: 1, + child: Row( + children: [ + Text(s.homeTabMenuFavotite), + Spacer(), + if (_filter == Filter.liked) DotIndicator() + ], + ), + ), + PopupMenuItem( + value: 2, + child: Row( + children: [ + Text(s.downloaded), + Spacer(), + if (_filter == Filter.downloaded) DotIndicator() + ], + ), + ), + PopupMenuItem( + value: 3, + child: Container( + padding: + EdgeInsets.only(top: 5, bottom: 5, left: 2, right: 2), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(5), + border: Border.all( + width: 2, + color: context.textColor.withOpacity(0.2))), + child: _query == '' + ? Row( + children: [ + Text(s.search, + style: TextStyle( + color: context.textColor + .withOpacity(0.4))), + Spacer() + ], + ) + : Row( + children: [ + Expanded( + child: Text(_query, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: context.accentColor)), + ), + ], + ), + ), + ), + ], + onSelected: (value) { + switch (value) { + case 0: + if (_filter != Filter.all) { + setState(() { + _filter = Filter.all; + _query = ''; + }); + } + break; + case 1: + if (_filter != Filter.liked) { + setState(() { + _query = ''; + _filter = Filter.liked; + }); + } + break; + case 2: + if (_filter != Filter.downloaded) { + setState(() { + _query = ''; + _filter = Filter.downloaded; + }); + } + break; + case 3: + showGeneralDialog( + context: context, + barrierDismissible: true, + barrierLabel: MaterialLocalizations.of(context) + .modalBarrierDismissLabel, + barrierColor: Colors.black54, + transitionDuration: const Duration(milliseconds: 200), + pageBuilder: + (context, animaiton, secondaryAnimation) => + SearchEpisode( + onSearch: (query) { + setState(() { + _query = query; + _filter = Filter.search; + }); + }, + )); + break; + default: + } + }), + Spacer(), + Material( + color: Colors.transparent, + clipBehavior: Clip.hardEdge, + borderRadius: BorderRadius.circular(100), + child: TweenAnimationBuilder( + duration: Duration(milliseconds: 500), + curve: Curves.easeInOutQuart, + tween: Tween(begin: 0.0, end: 1.0), + builder: (context, angle, child) => Transform.rotate( + angle: math.pi * 2 * angle, + child: SizedBox( + width: 30, + child: IconButton( + padding: EdgeInsets.zero, + tooltip: s.homeSubMenuSortBy, + icon: Icon( + _reverse + ? LineIcons.hourglass_start_solid + : LineIcons.hourglass_end_solid, + color: _reverse ? context.accentColor : null, + ), + iconSize: 18, + onPressed: () { + setState(() => _reverse = !_reverse); + }, + ), + ), + ), + )), + FutureBuilder( + future: _getHideListened(), + builder: (context, snapshot) { + if (_hideListened == null) { + _hideListened = snapshot.data; + } + return Material( + color: Colors.transparent, + clipBehavior: Clip.hardEdge, + borderRadius: BorderRadius.circular(100), + child: IconButton( + icon: SizedBox( + width: 30, + height: 30, + child: HideListened( + hideListened: _hideListened ?? false, + ), + ), + onPressed: () { + setState(() => _hideListened = !_hideListened); + }, + )); + }), + FutureBuilder( + future: _getLayout(), + builder: (context, snapshot) { + if (_layout == null && snapshot.data != null) { + _layout = Layout.values[snapshot.data]; + } + return Material( + color: Colors.transparent, + clipBehavior: Clip.hardEdge, + borderRadius: BorderRadius.circular(100), + child: LayoutButton( + layout: _layout ?? Layout.two, + onPressed: (layout) => setState(() { + _layout = layout; + }), + ), + ); + }), + Material( + color: Colors.transparent, + clipBehavior: Clip.hardEdge, + borderRadius: BorderRadius.circular(100), + child: IconButton( + icon: SizedBox( + width: 20, + height: 10, + child: CustomPaint( + painter: + MultiSelectPainter(color: context.accentColor)), + ), + onPressed: () { + setState(() { + _top = -1; + _selectedEpisodes = []; + _multiSelect = true; + }); + }, + )), + SizedBox(width: 10) + ], + )); + } + + @override + Widget build(BuildContext context) { + final color = widget.podcastLocal.primaryColor.colorizedark(); + final s = context.s; + return AnnotatedRegion( + value: SystemUiOverlayStyle( + statusBarIconBrightness: Brightness.dark, + systemNavigationBarColor: Theme.of(context).primaryColor, + systemNavigationBarIconBrightness: + Theme.of(context).accentColorBrightness, + ), + child: WillPopScope( + onWillPop: () { + if (_playerKey.currentState != null && + _playerKey.currentState.initSize > 100) { + _playerKey.currentState.backToMini(); + return Future.value(false); + } else { + return Future.value(true); + } + }, + child: Scaffold( + body: SafeArea( + top: false, + child: RefreshIndicator( + key: _refreshIndicatorKey, + color: context.accentColor, + onRefresh: () async { + await _updateRssItem(context, widget.podcastLocal); + }, + child: Stack( + children: [ + Column( + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: ScrollConfiguration( + behavior: NoGrowBehavior(), + child: CustomScrollView( + controller: _controller + ..addListener(() async { + if (_controller.offset == + _controller.position.maxScrollExtent && + _dataCount == _top) { + if (mounted) { + setState(() => _loadMore = true); + } + await Future.delayed(Duration(seconds: 3)); + if (mounted && _loadMore) { + setState(() { + _top = _top + 36; + _loadMore = false; + }); + } + } + if (_controller.offset > 0 && + mounted && + !_scroll) { + setState(() => _scroll = true); + } + }), + physics: const AlwaysScrollableScrollPhysics(), + slivers: [ + SliverAppBar( + brightness: Brightness.dark, + actions: [_rightTopMenu(context)], + elevation: 0, + iconTheme: IconThemeData( + color: Colors.white, + ), + expandedHeight: 150 + context.paddingTop, + backgroundColor: color, + floating: true, + pinned: true, + leading: CustomBackButton(), + flexibleSpace: LayoutBuilder( + builder: (context, constraints) { + _topHeight = constraints.biggest.height; + return FlexibleSpaceBar( + background: Stack( + children: [ + Container( + margin: EdgeInsets.only( + top: 120 + context.paddingTop), + padding: EdgeInsets.only( + left: 80, right: 120), + color: Colors.white10, + alignment: Alignment.centerLeft, + child: Column( + mainAxisAlignment: + MainAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text( + widget.podcastLocal.author ?? + '', + maxLines: 1, + overflow: + TextOverflow.ellipsis, + style: TextStyle( + color: Colors.white)), + if (widget.podcastLocal.provider + .isNotEmpty) + Text( + s.hostedOn(widget + .podcastLocal.provider), + maxLines: 1, + style: TextStyle( + color: Colors.white), + ), + ], + ), + ), + Container( + alignment: Alignment.centerRight, + padding: EdgeInsets.only(right: 10), + child: SizedBox( + height: 120, + child: Image.file(File( + "${widget.podcastLocal.imagePath}")), + ), + ), + Align( + alignment: Alignment.center, + child: _podcastInfo(context), + ), + ], + ), + title: _topHeight < 70 + context.paddingTop + ? Text(widget.podcastLocal.title, + maxLines: 1, + overflow: TextOverflow.clip, + style: + TextStyle(color: Colors.white)) + : Center(), + ); + }), + ), + SliverToBoxAdapter( + child: _hostsList(context, widget.podcastLocal), + ), + SliverToBoxAdapter( + child: _multiSelect + ? Center() + : _actionBar(context)), + if (_loadEpisodes) + FutureBuilder>( + future: _getRssItem(widget.podcastLocal, + count: _top, + reverse: _reverse, + filter: _filter, + query: _query), + builder: (context, snapshot) { + if (snapshot.hasData) { + if (_selectAll) { + _selectedEpisodes = snapshot.data; + } + if (_selectBefore) { + final index = snapshot.data + .indexOf(_selectedEpisodes.first); + if (index != 0) { + _selectedEpisodes = snapshot.data + .sublist(0, index + 1); + } + } + if (_selectAfter) { + final index = snapshot.data + .indexOf(_selectedEpisodes.first); + _selectedEpisodes = + snapshot.data.sublist(index); + } + return EpisodeGrid( + episodes: snapshot.data, + showFavorite: true, + showNumber: _filter == Filter.all && + !_hideListened + ? true + : false, + layout: _layout, + reverse: _reverse, + episodeCount: _episodeCount, + initNum: _scroll ? 0 : 12, + multiSelect: _multiSelect, + selectedList: _selectedEpisodes ?? [], + onSelect: (value) => setState(() { + _selectAll = false; + _selectBefore = false; + _selectAfter = false; + _selectedEpisodes = value; + }), + ); + } + return SliverToBoxAdapter( + child: Center()); + }), + SliverList( + delegate: SliverChildBuilderDelegate( + (context, index) { + return _loadMore + ? Container( + height: 2, + child: LinearProgressIndicator()) + : Center(); + }, + childCount: 1, + ), + ), + ], + ), + ), + ), + Selector>( + selector: (_, audio) => + Tuple2(audio.playerRunning, audio.playerHeight), + builder: (_, data, __) { + var height = kMinPlayerHeight[data.item2.index]; + return Column( + children: [ + if (_multiSelect) + MultiSelectMenuBar( + selectedList: _selectedEpisodes, + selectAll: _selectAll, + onSelectAll: (value) { + setState(() { + _selectAll = value; + _selectAfter = false; + _selectBefore = false; + if (!value) { + _selectedEpisodes = []; + } + }); + }, + onSelectAfter: (value) { + setState(() { + _selectBefore = false; + _selectAfter = true; + }); + }, + onSelectBefore: (value) { + setState(() { + _selectAfter = false; + _selectBefore = true; + }); + }, + onClose: (value) { + setState(() { + if (value) { + _multiSelect = false; + _selectAll = false; + _selectAfter = false; + _selectBefore = false; + } + }); + }, + ), + SizedBox( + height: data.item1 ? height : 0, + ), + ], + ); + }), + ], + ), + Container( + child: PlayerWidget( + playerKey: _playerKey, + )), + ], + ), + ), + ), + ), + ), + ); + } +} + +class AboutPodcast extends StatefulWidget { + final PodcastLocal podcastLocal; + AboutPodcast({this.podcastLocal, Key key}) : super(key: key); + + @override + _AboutPodcastState createState() => _AboutPodcastState(); +} + +class _AboutPodcastState extends State { + String _description; + bool _load; + bool _expand; + void getDescription(String id) async { + var dbHelper = DBHelper(); + var description = await dbHelper.getFeedDescription(id); + if (description == null || description.isEmpty) { + _description = ''; + } else { + var doc = parse(description); + _description = parse(doc.body.text).documentElement.text; + } + if (mounted) setState(() => _load = true); + } + + @override + void initState() { + super.initState(); + _load = false; + _expand = false; + getDescription(widget.podcastLocal.id); + } + + @override + Widget build(BuildContext context) { + return !_load + ? Center() + : LayoutBuilder( + builder: (context, size) { + final span = TextSpan(text: _description); + final tp = TextPainter( + text: span, maxLines: 3, textDirection: TextDirection.ltr); + tp.layout(maxWidth: size.maxWidth); + + if (tp.didExceedMaxLines) { + return GestureDetector( + onTap: () { + setState(() => _expand = !_expand); + }, + child: !_expand + ? Column( + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Linkify( + onOpen: (link) { + link.url.launchUrl; + }, + text: _description, + linkStyle: TextStyle( + color: Theme.of(context).accentColor, + decoration: TextDecoration.underline, + textBaseline: TextBaseline.ideographic), + maxLines: 3, + overflow: TextOverflow.ellipsis, + ), + ], + ) + : Linkify( + onOpen: (link) { + link.url.launchUrl; + }, + text: _description, + linkStyle: TextStyle( + color: Theme.of(context).accentColor, + decoration: TextDecoration.underline, + textBaseline: TextBaseline.ideographic), + ), + ); + } else { + return Linkify( + text: _description, + onOpen: (link) { + link.url.launchUrl; + }, + linkStyle: TextStyle( + color: Theme.of(context).accentColor, + decoration: TextDecoration.underline, + textBaseline: TextBaseline.ideographic), + ); + } + }, + ); + } +} + +class SearchEpisode extends StatefulWidget { + SearchEpisode({this.onSearch, Key key}) : super(key: key); + final ValueChanged onSearch; + @override + _SearchEpisodeState createState() => _SearchEpisodeState(); +} + +class _SearchEpisodeState extends State { + TextEditingController _controller; + String _query; + + @override + void initState() { + super.initState(); + _controller = TextEditingController(); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final s = context.s; + return AnnotatedRegion( + value: SystemUiOverlayStyle( + statusBarIconBrightness: Brightness.light, + systemNavigationBarColor: + Theme.of(context).brightness == Brightness.light + ? Color.fromRGBO(113, 113, 113, 1) + : Color.fromRGBO(5, 5, 5, 1), + ), + child: AlertDialog( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(10))), + elevation: 1, + contentPadding: const EdgeInsets.symmetric(horizontal: 20), + titlePadding: const EdgeInsets.all(20), + actionsPadding: EdgeInsets.zero, + actions: [ + FlatButton( + splashColor: context.accentColor.withAlpha(70), + onPressed: () => Navigator.of(context).pop(), + child: Text( + s.cancel, + textAlign: TextAlign.end, + style: TextStyle(color: Colors.grey[600]), + ), + ), + FlatButton( + splashColor: context.accentColor.withAlpha(70), + onPressed: () { + if ((_query ?? '').isNotEmpty) { + widget.onSearch(_query); + Navigator.of(context).pop(); + } + }, + child: + Text(s.confirm, style: TextStyle(color: context.accentColor)), + ) + ], + title: SizedBox(width: context.width - 160, child: Text(s.search)), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextField( + decoration: InputDecoration( + contentPadding: EdgeInsets.symmetric(horizontal: 10), + hintText: s.searchEpisode, + hintStyle: TextStyle(fontSize: 18), + filled: true, + focusedBorder: UnderlineInputBorder( + borderSide: + BorderSide(color: context.accentColor, width: 2.0), + ), + enabledBorder: UnderlineInputBorder( + borderSide: + BorderSide(color: context.accentColor, width: 2.0), + ), + ), + cursorRadius: Radius.circular(2), + autofocus: true, + maxLines: 1, + controller: _controller, + onChanged: (value) { + setState(() => _query = value); + }, + ), + ], + ), + ), + ); + } +} diff --git a/lib/podcasts/podcast_group.dart b/lib/podcasts/podcast_group.dart index d25c272..1cf7708 100644 --- a/lib/podcasts/podcast_group.dart +++ b/lib/podcasts/podcast_group.dart @@ -1,603 +1,603 @@ -import 'dart:io'; -import 'dart:math' as math; - -import 'package:flutter/foundation.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:fluttertoast/fluttertoast.dart'; -import 'package:permission_handler/permission_handler.dart'; -import 'package:provider/provider.dart'; - -import '../local_storage/sqflite_localpodcast.dart'; -import '../state/podcast_group.dart'; -import '../type/podcastlocal.dart'; -import '../util/duraiton_picker.dart'; -import '../util/extension_helper.dart'; -import '../util/general_dialog.dart'; - -class PodcastGroupList extends StatefulWidget { - final PodcastGroup group; - PodcastGroupList({this.group, Key key}) : super(key: key); - @override - _PodcastGroupListState createState() => _PodcastGroupListState(); -} - -class _PodcastGroupListState extends State { - @override - Widget build(BuildContext context) { - var groupList = Provider.of(context, listen: false); - return widget.group.podcastList.length == 0 - ? Container( - color: Theme.of(context).primaryColor, - ) - : Container( - color: Theme.of(context).primaryColor, - child: ReorderableListView( - onReorder: (oldIndex, newIndex) { - setState(() { - if (newIndex > oldIndex) { - newIndex -= 1; - } - final podcast = widget.group.podcasts.removeAt(oldIndex); - widget.group.podcasts.insert(newIndex, podcast); - }); - widget.group.orderedPodcasts = widget.group.podcasts; - groupList.addToOrderChanged(widget.group); - }, - children: widget.group.podcasts.map((podcastLocal) { - return Container( - decoration: - BoxDecoration(color: Theme.of(context).primaryColor), - key: ObjectKey(podcastLocal.title), - child: _PodcastCard( - podcastLocal: podcastLocal, - group: widget.group, - ), - ); - }).toList(), - ), - ); - } -} - -class _PodcastCard extends StatefulWidget { - final PodcastLocal podcastLocal; - final PodcastGroup group; - _PodcastCard({this.podcastLocal, this.group, Key key}) : super(key: key); - @override - __PodcastCardState createState() => __PodcastCardState(); -} - -class __PodcastCardState extends State<_PodcastCard> - with SingleTickerProviderStateMixin { - bool _loadMenu; - bool _addGroup; - List _selectedGroups; - List _belongGroups; - AnimationController _controller; - Animation _animation; - double _value; - int _seconds; - int _skipSeconds; - - Future _getSkipSecond(String id) async { - var dbHelper = DBHelper(); - var seconds = await dbHelper.getSkipSecondsStart(id); - _skipSeconds = seconds; - return seconds; - } - - _saveSkipSeconds(String id, int seconds) async { - var dbHelper = DBHelper(); - await dbHelper.saveSkipSecondsStart(id, seconds); - } - - _setAutoDownload(String id, bool boo) async { - var permission = await _checkPermmison(); - if (permission) { - var dbHelper = DBHelper(); - await dbHelper.saveAutoDownload(id, boo: boo); - } - } - - Future _getAutoDownload(String id) async { - var dbHelper = DBHelper(); - return await dbHelper.getAutoDownload(id); - } - - Future _checkPermmison() async { - var permission = await Permission.storage.status; - if (permission != PermissionStatus.granted) { - var permissions = await [Permission.storage].request(); - if (permissions[Permission.storage] == PermissionStatus.granted) { - return true; - } else { - return false; - } - } else { - return true; - } - } - - @override - void initState() { - super.initState(); - _loadMenu = false; - _addGroup = false; - _selectedGroups = [widget.group]; - _value = 0; - _seconds = 0; - _controller = - AnimationController(vsync: this, duration: Duration(milliseconds: 300)); - _animation = Tween(begin: 0.0, end: 1.0).animate(_controller) - ..addListener(() { - setState(() { - _value = _animation.value; - }); - }); - } - - Widget _buttonOnMenu({Widget icon, VoidCallback onTap, String tooltip}) => - Material( - color: Colors.transparent, - child: InkWell( - onTap: onTap, - child: Container( - height: 50.0, - padding: EdgeInsets.symmetric(horizontal: 5.0), - child: Column( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Expanded( - child: icon, - ), - Text(tooltip, style: context.textTheme.subtitle2), - ], - )), - ), - ); - - @override - Widget build(BuildContext context) { - final c = widget.podcastLocal.backgroudColor(context); - final s = context.s; - var width = context.width; - var groupList = context.watch(); - _belongGroups = groupList.getPodcastGroup(widget.podcastLocal.id); - - return Container( - decoration: BoxDecoration( - border: Border( - bottom: Divider.createBorderSide(context), - ), - ), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - InkWell( - onTap: () => setState( - () { - _loadMenu = !_loadMenu; - if (_value == 0) { - _controller.forward(); - } else { - _controller.reverse(); - } - }, - ), - child: Container( - padding: EdgeInsets.symmetric(horizontal: 12), - height: 100, - child: Row( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Container( - child: Icon( - Icons.unfold_more, - color: c, - ), - ), - Container( - child: ClipRRect( - borderRadius: BorderRadius.all(Radius.circular(30)), - child: Container( - height: 60, - width: 60, - child: Image.file( - File("${widget.podcastLocal.imagePath}")), - ), - ), - ), - Container( - width: width / 2, - padding: EdgeInsets.symmetric(horizontal: 10), - alignment: Alignment.centerLeft, - child: Column( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Container( - alignment: Alignment.centerLeft, - child: Text( - widget.podcastLocal.title, - maxLines: 2, - overflow: TextOverflow.fade, - style: TextStyle( - fontWeight: FontWeight.bold, fontSize: 15), - ), - ), - Row( - children: _belongGroups.map((group) { - return Container( - padding: EdgeInsets.only(right: 5.0), - child: Text(group.name)); - }).toList(), - ), - ], - )), - Spacer(), - Transform.rotate( - angle: math.pi * _value, - child: Icon(Icons.keyboard_arrow_down), - ), - Padding( - padding: EdgeInsets.symmetric(horizontal: 5.0), - ), - ]), - ), - ), - !_loadMenu - ? Center() - : Container( - child: Container( - decoration: BoxDecoration( - color: Theme.of(context).primaryColor, - border: Border( - bottom: BorderSide( - color: Theme.of(context).primaryColorDark), - top: BorderSide( - color: Theme.of(context).primaryColorDark))), - height: 50, - child: _addGroup - ? Row( - mainAxisAlignment: MainAxisAlignment.start, - children: [ - Expanded( - child: SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: Row( - children: - groupList.groups.map((group) { - return Container( - padding: EdgeInsets.only(left: 5.0), - child: FilterChip( - key: ValueKey(group.id), - label: Text(group.name), - selected: - _selectedGroups.contains(group), - onSelected: (value) { - setState(() { - if (!value) { - _selectedGroups.remove(group); - } else { - _selectedGroups.add(group); - } - }); - }, - ), - ); - }).toList()), - ), - ), - SizedBox( - width: 100, - child: Row( - mainAxisAlignment: MainAxisAlignment.end, - children: [ - IconButton( - icon: Icon(Icons.clear), - onPressed: () => setState(() { - _addGroup = false; - }), - ), - IconButton( - onPressed: () async { - if (_selectedGroups.length > 0) { - setState(() { - _addGroup = false; - }); - await groupList.changeGroup( - widget.podcastLocal.id, - _selectedGroups, - ); - Fluttertoast.showToast( - msg: s.toastSettingSaved, - gravity: ToastGravity.BOTTOM, - ); - } else { - Fluttertoast.showToast( - msg: s.toastOneGroup, - gravity: ToastGravity.BOTTOM, - ); - } - }, - icon: Icon(Icons.done), - ), - ], - ), - ) - ], - ) - : Row( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - children: [ - _buttonOnMenu( - icon: Icon(Icons.add, - size: _value == 0 ? 1 : 20 * _value), - onTap: () { - setState(() { - _addGroup = true; - }); - }, - tooltip: s.groups(0)), - FutureBuilder( - future: - _getAutoDownload(widget.podcastLocal.id), - initialData: false, - builder: (context, snapshot) { - return _buttonOnMenu( - icon: Container( - child: Icon(Icons.file_download, - size: _value * 15, - color: snapshot.data - ? Colors.white - : null), - height: _value == 0 ? 1 : 20 * _value, - width: _value == 0 ? 1 : 20 * _value, - decoration: BoxDecoration( - border: snapshot.data - ? Border.all( - width: 1, - color: snapshot.data - ? context.accentColor - : context.textTheme - .subtitle1.color) - : null, - shape: BoxShape.circle, - color: snapshot.data - ? context.accentColor - : null), - ), - tooltip: s.autoDownload, - onTap: () async { - await _setAutoDownload( - widget.podcastLocal.id, - !snapshot.data); - setState(() {}); - }, - ); - }, - ), - FutureBuilder( - future: - _getSkipSecond(widget.podcastLocal.id), - initialData: 0, - builder: (context, snapshot) { - return _buttonOnMenu( - icon: Icon( - Icons.fast_forward, - size: _value == 0 ? 1 : 20 * (_value), - ), - tooltip: - 'Skip${snapshot.data == 0 ? '' : snapshot.data.toTime}', - onTap: () { - generalDialog( - context, - title: Text(s.skipSecondsAtStart, - maxLines: 2), - content: DurationPicker( - duration: Duration( - seconds: _skipSeconds ?? 0), - onChange: (value) => - _seconds = value.inSeconds, - ), - actions: [ - FlatButton( - splashColor: context.accentColor - .withAlpha(70), - onPressed: () { - Navigator.of(context).pop(); - _seconds = 0; - }, - child: Text( - s.cancel, - style: TextStyle( - color: Colors.grey[600]), - ), - ), - FlatButton( - splashColor: context.accentColor - .withAlpha(70), - onPressed: () { - Navigator.of(context).pop(); - _saveSkipSeconds( - widget.podcastLocal.id, - _seconds); - }, - child: Text( - s.confirm, - style: TextStyle( - color: - context.accentColor), - ), - ) - ], - ); - }); - }), - _buttonOnMenu( - icon: Icon( - Icons.delete, - color: Colors.red, - size: _value == 0 ? 1 : 20 * _value, - ), - tooltip: s.remove, - onTap: () { - generalDialog( - context, - title: Text(s.removeConfirm), - content: Text(s.removePodcastDes), - actions: [ - FlatButton( - splashColor: - context.accentColor.withAlpha(70), - onPressed: () => - Navigator.of(context).pop(), - child: Text( - s.cancel, - style: TextStyle( - color: Colors.grey[600]), - ), - ), - FlatButton( - splashColor: Colors.red.withAlpha(70), - onPressed: () { - groupList.removePodcast( - widget.podcastLocal); - Navigator.of(context).pop(); - }, - child: Text( - s.confirm, - style: TextStyle(color: Colors.red), - ), - ) - ], - ); - }), - ], - ), - ), - ), - ], - ), - ); - } -} - -class RenameGroup extends StatefulWidget { - final PodcastGroup group; - RenameGroup({this.group, Key key}) : super(key: key); - @override - _RenameGroupState createState() => _RenameGroupState(); -} - -class _RenameGroupState extends State { - TextEditingController _controller; - String _newName; - int _error; - - @override - void initState() { - super.initState(); - _error = 0; - _controller = TextEditingController(text: widget.group.name); - } - - @override - void dispose() { - _controller.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - var groupList = Provider.of(context, listen: false); - List list = groupList.groups.map((e) => e.name).toList(); - final s = context.s; - return AnnotatedRegion( - value: SystemUiOverlayStyle( - statusBarIconBrightness: Brightness.light, - systemNavigationBarColor: - Theme.of(context).brightness == Brightness.light - ? Color.fromRGBO(113, 113, 113, 1) - : Color.fromRGBO(5, 5, 5, 1), - ), - child: AlertDialog( - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(10))), - elevation: 1, - contentPadding: EdgeInsets.symmetric(horizontal: 20), - titlePadding: EdgeInsets.only(top: 20, left: 20, right: 20, bottom: 20), - actionsPadding: EdgeInsets.all(0), - actions: [ - FlatButton( - splashColor: context.accentColor.withAlpha(70), - onPressed: () => Navigator.of(context).pop(), - child: Text( - s.cancel, - style: TextStyle(color: Colors.grey[600]), - ), - ), - FlatButton( - splashColor: context.accentColor.withAlpha(70), - onPressed: () async { - if (list.contains(_newName)) { - setState(() => _error = 1); - } else { - var newGroup = PodcastGroup(_newName, - color: widget.group.color, - id: widget.group.id, - podcastList: widget.group.podcastList); - groupList.updateGroup(newGroup); - Navigator.of(context).pop(); - } - }, - child: Text(s.confirm, - style: TextStyle(color: Theme.of(context).accentColor)), - ) - ], - title: - SizedBox(width: context.width - 160, child: Text(s.editGroupName)), - content: Column( - mainAxisSize: MainAxisSize.min, - children: [ - TextField( - decoration: InputDecoration( - contentPadding: EdgeInsets.symmetric(horizontal: 10), - hintStyle: TextStyle(fontSize: 18), - filled: true, - focusedBorder: UnderlineInputBorder( - borderSide: BorderSide( - color: Theme.of(context).accentColor, width: 2.0), - ), - enabledBorder: UnderlineInputBorder( - borderSide: BorderSide( - color: Theme.of(context).accentColor, width: 2.0), - ), - ), - cursorRadius: Radius.circular(2), - autofocus: true, - maxLines: 1, - controller: _controller, - onChanged: (value) { - _newName = value; - }, - ), - Container( - alignment: Alignment.centerLeft, - child: (_error == 1) - ? Text( - s.groupExisted, - style: TextStyle(color: Colors.red[400]), - ) - : Center(), - ), - ], - ), - ), - ); - } -} +import 'dart:io'; +import 'dart:math' as math; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:permission_handler/permission_handler.dart'; +import 'package:provider/provider.dart'; + +import '../local_storage/sqflite_localpodcast.dart'; +import '../state/podcast_group.dart'; +import '../type/podcastlocal.dart'; +import '../util/duraiton_picker.dart'; +import '../util/extension_helper.dart'; +import '../util/general_dialog.dart'; + +class PodcastGroupList extends StatefulWidget { + final PodcastGroup group; + PodcastGroupList({this.group, Key key}) : super(key: key); + @override + _PodcastGroupListState createState() => _PodcastGroupListState(); +} + +class _PodcastGroupListState extends State { + @override + Widget build(BuildContext context) { + var groupList = Provider.of(context, listen: false); + return widget.group.podcastList.length == 0 + ? Container( + color: Theme.of(context).primaryColor, + ) + : Container( + color: Theme.of(context).primaryColor, + child: ReorderableListView( + onReorder: (oldIndex, newIndex) { + setState(() { + if (newIndex > oldIndex) { + newIndex -= 1; + } + final podcast = widget.group.podcasts.removeAt(oldIndex); + widget.group.podcasts.insert(newIndex, podcast); + }); + widget.group.orderedPodcasts = widget.group.podcasts; + groupList.addToOrderChanged(widget.group); + }, + children: widget.group.podcasts.map((podcastLocal) { + return Container( + decoration: + BoxDecoration(color: Theme.of(context).primaryColor), + key: ObjectKey(podcastLocal.title), + child: _PodcastCard( + podcastLocal: podcastLocal, + group: widget.group, + ), + ); + }).toList(), + ), + ); + } +} + +class _PodcastCard extends StatefulWidget { + final PodcastLocal podcastLocal; + final PodcastGroup group; + _PodcastCard({this.podcastLocal, this.group, Key key}) : super(key: key); + @override + __PodcastCardState createState() => __PodcastCardState(); +} + +class __PodcastCardState extends State<_PodcastCard> + with SingleTickerProviderStateMixin { + bool _loadMenu; + bool _addGroup; + List _selectedGroups; + List _belongGroups; + AnimationController _controller; + Animation _animation; + double _value; + int _seconds; + int _skipSeconds; + + Future _getSkipSecond(String id) async { + var dbHelper = DBHelper(); + var seconds = await dbHelper.getSkipSecondsStart(id); + _skipSeconds = seconds; + return seconds; + } + + _saveSkipSeconds(String id, int seconds) async { + var dbHelper = DBHelper(); + await dbHelper.saveSkipSecondsStart(id, seconds); + } + + _setAutoDownload(String id, bool boo) async { + var permission = await _checkPermmison(); + if (permission) { + var dbHelper = DBHelper(); + await dbHelper.saveAutoDownload(id, boo: boo); + } + } + + Future _getAutoDownload(String id) async { + var dbHelper = DBHelper(); + return await dbHelper.getAutoDownload(id); + } + + Future _checkPermmison() async { + var permission = await Permission.storage.status; + if (permission != PermissionStatus.granted) { + var permissions = await [Permission.storage].request(); + if (permissions[Permission.storage] == PermissionStatus.granted) { + return true; + } else { + return false; + } + } else { + return true; + } + } + + @override + void initState() { + super.initState(); + _loadMenu = false; + _addGroup = false; + _selectedGroups = [widget.group]; + _value = 0; + _seconds = 0; + _controller = + AnimationController(vsync: this, duration: Duration(milliseconds: 300)); + _animation = Tween(begin: 0.0, end: 1.0).animate(_controller) + ..addListener(() { + setState(() { + _value = _animation.value; + }); + }); + } + + Widget _buttonOnMenu({Widget icon, VoidCallback onTap, String tooltip}) => + Material( + color: Colors.transparent, + child: InkWell( + onTap: onTap, + child: Container( + height: 50.0, + padding: EdgeInsets.symmetric(horizontal: 5.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Expanded( + child: icon, + ), + Text(tooltip, style: context.textTheme.subtitle2), + ], + )), + ), + ); + + @override + Widget build(BuildContext context) { + final c = widget.podcastLocal.backgroudColor(context); + final s = context.s; + var width = context.width; + var groupList = context.watch(); + _belongGroups = groupList.getPodcastGroup(widget.podcastLocal.id); + + return Container( + decoration: BoxDecoration( + border: Border( + bottom: Divider.createBorderSide(context), + ), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + InkWell( + onTap: () => setState( + () { + _loadMenu = !_loadMenu; + if (_value == 0) { + _controller.forward(); + } else { + _controller.reverse(); + } + }, + ), + child: Container( + padding: EdgeInsets.symmetric(horizontal: 12), + height: 100, + child: Row( + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Container( + child: Icon( + Icons.unfold_more, + color: c, + ), + ), + Container( + child: ClipRRect( + borderRadius: BorderRadius.all(Radius.circular(30)), + child: Container( + height: 60, + width: 60, + child: Image.file( + File("${widget.podcastLocal.imagePath}")), + ), + ), + ), + Container( + width: width / 2, + padding: EdgeInsets.symmetric(horizontal: 10), + alignment: Alignment.centerLeft, + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Container( + alignment: Alignment.centerLeft, + child: Text( + widget.podcastLocal.title, + maxLines: 2, + overflow: TextOverflow.fade, + style: TextStyle( + fontWeight: FontWeight.bold, fontSize: 15), + ), + ), + Row( + children: _belongGroups.map((group) { + return Container( + padding: EdgeInsets.only(right: 5.0), + child: Text(group.name)); + }).toList(), + ), + ], + )), + Spacer(), + Transform.rotate( + angle: math.pi * _value, + child: Icon(Icons.keyboard_arrow_down), + ), + Padding( + padding: EdgeInsets.symmetric(horizontal: 5.0), + ), + ]), + ), + ), + !_loadMenu + ? Center() + : Container( + child: Container( + decoration: BoxDecoration( + color: Theme.of(context).primaryColor, + border: Border( + bottom: BorderSide( + color: Theme.of(context).primaryColorDark), + top: BorderSide( + color: Theme.of(context).primaryColorDark))), + height: 50, + child: _addGroup + ? Row( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + Expanded( + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: + groupList.groups.map((group) { + return Container( + padding: EdgeInsets.only(left: 5.0), + child: FilterChip( + key: ValueKey(group.id), + label: Text(group.name), + selected: + _selectedGroups.contains(group), + onSelected: (value) { + setState(() { + if (!value) { + _selectedGroups.remove(group); + } else { + _selectedGroups.add(group); + } + }); + }, + ), + ); + }).toList()), + ), + ), + SizedBox( + width: 100, + child: Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + IconButton( + icon: Icon(Icons.clear), + onPressed: () => setState(() { + _addGroup = false; + }), + ), + IconButton( + onPressed: () async { + if (_selectedGroups.length > 0) { + setState(() { + _addGroup = false; + }); + await groupList.changeGroup( + widget.podcastLocal.id, + _selectedGroups, + ); + Fluttertoast.showToast( + msg: s.toastSettingSaved, + gravity: ToastGravity.BOTTOM, + ); + } else { + Fluttertoast.showToast( + msg: s.toastOneGroup, + gravity: ToastGravity.BOTTOM, + ); + } + }, + icon: Icon(Icons.done), + ), + ], + ), + ) + ], + ) + : Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + _buttonOnMenu( + icon: Icon(Icons.add, + size: _value == 0 ? 1 : 20 * _value), + onTap: () { + setState(() { + _addGroup = true; + }); + }, + tooltip: s.groups(0)), + FutureBuilder( + future: + _getAutoDownload(widget.podcastLocal.id), + initialData: false, + builder: (context, snapshot) { + return _buttonOnMenu( + icon: Container( + child: Icon(Icons.file_download, + size: _value * 15, + color: snapshot.data + ? Colors.white + : null), + height: _value == 0 ? 1 : 20 * _value, + width: _value == 0 ? 1 : 20 * _value, + decoration: BoxDecoration( + border: snapshot.data + ? Border.all( + width: 1, + color: snapshot.data + ? context.accentColor + : context.textTheme + .subtitle1.color) + : null, + shape: BoxShape.circle, + color: snapshot.data + ? context.accentColor + : null), + ), + tooltip: s.autoDownload, + onTap: () async { + await _setAutoDownload( + widget.podcastLocal.id, + !snapshot.data); + setState(() {}); + }, + ); + }, + ), + FutureBuilder( + future: + _getSkipSecond(widget.podcastLocal.id), + initialData: 0, + builder: (context, snapshot) { + return _buttonOnMenu( + icon: Icon( + Icons.fast_forward, + size: _value == 0 ? 1 : 20 * (_value), + ), + tooltip: + 'Skip${snapshot.data == 0 ? '' : snapshot.data.toTime}', + onTap: () { + generalDialog( + context, + title: Text(s.skipSecondsAtStart, + maxLines: 2), + content: DurationPicker( + duration: Duration( + seconds: _skipSeconds ?? 0), + onChange: (value) => + _seconds = value.inSeconds, + ), + actions: [ + FlatButton( + splashColor: context.accentColor + .withAlpha(70), + onPressed: () { + Navigator.of(context).pop(); + _seconds = 0; + }, + child: Text( + s.cancel, + style: TextStyle( + color: Colors.grey[600]), + ), + ), + FlatButton( + splashColor: context.accentColor + .withAlpha(70), + onPressed: () { + Navigator.of(context).pop(); + _saveSkipSeconds( + widget.podcastLocal.id, + _seconds); + }, + child: Text( + s.confirm, + style: TextStyle( + color: + context.accentColor), + ), + ) + ], + ); + }); + }), + _buttonOnMenu( + icon: Icon( + Icons.delete, + color: Colors.red, + size: _value == 0 ? 1 : 20 * _value, + ), + tooltip: s.remove, + onTap: () { + generalDialog( + context, + title: Text(s.removeConfirm), + content: Text(s.removePodcastDes), + actions: [ + FlatButton( + splashColor: + context.accentColor.withAlpha(70), + onPressed: () => + Navigator.of(context).pop(), + child: Text( + s.cancel, + style: TextStyle( + color: Colors.grey[600]), + ), + ), + FlatButton( + splashColor: Colors.red.withAlpha(70), + onPressed: () { + groupList.removePodcast( + widget.podcastLocal); + Navigator.of(context).pop(); + }, + child: Text( + s.confirm, + style: TextStyle(color: Colors.red), + ), + ) + ], + ); + }), + ], + ), + ), + ), + ], + ), + ); + } +} + +class RenameGroup extends StatefulWidget { + final PodcastGroup group; + RenameGroup({this.group, Key key}) : super(key: key); + @override + _RenameGroupState createState() => _RenameGroupState(); +} + +class _RenameGroupState extends State { + TextEditingController _controller; + String _newName; + int _error; + + @override + void initState() { + super.initState(); + _error = 0; + _controller = TextEditingController(text: widget.group.name); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + var groupList = Provider.of(context, listen: false); + List list = groupList.groups.map((e) => e.name).toList(); + final s = context.s; + return AnnotatedRegion( + value: SystemUiOverlayStyle( + statusBarIconBrightness: Brightness.light, + systemNavigationBarColor: + Theme.of(context).brightness == Brightness.light + ? Color.fromRGBO(113, 113, 113, 1) + : Color.fromRGBO(5, 5, 5, 1), + ), + child: AlertDialog( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(10))), + elevation: 1, + contentPadding: EdgeInsets.symmetric(horizontal: 20), + titlePadding: EdgeInsets.only(top: 20, left: 20, right: 20, bottom: 20), + actionsPadding: EdgeInsets.all(0), + actions: [ + FlatButton( + splashColor: context.accentColor.withAlpha(70), + onPressed: () => Navigator.of(context).pop(), + child: Text( + s.cancel, + style: TextStyle(color: Colors.grey[600]), + ), + ), + FlatButton( + splashColor: context.accentColor.withAlpha(70), + onPressed: () async { + if (list.contains(_newName)) { + setState(() => _error = 1); + } else { + var newGroup = PodcastGroup(_newName, + color: widget.group.color, + id: widget.group.id, + podcastList: widget.group.podcastList); + groupList.updateGroup(newGroup); + Navigator.of(context).pop(); + } + }, + child: Text(s.confirm, + style: TextStyle(color: Theme.of(context).accentColor)), + ) + ], + title: + SizedBox(width: context.width - 160, child: Text(s.editGroupName)), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextField( + decoration: InputDecoration( + contentPadding: EdgeInsets.symmetric(horizontal: 10), + hintStyle: TextStyle(fontSize: 18), + filled: true, + focusedBorder: UnderlineInputBorder( + borderSide: BorderSide( + color: Theme.of(context).accentColor, width: 2.0), + ), + enabledBorder: UnderlineInputBorder( + borderSide: BorderSide( + color: Theme.of(context).accentColor, width: 2.0), + ), + ), + cursorRadius: Radius.circular(2), + autofocus: true, + maxLines: 1, + controller: _controller, + onChanged: (value) { + _newName = value; + }, + ), + Container( + alignment: Alignment.centerLeft, + child: (_error == 1) + ? Text( + s.groupExisted, + style: TextStyle(color: Colors.red[400]), + ) + : Center(), + ), + ], + ), + ), + ); + } +} diff --git a/lib/podcasts/podcast_manage.dart b/lib/podcasts/podcast_manage.dart index 96e088e..80976bf 100644 --- a/lib/podcasts/podcast_manage.dart +++ b/lib/podcasts/podcast_manage.dart @@ -1,663 +1,663 @@ -import 'dart:math' as math; - -import 'package:feature_discovery/feature_discovery.dart'; -import 'package:flutter/gestures.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:fluttertoast/fluttertoast.dart'; -import 'package:line_icons/line_icons.dart'; -import 'package:provider/provider.dart'; - -import '../state/podcast_group.dart'; -import '../util/custom_widget.dart'; -import '../util/extension_helper.dart'; -import '../util/general_dialog.dart'; -import '../util/pageroute.dart'; -import 'custom_tabview.dart'; -import 'podcast_group.dart'; -import 'podcastlist.dart'; - -const String addGroupFeature = 'addGroupFeature'; -const String configureGroup = 'configureFeature'; -const String configurePodcast = 'configurePodcast'; - -class PodcastManage extends StatefulWidget { - @override - _PodcastManageState createState() => _PodcastManageState(); -} - -class _PodcastManageState extends State - with TickerProviderStateMixin { - bool _showSetting; - double _menuValue; - AnimationController _controller; - AnimationController _menuController; - Animation _animation; - Animation _menuAnimation; - double _fraction; - int _index; - - @override - void initState() { - super.initState(); - _showSetting = false; - _fraction = 0; - _menuValue = 0; - _index = 0; - _menuController = AnimationController( - vsync: this, duration: const Duration(milliseconds: 150)); - _controller = AnimationController( - vsync: this, duration: const Duration(milliseconds: 500)); - _animation = Tween(begin: 0.0, end: 1.0).animate(_controller) - ..addListener(() { - if (mounted) { - setState(() => _fraction = _animation.value); - } - }); - _menuAnimation = Tween(begin: 0.0, end: 1.0).animate( - CurvedAnimation(parent: _menuController, curve: Curves.elasticInOut)) - ..addListener(() { - if (mounted) setState(() => _menuValue = _menuAnimation.value); - }); - - _controller.addStatusListener((status) { - if (status == AnimationStatus.completed) { - _controller.stop(); - } else if (status == AnimationStatus.dismissed) { - _controller.stop(); - } - }); - FeatureDiscovery.isDisplayed(context, addGroupFeature).then((value) { - if (!value) { - WidgetsBinding.instance.addPostFrameCallback((_) { - FeatureDiscovery.discoverFeatures(context, const { - addGroupFeature, - configureGroup, - configurePodcast - }); - }); - } - }); - } - - @override - void dispose() { - _controller.dispose(); - _menuController.dispose(); - super.dispose(); - } - - Widget _saveButton() { - final s = context.s; - return Consumer( - builder: (_, groupList, __) { - if (groupList.orderChanged.contains(groupList.groups[_index])) { - _controller.forward(); - } else if (_fraction > 0) { - _controller.reverse(); - } - return DescribedFeatureOverlay( - featureId: configureGroup, - tapTarget: Icon(Icons.menu), - title: Padding( - padding: const EdgeInsets.only(top: 20.0), - child: Text(s.featureDiscoveryEditGroup), - ), - overflowMode: OverflowMode.clipContent, - backgroundColor: Colors.cyan[600], - onDismiss: () => Future.value(true), - description: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(s.featureDiscoveryEditGroupDes), - FlatButton( - color: Colors.cyan[500], - padding: const EdgeInsets.all(0), - child: Text(s.understood, - style: Theme.of(context) - .textTheme - .button - .copyWith(color: Colors.white)), - onPressed: () async => - FeatureDiscovery.completeCurrentStep(context), - ), - FlatButton( - color: Colors.cyan[500], - padding: const EdgeInsets.all(0), - child: Text(s.dismiss, - style: Theme.of(context) - .textTheme - .button - .copyWith(color: Colors.white)), - onPressed: () => FeatureDiscovery.dismissAll(context), - ), - ], - ), - child: Transform( - alignment: FractionalOffset(0.5, 0.5), - transform: Matrix4.rotationY(math.pi * _fraction), - child: InkWell( - onTap: () async { - if (_fraction == 0) { - !_showSetting - ? _menuController.forward() - : await _menuController.reverse(); - if (mounted) { - setState(() { - _showSetting = !_showSetting; - }); - } - } else { - groupList.saveOrder(groupList.groups[_index]); - groupList.drlFromOrderChanged(groupList.groups[_index].name); - Fluttertoast.showToast( - msg: context.s.toastSettingSaved, - gravity: ToastGravity.BOTTOM, - ); - _controller.reverse(); - } - }, - child: Container( - width: 50, - height: 50, - decoration: BoxDecoration( - color: _fraction > 0.5 - ? Colors.red - : Theme.of(context).accentColor, - shape: BoxShape.circle, - boxShadow: [ - BoxShadow( - color: Colors.grey[700].withOpacity(0.5), - blurRadius: 1, - offset: Offset(1, 1), - ), - ]), - alignment: Alignment.center, - child: _fraction > 0.5 - ? Icon(LineIcons.save_solid, color: Colors.white) - : AnimatedIcon( - color: Colors.white, - icon: AnimatedIcons.menu_close, - progress: _menuController, - ), - // color: Colors.white, - ), - ), - ), - ); - }, - ); - } - - @override - Widget build(BuildContext context) { - final s = context.s; - return AnnotatedRegion( - value: SystemUiOverlayStyle( - statusBarIconBrightness: Theme.of(context).accentColorBrightness, - systemNavigationBarColor: Theme.of(context).primaryColor, - systemNavigationBarIconBrightness: - Theme.of(context).accentColorBrightness, - // statusBarColor: Theme.of(context).primaryColor, - ), - child: Scaffold( - appBar: AppBar( - centerTitle: true, - title: Text(context.s.groups(2)), - leading: CustomBackButton(), - actions: [ - DescribedFeatureOverlay( - featureId: addGroupFeature, - tapTarget: Icon(Icons.add), - title: Text(s.featureDiscoveryGroup), - overflowMode: OverflowMode.clipContent, - backgroundColor: Colors.cyan[600], - onDismiss: () => Future.value(true), - description: Column( - crossAxisAlignment: CrossAxisAlignment.end, - children: [ - Text(s.featureDiscoveryGroupDes), - FlatButton( - color: Colors.cyan[500], - padding: const EdgeInsets.all(0), - child: Text(context.s.understood, - style: Theme.of(context) - .textTheme - .button - .copyWith(color: Colors.white)), - onPressed: () async => - FeatureDiscovery.completeCurrentStep(context), - ), - FlatButton( - color: Colors.cyan[500], - padding: const EdgeInsets.all(0), - child: Text(context.s.dismiss, - style: Theme.of(context) - .textTheme - .button - .copyWith(color: Colors.white)), - onPressed: () => FeatureDiscovery.dismissAll(context), - ), - ], - ), - child: IconButton( - onPressed: () => showGeneralDialog( - context: context, - barrierDismissible: true, - barrierLabel: MaterialLocalizations.of(context) - .modalBarrierDismissLabel, - barrierColor: Colors.black54, - transitionDuration: const Duration(milliseconds: 200), - pageBuilder: (context, animaiton, secondaryAnimation) => - AddGroup()), - icon: Icon(Icons.add)), - ), - _OrderMenu(), - ], - ), - body: WillPopScope( - onWillPop: () async { - await Provider.of(context, listen: false) - .clearOrderChanged(); - return true; - }, - child: Consumer( - builder: (_, groupList, __) { - var _isLoading = groupList.isLoading; - var _groups = groupList.groups; - return _isLoading - ? Center() - : Stack( - children: [ - Container( - color: context.scaffoldBackgroundColor, - child: CustomTabView( - itemCount: _groups.length, - tabBuilder: (context, index) => Tab( - child: Container( - height: 30.0, - padding: - EdgeInsets.symmetric(horizontal: 10.0), - alignment: Alignment.center, - decoration: BoxDecoration( - color: Colors.grey[600].withOpacity(0.3), - borderRadius: BorderRadius.circular(15), - ), - child: Text( - _groups[index].name, - )), - ), - pageBuilder: (context, index) => - DescribedFeatureOverlay( - featureId: configurePodcast, - tapTarget: Text(s.podcast(1)), - title: Text(s.featureDiscoveryGroupPodcast), - overflowMode: OverflowMode.clipContent, - onDismiss: () => Future.value(true), - enablePulsingAnimation: false, - backgroundColor: Colors.cyan[600], - description: Column( - crossAxisAlignment: CrossAxisAlignment.end, - children: [ - Text(s.featureDiscoveryGroupPodcastDes), - FlatButton( - color: Colors.cyan[500], - padding: const EdgeInsets.all(0), - child: Text(context.s.understood, - style: context.textTheme.button - .copyWith(color: Colors.white)), - onPressed: () async => - FeatureDiscovery.completeCurrentStep( - context), - ), - FlatButton( - color: Colors.cyan[500], - padding: const EdgeInsets.all(0), - child: Text(context.s.dismiss, - style: context.textTheme.button - .copyWith(color: Colors.white)), - onPressed: () => - FeatureDiscovery.dismissAll(context), - ), - ], - ), - child: Container( - key: ValueKey(_groups[index].name), - child: - PodcastGroupList(group: _groups[index])), - ), - onPositionChange: (value) => - // setState(() => - _index = value, - ), - ), - if (_showSetting) - Positioned.fill( - top: 50, - child: GestureDetector( - onTap: () async { - await _menuController.reverse(); - if (mounted) { - setState(() => _showSetting = false); - } - }, - child: Container( - color: context.scaffoldBackgroundColor - .withOpacity(0.8 * - math.min( - _menuController.value * 2, 1.0)), - ), - ), - ), - Positioned( - right: 30, - bottom: 30, - child: _saveButton(), - ), - if (_showSetting) - Positioned( - right: 100 * _menuValue - 70, - bottom: 100, - child: Column( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.end, - children: [ - Material( - color: Colors.transparent, - child: InkWell( - onTap: () { - _menuController.reverse(); - setState(() => _showSetting = false); - _index == 0 - ? Fluttertoast.showToast( - msg: s.toastHomeGroupNotSupport, - gravity: ToastGravity.BOTTOM, - ) - : showGeneralDialog( - context: context, - barrierDismissible: true, - barrierLabel: - MaterialLocalizations.of( - context) - .modalBarrierDismissLabel, - barrierColor: Colors.black54, - transitionDuration: - const Duration( - milliseconds: 300), - pageBuilder: (context, animaiton, - secondaryAnimation) => - RenameGroup( - group: _groups[_index], - )); - }, - child: Container( - height: 30.0, - decoration: BoxDecoration( - color: Colors.grey[700], - borderRadius: - BorderRadius.circular(10.0)), - padding: - EdgeInsets.symmetric(horizontal: 10), - child: Row( - children: [ - Icon( - Icons.text_fields, - color: Colors.white, - size: 15.0, - ), - Padding( - padding: EdgeInsets.symmetric( - horizontal: 5.0), - ), - Text(context.s.editGroupName, - style: TextStyle( - color: Colors.white)), - ], - ), - ), - ), - ), - Padding( - padding: - EdgeInsets.symmetric(vertical: 10.0)), - Material( - color: Colors.transparent, - child: InkWell( - onTap: () { - _menuController.reverse(); - setState(() => _showSetting = false); - _index == 0 - ? Fluttertoast.showToast( - msg: s.toastHomeGroupNotSupport, - gravity: ToastGravity.BOTTOM, - ) - : generalDialog( - context, - title: Text(s.removeConfirm), - content: - Text(s.groupRemoveConfirm), - actions: [ - FlatButton( - splashColor: context - .accentColor - .withAlpha(70), - onPressed: () => - Navigator.of(context) - .pop(), - child: Text( - context.s.cancel, - style: TextStyle( - color: - Colors.grey[600]), - ), - ), - FlatButton( - splashColor: context - .accentColor - .withAlpha(70), - onPressed: () { - if (_index == - groupList - .groups.length - - 1) { - setState(() { - _index = _index - 1; - }); - groupList.delGroup( - _groups[_index + 1]); - } else { - groupList.delGroup( - _groups[_index]); - } - Navigator.of(context).pop(); - }, - child: Text( - context.s.confirm, - style: TextStyle( - color: Colors.red), - ), - ) - ], - ); - }, - child: Container( - height: 30, - decoration: BoxDecoration( - color: Colors.grey[700], - borderRadius: BorderRadius.all( - Radius.circular(10.0))), - padding: - EdgeInsets.symmetric(horizontal: 10), - child: Row( - children: [ - Icon( - Icons.delete_outline, - color: Colors.red, - size: 15.0, - ), - Padding( - padding: EdgeInsets.symmetric( - horizontal: 5.0), - ), - Text(s.remove, - style: - TextStyle(color: Colors.red)), - ], - ), - ), - ), - ), - ], - ), - ), - ], - ); - }, - ), - ), - ), - ); - } -} - -class _OrderMenu extends StatelessWidget { - @override - Widget build(BuildContext context) { - final s = context.s; - return PopupMenuButton( - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(10))), - elevation: 2, - tooltip: s.menu, - itemBuilder: (context) => [ - PopupMenuItem( - value: 1, - child: Row( - children: [ - Icon(Icons.all_out), - Padding( - padding: EdgeInsets.symmetric(horizontal: 5.0), - ), - Text(s.menuAllPodcasts), - ], - ), - ), - ], - onSelected: (value) { - if (value == 1) { - Navigator.push(context, ScaleRoute(page: PodcastList())); - } - }, - ); - } -} - -class AddGroup extends StatefulWidget { - @override - _AddGroupState createState() => _AddGroupState(); -} - -class _AddGroupState extends State { - TextEditingController _controller; - String _newGroup; - int _error; - - @override - void initState() { - super.initState(); - _error = 0; - _controller = TextEditingController(); - } - - @override - void dispose() { - _controller.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - final s = context.s; - var groupList = Provider.of(context, listen: false); - List list = groupList.groups.map((e) => e.name).toList(); - return AnnotatedRegion( - value: SystemUiOverlayStyle( - statusBarIconBrightness: Brightness.light, - systemNavigationBarColor: - Theme.of(context).brightness == Brightness.light - ? Color.fromRGBO(113, 113, 113, 1) - : Color.fromRGBO(5, 5, 5, 1), - ), - child: AlertDialog( - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(10))), - elevation: 1, - contentPadding: const EdgeInsets.symmetric(horizontal: 20), - titlePadding: - const EdgeInsets.only(top: 20, left: 20, right: 20, bottom: 20), - actionsPadding: EdgeInsets.all(0), - actions: [ - FlatButton( - splashColor: context.accentColor.withAlpha(70), - onPressed: () => Navigator.of(context).pop(), - child: Text( - s.cancel, - style: TextStyle(color: Colors.grey[600]), - ), - ), - FlatButton( - splashColor: context.accentColor.withAlpha(70), - onPressed: () async { - if (list.contains(_newGroup)) { - setState(() => _error = 1); - } else { - groupList.addGroup(PodcastGroup(_newGroup)); - Navigator.of(context).pop(); - } - }, - child: Text(s.confirm, - style: TextStyle(color: Theme.of(context).accentColor)), - ) - ], - title: SizedBox(width: context.width - 160, child: Text(s.newGroup)), - content: Column( - mainAxisSize: MainAxisSize.min, - children: [ - TextField( - decoration: InputDecoration( - contentPadding: EdgeInsets.symmetric(horizontal: 10), - hintText: s.newGroup, - hintStyle: TextStyle(fontSize: 18), - filled: true, - focusedBorder: UnderlineInputBorder( - borderSide: BorderSide( - color: Theme.of(context).accentColor, width: 2.0), - ), - enabledBorder: UnderlineInputBorder( - borderSide: BorderSide( - color: Theme.of(context).accentColor, width: 2.0), - ), - ), - cursorRadius: Radius.circular(2), - autofocus: true, - maxLines: 1, - controller: _controller, - onChanged: (value) { - _newGroup = value; - }, - ), - Container( - alignment: Alignment.centerLeft, - child: (_error == 1) - ? Text( - s.groupExisted, - style: TextStyle(color: Colors.red[400]), - ) - : Center(), - ), - ], - ), - ), - ); - } -} +import 'dart:math' as math; + +import 'package:feature_discovery/feature_discovery.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:line_icons/line_icons.dart'; +import 'package:provider/provider.dart'; + +import '../state/podcast_group.dart'; +import '../util/custom_widget.dart'; +import '../util/extension_helper.dart'; +import '../util/general_dialog.dart'; +import '../util/pageroute.dart'; +import 'custom_tabview.dart'; +import 'podcast_group.dart'; +import 'podcastlist.dart'; + +const String addGroupFeature = 'addGroupFeature'; +const String configureGroup = 'configureFeature'; +const String configurePodcast = 'configurePodcast'; + +class PodcastManage extends StatefulWidget { + @override + _PodcastManageState createState() => _PodcastManageState(); +} + +class _PodcastManageState extends State + with TickerProviderStateMixin { + bool _showSetting; + double _menuValue; + AnimationController _controller; + AnimationController _menuController; + Animation _animation; + Animation _menuAnimation; + double _fraction; + int _index; + + @override + void initState() { + super.initState(); + _showSetting = false; + _fraction = 0; + _menuValue = 0; + _index = 0; + _menuController = AnimationController( + vsync: this, duration: const Duration(milliseconds: 150)); + _controller = AnimationController( + vsync: this, duration: const Duration(milliseconds: 500)); + _animation = Tween(begin: 0.0, end: 1.0).animate(_controller) + ..addListener(() { + if (mounted) { + setState(() => _fraction = _animation.value); + } + }); + _menuAnimation = Tween(begin: 0.0, end: 1.0).animate( + CurvedAnimation(parent: _menuController, curve: Curves.elasticInOut)) + ..addListener(() { + if (mounted) setState(() => _menuValue = _menuAnimation.value); + }); + + _controller.addStatusListener((status) { + if (status == AnimationStatus.completed) { + _controller.stop(); + } else if (status == AnimationStatus.dismissed) { + _controller.stop(); + } + }); + FeatureDiscovery.isDisplayed(context, addGroupFeature).then((value) { + if (!value) { + WidgetsBinding.instance.addPostFrameCallback((_) { + FeatureDiscovery.discoverFeatures(context, const { + addGroupFeature, + configureGroup, + configurePodcast + }); + }); + } + }); + } + + @override + void dispose() { + _controller.dispose(); + _menuController.dispose(); + super.dispose(); + } + + Widget _saveButton() { + final s = context.s; + return Consumer( + builder: (_, groupList, __) { + if (groupList.orderChanged.contains(groupList.groups[_index])) { + _controller.forward(); + } else if (_fraction > 0) { + _controller.reverse(); + } + return DescribedFeatureOverlay( + featureId: configureGroup, + tapTarget: Icon(Icons.menu), + title: Padding( + padding: const EdgeInsets.only(top: 20.0), + child: Text(s.featureDiscoveryEditGroup), + ), + overflowMode: OverflowMode.clipContent, + backgroundColor: Colors.cyan[600], + onDismiss: () => Future.value(true), + description: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(s.featureDiscoveryEditGroupDes), + FlatButton( + color: Colors.cyan[500], + padding: const EdgeInsets.all(0), + child: Text(s.understood, + style: Theme.of(context) + .textTheme + .button + .copyWith(color: Colors.white)), + onPressed: () async => + FeatureDiscovery.completeCurrentStep(context), + ), + FlatButton( + color: Colors.cyan[500], + padding: const EdgeInsets.all(0), + child: Text(s.dismiss, + style: Theme.of(context) + .textTheme + .button + .copyWith(color: Colors.white)), + onPressed: () => FeatureDiscovery.dismissAll(context), + ), + ], + ), + child: Transform( + alignment: FractionalOffset(0.5, 0.5), + transform: Matrix4.rotationY(math.pi * _fraction), + child: InkWell( + onTap: () async { + if (_fraction == 0) { + !_showSetting + ? _menuController.forward() + : await _menuController.reverse(); + if (mounted) { + setState(() { + _showSetting = !_showSetting; + }); + } + } else { + groupList.saveOrder(groupList.groups[_index]); + groupList.drlFromOrderChanged(groupList.groups[_index].name); + Fluttertoast.showToast( + msg: context.s.toastSettingSaved, + gravity: ToastGravity.BOTTOM, + ); + _controller.reverse(); + } + }, + child: Container( + width: 50, + height: 50, + decoration: BoxDecoration( + color: _fraction > 0.5 + ? Colors.red + : Theme.of(context).accentColor, + shape: BoxShape.circle, + boxShadow: [ + BoxShadow( + color: Colors.grey[700].withOpacity(0.5), + blurRadius: 1, + offset: Offset(1, 1), + ), + ]), + alignment: Alignment.center, + child: _fraction > 0.5 + ? Icon(LineIcons.save_solid, color: Colors.white) + : AnimatedIcon( + color: Colors.white, + icon: AnimatedIcons.menu_close, + progress: _menuController, + ), + // color: Colors.white, + ), + ), + ), + ); + }, + ); + } + + @override + Widget build(BuildContext context) { + final s = context.s; + return AnnotatedRegion( + value: SystemUiOverlayStyle( + statusBarIconBrightness: Theme.of(context).accentColorBrightness, + systemNavigationBarColor: Theme.of(context).primaryColor, + systemNavigationBarIconBrightness: + Theme.of(context).accentColorBrightness, + // statusBarColor: Theme.of(context).primaryColor, + ), + child: Scaffold( + appBar: AppBar( + centerTitle: true, + title: Text(context.s.groups(2)), + leading: CustomBackButton(), + actions: [ + DescribedFeatureOverlay( + featureId: addGroupFeature, + tapTarget: Icon(Icons.add), + title: Text(s.featureDiscoveryGroup), + overflowMode: OverflowMode.clipContent, + backgroundColor: Colors.cyan[600], + onDismiss: () => Future.value(true), + description: Column( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Text(s.featureDiscoveryGroupDes), + FlatButton( + color: Colors.cyan[500], + padding: const EdgeInsets.all(0), + child: Text(context.s.understood, + style: Theme.of(context) + .textTheme + .button + .copyWith(color: Colors.white)), + onPressed: () async => + FeatureDiscovery.completeCurrentStep(context), + ), + FlatButton( + color: Colors.cyan[500], + padding: const EdgeInsets.all(0), + child: Text(context.s.dismiss, + style: Theme.of(context) + .textTheme + .button + .copyWith(color: Colors.white)), + onPressed: () => FeatureDiscovery.dismissAll(context), + ), + ], + ), + child: IconButton( + onPressed: () => showGeneralDialog( + context: context, + barrierDismissible: true, + barrierLabel: MaterialLocalizations.of(context) + .modalBarrierDismissLabel, + barrierColor: Colors.black54, + transitionDuration: const Duration(milliseconds: 200), + pageBuilder: (context, animaiton, secondaryAnimation) => + AddGroup()), + icon: Icon(Icons.add)), + ), + _OrderMenu(), + ], + ), + body: WillPopScope( + onWillPop: () async { + await Provider.of(context, listen: false) + .clearOrderChanged(); + return true; + }, + child: Consumer( + builder: (_, groupList, __) { + var _isLoading = groupList.isLoading; + var _groups = groupList.groups; + return _isLoading + ? Center() + : Stack( + children: [ + Container( + color: context.scaffoldBackgroundColor, + child: CustomTabView( + itemCount: _groups.length, + tabBuilder: (context, index) => Tab( + child: Container( + height: 30.0, + padding: + EdgeInsets.symmetric(horizontal: 10.0), + alignment: Alignment.center, + decoration: BoxDecoration( + color: Colors.grey[600].withOpacity(0.3), + borderRadius: BorderRadius.circular(15), + ), + child: Text( + _groups[index].name, + )), + ), + pageBuilder: (context, index) => + DescribedFeatureOverlay( + featureId: configurePodcast, + tapTarget: Text(s.podcast(1)), + title: Text(s.featureDiscoveryGroupPodcast), + overflowMode: OverflowMode.clipContent, + onDismiss: () => Future.value(true), + enablePulsingAnimation: false, + backgroundColor: Colors.cyan[600], + description: Column( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Text(s.featureDiscoveryGroupPodcastDes), + FlatButton( + color: Colors.cyan[500], + padding: const EdgeInsets.all(0), + child: Text(context.s.understood, + style: context.textTheme.button + .copyWith(color: Colors.white)), + onPressed: () async => + FeatureDiscovery.completeCurrentStep( + context), + ), + FlatButton( + color: Colors.cyan[500], + padding: const EdgeInsets.all(0), + child: Text(context.s.dismiss, + style: context.textTheme.button + .copyWith(color: Colors.white)), + onPressed: () => + FeatureDiscovery.dismissAll(context), + ), + ], + ), + child: Container( + key: ValueKey(_groups[index].name), + child: + PodcastGroupList(group: _groups[index])), + ), + onPositionChange: (value) => + // setState(() => + _index = value, + ), + ), + if (_showSetting) + Positioned.fill( + top: 50, + child: GestureDetector( + onTap: () async { + await _menuController.reverse(); + if (mounted) { + setState(() => _showSetting = false); + } + }, + child: Container( + color: context.scaffoldBackgroundColor + .withOpacity(0.8 * + math.min( + _menuController.value * 2, 1.0)), + ), + ), + ), + Positioned( + right: 30, + bottom: 30, + child: _saveButton(), + ), + if (_showSetting) + Positioned( + right: 100 * _menuValue - 70, + bottom: 100, + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Material( + color: Colors.transparent, + child: InkWell( + onTap: () { + _menuController.reverse(); + setState(() => _showSetting = false); + _index == 0 + ? Fluttertoast.showToast( + msg: s.toastHomeGroupNotSupport, + gravity: ToastGravity.BOTTOM, + ) + : showGeneralDialog( + context: context, + barrierDismissible: true, + barrierLabel: + MaterialLocalizations.of( + context) + .modalBarrierDismissLabel, + barrierColor: Colors.black54, + transitionDuration: + const Duration( + milliseconds: 300), + pageBuilder: (context, animaiton, + secondaryAnimation) => + RenameGroup( + group: _groups[_index], + )); + }, + child: Container( + height: 30.0, + decoration: BoxDecoration( + color: Colors.grey[700], + borderRadius: + BorderRadius.circular(10.0)), + padding: + EdgeInsets.symmetric(horizontal: 10), + child: Row( + children: [ + Icon( + Icons.text_fields, + color: Colors.white, + size: 15.0, + ), + Padding( + padding: EdgeInsets.symmetric( + horizontal: 5.0), + ), + Text(context.s.editGroupName, + style: TextStyle( + color: Colors.white)), + ], + ), + ), + ), + ), + Padding( + padding: + EdgeInsets.symmetric(vertical: 10.0)), + Material( + color: Colors.transparent, + child: InkWell( + onTap: () { + _menuController.reverse(); + setState(() => _showSetting = false); + _index == 0 + ? Fluttertoast.showToast( + msg: s.toastHomeGroupNotSupport, + gravity: ToastGravity.BOTTOM, + ) + : generalDialog( + context, + title: Text(s.removeConfirm), + content: + Text(s.groupRemoveConfirm), + actions: [ + FlatButton( + splashColor: context + .accentColor + .withAlpha(70), + onPressed: () => + Navigator.of(context) + .pop(), + child: Text( + context.s.cancel, + style: TextStyle( + color: + Colors.grey[600]), + ), + ), + FlatButton( + splashColor: context + .accentColor + .withAlpha(70), + onPressed: () { + if (_index == + groupList + .groups.length - + 1) { + setState(() { + _index = _index - 1; + }); + groupList.delGroup( + _groups[_index + 1]); + } else { + groupList.delGroup( + _groups[_index]); + } + Navigator.of(context).pop(); + }, + child: Text( + context.s.confirm, + style: TextStyle( + color: Colors.red), + ), + ) + ], + ); + }, + child: Container( + height: 30, + decoration: BoxDecoration( + color: Colors.grey[700], + borderRadius: BorderRadius.all( + Radius.circular(10.0))), + padding: + EdgeInsets.symmetric(horizontal: 10), + child: Row( + children: [ + Icon( + Icons.delete_outline, + color: Colors.red, + size: 15.0, + ), + Padding( + padding: EdgeInsets.symmetric( + horizontal: 5.0), + ), + Text(s.remove, + style: + TextStyle(color: Colors.red)), + ], + ), + ), + ), + ), + ], + ), + ), + ], + ); + }, + ), + ), + ), + ); + } +} + +class _OrderMenu extends StatelessWidget { + @override + Widget build(BuildContext context) { + final s = context.s; + return PopupMenuButton( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(10))), + elevation: 2, + tooltip: s.menu, + itemBuilder: (context) => [ + PopupMenuItem( + value: 1, + child: Row( + children: [ + Icon(Icons.all_out), + Padding( + padding: EdgeInsets.symmetric(horizontal: 5.0), + ), + Text(s.menuAllPodcasts), + ], + ), + ), + ], + onSelected: (value) { + if (value == 1) { + Navigator.push(context, ScaleRoute(page: PodcastList())); + } + }, + ); + } +} + +class AddGroup extends StatefulWidget { + @override + _AddGroupState createState() => _AddGroupState(); +} + +class _AddGroupState extends State { + TextEditingController _controller; + String _newGroup; + int _error; + + @override + void initState() { + super.initState(); + _error = 0; + _controller = TextEditingController(); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final s = context.s; + var groupList = Provider.of(context, listen: false); + List list = groupList.groups.map((e) => e.name).toList(); + return AnnotatedRegion( + value: SystemUiOverlayStyle( + statusBarIconBrightness: Brightness.light, + systemNavigationBarColor: + Theme.of(context).brightness == Brightness.light + ? Color.fromRGBO(113, 113, 113, 1) + : Color.fromRGBO(5, 5, 5, 1), + ), + child: AlertDialog( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(10))), + elevation: 1, + contentPadding: const EdgeInsets.symmetric(horizontal: 20), + titlePadding: + const EdgeInsets.only(top: 20, left: 20, right: 20, bottom: 20), + actionsPadding: EdgeInsets.all(0), + actions: [ + FlatButton( + splashColor: context.accentColor.withAlpha(70), + onPressed: () => Navigator.of(context).pop(), + child: Text( + s.cancel, + style: TextStyle(color: Colors.grey[600]), + ), + ), + FlatButton( + splashColor: context.accentColor.withAlpha(70), + onPressed: () async { + if (list.contains(_newGroup)) { + setState(() => _error = 1); + } else { + groupList.addGroup(PodcastGroup(_newGroup)); + Navigator.of(context).pop(); + } + }, + child: Text(s.confirm, + style: TextStyle(color: Theme.of(context).accentColor)), + ) + ], + title: SizedBox(width: context.width - 160, child: Text(s.newGroup)), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextField( + decoration: InputDecoration( + contentPadding: EdgeInsets.symmetric(horizontal: 10), + hintText: s.newGroup, + hintStyle: TextStyle(fontSize: 18), + filled: true, + focusedBorder: UnderlineInputBorder( + borderSide: BorderSide( + color: Theme.of(context).accentColor, width: 2.0), + ), + enabledBorder: UnderlineInputBorder( + borderSide: BorderSide( + color: Theme.of(context).accentColor, width: 2.0), + ), + ), + cursorRadius: Radius.circular(2), + autofocus: true, + maxLines: 1, + controller: _controller, + onChanged: (value) { + _newGroup = value; + }, + ), + Container( + alignment: Alignment.centerLeft, + child: (_error == 1) + ? Text( + s.groupExisted, + style: TextStyle(color: Colors.red[400]), + ) + : Center(), + ), + ], + ), + ), + ); + } +} diff --git a/lib/podcasts/podcast_settings.dart b/lib/podcasts/podcast_settings.dart index 59cf836..a15733d 100644 --- a/lib/podcasts/podcast_settings.dart +++ b/lib/podcasts/podcast_settings.dart @@ -1,470 +1,470 @@ -import 'dart:developer' as developer; -import 'dart:io'; - -import 'package:dio/dio.dart'; -import 'package:flutter/material.dart'; -import 'package:image/image.dart' as img; -import 'package:path_provider/path_provider.dart'; -import 'package:permission_handler/permission_handler.dart'; -import 'package:provider/provider.dart'; -import 'package:webfeed/webfeed.dart'; - -import '../local_storage/sqflite_localpodcast.dart'; -import '../state/podcast_group.dart'; -import '../type/play_histroy.dart'; -import '../type/podcastlocal.dart'; -import '../util/custom_widget.dart'; -import '../util/duraiton_picker.dart'; -import '../util/extension_helper.dart'; - -enum MarkStatus { start, complete, none } -enum RefreshCoverStatus { start, complete, error, none } - -class PodcastSetting extends StatefulWidget { - const PodcastSetting({this.podcastLocal, Key key}) : super(key: key); - final PodcastLocal podcastLocal; - - @override - _PodcastSettingState createState() => _PodcastSettingState(); -} - -class _PodcastSettingState extends State { - final _dbHelper = DBHelper(); - MarkStatus _markStatus = MarkStatus.none; - RefreshCoverStatus _coverStatus = RefreshCoverStatus.none; - int _secondsStart; - int _secondsEnd; - bool _markConfirm; - bool _removeConfirm; - bool _showStartTimePicker; - bool _showEndTimePicker; - - @override - void initState() { - super.initState(); - _secondsStart = 0; - _secondsEnd = 0; - _markConfirm = false; - _removeConfirm = false; - _showStartTimePicker = false; - _showEndTimePicker = false; - } - - Future _setAutoDownload(bool boo) async { - var permission = await _checkPermmison(); - if (permission) { - await _dbHelper.saveAutoDownload(widget.podcastLocal.id, boo: boo); - } - if (mounted) setState(() {}); - } - - Future _setNeverUpdate(bool boo) async { - await _dbHelper.saveNeverUpdate(widget.podcastLocal.id, boo: boo); - if (mounted) setState(() {}); - } - - Future _saveSkipSecondsStart(int seconds) async { - await _dbHelper.saveSkipSecondsStart(widget.podcastLocal.id, seconds); - } - - Future _saveSkipSecondsEnd(int seconds) async { - await _dbHelper.saveSkipSecondsEnd(widget.podcastLocal.id, seconds); - } - - Future _getAutoDownload(String id) async { - return await _dbHelper.getAutoDownload(id); - } - - Future _getNeverUpdate(String id) async { - return await _dbHelper.getNeverUpdate(id); - } - - Future _getSkipSecondStart(String id) async { - return await _dbHelper.getSkipSecondsStart(id); - } - - Future _getSkipSecondEnd(String id) async { - return await _dbHelper.getSkipSecondsEnd(id); - } - - Future _markListened(String podcastId) async { - setState(() { - _markStatus = MarkStatus.start; - }); - final episodes = await _dbHelper.getRssItem(podcastId, -1, - reverse: true, hideListened: true); - for (var episode in episodes) { - final history = PlayHistory(episode.title, episode.enclosureUrl, 0, 1); - await _dbHelper.saveHistory(history); - } - if (mounted) { - setState(() { - _markStatus = MarkStatus.complete; - }); - } - } - - Future _refreshArtWork() async { - setState(() => _coverStatus = RefreshCoverStatus.start); - var options = BaseOptions( - connectTimeout: 30000, - receiveTimeout: 90000, - ); - - var dio = Dio(options); - String imageUrl; - - try { - var response = await dio.get(widget.podcastLocal.rssUrl); - try { - var p = RssFeed.parse(response.data); - imageUrl = p.itunes.image.href ?? p.image.url; - } catch (e) { - developer.log(e.toString()); - if (mounted) setState(() => _coverStatus = RefreshCoverStatus.error); - } - } catch (e) { - developer.log(e.toString()); - if (mounted) setState(() => _coverStatus = RefreshCoverStatus.error); - } - if (imageUrl != null && - imageUrl.contains('http') && - (imageUrl != widget.podcastLocal.imageUrl || - !File(widget.podcastLocal.imageUrl).existsSync())) { - try { - img.Image thumbnail; - var imageResponse = await dio.get>(imageUrl, - options: Options( - responseType: ResponseType.bytes, - )); - var image = img.decodeImage(imageResponse.data); - thumbnail = img.copyResize(image, width: 300); - if (thumbnail != null) { - var dir = await getApplicationDocumentsDirectory(); - File("${dir.path}/${widget.podcastLocal.id}.png") - ..writeAsBytesSync(img.encodePng(thumbnail)); - if (mounted) { - setState(() => _coverStatus = RefreshCoverStatus.complete); - } - } - } catch (e) { - developer.log(e.toString()); - if (mounted) setState(() => _coverStatus = RefreshCoverStatus.error); - } - } else if (_coverStatus == RefreshCoverStatus.start && mounted) { - setState(() => _coverStatus = RefreshCoverStatus.complete); - } - } - - Future _checkPermmison() async { - var permission = await Permission.storage.status; - if (permission != PermissionStatus.granted) { - var permissions = await [Permission.storage].request(); - if (permissions[Permission.storage] == PermissionStatus.granted) { - return true; - } else { - return false; - } - } else { - return true; - } - } - - Widget _getRefreshStatusIcon(RefreshCoverStatus status) { - switch (status) { - case RefreshCoverStatus.none: - return Center(); - break; - case RefreshCoverStatus.start: - return CircularProgressIndicator(strokeWidth: 2); - break; - case RefreshCoverStatus.complete: - return Icon(Icons.done); - break; - case RefreshCoverStatus.error: - return Icon(Icons.refresh, color: Colors.red); - break; - default: - return Center(); - } - } - - @override - Widget build(BuildContext context) { - final s = context.s; - final groupList = context.watch(); - return Column( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - FutureBuilder( - future: _getAutoDownload(widget.podcastLocal.id), - initialData: false, - builder: (context, snapshot) { - return ListTile( - onTap: () => _setAutoDownload(!snapshot.data), - leading: SizedBox( - height: 22, - width: 24, - child: CustomPaint( - painter: DownloadPainter( - color: context.brightness == Brightness.light - ? Colors.grey[600] - : Colors.white, - fraction: 0, - progressColor: context.accentColor, - ), - ), - ), - title: Text(s.autoDownload), - trailing: Transform.scale( - scale: 0.9, - child: - Switch(value: snapshot.data, onChanged: _setAutoDownload), - ), - ); - }), - FutureBuilder( - future: _getNeverUpdate(widget.podcastLocal.id), - initialData: false, - builder: (context, snapshot) { - return ListTile( - onTap: () => _setNeverUpdate(!snapshot.data), - leading: Icon(Icons.lock), - title: Text(s.neverAutoUpdate), - trailing: Transform.scale( - scale: 0.9, - child: - Switch(value: snapshot.data, onChanged: _setNeverUpdate), - ), - ); - }), - FutureBuilder( - future: _getSkipSecondStart(widget.podcastLocal.id), - initialData: 0, - builder: (context, snapshot) => ListTile( - onTap: () { - _secondsStart = 0; - setState(() { - _removeConfirm = false; - _markConfirm = false; - _showEndTimePicker = false; - _showStartTimePicker = !_showStartTimePicker; - }); - }, - leading: Icon(Icons.fast_forward), - title: Text(s.skipSecondsAtStart), - trailing: Padding( - padding: const EdgeInsets.only(right: 10.0), - child: Text(snapshot.data.toTime), - ), - ), - ), - if (_showStartTimePicker) - _TimePicker( - onCancel: () { - _secondsStart = 0; - setState(() => _showStartTimePicker = false); - }, - onConfirm: () async { - await _saveSkipSecondsStart(_secondsStart); - if (mounted) setState(() => _showStartTimePicker = false); - }, - onChange: (value) => _secondsStart = value.inSeconds), - // FutureBuilder( - // future: _getSkipSecondEnd(widget.podcastLocal.id), - // initialData: 0, - // builder: (context, snapshot) => ListTile( - // onTap: () { - // _secondsEnd = 0; - // setState(() { - // _removeConfirm = false; - // _markConfirm = false; - // _showStartTimePicker = false; - // _showEndTimePicker = !_showEndTimePicker; - // }); - // }, - // leading: Icon(Icons.fast_rewind), - // title: Text(s.skipSecondsAtEnd), - // trailing: Padding( - // padding: const EdgeInsets.only(right: 10.0), - // child: Text(snapshot.data.toTime), - // ), - // ), - // ), - // if (_showEndTimePicker) - // _TimePicker( - // onCancel: () { - // _secondsEnd = 0; - // setState(() => _showEndTimePicker = false); - // }, - // onConfirm: () async { - // await _saveSkipSecondsEnd(_secondsEnd); - // setState(() => _showEndTimePicker = false); - // }, - // onChange: (value) => _secondsEnd = value.inSeconds, - // ), - ListTile( - onTap: () { - if (_coverStatus != RefreshCoverStatus.start) { - _refreshArtWork(); - } - }, - title: Text(s.refreshArtwork), - leading: Icon(Icons.refresh), - trailing: Padding( - padding: const EdgeInsets.only(right: 15.0), - child: SizedBox( - height: 20, - width: 20, - child: _getRefreshStatusIcon(_coverStatus)))), - Divider(height: 1), - ListTile( - onTap: () { - setState(() { - _removeConfirm = false; - _showStartTimePicker = false; - _showEndTimePicker = false; - _markConfirm = !_markConfirm; - }); - }, - title: Text(s.menuMarkAllListened, - style: TextStyle( - color: context.accentColor, fontWeight: FontWeight.bold)), - leading: SizedBox( - height: 22, - width: 24, - child: CustomPaint( - painter: ListenedAllPainter( - context.brightness == Brightness.light - ? Colors.grey[600] - : Colors.white, - stroke: 2), - ), - ), - trailing: Padding( - padding: const EdgeInsets.only(right: 10.0), - child: SizedBox( - height: 20, - width: 20, - child: _markStatus == MarkStatus.none - ? Center() - : _markStatus == MarkStatus.start - ? CircularProgressIndicator(strokeWidth: 2) - : Icon(Icons.done)), - )), - if (_markConfirm) - Container( - width: double.infinity, - color: context.primaryColorDark, - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceAround, - children: [ - FlatButton( - onPressed: () => setState(() { - _markConfirm = false; - }), - child: Text( - s.cancel, - style: TextStyle(color: Colors.grey[600]), - )), - FlatButton( - onPressed: () { - if (_markStatus != MarkStatus.start) { - _markListened(widget.podcastLocal.id); - } - setState(() { - _markConfirm = false; - }); - }, - child: Text(s.confirm, - style: TextStyle(color: context.accentColor))), - ], - ), - ), - ListTile( - onTap: () { - setState(() { - _markConfirm = false; - _showStartTimePicker = false; - _showEndTimePicker = false; - _removeConfirm = !_removeConfirm; - }); - }, - title: Text(s.remove, - style: TextStyle(color: Colors.red, fontWeight: FontWeight.bold)), - leading: Icon(Icons.delete, color: Colors.red), - ), - if (_removeConfirm) - Container( - width: double.infinity, - color: context.primaryColorDark, - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceAround, - children: [ - FlatButton( - onPressed: () => setState(() { - _removeConfirm = false; - }), - child: - Text(s.cancel, style: TextStyle(color: Colors.grey[600])), - ), - FlatButton( - splashColor: Colors.red.withAlpha(70), - onPressed: () async { - await groupList.removePodcast(widget.podcastLocal); - Navigator.of(context).pop(); - }, - child: - Text(s.confirm, style: TextStyle(color: Colors.red))), - ], - ), - ), - ], - ); - } -} - -class _TimePicker extends StatelessWidget { - const _TimePicker({this.onConfirm, this.onCancel, this.onChange, Key key}) - : super(key: key); - final VoidCallback onConfirm; - final VoidCallback onCancel; - final ValueChanged onChange; - - @override - Widget build(BuildContext context) { - final s = context.s; - return Container( - color: context.primaryColorDark, - child: Column( - children: [ - SizedBox(height: 10), - DurationPicker( - onChange: onChange, - ), - Row( - mainAxisAlignment: MainAxisAlignment.spaceAround, - children: [ - FlatButton( - onPressed: onCancel, - child: Text( - s.cancel, - style: TextStyle(color: Colors.grey[600]), - ), - ), - FlatButton( - splashColor: context.accentColor.withAlpha(70), - onPressed: onConfirm, - child: Text( - s.confirm, - style: TextStyle(color: context.accentColor), - ), - ) - ], - ) - ], - ), - ); - } -} +import 'dart:developer' as developer; +import 'dart:io'; + +import 'package:dio/dio.dart'; +import 'package:flutter/material.dart'; +import 'package:image/image.dart' as img; +import 'package:path_provider/path_provider.dart'; +import 'package:permission_handler/permission_handler.dart'; +import 'package:provider/provider.dart'; +import 'package:webfeed/webfeed.dart'; + +import '../local_storage/sqflite_localpodcast.dart'; +import '../state/podcast_group.dart'; +import '../type/play_histroy.dart'; +import '../type/podcastlocal.dart'; +import '../util/custom_widget.dart'; +import '../util/duraiton_picker.dart'; +import '../util/extension_helper.dart'; + +enum MarkStatus { start, complete, none } +enum RefreshCoverStatus { start, complete, error, none } + +class PodcastSetting extends StatefulWidget { + const PodcastSetting({this.podcastLocal, Key key}) : super(key: key); + final PodcastLocal podcastLocal; + + @override + _PodcastSettingState createState() => _PodcastSettingState(); +} + +class _PodcastSettingState extends State { + final _dbHelper = DBHelper(); + MarkStatus _markStatus = MarkStatus.none; + RefreshCoverStatus _coverStatus = RefreshCoverStatus.none; + int _secondsStart; + int _secondsEnd; + bool _markConfirm; + bool _removeConfirm; + bool _showStartTimePicker; + bool _showEndTimePicker; + + @override + void initState() { + super.initState(); + _secondsStart = 0; + _secondsEnd = 0; + _markConfirm = false; + _removeConfirm = false; + _showStartTimePicker = false; + _showEndTimePicker = false; + } + + Future _setAutoDownload(bool boo) async { + var permission = await _checkPermmison(); + if (permission) { + await _dbHelper.saveAutoDownload(widget.podcastLocal.id, boo: boo); + } + if (mounted) setState(() {}); + } + + Future _setNeverUpdate(bool boo) async { + await _dbHelper.saveNeverUpdate(widget.podcastLocal.id, boo: boo); + if (mounted) setState(() {}); + } + + Future _saveSkipSecondsStart(int seconds) async { + await _dbHelper.saveSkipSecondsStart(widget.podcastLocal.id, seconds); + } + + Future _saveSkipSecondsEnd(int seconds) async { + await _dbHelper.saveSkipSecondsEnd(widget.podcastLocal.id, seconds); + } + + Future _getAutoDownload(String id) async { + return await _dbHelper.getAutoDownload(id); + } + + Future _getNeverUpdate(String id) async { + return await _dbHelper.getNeverUpdate(id); + } + + Future _getSkipSecondStart(String id) async { + return await _dbHelper.getSkipSecondsStart(id); + } + + Future _getSkipSecondEnd(String id) async { + return await _dbHelper.getSkipSecondsEnd(id); + } + + Future _markListened(String podcastId) async { + setState(() { + _markStatus = MarkStatus.start; + }); + final episodes = await _dbHelper.getRssItem(podcastId, -1, + reverse: true, hideListened: true); + for (var episode in episodes) { + final history = PlayHistory(episode.title, episode.enclosureUrl, 0, 1); + await _dbHelper.saveHistory(history); + } + if (mounted) { + setState(() { + _markStatus = MarkStatus.complete; + }); + } + } + + Future _refreshArtWork() async { + setState(() => _coverStatus = RefreshCoverStatus.start); + var options = BaseOptions( + connectTimeout: 30000, + receiveTimeout: 90000, + ); + + var dio = Dio(options); + String imageUrl; + + try { + var response = await dio.get(widget.podcastLocal.rssUrl); + try { + var p = RssFeed.parse(response.data); + imageUrl = p.itunes.image.href ?? p.image.url; + } catch (e) { + developer.log(e.toString()); + if (mounted) setState(() => _coverStatus = RefreshCoverStatus.error); + } + } catch (e) { + developer.log(e.toString()); + if (mounted) setState(() => _coverStatus = RefreshCoverStatus.error); + } + if (imageUrl != null && + imageUrl.contains('http') && + (imageUrl != widget.podcastLocal.imageUrl || + !File(widget.podcastLocal.imageUrl).existsSync())) { + try { + img.Image thumbnail; + var imageResponse = await dio.get>(imageUrl, + options: Options( + responseType: ResponseType.bytes, + )); + var image = img.decodeImage(imageResponse.data); + thumbnail = img.copyResize(image, width: 300); + if (thumbnail != null) { + var dir = await getApplicationDocumentsDirectory(); + File("${dir.path}/${widget.podcastLocal.id}.png") + ..writeAsBytesSync(img.encodePng(thumbnail)); + if (mounted) { + setState(() => _coverStatus = RefreshCoverStatus.complete); + } + } + } catch (e) { + developer.log(e.toString()); + if (mounted) setState(() => _coverStatus = RefreshCoverStatus.error); + } + } else if (_coverStatus == RefreshCoverStatus.start && mounted) { + setState(() => _coverStatus = RefreshCoverStatus.complete); + } + } + + Future _checkPermmison() async { + var permission = await Permission.storage.status; + if (permission != PermissionStatus.granted) { + var permissions = await [Permission.storage].request(); + if (permissions[Permission.storage] == PermissionStatus.granted) { + return true; + } else { + return false; + } + } else { + return true; + } + } + + Widget _getRefreshStatusIcon(RefreshCoverStatus status) { + switch (status) { + case RefreshCoverStatus.none: + return Center(); + break; + case RefreshCoverStatus.start: + return CircularProgressIndicator(strokeWidth: 2); + break; + case RefreshCoverStatus.complete: + return Icon(Icons.done); + break; + case RefreshCoverStatus.error: + return Icon(Icons.refresh, color: Colors.red); + break; + default: + return Center(); + } + } + + @override + Widget build(BuildContext context) { + final s = context.s; + final groupList = context.watch(); + return Column( + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + FutureBuilder( + future: _getAutoDownload(widget.podcastLocal.id), + initialData: false, + builder: (context, snapshot) { + return ListTile( + onTap: () => _setAutoDownload(!snapshot.data), + leading: SizedBox( + height: 22, + width: 24, + child: CustomPaint( + painter: DownloadPainter( + color: context.brightness == Brightness.light + ? Colors.grey[600] + : Colors.white, + fraction: 0, + progressColor: context.accentColor, + ), + ), + ), + title: Text(s.autoDownload), + trailing: Transform.scale( + scale: 0.9, + child: + Switch(value: snapshot.data, onChanged: _setAutoDownload), + ), + ); + }), + FutureBuilder( + future: _getNeverUpdate(widget.podcastLocal.id), + initialData: false, + builder: (context, snapshot) { + return ListTile( + onTap: () => _setNeverUpdate(!snapshot.data), + leading: Icon(Icons.lock), + title: Text(s.neverAutoUpdate), + trailing: Transform.scale( + scale: 0.9, + child: + Switch(value: snapshot.data, onChanged: _setNeverUpdate), + ), + ); + }), + FutureBuilder( + future: _getSkipSecondStart(widget.podcastLocal.id), + initialData: 0, + builder: (context, snapshot) => ListTile( + onTap: () { + _secondsStart = 0; + setState(() { + _removeConfirm = false; + _markConfirm = false; + _showEndTimePicker = false; + _showStartTimePicker = !_showStartTimePicker; + }); + }, + leading: Icon(Icons.fast_forward), + title: Text(s.skipSecondsAtStart), + trailing: Padding( + padding: const EdgeInsets.only(right: 10.0), + child: Text(snapshot.data.toTime), + ), + ), + ), + if (_showStartTimePicker) + _TimePicker( + onCancel: () { + _secondsStart = 0; + setState(() => _showStartTimePicker = false); + }, + onConfirm: () async { + await _saveSkipSecondsStart(_secondsStart); + if (mounted) setState(() => _showStartTimePicker = false); + }, + onChange: (value) => _secondsStart = value.inSeconds), + // FutureBuilder( + // future: _getSkipSecondEnd(widget.podcastLocal.id), + // initialData: 0, + // builder: (context, snapshot) => ListTile( + // onTap: () { + // _secondsEnd = 0; + // setState(() { + // _removeConfirm = false; + // _markConfirm = false; + // _showStartTimePicker = false; + // _showEndTimePicker = !_showEndTimePicker; + // }); + // }, + // leading: Icon(Icons.fast_rewind), + // title: Text(s.skipSecondsAtEnd), + // trailing: Padding( + // padding: const EdgeInsets.only(right: 10.0), + // child: Text(snapshot.data.toTime), + // ), + // ), + // ), + // if (_showEndTimePicker) + // _TimePicker( + // onCancel: () { + // _secondsEnd = 0; + // setState(() => _showEndTimePicker = false); + // }, + // onConfirm: () async { + // await _saveSkipSecondsEnd(_secondsEnd); + // setState(() => _showEndTimePicker = false); + // }, + // onChange: (value) => _secondsEnd = value.inSeconds, + // ), + ListTile( + onTap: () { + if (_coverStatus != RefreshCoverStatus.start) { + _refreshArtWork(); + } + }, + title: Text(s.refreshArtwork), + leading: Icon(Icons.refresh), + trailing: Padding( + padding: const EdgeInsets.only(right: 15.0), + child: SizedBox( + height: 20, + width: 20, + child: _getRefreshStatusIcon(_coverStatus)))), + Divider(height: 1), + ListTile( + onTap: () { + setState(() { + _removeConfirm = false; + _showStartTimePicker = false; + _showEndTimePicker = false; + _markConfirm = !_markConfirm; + }); + }, + title: Text(s.menuMarkAllListened, + style: TextStyle( + color: context.accentColor, fontWeight: FontWeight.bold)), + leading: SizedBox( + height: 22, + width: 24, + child: CustomPaint( + painter: ListenedAllPainter( + context.brightness == Brightness.light + ? Colors.grey[600] + : Colors.white, + stroke: 2), + ), + ), + trailing: Padding( + padding: const EdgeInsets.only(right: 10.0), + child: SizedBox( + height: 20, + width: 20, + child: _markStatus == MarkStatus.none + ? Center() + : _markStatus == MarkStatus.start + ? CircularProgressIndicator(strokeWidth: 2) + : Icon(Icons.done)), + )), + if (_markConfirm) + Container( + width: double.infinity, + color: context.primaryColorDark, + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + FlatButton( + onPressed: () => setState(() { + _markConfirm = false; + }), + child: Text( + s.cancel, + style: TextStyle(color: Colors.grey[600]), + )), + FlatButton( + onPressed: () { + if (_markStatus != MarkStatus.start) { + _markListened(widget.podcastLocal.id); + } + setState(() { + _markConfirm = false; + }); + }, + child: Text(s.confirm, + style: TextStyle(color: context.accentColor))), + ], + ), + ), + ListTile( + onTap: () { + setState(() { + _markConfirm = false; + _showStartTimePicker = false; + _showEndTimePicker = false; + _removeConfirm = !_removeConfirm; + }); + }, + title: Text(s.remove, + style: TextStyle(color: Colors.red, fontWeight: FontWeight.bold)), + leading: Icon(Icons.delete, color: Colors.red), + ), + if (_removeConfirm) + Container( + width: double.infinity, + color: context.primaryColorDark, + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + FlatButton( + onPressed: () => setState(() { + _removeConfirm = false; + }), + child: + Text(s.cancel, style: TextStyle(color: Colors.grey[600])), + ), + FlatButton( + splashColor: Colors.red.withAlpha(70), + onPressed: () async { + await groupList.removePodcast(widget.podcastLocal); + Navigator.of(context).pop(); + }, + child: + Text(s.confirm, style: TextStyle(color: Colors.red))), + ], + ), + ), + ], + ); + } +} + +class _TimePicker extends StatelessWidget { + const _TimePicker({this.onConfirm, this.onCancel, this.onChange, Key key}) + : super(key: key); + final VoidCallback onConfirm; + final VoidCallback onCancel; + final ValueChanged onChange; + + @override + Widget build(BuildContext context) { + final s = context.s; + return Container( + color: context.primaryColorDark, + child: Column( + children: [ + SizedBox(height: 10), + DurationPicker( + onChange: onChange, + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + FlatButton( + onPressed: onCancel, + child: Text( + s.cancel, + style: TextStyle(color: Colors.grey[600]), + ), + ), + FlatButton( + splashColor: context.accentColor.withAlpha(70), + onPressed: onConfirm, + child: Text( + s.confirm, + style: TextStyle(color: context.accentColor), + ), + ) + ], + ) + ], + ), + ); + } +} diff --git a/lib/podcasts/podcastlist.dart b/lib/podcasts/podcastlist.dart index e0108c9..be480af 100644 --- a/lib/podcasts/podcastlist.dart +++ b/lib/podcasts/podcastlist.dart @@ -1,213 +1,213 @@ -import 'dart:async'; -import 'dart:io'; - -import 'package:flutter/foundation.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter/rendering.dart'; -import 'package:flutter/services.dart'; -import 'package:flutter_html/flutter_html.dart'; -import 'package:provider/provider.dart'; - -import '../local_storage/sqflite_localpodcast.dart'; -import '../state/podcast_group.dart'; -import '../type/podcastlocal.dart'; -import '../util/custom_widget.dart'; -import '../util/extension_helper.dart'; -import '../util/general_dialog.dart'; -import '../util/pageroute.dart'; -import 'podcast_detail.dart'; -import 'podcast_settings.dart'; - -class AboutPodcast extends StatefulWidget { - final PodcastLocal podcastLocal; - AboutPodcast({this.podcastLocal, Key key}) : super(key: key); - - @override - _AboutPodcastState createState() => _AboutPodcastState(); -} - -class _AboutPodcastState extends State { - String _description; - bool _load; - - void getDescription(String id) async { - var dbHelper = DBHelper(); - var description = await dbHelper.getFeedDescription(id); - _description = description; - setState(() { - _load = true; - }); - } - - @override - void initState() { - super.initState(); - _load = false; - getDescription(widget.podcastLocal.id); - } - - @override - Widget build(BuildContext context) { - var _groupList = Provider.of(context, listen: false); - final s = context.s; - return AlertDialog( - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(10.0))), - titlePadding: EdgeInsets.only( - top: 20, left: 20, right: context.width / 3, bottom: 20), - actions: [ - FlatButton( - splashColor: context.accentColor.withAlpha(70), - padding: EdgeInsets.all(10.0), - onPressed: () { - _groupList.removePodcast(widget.podcastLocal); - Navigator.of(context).pop(); - }, - textColor: Colors.red, - child: Text( - s.remove, - ), - ), - ], - title: Text(widget.podcastLocal.title), - content: SingleChildScrollView( - scrollDirection: Axis.vertical, - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - !_load - ? Center() - : _description != null - ? Html(data: _description) - : Center(), - if (widget.podcastLocal.author != null) - Text(widget.podcastLocal.author, - style: TextStyle(color: Colors.blue)) - ], - ), - ), - ); - } -} - -class PodcastList extends StatefulWidget { - @override - _PodcastListState createState() => _PodcastListState(); -} - -class _PodcastListState extends State { - Future> _getPodcastLocal() async { - var dbHelper = DBHelper(); - var podcastList = await dbHelper.getPodcastLocalAll(); - return podcastList; - } - - @override - Widget build(BuildContext context) { - final width = context.width; - return AnnotatedRegion( - value: SystemUiOverlayStyle( - statusBarIconBrightness: Theme.of(context).accentColorBrightness, - systemNavigationBarColor: context.primaryColor, - systemNavigationBarIconBrightness: - Theme.of(context).accentColorBrightness, - ), - child: Scaffold( - appBar: AppBar( - title: Text(context.s.podcast(2)), - leading: CustomBackButton(), - centerTitle: true, - ), - body: SafeArea( - child: Container( - color: context.primaryColor, - child: FutureBuilder>( - future: _getPodcastLocal(), - builder: (context, snapshot) { - if (snapshot.hasData) { - return CustomScrollView( - slivers: [ - SliverPadding( - padding: const EdgeInsets.all(10.0), - sliver: SliverGrid( - gridDelegate: - SliverGridDelegateWithFixedCrossAxisCount( - childAspectRatio: 0.8, - crossAxisCount: 3, - ), - delegate: SliverChildBuilderDelegate( - (context, index) { - return InkWell( - onTap: () { - Navigator.push( - context, - ScaleRoute( - page: PodcastDetail( - podcastLocal: snapshot.data[index], - )), - ); - }, - onLongPress: () async { - generalSheet( - context, - title: snapshot.data[index].title, - child: PodcastSetting( - podcastLocal: snapshot.data[index]), - ).then((value) { - if (mounted) setState(() {}); - }); - }, - child: Align( - alignment: Alignment.center, - child: Column( - mainAxisAlignment: MainAxisAlignment.start, - children: [ - SizedBox( - height: 10.0, - ), - ClipRRect( - borderRadius: - BorderRadius.circular(width / 8), - child: Container( - height: width / 4, - width: width / 4, - child: Image.file(File( - "${snapshot.data[index].imagePath}")), - ), - ), - Padding( - padding: const EdgeInsets.all(4.0), - child: Text( - snapshot.data[index].title, - textAlign: TextAlign.center, - style: context.textTheme.bodyText1, - maxLines: 2, - ), - ), - ], - ), - ), - ); - }, - childCount: snapshot.data.length, - ), - ), - ), - ], - ); - } - return Center( - child: SizedBox( - height: 20, - width: 20, - child: CircularProgressIndicator()), - ); - }, - ), - ), - ), - ), - ); - } -} +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_html/flutter_html.dart'; +import 'package:provider/provider.dart'; + +import '../local_storage/sqflite_localpodcast.dart'; +import '../state/podcast_group.dart'; +import '../type/podcastlocal.dart'; +import '../util/custom_widget.dart'; +import '../util/extension_helper.dart'; +import '../util/general_dialog.dart'; +import '../util/pageroute.dart'; +import 'podcast_detail.dart'; +import 'podcast_settings.dart'; + +class AboutPodcast extends StatefulWidget { + final PodcastLocal podcastLocal; + AboutPodcast({this.podcastLocal, Key key}) : super(key: key); + + @override + _AboutPodcastState createState() => _AboutPodcastState(); +} + +class _AboutPodcastState extends State { + String _description; + bool _load; + + void getDescription(String id) async { + var dbHelper = DBHelper(); + var description = await dbHelper.getFeedDescription(id); + _description = description; + setState(() { + _load = true; + }); + } + + @override + void initState() { + super.initState(); + _load = false; + getDescription(widget.podcastLocal.id); + } + + @override + Widget build(BuildContext context) { + var _groupList = Provider.of(context, listen: false); + final s = context.s; + return AlertDialog( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(10.0))), + titlePadding: EdgeInsets.only( + top: 20, left: 20, right: context.width / 3, bottom: 20), + actions: [ + FlatButton( + splashColor: context.accentColor.withAlpha(70), + padding: EdgeInsets.all(10.0), + onPressed: () { + _groupList.removePodcast(widget.podcastLocal); + Navigator.of(context).pop(); + }, + textColor: Colors.red, + child: Text( + s.remove, + ), + ), + ], + title: Text(widget.podcastLocal.title), + content: SingleChildScrollView( + scrollDirection: Axis.vertical, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + !_load + ? Center() + : _description != null + ? Html(data: _description) + : Center(), + if (widget.podcastLocal.author != null) + Text(widget.podcastLocal.author, + style: TextStyle(color: Colors.blue)) + ], + ), + ), + ); + } +} + +class PodcastList extends StatefulWidget { + @override + _PodcastListState createState() => _PodcastListState(); +} + +class _PodcastListState extends State { + Future> _getPodcastLocal() async { + var dbHelper = DBHelper(); + var podcastList = await dbHelper.getPodcastLocalAll(); + return podcastList; + } + + @override + Widget build(BuildContext context) { + final width = context.width; + return AnnotatedRegion( + value: SystemUiOverlayStyle( + statusBarIconBrightness: Theme.of(context).accentColorBrightness, + systemNavigationBarColor: context.primaryColor, + systemNavigationBarIconBrightness: + Theme.of(context).accentColorBrightness, + ), + child: Scaffold( + appBar: AppBar( + title: Text(context.s.podcast(2)), + leading: CustomBackButton(), + centerTitle: true, + ), + body: SafeArea( + child: Container( + color: context.primaryColor, + child: FutureBuilder>( + future: _getPodcastLocal(), + builder: (context, snapshot) { + if (snapshot.hasData) { + return CustomScrollView( + slivers: [ + SliverPadding( + padding: const EdgeInsets.all(10.0), + sliver: SliverGrid( + gridDelegate: + SliverGridDelegateWithFixedCrossAxisCount( + childAspectRatio: 0.8, + crossAxisCount: 3, + ), + delegate: SliverChildBuilderDelegate( + (context, index) { + return InkWell( + onTap: () { + Navigator.push( + context, + ScaleRoute( + page: PodcastDetail( + podcastLocal: snapshot.data[index], + )), + ); + }, + onLongPress: () async { + generalSheet( + context, + title: snapshot.data[index].title, + child: PodcastSetting( + podcastLocal: snapshot.data[index]), + ).then((value) { + if (mounted) setState(() {}); + }); + }, + child: Align( + alignment: Alignment.center, + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + SizedBox( + height: 10.0, + ), + ClipRRect( + borderRadius: + BorderRadius.circular(width / 8), + child: Container( + height: width / 4, + width: width / 4, + child: Image.file(File( + "${snapshot.data[index].imagePath}")), + ), + ), + Padding( + padding: const EdgeInsets.all(4.0), + child: Text( + snapshot.data[index].title, + textAlign: TextAlign.center, + style: context.textTheme.bodyText1, + maxLines: 2, + ), + ), + ], + ), + ), + ); + }, + childCount: snapshot.data.length, + ), + ), + ), + ], + ); + } + return Center( + child: SizedBox( + height: 20, + width: 20, + child: CircularProgressIndicator()), + ); + }, + ), + ), + ), + ), + ); + } +} diff --git a/lib/service/gpodder_api.dart b/lib/service/gpodder_api.dart index 3f19f0c..cdd780e 100644 --- a/lib/service/gpodder_api.dart +++ b/lib/service/gpodder_api.dart @@ -1,238 +1,238 @@ -import 'dart:convert'; -import 'dart:developer' as developer; - -import 'package:cookie_jar/cookie_jar.dart'; -import 'package:device_info/device_info.dart'; -import 'package:dio/dio.dart'; -import 'package:dio_cookie_manager/dio_cookie_manager.dart'; -import 'package:path_provider/path_provider.dart'; -import 'package:uuid/uuid.dart'; - -import '../local_storage/key_value_storage.dart'; -import '../local_storage/sqflite_localpodcast.dart'; - -enum GpodderSyncStatus { none, success, fail, authError } - -class Gpodder { - final _dio = Dio(BaseOptions( - connectTimeout: 30000, - receiveTimeout: 90000, - sendTimeout: 90000, - )); - final _storage = KeyValueStorage(gpodderApiKey); - final _addStorage = KeyValueStorage(gpodderAddKey); - final _removeStorage = KeyValueStorage(gpodderRemoveKey); - final _remoteAddStorage = KeyValueStorage(gpodderRemoteAddKey); - final _remoteRemoveStorage = KeyValueStorage(gpodderRemoteRemoveKey); - final _dateTimeStorage = KeyValueStorage(gpodderSyncDateTimeKey); - final _statusStorage = KeyValueStorage(gpodderSyncStatusKey); - - final _baseUrl = "https://gpodder.net"; - - Future _initDio() async { - final dir = await getApplicationDocumentsDirectory(); - var cookieJar = PersistCookieJar(dir: "${dir.path}/.cookies/"); - _dio.interceptors.add(CookieManager(cookieJar)); - } - - Future login({String username, String password}) async { - final dir = await getApplicationDocumentsDirectory(); - var cookieJar = PersistCookieJar(dir: "${dir.path}/.cookies/"); - cookieJar.delete(Uri.parse(_baseUrl)); - _dio.interceptors.add(CookieManager(cookieJar)); - final basicAuth = - 'Basic ${base64Encode(utf8.encode('$username:$password'))}'; - var status; - Response response; - try { - response = await _dio.post('$_baseUrl/api/2/auth/$username/login.json', - options: - Options(headers: {'authorization': basicAuth})); - status = response.statusCode; - } catch (e) { - developer.log(e.toString(), name: 'gpoderr login error'); - return 0; - } - return status; - } - - Future logout() async { - final loginInfo = await _storage.getStringList(); - final username = loginInfo[0]; - await _initDio(); - var status; - try { - var response = await _dio.post( - '$_baseUrl/api/2/auth/$username/logout.json', - ); - status = response.statusCode; - } catch (e) { - developer.log(e.toString(), name: 'gpoderr logout error'); - if (status == 400) { - await _initService(); - } - return 0; - } - if (status == 200) { - await _initService(); - } - return status; - } - - Future _initService() async { - final dir = await getApplicationDocumentsDirectory(); - var cookieJar = PersistCookieJar(dir: "${dir.path}/.cookies/"); - cookieJar.delete(Uri.parse(_baseUrl)); - await _storage.clearList(); - await _addStorage.clearList(); - await _remoteAddStorage.clearList(); - await _removeStorage.clearList(); - await _remoteAddStorage.clearList(); - await _statusStorage.saveInt(0); - await _dateTimeStorage.saveInt(0); - } - - Future checkLogin(String username) async { - await _initDio(); - var response = await _dio.post( - '$_baseUrl/api/2/auth/$username/login.json', - ); - final status = response.statusCode; - return status; - } - - Future updateDevice(String username) async { - await _initDio(); - final deviceId = Uuid().v1(); - final androidInfo = await DeviceInfoPlugin().androidInfo; - var status = 0; - try { - var response = await _dio - .post("$_baseUrl/api/2/devices/$username/$deviceId.json", data: { - "caption": "Tsacdop on ${androidInfo.model}", - "type": "mobile" - }); - status = response.statusCode; - } catch (e) { - developer.log(e.toString(), name: 'gpodder update device error'); - return 0; - } - if (status == 200) { - await _storage.saveStringList([username, deviceId]); - } - return status; - } - - Future getAllPodcast() async { - final loginInfo = await _storage.getStringList(); - final username = loginInfo[0]; - Response response; - await _initDio(); - try { - response = await _dio.get( - '$_baseUrl/subscriptions/$username.opml', - ); - } catch (e) { - developer.log(e.toString(), name: 'gpodder update podcasts error'); - return ''; - } - return response.data; - } - - Future uploadSubscriptions() async { - final syncDataTime = DateTime.now().millisecondsSinceEpoch; - await _dateTimeStorage.saveInt(syncDataTime); - final loginInfo = await _storage.getStringList(); - final username = loginInfo[0]; - final deviceId = loginInfo[1]; - await _initDio(); - final dbHelper = DBHelper(); - final podcasts = await dbHelper.getPodcastLocalAll(); - var subscriptions = ''; - for (var podcast in podcasts) { - subscriptions += '${podcast.rssUrl}\n'; - } - var status; - try { - final response = await _dio.put( - '$_baseUrl/subscriptions/$username/$deviceId.txt', - data: subscriptions); - status = response.statusCode; - } catch (e) { - developer.log(e.toString(), name: 'gpodder update podcasts error'); - return 0; - } - return status; - } - - Future getChanges() async { - final loginInfo = await _storage.getStringList(); - final username = loginInfo[0]; - final deviceId = loginInfo[1]; - final syncDataTime = DateTime.now().millisecondsSinceEpoch; - await _dateTimeStorage.saveInt(syncDataTime); - final timeStamp = loginInfo.length == 3 ? int.parse(loginInfo[2]) : 0; - var status; - Response response; - await _initDio(); - try { - response = await _dio.get( - "$_baseUrl/api/2/subscriptions/$username/$deviceId.json", - queryParameters: {'since': timeStamp}); - status = response.statusCode; - } catch (e) { - developer.log(e.toString(), name: 'gpodder update podcasts error'); - if (status == 401) { - _statusStorage.saveInt(3); - } else { - _statusStorage.saveInt(2); - } - return 0; - } - if (status == 200) { - Map changes = jsonDecode(response.toString()); - final timeStamp = changes['timestamp']; - final addList = changes['add'].cast(); - final removeList = changes['remove'].cast(); - await _storage.saveStringList([username, deviceId, timeStamp.toString()]); - await _remoteAddStorage.addList(addList); - await _remoteRemoveStorage.addList(removeList); - } - return status; - } - - Future updateChange() async { - final loginInfo = await _storage.getStringList(); - final addList = await _addStorage.getStringList(); - final removeList = await _removeStorage.getStringList(); - final username = loginInfo[0]; - final deviceId = loginInfo[1]; - await _initDio(); - var status; - Response response; - try { - response = await _dio.post( - '$_baseUrl/api/2/subscriptions/$username/$deviceId.json', - data: {'add': addList, 'remove': removeList}); - status = response.statusCode; - } catch (e) { - if (status == 401) { - _statusStorage.saveInt(3); - } else { - _statusStorage.saveInt(2); - } - developer.log(e.toString(), name: 'gpodder update podcasts error'); - return 0; - } - if (status == 200) { - await _addStorage.clearList(); - await _removeStorage.clearList(); - await _statusStorage.saveInt(1); - Map changes = jsonDecode(response.toString()); - final timeStamp = changes['timestamp'] as int; - await _storage - .saveStringList([username, deviceId, (timeStamp + 1).toString()]); - } - return status; - } -} +import 'dart:convert'; +import 'dart:developer' as developer; + +import 'package:cookie_jar/cookie_jar.dart'; +import 'package:device_info/device_info.dart'; +import 'package:dio/dio.dart'; +import 'package:dio_cookie_manager/dio_cookie_manager.dart'; +import 'package:path_provider/path_provider.dart'; +import 'package:uuid/uuid.dart'; + +import '../local_storage/key_value_storage.dart'; +import '../local_storage/sqflite_localpodcast.dart'; + +enum GpodderSyncStatus { none, success, fail, authError } + +class Gpodder { + final _dio = Dio(BaseOptions( + connectTimeout: 30000, + receiveTimeout: 90000, + sendTimeout: 90000, + )); + final _storage = KeyValueStorage(gpodderApiKey); + final _addStorage = KeyValueStorage(gpodderAddKey); + final _removeStorage = KeyValueStorage(gpodderRemoveKey); + final _remoteAddStorage = KeyValueStorage(gpodderRemoteAddKey); + final _remoteRemoveStorage = KeyValueStorage(gpodderRemoteRemoveKey); + final _dateTimeStorage = KeyValueStorage(gpodderSyncDateTimeKey); + final _statusStorage = KeyValueStorage(gpodderSyncStatusKey); + + final _baseUrl = "https://gpodder.net"; + + Future _initDio() async { + final dir = await getApplicationDocumentsDirectory(); + var cookieJar = PersistCookieJar(dir: "${dir.path}/.cookies/"); + _dio.interceptors.add(CookieManager(cookieJar)); + } + + Future login({String username, String password}) async { + final dir = await getApplicationDocumentsDirectory(); + var cookieJar = PersistCookieJar(dir: "${dir.path}/.cookies/"); + cookieJar.delete(Uri.parse(_baseUrl)); + _dio.interceptors.add(CookieManager(cookieJar)); + final basicAuth = + 'Basic ${base64Encode(utf8.encode('$username:$password'))}'; + var status; + Response response; + try { + response = await _dio.post('$_baseUrl/api/2/auth/$username/login.json', + options: + Options(headers: {'authorization': basicAuth})); + status = response.statusCode; + } catch (e) { + developer.log(e.toString(), name: 'gpoderr login error'); + return 0; + } + return status; + } + + Future logout() async { + final loginInfo = await _storage.getStringList(); + final username = loginInfo[0]; + await _initDio(); + var status; + try { + var response = await _dio.post( + '$_baseUrl/api/2/auth/$username/logout.json', + ); + status = response.statusCode; + } catch (e) { + developer.log(e.toString(), name: 'gpoderr logout error'); + if (status == 400) { + await _initService(); + } + return 0; + } + if (status == 200) { + await _initService(); + } + return status; + } + + Future _initService() async { + final dir = await getApplicationDocumentsDirectory(); + var cookieJar = PersistCookieJar(dir: "${dir.path}/.cookies/"); + cookieJar.delete(Uri.parse(_baseUrl)); + await _storage.clearList(); + await _addStorage.clearList(); + await _remoteAddStorage.clearList(); + await _removeStorage.clearList(); + await _remoteAddStorage.clearList(); + await _statusStorage.saveInt(0); + await _dateTimeStorage.saveInt(0); + } + + Future checkLogin(String username) async { + await _initDio(); + var response = await _dio.post( + '$_baseUrl/api/2/auth/$username/login.json', + ); + final status = response.statusCode; + return status; + } + + Future updateDevice(String username) async { + await _initDio(); + final deviceId = Uuid().v1(); + final androidInfo = await DeviceInfoPlugin().androidInfo; + var status = 0; + try { + var response = await _dio + .post("$_baseUrl/api/2/devices/$username/$deviceId.json", data: { + "caption": "Tsacdop on ${androidInfo.model}", + "type": "mobile" + }); + status = response.statusCode; + } catch (e) { + developer.log(e.toString(), name: 'gpodder update device error'); + return 0; + } + if (status == 200) { + await _storage.saveStringList([username, deviceId]); + } + return status; + } + + Future getAllPodcast() async { + final loginInfo = await _storage.getStringList(); + final username = loginInfo[0]; + Response response; + await _initDio(); + try { + response = await _dio.get( + '$_baseUrl/subscriptions/$username.opml', + ); + } catch (e) { + developer.log(e.toString(), name: 'gpodder update podcasts error'); + return ''; + } + return response.data; + } + + Future uploadSubscriptions() async { + final syncDataTime = DateTime.now().millisecondsSinceEpoch; + await _dateTimeStorage.saveInt(syncDataTime); + final loginInfo = await _storage.getStringList(); + final username = loginInfo[0]; + final deviceId = loginInfo[1]; + await _initDio(); + final dbHelper = DBHelper(); + final podcasts = await dbHelper.getPodcastLocalAll(); + var subscriptions = ''; + for (var podcast in podcasts) { + subscriptions += '${podcast.rssUrl}\n'; + } + var status; + try { + final response = await _dio.put( + '$_baseUrl/subscriptions/$username/$deviceId.txt', + data: subscriptions); + status = response.statusCode; + } catch (e) { + developer.log(e.toString(), name: 'gpodder update podcasts error'); + return 0; + } + return status; + } + + Future getChanges() async { + final loginInfo = await _storage.getStringList(); + final username = loginInfo[0]; + final deviceId = loginInfo[1]; + final syncDataTime = DateTime.now().millisecondsSinceEpoch; + await _dateTimeStorage.saveInt(syncDataTime); + final timeStamp = loginInfo.length == 3 ? int.parse(loginInfo[2]) : 0; + var status; + Response response; + await _initDio(); + try { + response = await _dio.get( + "$_baseUrl/api/2/subscriptions/$username/$deviceId.json", + queryParameters: {'since': timeStamp}); + status = response.statusCode; + } catch (e) { + developer.log(e.toString(), name: 'gpodder update podcasts error'); + if (status == 401) { + _statusStorage.saveInt(3); + } else { + _statusStorage.saveInt(2); + } + return 0; + } + if (status == 200) { + Map changes = jsonDecode(response.toString()); + final timeStamp = changes['timestamp']; + final addList = changes['add'].cast(); + final removeList = changes['remove'].cast(); + await _storage.saveStringList([username, deviceId, timeStamp.toString()]); + await _remoteAddStorage.addList(addList); + await _remoteRemoveStorage.addList(removeList); + } + return status; + } + + Future updateChange() async { + final loginInfo = await _storage.getStringList(); + final addList = await _addStorage.getStringList(); + final removeList = await _removeStorage.getStringList(); + final username = loginInfo[0]; + final deviceId = loginInfo[1]; + await _initDio(); + var status; + Response response; + try { + response = await _dio.post( + '$_baseUrl/api/2/subscriptions/$username/$deviceId.json', + data: {'add': addList, 'remove': removeList}); + status = response.statusCode; + } catch (e) { + if (status == 401) { + _statusStorage.saveInt(3); + } else { + _statusStorage.saveInt(2); + } + developer.log(e.toString(), name: 'gpodder update podcasts error'); + return 0; + } + if (status == 200) { + await _addStorage.clearList(); + await _removeStorage.clearList(); + await _statusStorage.saveInt(1); + Map changes = jsonDecode(response.toString()); + final timeStamp = changes['timestamp'] as int; + await _storage + .saveStringList([username, deviceId, (timeStamp + 1).toString()]); + } + return status; + } +} diff --git a/lib/service/opml_build.dart b/lib/service/opml_build.dart index 4d1ecc0..0b44120 100644 --- a/lib/service/opml_build.dart +++ b/lib/service/opml_build.dart @@ -1,84 +1,84 @@ -import 'dart:developer' as developer; - -import 'package:xml/xml.dart' as xml; -import '../state/podcast_group.dart'; - -class OmplOutline { - final String text; - final String xmlUrl; - OmplOutline({this.text, this.xmlUrl}); - - factory OmplOutline.parse(xml.XmlElement element) { - if (element == null) return null; - return OmplOutline( - text: element.getAttribute("text")?.trim(), - xmlUrl: element.getAttribute("xmlUrl")?.trim(), - ); - } -} - -class PodcastsBackup { - ///Group list for backup. - final List groups; - PodcastsBackup(this.groups) : assert(groups.isNotEmpty); - - xml.XmlNode omplBuilder() { - var builder = xml.XmlBuilder(); - builder.processing('xml', 'version="1.0" encoding="UTF-8"'); - builder.element('ompl', nest: () { - builder.attribute('version', '1.0'); - builder.element('head', nest: () { - builder.element('title', nest: 'Tsacdop Feed Groups'); - }); - builder.element('body', nest: () { - for (var group in groups) { - builder.element('outline', nest: () { - builder.attribute('text', '${group.name}'); - builder.attribute('title', '${group.name}'); - for (var e in group.podcasts) { - builder.element( - 'outline', - nest: () { - builder.attribute('type', 'rss'); - builder.attribute('text', '${e.title}'); - builder.attribute('title', '${e.title}'); - builder.attribute('xmlUrl', '${e.rssUrl}'); - }, - isSelfClosing: true, - ); - } - }); - } - }); - }); - return builder.buildDocument(); - } - - static parseOPML(String opml) { - var data = >{}; - // var opml = file.readAsStringSync(); - var content = xml.XmlDocument.parse(opml); - var title = - content.findAllElements('head').first.findElements('title').first.text; - developer.log(title, name: 'Import OPML'); - var groups = content.findAllElements('body').first.findElements('outline'); - if (title != 'Tsacdop Feed Groups') { - var total = content - .findAllElements('outline') - .map((ele) => OmplOutline.parse(ele)) - .toList(); - data['Home'] = total; - return data; - } - - for (var element in groups) { - var title = element.getAttribute('title'); - var total = element - .findElements('outline') - .map((ele) => OmplOutline.parse(ele)) - .toList(); - data[title] = total; - } - return data; - } -} +import 'dart:developer' as developer; + +import 'package:xml/xml.dart' as xml; +import '../state/podcast_group.dart'; + +class OmplOutline { + final String text; + final String xmlUrl; + OmplOutline({this.text, this.xmlUrl}); + + factory OmplOutline.parse(xml.XmlElement element) { + if (element == null) return null; + return OmplOutline( + text: element.getAttribute("text")?.trim(), + xmlUrl: element.getAttribute("xmlUrl")?.trim(), + ); + } +} + +class PodcastsBackup { + ///Group list for backup. + final List groups; + PodcastsBackup(this.groups) : assert(groups.isNotEmpty); + + xml.XmlNode omplBuilder() { + var builder = xml.XmlBuilder(); + builder.processing('xml', 'version="1.0" encoding="UTF-8"'); + builder.element('ompl', nest: () { + builder.attribute('version', '1.0'); + builder.element('head', nest: () { + builder.element('title', nest: 'Tsacdop Feed Groups'); + }); + builder.element('body', nest: () { + for (var group in groups) { + builder.element('outline', nest: () { + builder.attribute('text', '${group.name}'); + builder.attribute('title', '${group.name}'); + for (var e in group.podcasts) { + builder.element( + 'outline', + nest: () { + builder.attribute('type', 'rss'); + builder.attribute('text', '${e.title}'); + builder.attribute('title', '${e.title}'); + builder.attribute('xmlUrl', '${e.rssUrl}'); + }, + isSelfClosing: true, + ); + } + }); + } + }); + }); + return builder.buildDocument(); + } + + static parseOPML(String opml) { + var data = >{}; + // var opml = file.readAsStringSync(); + var content = xml.XmlDocument.parse(opml); + var title = + content.findAllElements('head').first.findElements('title').first.text; + developer.log(title, name: 'Import OPML'); + var groups = content.findAllElements('body').first.findElements('outline'); + if (title != 'Tsacdop Feed Groups') { + var total = content + .findAllElements('outline') + .map((ele) => OmplOutline.parse(ele)) + .toList(); + data['Home'] = total; + return data; + } + + for (var element in groups) { + var title = element.getAttribute('title'); + var total = element + .findElements('outline') + .map((ele) => OmplOutline.parse(ele)) + .toList(); + data[title] = total; + } + return data; + } +} diff --git a/lib/service/search_api.dart b/lib/service/search_api.dart index f297464..fccaba4 100644 --- a/lib/service/search_api.dart +++ b/lib/service/search_api.dart @@ -1,125 +1,125 @@ -import 'dart:convert'; - -import 'package:convert/convert.dart'; -import 'package:crypto/crypto.dart'; -import 'package:dio/dio.dart'; - -import '../.env.dart'; -import '../home/about.dart'; -import '../type/search_api/index_episode.dart'; -import '../type/search_api/index_podcast.dart'; -import '../type/search_api/itunes_podcast.dart'; -import '../type/search_api/search_top_podcast.dart'; -import '../type/search_api/searchepisodes.dart'; -import '../type/search_api/searchpodcast.dart'; - -enum SearchEngine { podcastIndex, listenNotes } - -class ListenNotesSearch { - final _apiKey = environment['apiKey']; - - Future> searchPodcasts( - {String searchText, int nextOffset}) async { - var url = "https://listen-api.listennotes.com/api/v2/search?q=" - "${Uri.encodeComponent(searchText)}${"&sort_by_date=0&type=podcast&offset=$nextOffset"}"; - var response = await Dio().get(url, - options: Options(headers: { - 'X-ListenAPI-Key': "$_apiKey", - 'Accept': "application/json" - })); - Map searchResultMap = jsonDecode(response.toString()); - var searchResult = SearchPodcast.fromJson(searchResultMap); - return searchResult; - } - - Future> fetchEpisode( - {String id, int nextEpisodeDate}) async { - var url = - "https://listen-api.listennotes.com/api/v2/podcasts/$id?next_episode_pub_date=$nextEpisodeDate"; - var response = await Dio().get(url, - options: Options(headers: { - 'X-ListenAPI-Key': "$_apiKey", - 'Accept': "application/json" - })); - Map searchResultMap = jsonDecode(response.toString()); - var searchResult = SearchEpisodes.fromJson(searchResultMap); - return searchResult; - } - - Future> fetchBestPodcast( - {String genre, int page, String region = 'us'}) async { - var url = - "https://listen-api.listennotes.com/api/v2/best_podcasts?genre_id=$genre&page=$page®ion=$region"; - var response = await Dio().get(url, - options: Options(headers: { - 'X-ListenAPI-Key': "$_apiKey", - 'Accept': "application/json" - })); - Map searchResultMap = jsonDecode(response.toString()); - var searchResult = SearchTopPodcast.fromJson(searchResultMap); - return searchResult; - } -} - -class ItunesSearch { - Future> searchPodcasts( - {String searchText, int limit}) async { - final url = "https://itunes.apple.com/search?term=" - "${Uri.encodeComponent(searchText)}&media=podcast&entity=podcast&limit=$limit"; - final response = await Dio() - .get(url, options: Options(headers: {'Accept': "application/json"})); - print(response.toString()); - Map searchResultMap = jsonDecode(response.toString()); - final searchResult = ItunesSearchResult.fromJson(searchResultMap); - return searchResult; - } -} - -class PodcastsIndexSearch { - final _dio = Dio(BaseOptions(connectTimeout: 30000, receiveTimeout: 90000)); - final _baseUrl = 'https://api.podcastindex.org'; - Map _initSearch() { - final unixTime = - (DateTime.now().millisecondsSinceEpoch / 1000).round().toString(); - final apiKey = environment['podcastIndexApiKey']; - final apiSecret = environment['podcastIndexApiSecret']; - final firstChunk = utf8.encode(apiKey); - final secondChunk = utf8.encode(apiSecret); - final thirdChunk = utf8.encode(unixTime); - var output = AccumulatorSink(); - var input = sha1.startChunkedConversion(output); - input.add(firstChunk); - input.add(secondChunk); - input.add(thirdChunk); - input.close(); - var digest = output.events.single; - - var headers = { - "X-Auth-Date": unixTime, - "X-Auth-Key": apiKey, - "Authorization": digest.toString(), - "User-Agent": "Tsacdop/$version" - }; - return headers; - } - - Future> searchPodcasts( - {String searchText, int limit = 99}) async { - final url = "$_baseUrl/api/1.0/search/byterm" - "?q=${Uri.encodeComponent(searchText)}&max=$limit&fulltext=true"; - final headers = _initSearch(); - final response = await _dio.get(url, options: Options(headers: headers)); - Map searchResultMap = jsonDecode(response.toString()); - final searchResult = PodcastIndexSearchResult.fromJson(searchResultMap); - return searchResult; - } - - Future> fetchEpisode({String rssUrl}) async { - final url = "$_baseUrl/api/1.0/episodes/byfeedurl?url=$rssUrl"; - final headers = _initSearch(); - final response = await _dio.get(url, options: Options(headers: headers)); - Map searchResultMap = jsonDecode(response.toString()); - final searchResult = IndexEpisodeResult.fromJson(searchResultMap); - return searchResult; - } -} +import 'dart:convert'; + +import 'package:convert/convert.dart'; +import 'package:crypto/crypto.dart'; +import 'package:dio/dio.dart'; + +import '../.env.dart'; +import '../home/about.dart'; +import '../type/search_api/index_episode.dart'; +import '../type/search_api/index_podcast.dart'; +import '../type/search_api/itunes_podcast.dart'; +import '../type/search_api/search_top_podcast.dart'; +import '../type/search_api/searchepisodes.dart'; +import '../type/search_api/searchpodcast.dart'; + +enum SearchEngine { podcastIndex, listenNotes } + +class ListenNotesSearch { + final _apiKey = environment['apiKey']; + + Future> searchPodcasts( + {String searchText, int nextOffset}) async { + var url = "https://listen-api.listennotes.com/api/v2/search?q=" + "${Uri.encodeComponent(searchText)}${"&sort_by_date=0&type=podcast&offset=$nextOffset"}"; + var response = await Dio().get(url, + options: Options(headers: { + 'X-ListenAPI-Key': "$_apiKey", + 'Accept': "application/json" + })); + Map searchResultMap = jsonDecode(response.toString()); + var searchResult = SearchPodcast.fromJson(searchResultMap); + return searchResult; + } + + Future> fetchEpisode( + {String id, int nextEpisodeDate}) async { + var url = + "https://listen-api.listennotes.com/api/v2/podcasts/$id?next_episode_pub_date=$nextEpisodeDate"; + var response = await Dio().get(url, + options: Options(headers: { + 'X-ListenAPI-Key': "$_apiKey", + 'Accept': "application/json" + })); + Map searchResultMap = jsonDecode(response.toString()); + var searchResult = SearchEpisodes.fromJson(searchResultMap); + return searchResult; + } + + Future> fetchBestPodcast( + {String genre, int page, String region = 'us'}) async { + var url = + "https://listen-api.listennotes.com/api/v2/best_podcasts?genre_id=$genre&page=$page®ion=$region"; + var response = await Dio().get(url, + options: Options(headers: { + 'X-ListenAPI-Key': "$_apiKey", + 'Accept': "application/json" + })); + Map searchResultMap = jsonDecode(response.toString()); + var searchResult = SearchTopPodcast.fromJson(searchResultMap); + return searchResult; + } +} + +class ItunesSearch { + Future> searchPodcasts( + {String searchText, int limit}) async { + final url = "https://itunes.apple.com/search?term=" + "${Uri.encodeComponent(searchText)}&media=podcast&entity=podcast&limit=$limit"; + final response = await Dio() + .get(url, options: Options(headers: {'Accept': "application/json"})); + print(response.toString()); + Map searchResultMap = jsonDecode(response.toString()); + final searchResult = ItunesSearchResult.fromJson(searchResultMap); + return searchResult; + } +} + +class PodcastsIndexSearch { + final _dio = Dio(BaseOptions(connectTimeout: 30000, receiveTimeout: 90000)); + final _baseUrl = 'https://api.podcastindex.org'; + Map _initSearch() { + final unixTime = + (DateTime.now().millisecondsSinceEpoch / 1000).round().toString(); + final apiKey = environment['podcastIndexApiKey']; + final apiSecret = environment['podcastIndexApiSecret']; + final firstChunk = utf8.encode(apiKey); + final secondChunk = utf8.encode(apiSecret); + final thirdChunk = utf8.encode(unixTime); + var output = AccumulatorSink(); + var input = sha1.startChunkedConversion(output); + input.add(firstChunk); + input.add(secondChunk); + input.add(thirdChunk); + input.close(); + var digest = output.events.single; + + var headers = { + "X-Auth-Date": unixTime, + "X-Auth-Key": apiKey, + "Authorization": digest.toString(), + "User-Agent": "Tsacdop/$version" + }; + return headers; + } + + Future> searchPodcasts( + {String searchText, int limit = 99}) async { + final url = "$_baseUrl/api/1.0/search/byterm" + "?q=${Uri.encodeComponent(searchText)}&max=$limit&fulltext=true"; + final headers = _initSearch(); + final response = await _dio.get(url, options: Options(headers: headers)); + Map searchResultMap = jsonDecode(response.toString()); + final searchResult = PodcastIndexSearchResult.fromJson(searchResultMap); + return searchResult; + } + + Future> fetchEpisode({String rssUrl}) async { + final url = "$_baseUrl/api/1.0/episodes/byfeedurl?url=$rssUrl"; + final headers = _initSearch(); + final response = await _dio.get(url, options: Options(headers: headers)); + Map searchResultMap = jsonDecode(response.toString()); + final searchResult = IndexEpisodeResult.fromJson(searchResultMap); + return searchResult; + } +} diff --git a/lib/settings/data_backup.dart b/lib/settings/data_backup.dart index 87c7680..097c7a9 100644 --- a/lib/settings/data_backup.dart +++ b/lib/settings/data_backup.dart @@ -1,1129 +1,1129 @@ -import 'dart:convert'; -import 'dart:developer' as developer; -import 'dart:io'; - -import 'package:device_info/device_info.dart'; -import 'package:file_picker/file_picker.dart'; -import 'package:flutter/gestures.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:flutter_file_dialog/flutter_file_dialog.dart'; -import 'package:fluttertoast/fluttertoast.dart'; -import 'package:line_icons/line_icons.dart'; -import 'package:confetti/confetti.dart'; -import 'package:path/path.dart' as path; -import 'package:path_provider/path_provider.dart'; -import 'package:provider/provider.dart'; -import 'package:wc_flutter_share/wc_flutter_share.dart'; - -import '../local_storage/key_value_storage.dart'; -import '../local_storage/sqflite_localpodcast.dart'; -import '../service/gpodder_api.dart'; -import '../service/opml_build.dart'; -import '../state/podcast_group.dart'; -import '../state/setting_state.dart'; -import '../type/settings_backup.dart'; -import '../util/custom_widget.dart'; -import '../util/extension_helper.dart'; - -class DataBackup extends StatefulWidget { - @override - _DataBackupState createState() => _DataBackupState(); -} - -class _DataBackupState extends State { - final _gpodder = Gpodder(); - var _syncing = false; - - Future _exportOmpl(BuildContext context) async { - var groups = context.read().groups; - var opml = PodcastsBackup(groups).omplBuilder(); - var tempdir = await getTemporaryDirectory(); - var now = DateTime.now(); - var datePlus = now.year.toString() + - now.month.toString() + - now.day.toString() + - now.second.toString(); - var file = File(path.join(tempdir.path, 'tsacdop_opml_$datePlus.xml')); - await file.writeAsString(opml.toXmlString()); - return file; - } - - Future _saveFile(File file) async { - final params = SaveFileDialogParams(sourceFilePath: file.path); - await FlutterFileDialog.saveFile(params: params); - } - - Future _shareFile(File file) async { - final bytes = await file.readAsBytes(); - await WcFlutterShare.share( - sharePopupTitle: 'Share file', - fileName: file.path.split('/').last, - mimeType: 'text/plain', - bytesOfFile: bytes.buffer.asUint8List()); - } - - Future _exportSetting(BuildContext context) async { - var settings = context.read(); - var settingsBack = await settings.backup(); - var json = settingsBack.toJson(); - var tempdir = await getTemporaryDirectory(); - var now = DateTime.now(); - var datePlus = now.year.toString() + - now.month.toString() + - now.day.toString() + - now.second.toString(); - var file = File(path.join(tempdir.path, 'tsacdop_settings_$datePlus.json')); - await file.writeAsString(jsonEncode(json)); - return file; - } - - Future _importSetting(String path, BuildContext context) async { - final s = context.s; - var settings = context.read(); - var file = File(path); - try { - var json = file.readAsStringSync(); - var backup = SettingsBackup.fromJson(jsonDecode(json)); - await settings.restore(backup); - Fluttertoast.showToast( - msg: s.toastImportSettingsSuccess, - gravity: ToastGravity.BOTTOM, - ); - } catch (e) { - developer.log(e, name: 'Import settings'); - Fluttertoast.showToast( - msg: s.toastFileError, - gravity: ToastGravity.BOTTOM, - ); - } - } - - Widget _syncStauts(int index) { - switch (index) { - case 1: - return Text('Successed', style: TextStyle(color: Colors.green)); - break; - case 2: - return Text('Failed', style: TextStyle(color: Colors.red)); - break; - case 3: - return Text('Unauthorized', style: TextStyle(color: Colors.red)); - break; - default: - return Text('Unknown'); - break; - } - } - - void _getFilePath(BuildContext context) async { - final s = context.s; - try { - var filePickResult = - await FilePicker.platform.pickFiles(type: FileType.any); - if (filePickResult == null) { - return; - } - Fluttertoast.showToast( - msg: s.toastReadFile, - gravity: ToastGravity.BOTTOM, - ); - final filePath = filePickResult.files.first.path; - _importSetting(filePath, context); - } on PlatformException catch (e) { - developer.log(e.toString(), name: 'Get file path'); - } - } - - Future _logout() async { - await _gpodder.logout(); - final subscribeWorker = context.read(); - subscribeWorker.cancelWork(); - Fluttertoast.showToast( - msg: 'Logout successfully', - gravity: ToastGravity.BOTTOM, - ); - if (mounted) setState(() {}); - } - - Future> _getLoginInfo() async { - final storage = KeyValueStorage(gpodderApiKey); - return await storage.getStringList(); - } - - Future _syncNow() async { - if (mounted) { - setState(() { - _syncing = true; - }); - } - final gpodder = Gpodder(); - final status = await gpodder.getChanges(); - - if (status == 200) { - final groupList = context.read(); - await gpodder.updateChange(); - await groupList.gpodderSyncNow(); - } - if (mounted) { - setState(() { - _syncing = false; - }); - } - } - - Future> _getSyncStatus() async { - var dateTimeStorage = KeyValueStorage(gpodderSyncDateTimeKey); - var statusStorage = KeyValueStorage(gpodderSyncStatusKey); - final syncDateTime = await dateTimeStorage.getInt(); - final statusIndex = await statusStorage.getInt(); - return [syncDateTime, statusIndex]; - } - - @override - Widget build(BuildContext context) { - final s = context.s; - return AnnotatedRegion( - value: SystemUiOverlayStyle( - statusBarIconBrightness: Theme.of(context).accentColorBrightness, - systemNavigationBarColor: Theme.of(context).primaryColor, - systemNavigationBarIconBrightness: - Theme.of(context).accentColorBrightness, - ), - child: Scaffold( - appBar: AppBar( - elevation: 0, - title: Text(s.settingsBackup), - leading: CustomBackButton(), - backgroundColor: context.primaryColor, - ), - body: Column( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Padding( - padding: EdgeInsets.all(10.0), - ), - FutureBuilder>( - future: _getLoginInfo(), - initialData: [], - builder: (context, snapshot) { - final loginInfo = snapshot.data; - return Container( - height: 160, - width: double.infinity, - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Stack( - children: [ - Hero( - tag: 'gpodder.net', - child: CircleAvatar( - minRadius: 40, - backgroundColor: context.primaryColor, - child: SizedBox( - height: 60, - width: 60, - child: Image.asset('assets/gpodder.png')), - ), - ), - if (_syncing) - Positioned( - left: context.width / 2 - 40, - child: SizedBox( - height: 80, - width: 80, - child: CircularProgressIndicator( - strokeWidth: 1, - ), - ), - ), - if (_syncing) - Positioned( - bottom: 39, - left: context.width / 2 - 12, - child: _OpenEye()), - if (_syncing) - Positioned( - bottom: 39, - left: context.width / 2 + 3, - child: _OpenEye()), - ], - ), - Text( - loginInfo.isEmpty - ? s.intergateWith('gpodder.net') - : s.loggedInAs(loginInfo.first), - style: TextStyle(color: Colors.purple[700])), - ButtonTheme( - height: 32, - child: OutlineButton( - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(100.0), - side: BorderSide(color: Colors.purple[700])), - highlightedBorderColor: Colors.purple[700], - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Icon( - LineIcons.user, - color: Colors.purple[700], - size: context.textTheme.headline6.fontSize, - ), - SizedBox(width: 10), - Text(loginInfo.isEmpty ? s.login : s.logout, - style: - TextStyle(color: Colors.purple[700])), - ], - ), - onPressed: () { - if (loginInfo.isEmpty) { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => _LoginGpodder(), - fullscreenDialog: true)); - } else { - _logout(); - } - }, - ), - ), - ], - ), - ); - }), - FutureBuilder>( - future: _getLoginInfo(), - initialData: [], - builder: (context, snapshot) { - final loginInfo = snapshot.data; - if (loginInfo.isNotEmpty) { - return ListTile( - contentPadding: const EdgeInsets.only( - left: 70.0, right: 20, top: 10, bottom: 10), - onTap: _syncNow, - title: Text(s.syncNow), - trailing: IconButton( - onPressed: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => _GpodderInfo())); - }, - icon: Icon(LineIcons.info_circle_solid), - ), - subtitle: FutureBuilder>( - future: _getSyncStatus(), - initialData: [0, 0], - builder: (context, snapshot) { - final dateTime = snapshot.data[0]; - final status = snapshot.data[1]; - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - '${s.lastUpdate}: ${dateTime.toDate(context)}'), - SizedBox(width: 8), - Row( - children: [ - Text('${s.status}: '), - _syncStauts(status), - ], - ), - ], - ); - }), - ); - } - return Center(); - }), - // ListTile( - // onTap: () async { - // final subscribeWorker = context.read(); - // await subscribeWorker.cancelWork(); - // subscribeWorker.setWorkManager(); - // }, - // title: Text('reset'), - // ), - Divider(height: 1), - Container( - height: 30.0, - padding: EdgeInsets.fromLTRB(70, 0, 70, 0), - alignment: Alignment.centerLeft, - child: Text(s.subscribe, - style: context.textTheme.bodyText1 - .copyWith(color: context.accentColor)), - ), - Padding( - padding: - EdgeInsets.only(left: 70.0, right: 20, top: 10, bottom: 10), - child: Text(s.subscribeExportDes), - ), - Padding( - padding: EdgeInsets.only(left: 70.0, right: 20), - child: Row( - mainAxisAlignment: MainAxisAlignment.start, - children: [ - ButtonTheme( - height: 32, - child: OutlineButton( - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(100.0), - side: BorderSide(color: Colors.green[700])), - highlightedBorderColor: Colors.green[700], - child: Row( - children: [ - Icon( - LineIcons.save, - color: Colors.green[700], - size: context.textTheme.headline6.fontSize, - ), - SizedBox(width: 10), - Text(s.save, - style: TextStyle(color: Colors.green[700])), - ], - ), - onPressed: () async { - var file = await _exportOmpl(context); - await _saveFile(file); - }), - ), - SizedBox(width: 10), - ButtonTheme( - height: 32, - child: OutlineButton( - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(100.0), - side: BorderSide(color: Colors.blue[700])), - highlightedBorderColor: Colors.blue[700], - child: Row( - children: [ - Icon( - Icons.share, - size: context.textTheme.headline6.fontSize, - color: Colors.blue[700], - ), - SizedBox(width: 10), - Text(s.share, - style: TextStyle(color: Colors.blue[700])), - ], - ), - onPressed: () async { - var file = await _exportOmpl(context); - await _shareFile(file); - }), - ) - ], - ), - ), - Divider(height: 1), - Container( - height: 30.0, - padding: EdgeInsets.symmetric(horizontal: 70), - alignment: Alignment.centerLeft, - child: Text(s.settings, - style: context.textTheme.bodyText1 - .copyWith(color: Theme.of(context).accentColor)), - ), - Padding( - padding: - EdgeInsets.only(left: 70.0, right: 20, top: 10, bottom: 10), - child: Text(s.settingsExportDes), - ), - Padding( - padding: EdgeInsets.only(left: 70.0, right: 10), - child: Wrap(children: [ - ButtonTheme( - height: 32, - child: OutlineButton( - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(100.0), - side: BorderSide(color: Colors.green[700])), - highlightedBorderColor: Colors.green[700], - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Icon( - LineIcons.save, - color: Colors.green[700], - size: context.textTheme.headline6.fontSize, - ), - SizedBox(width: 10), - Text(s.save, - style: TextStyle(color: Colors.green[700])), - ], - ), - onPressed: () async { - var file = await _exportSetting(context); - await _saveFile(file); - }), - ), - SizedBox(width: 10), - ButtonTheme( - height: 32, - child: OutlineButton( - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(100.0), - side: BorderSide(color: Colors.blue[700])), - highlightedBorderColor: Colors.blue[700], - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Icon( - Icons.share, - size: context.textTheme.headline6.fontSize, - color: Colors.blue[700], - ), - SizedBox(width: 10), - Text(s.share, - style: TextStyle(color: Colors.blue[700])), - ], - ), - onPressed: () async { - var file = await _exportSetting(context); - await _shareFile(file); - }), - ), - SizedBox(width: 10), - ButtonTheme( - height: 32, - child: OutlineButton( - highlightedBorderColor: Colors.red[700], - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(100.0), - side: BorderSide(color: Colors.red[700])), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Icon( - LineIcons.paperclip_solid, - size: context.textTheme.headline6.fontSize, - color: Colors.red[700], - ), - SizedBox(width: 10), - Text(s.import, - style: TextStyle(color: Colors.red[700])), - ], - ), - onPressed: () { - _getFilePath(context); - }, - ), - ), - ]), - ), - Divider(height: 1) - ], - ), - ), - ); - } -} - -class _OpenEye extends StatefulWidget { - _OpenEye({Key key}) : super(key: key); - - @override - __OpenEyeState createState() => __OpenEyeState(); -} - -class __OpenEyeState extends State<_OpenEye> - with SingleTickerProviderStateMixin { - double _radius = 0.0; - Animation _animation; - AnimationController _controller; - - @override - void initState() { - super.initState(); - _controller = - AnimationController(vsync: this, duration: Duration(seconds: 1)); - _animation = Tween(begin: 0.0, end: 1.0).animate(_controller) - ..addListener(() { - if (mounted) { - setState(() { - _radius = _animation.value; - }); - } - }); - _controller.forward(); - _controller.addStatusListener((status) async { - if (status == AnimationStatus.completed) { - await Future.delayed(Duration(milliseconds: 400)); - _controller.reverse(); - } else if (status == AnimationStatus.dismissed) { - _controller.forward(); - } - }); - } - - @override - void dispose() { - _controller.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - return DotIndicator(radius: 8 * _radius + 0.5, color: Colors.white); - } -} - -enum LoginStatus { none, error, start, syncing, complete } - -class _LoginGpodder extends StatefulWidget { - _LoginGpodder({Key key}) : super(key: key); - - @override - __LoginGpodderState createState() => __LoginGpodderState(); -} - -class __LoginGpodderState extends State<_LoginGpodder> { - var _username = ''; - var _password = ''; - LoginStatus _loginStatus; - ConfettiController _controller; - - @override - void initState() { - _loginStatus = LoginStatus.none; - _controller = ConfettiController(duration: Duration(seconds: 3)); - super.initState(); - } - - @override - void dispose() { - _controller.dispose(); - super.dispose(); - } - - final GlobalKey> _passwordFieldKey = - GlobalKey>(); - final GlobalKey _formKey = GlobalKey(); - final _gpodder = Gpodder(); - - Future _handleLogin() async { - setState(() => _loginStatus = LoginStatus.start); - final form = _formKey.currentState; - if (form.validate()) { - form.save(); - final status = - await _gpodder.login(username: _username, password: _password); - if (status == 200) { - final updateDevice = await _gpodder.updateDevice(_username); - if (updateDevice == 200) { - if (mounted) { - setState(() { - _loginStatus = LoginStatus.syncing; - }); - } - final uploadStatus = await _gpodder.uploadSubscriptions(); - await _getSubscriptions(_gpodder); - if (uploadStatus == 200) { - if (mounted) { - setState(() { - _loginStatus = LoginStatus.complete; - _controller.play(); - }); - } - } - } else { - if (mounted) setState(() => _loginStatus = LoginStatus.error); - Fluttertoast.showToast( - msg: context.s.loginFailed, - gravity: ToastGravity.BOTTOM, - ); - } - } else { - if (mounted) setState(() => _loginStatus = LoginStatus.error); - Fluttertoast.showToast( - msg: context.s.loginFailed, - gravity: ToastGravity.BOTTOM, - ); - } - } else { - if (mounted) setState(() => _loginStatus = LoginStatus.none); - } - } - - Future _getSubscriptions(Gpodder gpodder) async { - var subscribeWorker = context.read(); - var rssExp = RegExp(r'^(https?):\/\/(.*)'); - final opml = await gpodder.getAllPodcast(); - if (opml != '') { - Map> data = PodcastsBackup.parseOPML(opml); - for (var entry in data.entries) { - var list = entry.value.reversed; - for (var rss in list) { - var rssLink = rssExp.stringMatch(rss.xmlUrl); - if (rssLink != null) { - final dbHelper = DBHelper(); - final exist = await dbHelper.checkPodcast(rssLink); - if (exist == '') { - var item = SubscribeItem( - rssLink, rss.text == '' ? rssLink : rss.text, - group: 'Home'); - await subscribeWorker.setSubscribeItem(item, syncGpodder: false); - await Future.delayed(Duration(milliseconds: 200)); - } - } - } - } - } - await subscribeWorker.cancelWork(); - subscribeWorker.setWorkManager(); - } - - String _validateName(String value) { - if (value.isEmpty) { - return context.s.usernameRequired; - } - final nameExp = RegExp(r'^[A-Za-z ]+$'); - if (!nameExp.hasMatch(value)) { - return context.s.invalidName; - } - return null; - } - - String _validatePassword(String value) { - final passwordField = _passwordFieldKey.currentState; - if (passwordField.value == null || passwordField.value.isEmpty) { - return context.s.passwdRequired; - } - return null; - } - - Widget _loginStatusButton() { - switch (_loginStatus) { - case LoginStatus.none: - return Text( - context.s.login, - style: TextStyle(color: Colors.white), - ); - break; - case LoginStatus.syncing: - return Text( - context.s.settingsSyncing, - style: TextStyle(color: Colors.white), - ); - break; - case LoginStatus.start: - return SizedBox( - height: 20, - width: 20, - child: CircularProgressIndicator( - strokeWidth: 2, - valueColor: AlwaysStoppedAnimation(Colors.white), - ), - ); - default: - return Text( - context.s.login, - style: TextStyle(color: Colors.white), - ); - break; - } - } - - @override - Widget build(BuildContext context) { - final s = context.s; - return AnnotatedRegion( - value: SystemUiOverlayStyle( - statusBarIconBrightness: Brightness.dark, - systemNavigationBarColor: Theme.of(context).primaryColor, - systemNavigationBarIconBrightness: - Theme.of(context).accentColorBrightness, - ), - child: Scaffold( - resizeToAvoidBottomInset: true, - body: SafeArea( - top: false, - child: CustomScrollView( - slivers: [ - SliverAppBar( - brightness: Brightness.dark, - iconTheme: IconThemeData( - color: Colors.white, - ), - elevation: 0, - leading: CustomBackButton(), - backgroundColor: context.accentColor, - expandedHeight: 200, - flexibleSpace: Container( - height: 200, - width: double.infinity, - color: context.accentColor, - child: Column( - mainAxisAlignment: MainAxisAlignment.end, - children: [ - Hero( - tag: 'gpodder.net', - child: CircleAvatar( - minRadius: 50, - backgroundColor: - context.primaryColor.withOpacity(0.3), - child: SizedBox( - height: 80, - width: 80, - child: Image.asset('assets/gpodder.png')), - ), - ), - Padding( - padding: const EdgeInsets.all(8.0), - child: Text(s.intergateWith('gpodder.net'), - style: TextStyle( - color: Colors.white, - fontWeight: FontWeight.bold)), - ), - ], - ), - ), - ), - _loginStatus == LoginStatus.complete - ? SliverList( - delegate: SliverChildListDelegate([ - Stack( - children: [ - Padding( - padding: - const EdgeInsets.fromLTRB(40.0, 50, 40, 100), - child: Text( - s.gpodderLoginDes, - textAlign: TextAlign.center, - style: context.textTheme.subtitle1 - .copyWith(height: 2), - ), - ), - Align( - alignment: Alignment.center, - child: ConfettiWidget( - confettiController: _controller, - blastDirectionality: - BlastDirectionality.explosive, - emissionFrequency: 0.05, - maximumSize: Size(20, 10), - shouldLoop: false, - colors: const [ - Colors.green, - Colors.blue, - Colors.pink, - Colors.orange, - Colors.purple - ], - ), - ), - ], - ), - Center( - child: OutlineButton( - onPressed: () { - Navigator.of(context).pop(); - }, - highlightedBorderColor: context.accentColor, - child: Text(s.back)), - ), - ]), - ) - : Form( - key: _formKey, - autovalidateMode: AutovalidateMode.disabled, - child: AutofillGroup( - child: SliverList( - delegate: SliverChildListDelegate( - [ - Padding( - padding: - const EdgeInsets.fromLTRB(40, 20, 40, 10), - child: TextFormField( - decoration: InputDecoration( - labelStyle: - TextStyle(color: context.accentColor), - focusColor: context.accentColor, - focusedBorder: OutlineInputBorder( - borderSide: BorderSide( - color: context.accentColor, - width: 2)), - border: OutlineInputBorder( - borderSide: BorderSide( - color: context.accentColor)), - labelText: s.username, - ), - maxLines: 1, - autofocus: true, - validator: _validateName, - autofillHints: [AutofillHints.username], - onSaved: (value) { - setState(() => _username = value); - }, - ), - ), - Padding( - padding: - const EdgeInsets.fromLTRB(40, 10, 40, 20), - child: PasswordField( - fieldKey: _passwordFieldKey, - labelText: s.password, - validator: _validatePassword, - onSaved: (value) { - setState(() { - _password = value; - }); - }, - ), - ), - Padding( - padding: - const EdgeInsets.fromLTRB(40, 10, 40, 20), - child: InkWell( - onTap: () { - _handleLogin(); - }, - borderRadius: BorderRadius.circular(5.0), - child: Container( - height: 40, - width: 150, - decoration: BoxDecoration( - color: context.accentColor, - borderRadius: - BorderRadius.circular(5.0)), - child: Center(child: _loginStatusButton()), - ), - ), - ), - SizedBox( - height: - MediaQuery.of(context).viewInsets.bottom, - ), - ], - ), - ), - ), - ), - ], - ), - ), - ), - ); - } -} - -class PasswordField extends StatefulWidget { - const PasswordField({ - this.fieldKey, - this.hintText, - this.labelText, - this.helperText, - this.onSaved, - this.validator, - this.onFieldSubmitted, - }); - - final Key fieldKey; - final String hintText; - final String labelText; - final String helperText; - final FormFieldSetter onSaved; - final FormFieldValidator validator; - final ValueChanged onFieldSubmitted; - - @override - _PasswordFieldState createState() => _PasswordFieldState(); -} - -class _PasswordFieldState extends State { - bool _obscureText = true; - - @override - Widget build(BuildContext context) { - return TextFormField( - key: widget.fieldKey, - obscureText: _obscureText, - autofillHints: [AutofillHints.password], - maxLength: 100, - onSaved: widget.onSaved, - validator: widget.validator, - onFieldSubmitted: widget.onFieldSubmitted, - decoration: InputDecoration( - hintStyle: TextStyle(color: context.accentColor), - labelStyle: TextStyle(color: context.accentColor), - border: OutlineInputBorder( - borderSide: BorderSide(color: context.accentColor)), - focusedBorder: OutlineInputBorder( - borderSide: BorderSide(color: context.accentColor, width: 2)), - hintText: widget.hintText, - labelText: widget.labelText, - helperText: widget.helperText, - suffixIcon: GestureDetector( - dragStartBehavior: DragStartBehavior.down, - onTap: () { - setState(() { - _obscureText = !_obscureText; - }); - }, - child: Icon( - _obscureText ? Icons.visibility : Icons.visibility_off, - color: context.accentColor, - semanticLabel: _obscureText ? 'Show' : 'Hide', - ), - ), - ), - ); - } -} - -class _GpodderInfo extends StatefulWidget { - _GpodderInfo({Key key}) : super(key: key); - - @override - __GpodderInfoState createState() => __GpodderInfoState(); -} - -class __GpodderInfoState extends State<_GpodderInfo> { - final _gpodder = Gpodder(); - var _syncing = false; - final _gpodderUrl = "https://gpodder.net"; - - Future> _getLoginInfo() async { - final storage = KeyValueStorage(gpodderApiKey); - final androidInfo = await DeviceInfoPlugin().androidInfo; - final deviceInfo = await storage.getStringList(); - deviceInfo.add("Tsacdop on ${androidInfo.model}"); - return deviceInfo; - } - - Future _fullSync() async { - if (mounted) { - setState(() { - _syncing = true; - }); - } - final uploadStatus = await _gpodder.uploadSubscriptions(); - if (uploadStatus == 200) { - var subscribeWorker = context.read(); - var rssExp = RegExp(r'^(https?):\/\/(.*)'); - final opml = await _gpodder.getAllPodcast(); - if (opml != '') { - Map> data = PodcastsBackup.parseOPML(opml); - for (var entry in data.entries) { - var list = entry.value.reversed; - for (var rss in list) { - var rssLink = rssExp.stringMatch(rss.xmlUrl); - if (rssLink != null) { - final dbHelper = DBHelper(); - final exist = await dbHelper.checkPodcast(rssLink); - if (exist == '') { - var item = SubscribeItem( - rssLink, rss.text == '' ? rssLink : rss.text, - group: 'Home'); - await subscribeWorker.setSubscribeItem(item, - syncGpodder: false); - await Future.delayed(Duration(milliseconds: 200)); - } - } - } - } - } - } - //await _syncNow(); - if (mounted) { - setState(() { - _syncing = false; - }); - } - } - - @override - Widget build(BuildContext context) { - final s = context.s; - return AnnotatedRegion( - value: SystemUiOverlayStyle( - statusBarIconBrightness: Brightness.dark, - systemNavigationBarColor: Theme.of(context).primaryColor, - systemNavigationBarIconBrightness: - Theme.of(context).accentColorBrightness, - ), - child: Scaffold( - resizeToAvoidBottomInset: true, - body: SafeArea( - top: false, - child: CustomScrollView( - slivers: [ - SliverAppBar( - brightness: Brightness.dark, - iconTheme: IconThemeData( - color: Colors.white, - ), - leading: CustomBackButton(), - elevation: 0, - backgroundColor: context.accentColor, - expandedHeight: 200, - flexibleSpace: Container( - height: 200, - width: double.infinity, - color: context.accentColor, - child: Column( - mainAxisAlignment: MainAxisAlignment.end, - children: [ - CircleAvatar( - minRadius: 50, - backgroundColor: context.primaryColor.withOpacity(0.3), - child: SizedBox( - height: 80, - width: 80, - child: Image.asset('assets/gpodder.png')), - ), - Padding( - padding: const EdgeInsets.all(8.0), - child: Text('gpodder.net', - style: TextStyle( - color: Colors.white, - fontWeight: FontWeight.bold)), - ), - ], - ), - ), - ), - SliverList( - delegate: SliverChildListDelegate([ - FutureBuilder>( - future: _getLoginInfo(), - initialData: [], - builder: (context, snapshot) { - final deviceId = - snapshot.data.isNotEmpty ? snapshot.data[1] : ''; - final deviceName = - snapshot.data.isNotEmpty ? snapshot.data[3] : ''; - return Column( - children: [ - ListTile( - title: Text('Device id'), - subtitle: Text(deviceId), - ), - ListTile( - title: Text('Device name'), - subtitle: Text(deviceName), - ), - ], - ); - }), - ListTile( - onTap: () => _gpodderUrl.launchUrl, - title: Text('Visit gpodder.net'), - subtitle: Text('Manage subscriptions online')), - ListTile( - onTap: _fullSync, - title: Text('Full sync'), - subtitle: Text('If error happened when syncing')), - ]), - ), - ], - ), - ), - ), - ); - } -} +import 'dart:convert'; +import 'dart:developer' as developer; +import 'dart:io'; + +import 'package:device_info/device_info.dart'; +import 'package:file_picker/file_picker.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_file_dialog/flutter_file_dialog.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:line_icons/line_icons.dart'; +import 'package:confetti/confetti.dart'; +import 'package:path/path.dart' as path; +import 'package:path_provider/path_provider.dart'; +import 'package:provider/provider.dart'; +import 'package:wc_flutter_share/wc_flutter_share.dart'; + +import '../local_storage/key_value_storage.dart'; +import '../local_storage/sqflite_localpodcast.dart'; +import '../service/gpodder_api.dart'; +import '../service/opml_build.dart'; +import '../state/podcast_group.dart'; +import '../state/setting_state.dart'; +import '../type/settings_backup.dart'; +import '../util/custom_widget.dart'; +import '../util/extension_helper.dart'; + +class DataBackup extends StatefulWidget { + @override + _DataBackupState createState() => _DataBackupState(); +} + +class _DataBackupState extends State { + final _gpodder = Gpodder(); + var _syncing = false; + + Future _exportOmpl(BuildContext context) async { + var groups = context.read().groups; + var opml = PodcastsBackup(groups).omplBuilder(); + var tempdir = await getTemporaryDirectory(); + var now = DateTime.now(); + var datePlus = now.year.toString() + + now.month.toString() + + now.day.toString() + + now.second.toString(); + var file = File(path.join(tempdir.path, 'tsacdop_opml_$datePlus.xml')); + await file.writeAsString(opml.toXmlString()); + return file; + } + + Future _saveFile(File file) async { + final params = SaveFileDialogParams(sourceFilePath: file.path); + await FlutterFileDialog.saveFile(params: params); + } + + Future _shareFile(File file) async { + final bytes = await file.readAsBytes(); + await WcFlutterShare.share( + sharePopupTitle: 'Share file', + fileName: file.path.split('/').last, + mimeType: 'text/plain', + bytesOfFile: bytes.buffer.asUint8List()); + } + + Future _exportSetting(BuildContext context) async { + var settings = context.read(); + var settingsBack = await settings.backup(); + var json = settingsBack.toJson(); + var tempdir = await getTemporaryDirectory(); + var now = DateTime.now(); + var datePlus = now.year.toString() + + now.month.toString() + + now.day.toString() + + now.second.toString(); + var file = File(path.join(tempdir.path, 'tsacdop_settings_$datePlus.json')); + await file.writeAsString(jsonEncode(json)); + return file; + } + + Future _importSetting(String path, BuildContext context) async { + final s = context.s; + var settings = context.read(); + var file = File(path); + try { + var json = file.readAsStringSync(); + var backup = SettingsBackup.fromJson(jsonDecode(json)); + await settings.restore(backup); + Fluttertoast.showToast( + msg: s.toastImportSettingsSuccess, + gravity: ToastGravity.BOTTOM, + ); + } catch (e) { + developer.log(e, name: 'Import settings'); + Fluttertoast.showToast( + msg: s.toastFileError, + gravity: ToastGravity.BOTTOM, + ); + } + } + + Widget _syncStauts(int index) { + switch (index) { + case 1: + return Text('Successed', style: TextStyle(color: Colors.green)); + break; + case 2: + return Text('Failed', style: TextStyle(color: Colors.red)); + break; + case 3: + return Text('Unauthorized', style: TextStyle(color: Colors.red)); + break; + default: + return Text('Unknown'); + break; + } + } + + void _getFilePath(BuildContext context) async { + final s = context.s; + try { + var filePickResult = + await FilePicker.platform.pickFiles(type: FileType.any); + if (filePickResult == null) { + return; + } + Fluttertoast.showToast( + msg: s.toastReadFile, + gravity: ToastGravity.BOTTOM, + ); + final filePath = filePickResult.files.first.path; + _importSetting(filePath, context); + } on PlatformException catch (e) { + developer.log(e.toString(), name: 'Get file path'); + } + } + + Future _logout() async { + await _gpodder.logout(); + final subscribeWorker = context.read(); + subscribeWorker.cancelWork(); + Fluttertoast.showToast( + msg: 'Logout successfully', + gravity: ToastGravity.BOTTOM, + ); + if (mounted) setState(() {}); + } + + Future> _getLoginInfo() async { + final storage = KeyValueStorage(gpodderApiKey); + return await storage.getStringList(); + } + + Future _syncNow() async { + if (mounted) { + setState(() { + _syncing = true; + }); + } + final gpodder = Gpodder(); + final status = await gpodder.getChanges(); + + if (status == 200) { + final groupList = context.read(); + await gpodder.updateChange(); + await groupList.gpodderSyncNow(); + } + if (mounted) { + setState(() { + _syncing = false; + }); + } + } + + Future> _getSyncStatus() async { + var dateTimeStorage = KeyValueStorage(gpodderSyncDateTimeKey); + var statusStorage = KeyValueStorage(gpodderSyncStatusKey); + final syncDateTime = await dateTimeStorage.getInt(); + final statusIndex = await statusStorage.getInt(); + return [syncDateTime, statusIndex]; + } + + @override + Widget build(BuildContext context) { + final s = context.s; + return AnnotatedRegion( + value: SystemUiOverlayStyle( + statusBarIconBrightness: Theme.of(context).accentColorBrightness, + systemNavigationBarColor: Theme.of(context).primaryColor, + systemNavigationBarIconBrightness: + Theme.of(context).accentColorBrightness, + ), + child: Scaffold( + appBar: AppBar( + elevation: 0, + title: Text(s.settingsBackup), + leading: CustomBackButton(), + backgroundColor: context.primaryColor, + ), + body: Column( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: EdgeInsets.all(10.0), + ), + FutureBuilder>( + future: _getLoginInfo(), + initialData: [], + builder: (context, snapshot) { + final loginInfo = snapshot.data; + return Container( + height: 160, + width: double.infinity, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Stack( + children: [ + Hero( + tag: 'gpodder.net', + child: CircleAvatar( + minRadius: 40, + backgroundColor: context.primaryColor, + child: SizedBox( + height: 60, + width: 60, + child: Image.asset('assets/gpodder.png')), + ), + ), + if (_syncing) + Positioned( + left: context.width / 2 - 40, + child: SizedBox( + height: 80, + width: 80, + child: CircularProgressIndicator( + strokeWidth: 1, + ), + ), + ), + if (_syncing) + Positioned( + bottom: 39, + left: context.width / 2 - 12, + child: _OpenEye()), + if (_syncing) + Positioned( + bottom: 39, + left: context.width / 2 + 3, + child: _OpenEye()), + ], + ), + Text( + loginInfo.isEmpty + ? s.intergateWith('gpodder.net') + : s.loggedInAs(loginInfo.first), + style: TextStyle(color: Colors.purple[700])), + ButtonTheme( + height: 32, + child: OutlineButton( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(100.0), + side: BorderSide(color: Colors.purple[700])), + highlightedBorderColor: Colors.purple[700], + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + LineIcons.user, + color: Colors.purple[700], + size: context.textTheme.headline6.fontSize, + ), + SizedBox(width: 10), + Text(loginInfo.isEmpty ? s.login : s.logout, + style: + TextStyle(color: Colors.purple[700])), + ], + ), + onPressed: () { + if (loginInfo.isEmpty) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => _LoginGpodder(), + fullscreenDialog: true)); + } else { + _logout(); + } + }, + ), + ), + ], + ), + ); + }), + FutureBuilder>( + future: _getLoginInfo(), + initialData: [], + builder: (context, snapshot) { + final loginInfo = snapshot.data; + if (loginInfo.isNotEmpty) { + return ListTile( + contentPadding: const EdgeInsets.only( + left: 70.0, right: 20, top: 10, bottom: 10), + onTap: _syncNow, + title: Text(s.syncNow), + trailing: IconButton( + onPressed: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => _GpodderInfo())); + }, + icon: Icon(LineIcons.info_circle_solid), + ), + subtitle: FutureBuilder>( + future: _getSyncStatus(), + initialData: [0, 0], + builder: (context, snapshot) { + final dateTime = snapshot.data[0]; + final status = snapshot.data[1]; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '${s.lastUpdate}: ${dateTime.toDate(context)}'), + SizedBox(width: 8), + Row( + children: [ + Text('${s.status}: '), + _syncStauts(status), + ], + ), + ], + ); + }), + ); + } + return Center(); + }), + // ListTile( + // onTap: () async { + // final subscribeWorker = context.read(); + // await subscribeWorker.cancelWork(); + // subscribeWorker.setWorkManager(); + // }, + // title: Text('reset'), + // ), + Divider(height: 1), + Container( + height: 30.0, + padding: EdgeInsets.fromLTRB(70, 0, 70, 0), + alignment: Alignment.centerLeft, + child: Text(s.subscribe, + style: context.textTheme.bodyText1 + .copyWith(color: context.accentColor)), + ), + Padding( + padding: + EdgeInsets.only(left: 70.0, right: 20, top: 10, bottom: 10), + child: Text(s.subscribeExportDes), + ), + Padding( + padding: EdgeInsets.only(left: 70.0, right: 20), + child: Row( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + ButtonTheme( + height: 32, + child: OutlineButton( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(100.0), + side: BorderSide(color: Colors.green[700])), + highlightedBorderColor: Colors.green[700], + child: Row( + children: [ + Icon( + LineIcons.save, + color: Colors.green[700], + size: context.textTheme.headline6.fontSize, + ), + SizedBox(width: 10), + Text(s.save, + style: TextStyle(color: Colors.green[700])), + ], + ), + onPressed: () async { + var file = await _exportOmpl(context); + await _saveFile(file); + }), + ), + SizedBox(width: 10), + ButtonTheme( + height: 32, + child: OutlineButton( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(100.0), + side: BorderSide(color: Colors.blue[700])), + highlightedBorderColor: Colors.blue[700], + child: Row( + children: [ + Icon( + Icons.share, + size: context.textTheme.headline6.fontSize, + color: Colors.blue[700], + ), + SizedBox(width: 10), + Text(s.share, + style: TextStyle(color: Colors.blue[700])), + ], + ), + onPressed: () async { + var file = await _exportOmpl(context); + await _shareFile(file); + }), + ) + ], + ), + ), + Divider(height: 1), + Container( + height: 30.0, + padding: EdgeInsets.symmetric(horizontal: 70), + alignment: Alignment.centerLeft, + child: Text(s.settings, + style: context.textTheme.bodyText1 + .copyWith(color: Theme.of(context).accentColor)), + ), + Padding( + padding: + EdgeInsets.only(left: 70.0, right: 20, top: 10, bottom: 10), + child: Text(s.settingsExportDes), + ), + Padding( + padding: EdgeInsets.only(left: 70.0, right: 10), + child: Wrap(children: [ + ButtonTheme( + height: 32, + child: OutlineButton( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(100.0), + side: BorderSide(color: Colors.green[700])), + highlightedBorderColor: Colors.green[700], + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + LineIcons.save, + color: Colors.green[700], + size: context.textTheme.headline6.fontSize, + ), + SizedBox(width: 10), + Text(s.save, + style: TextStyle(color: Colors.green[700])), + ], + ), + onPressed: () async { + var file = await _exportSetting(context); + await _saveFile(file); + }), + ), + SizedBox(width: 10), + ButtonTheme( + height: 32, + child: OutlineButton( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(100.0), + side: BorderSide(color: Colors.blue[700])), + highlightedBorderColor: Colors.blue[700], + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.share, + size: context.textTheme.headline6.fontSize, + color: Colors.blue[700], + ), + SizedBox(width: 10), + Text(s.share, + style: TextStyle(color: Colors.blue[700])), + ], + ), + onPressed: () async { + var file = await _exportSetting(context); + await _shareFile(file); + }), + ), + SizedBox(width: 10), + ButtonTheme( + height: 32, + child: OutlineButton( + highlightedBorderColor: Colors.red[700], + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(100.0), + side: BorderSide(color: Colors.red[700])), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + LineIcons.paperclip_solid, + size: context.textTheme.headline6.fontSize, + color: Colors.red[700], + ), + SizedBox(width: 10), + Text(s.import, + style: TextStyle(color: Colors.red[700])), + ], + ), + onPressed: () { + _getFilePath(context); + }, + ), + ), + ]), + ), + Divider(height: 1) + ], + ), + ), + ); + } +} + +class _OpenEye extends StatefulWidget { + _OpenEye({Key key}) : super(key: key); + + @override + __OpenEyeState createState() => __OpenEyeState(); +} + +class __OpenEyeState extends State<_OpenEye> + with SingleTickerProviderStateMixin { + double _radius = 0.0; + Animation _animation; + AnimationController _controller; + + @override + void initState() { + super.initState(); + _controller = + AnimationController(vsync: this, duration: Duration(seconds: 1)); + _animation = Tween(begin: 0.0, end: 1.0).animate(_controller) + ..addListener(() { + if (mounted) { + setState(() { + _radius = _animation.value; + }); + } + }); + _controller.forward(); + _controller.addStatusListener((status) async { + if (status == AnimationStatus.completed) { + await Future.delayed(Duration(milliseconds: 400)); + _controller.reverse(); + } else if (status == AnimationStatus.dismissed) { + _controller.forward(); + } + }); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return DotIndicator(radius: 8 * _radius + 0.5, color: Colors.white); + } +} + +enum LoginStatus { none, error, start, syncing, complete } + +class _LoginGpodder extends StatefulWidget { + _LoginGpodder({Key key}) : super(key: key); + + @override + __LoginGpodderState createState() => __LoginGpodderState(); +} + +class __LoginGpodderState extends State<_LoginGpodder> { + var _username = ''; + var _password = ''; + LoginStatus _loginStatus; + ConfettiController _controller; + + @override + void initState() { + _loginStatus = LoginStatus.none; + _controller = ConfettiController(duration: Duration(seconds: 3)); + super.initState(); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + final GlobalKey> _passwordFieldKey = + GlobalKey>(); + final GlobalKey _formKey = GlobalKey(); + final _gpodder = Gpodder(); + + Future _handleLogin() async { + setState(() => _loginStatus = LoginStatus.start); + final form = _formKey.currentState; + if (form.validate()) { + form.save(); + final status = + await _gpodder.login(username: _username, password: _password); + if (status == 200) { + final updateDevice = await _gpodder.updateDevice(_username); + if (updateDevice == 200) { + if (mounted) { + setState(() { + _loginStatus = LoginStatus.syncing; + }); + } + final uploadStatus = await _gpodder.uploadSubscriptions(); + await _getSubscriptions(_gpodder); + if (uploadStatus == 200) { + if (mounted) { + setState(() { + _loginStatus = LoginStatus.complete; + _controller.play(); + }); + } + } + } else { + if (mounted) setState(() => _loginStatus = LoginStatus.error); + Fluttertoast.showToast( + msg: context.s.loginFailed, + gravity: ToastGravity.BOTTOM, + ); + } + } else { + if (mounted) setState(() => _loginStatus = LoginStatus.error); + Fluttertoast.showToast( + msg: context.s.loginFailed, + gravity: ToastGravity.BOTTOM, + ); + } + } else { + if (mounted) setState(() => _loginStatus = LoginStatus.none); + } + } + + Future _getSubscriptions(Gpodder gpodder) async { + var subscribeWorker = context.read(); + var rssExp = RegExp(r'^(https?):\/\/(.*)'); + final opml = await gpodder.getAllPodcast(); + if (opml != '') { + Map> data = PodcastsBackup.parseOPML(opml); + for (var entry in data.entries) { + var list = entry.value.reversed; + for (var rss in list) { + var rssLink = rssExp.stringMatch(rss.xmlUrl); + if (rssLink != null) { + final dbHelper = DBHelper(); + final exist = await dbHelper.checkPodcast(rssLink); + if (exist == '') { + var item = SubscribeItem( + rssLink, rss.text == '' ? rssLink : rss.text, + group: 'Home'); + await subscribeWorker.setSubscribeItem(item, syncGpodder: false); + await Future.delayed(Duration(milliseconds: 200)); + } + } + } + } + } + await subscribeWorker.cancelWork(); + subscribeWorker.setWorkManager(); + } + + String _validateName(String value) { + if (value.isEmpty) { + return context.s.usernameRequired; + } + final nameExp = RegExp(r'^[A-Za-z ]+$'); + if (!nameExp.hasMatch(value)) { + return context.s.invalidName; + } + return null; + } + + String _validatePassword(String value) { + final passwordField = _passwordFieldKey.currentState; + if (passwordField.value == null || passwordField.value.isEmpty) { + return context.s.passwdRequired; + } + return null; + } + + Widget _loginStatusButton() { + switch (_loginStatus) { + case LoginStatus.none: + return Text( + context.s.login, + style: TextStyle(color: Colors.white), + ); + break; + case LoginStatus.syncing: + return Text( + context.s.settingsSyncing, + style: TextStyle(color: Colors.white), + ); + break; + case LoginStatus.start: + return SizedBox( + height: 20, + width: 20, + child: CircularProgressIndicator( + strokeWidth: 2, + valueColor: AlwaysStoppedAnimation(Colors.white), + ), + ); + default: + return Text( + context.s.login, + style: TextStyle(color: Colors.white), + ); + break; + } + } + + @override + Widget build(BuildContext context) { + final s = context.s; + return AnnotatedRegion( + value: SystemUiOverlayStyle( + statusBarIconBrightness: Brightness.dark, + systemNavigationBarColor: Theme.of(context).primaryColor, + systemNavigationBarIconBrightness: + Theme.of(context).accentColorBrightness, + ), + child: Scaffold( + resizeToAvoidBottomInset: true, + body: SafeArea( + top: false, + child: CustomScrollView( + slivers: [ + SliverAppBar( + brightness: Brightness.dark, + iconTheme: IconThemeData( + color: Colors.white, + ), + elevation: 0, + leading: CustomBackButton(), + backgroundColor: context.accentColor, + expandedHeight: 200, + flexibleSpace: Container( + height: 200, + width: double.infinity, + color: context.accentColor, + child: Column( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + Hero( + tag: 'gpodder.net', + child: CircleAvatar( + minRadius: 50, + backgroundColor: + context.primaryColor.withOpacity(0.3), + child: SizedBox( + height: 80, + width: 80, + child: Image.asset('assets/gpodder.png')), + ), + ), + Padding( + padding: const EdgeInsets.all(8.0), + child: Text(s.intergateWith('gpodder.net'), + style: TextStyle( + color: Colors.white, + fontWeight: FontWeight.bold)), + ), + ], + ), + ), + ), + _loginStatus == LoginStatus.complete + ? SliverList( + delegate: SliverChildListDelegate([ + Stack( + children: [ + Padding( + padding: + const EdgeInsets.fromLTRB(40.0, 50, 40, 100), + child: Text( + s.gpodderLoginDes, + textAlign: TextAlign.center, + style: context.textTheme.subtitle1 + .copyWith(height: 2), + ), + ), + Align( + alignment: Alignment.center, + child: ConfettiWidget( + confettiController: _controller, + blastDirectionality: + BlastDirectionality.explosive, + emissionFrequency: 0.05, + maximumSize: Size(20, 10), + shouldLoop: false, + colors: const [ + Colors.green, + Colors.blue, + Colors.pink, + Colors.orange, + Colors.purple + ], + ), + ), + ], + ), + Center( + child: OutlineButton( + onPressed: () { + Navigator.of(context).pop(); + }, + highlightedBorderColor: context.accentColor, + child: Text(s.back)), + ), + ]), + ) + : Form( + key: _formKey, + autovalidateMode: AutovalidateMode.disabled, + child: AutofillGroup( + child: SliverList( + delegate: SliverChildListDelegate( + [ + Padding( + padding: + const EdgeInsets.fromLTRB(40, 20, 40, 10), + child: TextFormField( + decoration: InputDecoration( + labelStyle: + TextStyle(color: context.accentColor), + focusColor: context.accentColor, + focusedBorder: OutlineInputBorder( + borderSide: BorderSide( + color: context.accentColor, + width: 2)), + border: OutlineInputBorder( + borderSide: BorderSide( + color: context.accentColor)), + labelText: s.username, + ), + maxLines: 1, + autofocus: true, + validator: _validateName, + autofillHints: [AutofillHints.username], + onSaved: (value) { + setState(() => _username = value); + }, + ), + ), + Padding( + padding: + const EdgeInsets.fromLTRB(40, 10, 40, 20), + child: PasswordField( + fieldKey: _passwordFieldKey, + labelText: s.password, + validator: _validatePassword, + onSaved: (value) { + setState(() { + _password = value; + }); + }, + ), + ), + Padding( + padding: + const EdgeInsets.fromLTRB(40, 10, 40, 20), + child: InkWell( + onTap: () { + _handleLogin(); + }, + borderRadius: BorderRadius.circular(5.0), + child: Container( + height: 40, + width: 150, + decoration: BoxDecoration( + color: context.accentColor, + borderRadius: + BorderRadius.circular(5.0)), + child: Center(child: _loginStatusButton()), + ), + ), + ), + SizedBox( + height: + MediaQuery.of(context).viewInsets.bottom, + ), + ], + ), + ), + ), + ), + ], + ), + ), + ), + ); + } +} + +class PasswordField extends StatefulWidget { + const PasswordField({ + this.fieldKey, + this.hintText, + this.labelText, + this.helperText, + this.onSaved, + this.validator, + this.onFieldSubmitted, + }); + + final Key fieldKey; + final String hintText; + final String labelText; + final String helperText; + final FormFieldSetter onSaved; + final FormFieldValidator validator; + final ValueChanged onFieldSubmitted; + + @override + _PasswordFieldState createState() => _PasswordFieldState(); +} + +class _PasswordFieldState extends State { + bool _obscureText = true; + + @override + Widget build(BuildContext context) { + return TextFormField( + key: widget.fieldKey, + obscureText: _obscureText, + autofillHints: [AutofillHints.password], + maxLength: 100, + onSaved: widget.onSaved, + validator: widget.validator, + onFieldSubmitted: widget.onFieldSubmitted, + decoration: InputDecoration( + hintStyle: TextStyle(color: context.accentColor), + labelStyle: TextStyle(color: context.accentColor), + border: OutlineInputBorder( + borderSide: BorderSide(color: context.accentColor)), + focusedBorder: OutlineInputBorder( + borderSide: BorderSide(color: context.accentColor, width: 2)), + hintText: widget.hintText, + labelText: widget.labelText, + helperText: widget.helperText, + suffixIcon: GestureDetector( + dragStartBehavior: DragStartBehavior.down, + onTap: () { + setState(() { + _obscureText = !_obscureText; + }); + }, + child: Icon( + _obscureText ? Icons.visibility : Icons.visibility_off, + color: context.accentColor, + semanticLabel: _obscureText ? 'Show' : 'Hide', + ), + ), + ), + ); + } +} + +class _GpodderInfo extends StatefulWidget { + _GpodderInfo({Key key}) : super(key: key); + + @override + __GpodderInfoState createState() => __GpodderInfoState(); +} + +class __GpodderInfoState extends State<_GpodderInfo> { + final _gpodder = Gpodder(); + var _syncing = false; + final _gpodderUrl = "https://gpodder.net"; + + Future> _getLoginInfo() async { + final storage = KeyValueStorage(gpodderApiKey); + final androidInfo = await DeviceInfoPlugin().androidInfo; + final deviceInfo = await storage.getStringList(); + deviceInfo.add("Tsacdop on ${androidInfo.model}"); + return deviceInfo; + } + + Future _fullSync() async { + if (mounted) { + setState(() { + _syncing = true; + }); + } + final uploadStatus = await _gpodder.uploadSubscriptions(); + if (uploadStatus == 200) { + var subscribeWorker = context.read(); + var rssExp = RegExp(r'^(https?):\/\/(.*)'); + final opml = await _gpodder.getAllPodcast(); + if (opml != '') { + Map> data = PodcastsBackup.parseOPML(opml); + for (var entry in data.entries) { + var list = entry.value.reversed; + for (var rss in list) { + var rssLink = rssExp.stringMatch(rss.xmlUrl); + if (rssLink != null) { + final dbHelper = DBHelper(); + final exist = await dbHelper.checkPodcast(rssLink); + if (exist == '') { + var item = SubscribeItem( + rssLink, rss.text == '' ? rssLink : rss.text, + group: 'Home'); + await subscribeWorker.setSubscribeItem(item, + syncGpodder: false); + await Future.delayed(Duration(milliseconds: 200)); + } + } + } + } + } + } + //await _syncNow(); + if (mounted) { + setState(() { + _syncing = false; + }); + } + } + + @override + Widget build(BuildContext context) { + final s = context.s; + return AnnotatedRegion( + value: SystemUiOverlayStyle( + statusBarIconBrightness: Brightness.dark, + systemNavigationBarColor: Theme.of(context).primaryColor, + systemNavigationBarIconBrightness: + Theme.of(context).accentColorBrightness, + ), + child: Scaffold( + resizeToAvoidBottomInset: true, + body: SafeArea( + top: false, + child: CustomScrollView( + slivers: [ + SliverAppBar( + brightness: Brightness.dark, + iconTheme: IconThemeData( + color: Colors.white, + ), + leading: CustomBackButton(), + elevation: 0, + backgroundColor: context.accentColor, + expandedHeight: 200, + flexibleSpace: Container( + height: 200, + width: double.infinity, + color: context.accentColor, + child: Column( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + CircleAvatar( + minRadius: 50, + backgroundColor: context.primaryColor.withOpacity(0.3), + child: SizedBox( + height: 80, + width: 80, + child: Image.asset('assets/gpodder.png')), + ), + Padding( + padding: const EdgeInsets.all(8.0), + child: Text('gpodder.net', + style: TextStyle( + color: Colors.white, + fontWeight: FontWeight.bold)), + ), + ], + ), + ), + ), + SliverList( + delegate: SliverChildListDelegate([ + FutureBuilder>( + future: _getLoginInfo(), + initialData: [], + builder: (context, snapshot) { + final deviceId = + snapshot.data.isNotEmpty ? snapshot.data[1] : ''; + final deviceName = + snapshot.data.isNotEmpty ? snapshot.data[3] : ''; + return Column( + children: [ + ListTile( + title: Text('Device id'), + subtitle: Text(deviceId), + ), + ListTile( + title: Text('Device name'), + subtitle: Text(deviceName), + ), + ], + ); + }), + ListTile( + onTap: () => _gpodderUrl.launchUrl, + title: Text('Visit gpodder.net'), + subtitle: Text('Manage subscriptions online')), + ListTile( + onTap: _fullSync, + title: Text('Full sync'), + subtitle: Text('If error happened when syncing')), + ]), + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/settings/downloads_manage.dart b/lib/settings/downloads_manage.dart index 5ae4598..5ed7917 100644 --- a/lib/settings/downloads_manage.dart +++ b/lib/settings/downloads_manage.dart @@ -1,442 +1,442 @@ -import 'dart:io'; - -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:google_fonts/google_fonts.dart'; -import 'package:intl/intl.dart'; -import 'package:line_icons/line_icons.dart'; -import 'package:path_provider/path_provider.dart'; -import 'package:provider/provider.dart'; - -import '../local_storage/sqflite_localpodcast.dart'; -import '../state/download_state.dart'; -import '../type/episodebrief.dart'; -import '../util/custom_widget.dart'; -import '../util/extension_helper.dart'; - -class DownloadsManage extends StatefulWidget { - @override - _DownloadsManageState createState() => _DownloadsManageState(); -} - -class _DownloadsManageState extends State { - //Downloaded size - int _size; - int _mode; - //Downloaded files - int _fileNum; - bool _clearing; - bool _onlyListened; - List _selectedList; - - Future> _getDownloadedEpisode(int mode) async { - var episodes = []; - var dbHelper = DBHelper(); - episodes = await dbHelper.getDownloadedEpisode(mode); - return episodes; - } - - Future _isListened(EpisodeBrief episode) async { - var dbHelper = DBHelper(); - return await dbHelper.isListened(episode.enclosureUrl); - } - - Future _getStorageSize() async { - _size = 0; - _fileNum = 0; - final dirs = await getExternalStorageDirectories(); - for (var dir in dirs) { - dir.list().forEach((d) { - var fileDir = Directory(d.path); - fileDir.list().forEach((file) async { - await File(file.path).stat().then((value) { - _size += value.size; - _fileNum += 1; - if (mounted) setState(() {}); - }); - }); - }); - } - } - - Future _delSelectedEpisodes() async { - setState(() => _clearing = true); - // await Future.forEach(_selectedList, (EpisodeBrief episode) async - for (var episode in _selectedList) { - var downloader = Provider.of(context, listen: false); - await downloader.delTask(episode); - if (mounted) setState(() {}); - } - await Future.delayed(Duration(seconds: 1)); - if (mounted) { - setState(() { - _clearing = false; - }); - } - await Future.delayed(Duration(seconds: 1)); - if (mounted) setState(() => _selectedList = []); - _getStorageSize(); - } - - String _downloadDateToString(BuildContext context, - {int downloadDate, int pubDate}) { - final s = context.s; - var date = DateTime.fromMillisecondsSinceEpoch(downloadDate); - var diffrence = DateTime.now().toUtc().difference(date); - if (diffrence.inHours < 24) { - return s.hoursAgo(diffrence.inHours); - } else if (diffrence.inDays < 7) { - return s.daysAgo(diffrence.inDays); - } else { - return DateFormat.yMMMd().format( - DateTime.fromMillisecondsSinceEpoch(pubDate, isUtc: true).toLocal()); - } - } - - int sumSelected() { - var sum = 0; - if (_selectedList.length == 0) { - return sum; - } else { - for (var episode in _selectedList) { - sum += episode.enclosureLength; - } - return sum; - } - } - - @override - void initState() { - super.initState(); - _clearing = false; - _selectedList = []; - _mode = 0; - _onlyListened = false; - _getStorageSize(); - } - - @override - Widget build(BuildContext context) { - final s = context.s; - return AnnotatedRegion( - value: SystemUiOverlayStyle( - statusBarIconBrightness: Theme.of(context).accentColorBrightness, - systemNavigationBarColor: Theme.of(context).primaryColor, - systemNavigationBarIconBrightness: - Theme.of(context).accentColorBrightness, - ), - child: Scaffold( - appBar: AppBar( - leading: CustomBackButton(), - elevation: 0, - backgroundColor: context.primaryColor, - ), - body: SafeArea( - child: Stack( - children: [ - Column( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Container( - height: 140.0, - color: context.primaryColor, - child: Column( - mainAxisAlignment: MainAxisAlignment.start, - children: [ - Padding( - padding: const EdgeInsets.only(left: 10), - child: RichText( - text: TextSpan( - text: 'Total ', - style: TextStyle( - color: context.accentColor, - fontSize: 20, - ), - children: [ - TextSpan( - text: _fileNum.toString(), - style: GoogleFonts.cairo( - textStyle: TextStyle( - color: context.accentColor, - fontSize: 40, - )), - ), - TextSpan( - text: _fileNum < 2 - ? ' episode' - : ' episodes ', - style: TextStyle( - color: context.accentColor, - fontSize: 20, - )), - TextSpan( - text: (_size ~/ 1000000) < 1000 - ? (_size ~/ 1000000).toString() - : (_size / 1000000000).toStringAsFixed(1), - style: GoogleFonts.cairo( - textStyle: TextStyle( - color: Theme.of(context).accentColor, - fontSize: 50, - )), - ), - TextSpan( - text: - (_size ~/ 1000000) < 1000 ? 'Mb' : 'Gb', - style: TextStyle( - color: Theme.of(context).accentColor, - fontSize: 20, - )), - ], - ), - ), - ), - Spacer(), - SizedBox( - height: 40, - child: Row( - children: [ - Material( - color: Colors.transparent, - child: PopupMenuButton( - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.all( - Radius.circular(10))), - elevation: 1, - tooltip: s.homeSubMenuSortBy, - child: Container( - height: 40, - padding: - EdgeInsets.symmetric(horizontal: 20), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Text(s.homeSubMenuSortBy), - Padding( - padding: EdgeInsets.symmetric( - horizontal: 5), - ), - Icon( - _mode == 0 - ? LineIcons - .hourglass_start_solid - : _mode == 1 - ? LineIcons - .hourglass_half_solid - : LineIcons.save, - size: 18, - ) - ], - )), - itemBuilder: (context) => [ - PopupMenuItem( - value: 0, - child: Text(s.newestFirst), - ), - PopupMenuItem( - value: 1, - child: Text(s.oldestFirst), - ), - PopupMenuItem( - value: 2, - child: Text(s.size), - ), - ], - onSelected: (value) { - if (value == 0) { - setState(() => _mode = 0); - } else if (value == 1) { - setState(() => _mode = 1); - } else if (value == 2) { - setState(() => _mode = 2); - } - }, - ), - ), - //Spacer(), - - Material( - color: Colors.transparent, - child: InkWell( - onTap: () => setState(() { - _onlyListened = !_onlyListened; - }), - child: Row( - children: [ - Padding( - padding: - EdgeInsets.symmetric(horizontal: 5), - ), - Text(s.listened), - Transform.scale( - scale: 0.8, - child: Checkbox( - value: _onlyListened, - onChanged: (value) { - setState(() { - _onlyListened = value; - }); - }), - ), - ], - ), - ), - ), - ], - ), - ), - ], - ), - ), - Expanded( - child: FutureBuilder>( - future: _getDownloadedEpisode(_mode), - initialData: [], - builder: (context, snapshot) { - var _episodes = snapshot.data; - return ListView.builder( - itemCount: _episodes.length, - shrinkWrap: true, - scrollDirection: Axis.vertical, - itemBuilder: (context, index) { - return FutureBuilder( - future: _isListened(_episodes[index]), - initialData: 0, - builder: (context, snapshot) { - return (_onlyListened && snapshot.data == 0) - ? Center() - : Column( - children: [ - ListTile( - onTap: () { - if (_selectedList.contains( - _episodes[index])) { - setState(() => _selectedList - .removeWhere((episode) => - episode - .enclosureUrl == - _episodes[index] - .enclosureUrl)); - } else { - setState(() => _selectedList - .add(_episodes[index])); - } - }, - leading: CircleAvatar( - backgroundImage: - _episodes[index] - .avatarImage), - title: Text( - _episodes[index].title, - maxLines: 1, - overflow: - TextOverflow.ellipsis, - ), - subtitle: Row( - children: [ - Text(_downloadDateToString( - context, - downloadDate: - _episodes[index] - .downloadDate, - pubDate: - _episodes[index] - .pubDate)), - SizedBox(width: 20), - if (_episodes[index] - .enclosureLength != - 0) - Text( - '${(_episodes[index].enclosureLength) ~/ 1000000} Mb'), - ], - ), - trailing: Checkbox( - value: _selectedList.contains( - _episodes[index]), - onChanged: (boo) { - if (boo) { - setState(() => - _selectedList.add( - _episodes[ - index])); - } else { - setState(() => _selectedList - .removeWhere((episode) => - episode - .enclosureUrl == - _episodes[index] - .enclosureUrl)); - } - }, - ), - ), - Divider( - height: 2, - ), - ], - ); - }); - }); - }, - ), - ) - ], - ), - AnimatedPositioned( - duration: Duration(milliseconds: 800), - curve: Curves.elasticInOut, - left: context.width / 2 - 50, - bottom: _selectedList.length == 0 ? -100 : 30, - child: InkWell( - onTap: _delSelectedEpisodes, - child: Stack( - alignment: _clearing - ? Alignment.centerLeft - : Alignment.centerRight, - children: [ - Container( - alignment: Alignment.center, - width: 100, - height: 40, - decoration: BoxDecoration( - borderRadius: - BorderRadius.all(Radius.circular(20.0)), - color: Theme.of(context).accentColor, - ), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - children: [ - Icon( - LineIcons.trash_alt_solid, - color: Colors.white, - ), - Text('${sumSelected() ~/ 1000000}Mb', - style: TextStyle(color: Colors.white)), - ], - ), - ), - SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: AnimatedContainer( - duration: Duration(milliseconds: 500), - alignment: Alignment.center, - width: _clearing ? 100 : 0, - height: _clearing ? 40 : 0, - decoration: BoxDecoration( - borderRadius: - BorderRadius.all(Radius.circular(20.0)), - color: Colors.red.withOpacity(0.6), - ), - ), - ), - ], - )), - ), - ], - ), - ), - ), - ); - } -} +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:intl/intl.dart'; +import 'package:line_icons/line_icons.dart'; +import 'package:path_provider/path_provider.dart'; +import 'package:provider/provider.dart'; + +import '../local_storage/sqflite_localpodcast.dart'; +import '../state/download_state.dart'; +import '../type/episodebrief.dart'; +import '../util/custom_widget.dart'; +import '../util/extension_helper.dart'; + +class DownloadsManage extends StatefulWidget { + @override + _DownloadsManageState createState() => _DownloadsManageState(); +} + +class _DownloadsManageState extends State { + //Downloaded size + int _size; + int _mode; + //Downloaded files + int _fileNum; + bool _clearing; + bool _onlyListened; + List _selectedList; + + Future> _getDownloadedEpisode(int mode) async { + var episodes = []; + var dbHelper = DBHelper(); + episodes = await dbHelper.getDownloadedEpisode(mode); + return episodes; + } + + Future _isListened(EpisodeBrief episode) async { + var dbHelper = DBHelper(); + return await dbHelper.isListened(episode.enclosureUrl); + } + + Future _getStorageSize() async { + _size = 0; + _fileNum = 0; + final dirs = await getExternalStorageDirectories(); + for (var dir in dirs) { + dir.list().forEach((d) { + var fileDir = Directory(d.path); + fileDir.list().forEach((file) async { + await File(file.path).stat().then((value) { + _size += value.size; + _fileNum += 1; + if (mounted) setState(() {}); + }); + }); + }); + } + } + + Future _delSelectedEpisodes() async { + setState(() => _clearing = true); + // await Future.forEach(_selectedList, (EpisodeBrief episode) async + for (var episode in _selectedList) { + var downloader = Provider.of(context, listen: false); + await downloader.delTask(episode); + if (mounted) setState(() {}); + } + await Future.delayed(Duration(seconds: 1)); + if (mounted) { + setState(() { + _clearing = false; + }); + } + await Future.delayed(Duration(seconds: 1)); + if (mounted) setState(() => _selectedList = []); + _getStorageSize(); + } + + String _downloadDateToString(BuildContext context, + {int downloadDate, int pubDate}) { + final s = context.s; + var date = DateTime.fromMillisecondsSinceEpoch(downloadDate); + var diffrence = DateTime.now().toUtc().difference(date); + if (diffrence.inHours < 24) { + return s.hoursAgo(diffrence.inHours); + } else if (diffrence.inDays < 7) { + return s.daysAgo(diffrence.inDays); + } else { + return DateFormat.yMMMd().format( + DateTime.fromMillisecondsSinceEpoch(pubDate, isUtc: true).toLocal()); + } + } + + int sumSelected() { + var sum = 0; + if (_selectedList.length == 0) { + return sum; + } else { + for (var episode in _selectedList) { + sum += episode.enclosureLength; + } + return sum; + } + } + + @override + void initState() { + super.initState(); + _clearing = false; + _selectedList = []; + _mode = 0; + _onlyListened = false; + _getStorageSize(); + } + + @override + Widget build(BuildContext context) { + final s = context.s; + return AnnotatedRegion( + value: SystemUiOverlayStyle( + statusBarIconBrightness: Theme.of(context).accentColorBrightness, + systemNavigationBarColor: Theme.of(context).primaryColor, + systemNavigationBarIconBrightness: + Theme.of(context).accentColorBrightness, + ), + child: Scaffold( + appBar: AppBar( + leading: CustomBackButton(), + elevation: 0, + backgroundColor: context.primaryColor, + ), + body: SafeArea( + child: Stack( + children: [ + Column( + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + height: 140.0, + color: context.primaryColor, + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.only(left: 10), + child: RichText( + text: TextSpan( + text: 'Total ', + style: TextStyle( + color: context.accentColor, + fontSize: 20, + ), + children: [ + TextSpan( + text: _fileNum.toString(), + style: GoogleFonts.cairo( + textStyle: TextStyle( + color: context.accentColor, + fontSize: 40, + )), + ), + TextSpan( + text: _fileNum < 2 + ? ' episode' + : ' episodes ', + style: TextStyle( + color: context.accentColor, + fontSize: 20, + )), + TextSpan( + text: (_size ~/ 1000000) < 1000 + ? (_size ~/ 1000000).toString() + : (_size / 1000000000).toStringAsFixed(1), + style: GoogleFonts.cairo( + textStyle: TextStyle( + color: Theme.of(context).accentColor, + fontSize: 50, + )), + ), + TextSpan( + text: + (_size ~/ 1000000) < 1000 ? 'Mb' : 'Gb', + style: TextStyle( + color: Theme.of(context).accentColor, + fontSize: 20, + )), + ], + ), + ), + ), + Spacer(), + SizedBox( + height: 40, + child: Row( + children: [ + Material( + color: Colors.transparent, + child: PopupMenuButton( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.all( + Radius.circular(10))), + elevation: 1, + tooltip: s.homeSubMenuSortBy, + child: Container( + height: 40, + padding: + EdgeInsets.symmetric(horizontal: 20), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text(s.homeSubMenuSortBy), + Padding( + padding: EdgeInsets.symmetric( + horizontal: 5), + ), + Icon( + _mode == 0 + ? LineIcons + .hourglass_start_solid + : _mode == 1 + ? LineIcons + .hourglass_half_solid + : LineIcons.save, + size: 18, + ) + ], + )), + itemBuilder: (context) => [ + PopupMenuItem( + value: 0, + child: Text(s.newestFirst), + ), + PopupMenuItem( + value: 1, + child: Text(s.oldestFirst), + ), + PopupMenuItem( + value: 2, + child: Text(s.size), + ), + ], + onSelected: (value) { + if (value == 0) { + setState(() => _mode = 0); + } else if (value == 1) { + setState(() => _mode = 1); + } else if (value == 2) { + setState(() => _mode = 2); + } + }, + ), + ), + //Spacer(), + + Material( + color: Colors.transparent, + child: InkWell( + onTap: () => setState(() { + _onlyListened = !_onlyListened; + }), + child: Row( + children: [ + Padding( + padding: + EdgeInsets.symmetric(horizontal: 5), + ), + Text(s.listened), + Transform.scale( + scale: 0.8, + child: Checkbox( + value: _onlyListened, + onChanged: (value) { + setState(() { + _onlyListened = value; + }); + }), + ), + ], + ), + ), + ), + ], + ), + ), + ], + ), + ), + Expanded( + child: FutureBuilder>( + future: _getDownloadedEpisode(_mode), + initialData: [], + builder: (context, snapshot) { + var _episodes = snapshot.data; + return ListView.builder( + itemCount: _episodes.length, + shrinkWrap: true, + scrollDirection: Axis.vertical, + itemBuilder: (context, index) { + return FutureBuilder( + future: _isListened(_episodes[index]), + initialData: 0, + builder: (context, snapshot) { + return (_onlyListened && snapshot.data == 0) + ? Center() + : Column( + children: [ + ListTile( + onTap: () { + if (_selectedList.contains( + _episodes[index])) { + setState(() => _selectedList + .removeWhere((episode) => + episode + .enclosureUrl == + _episodes[index] + .enclosureUrl)); + } else { + setState(() => _selectedList + .add(_episodes[index])); + } + }, + leading: CircleAvatar( + backgroundImage: + _episodes[index] + .avatarImage), + title: Text( + _episodes[index].title, + maxLines: 1, + overflow: + TextOverflow.ellipsis, + ), + subtitle: Row( + children: [ + Text(_downloadDateToString( + context, + downloadDate: + _episodes[index] + .downloadDate, + pubDate: + _episodes[index] + .pubDate)), + SizedBox(width: 20), + if (_episodes[index] + .enclosureLength != + 0) + Text( + '${(_episodes[index].enclosureLength) ~/ 1000000} Mb'), + ], + ), + trailing: Checkbox( + value: _selectedList.contains( + _episodes[index]), + onChanged: (boo) { + if (boo) { + setState(() => + _selectedList.add( + _episodes[ + index])); + } else { + setState(() => _selectedList + .removeWhere((episode) => + episode + .enclosureUrl == + _episodes[index] + .enclosureUrl)); + } + }, + ), + ), + Divider( + height: 2, + ), + ], + ); + }); + }); + }, + ), + ) + ], + ), + AnimatedPositioned( + duration: Duration(milliseconds: 800), + curve: Curves.elasticInOut, + left: context.width / 2 - 50, + bottom: _selectedList.length == 0 ? -100 : 30, + child: InkWell( + onTap: _delSelectedEpisodes, + child: Stack( + alignment: _clearing + ? Alignment.centerLeft + : Alignment.centerRight, + children: [ + Container( + alignment: Alignment.center, + width: 100, + height: 40, + decoration: BoxDecoration( + borderRadius: + BorderRadius.all(Radius.circular(20.0)), + color: Theme.of(context).accentColor, + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Icon( + LineIcons.trash_alt_solid, + color: Colors.white, + ), + Text('${sumSelected() ~/ 1000000}Mb', + style: TextStyle(color: Colors.white)), + ], + ), + ), + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: AnimatedContainer( + duration: Duration(milliseconds: 500), + alignment: Alignment.center, + width: _clearing ? 100 : 0, + height: _clearing ? 40 : 0, + decoration: BoxDecoration( + borderRadius: + BorderRadius.all(Radius.circular(20.0)), + color: Colors.red.withOpacity(0.6), + ), + ), + ), + ], + )), + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/settings/history.dart b/lib/settings/history.dart index a7b22a1..3a64016 100644 --- a/lib/settings/history.dart +++ b/lib/settings/history.dart @@ -1,541 +1,541 @@ -import 'dart:developer' as developer; - -import 'package:dio/dio.dart'; -import 'package:fl_chart/fl_chart.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:fluttertoast/fluttertoast.dart'; -import 'package:intl/intl.dart'; -import 'package:line_icons/line_icons.dart'; -import 'package:provider/provider.dart'; -import 'package:webfeed/webfeed.dart'; - -import '../local_storage/sqflite_localpodcast.dart'; -import '../state/podcast_group.dart'; -import '../type/play_histroy.dart'; -import '../type/search_api/searchpodcast.dart'; -import '../type/sub_history.dart'; -import '../util/custom_widget.dart'; -import '../util/extension_helper.dart'; - -class PlayedHistory extends StatefulWidget { - @override - _PlayedHistoryState createState() => _PlayedHistoryState(); -} - -class _PlayedHistoryState extends State - with SingleTickerProviderStateMixin { - /// Get play history. - Future> _getPlayHistory(int top) async { - var dbHelper = DBHelper(); - List playHistory; - playHistory = await dbHelper.getPlayHistory(top); - for (var record in playHistory) { - await record.getEpisode(); - } - return playHistory; - } - - bool _loadMore = false; - - Future _loadMoreData() async { - if (mounted) { - setState(() { - _loadMore = true; - }); - } - await Future.delayed(Duration(milliseconds: 500)); - if (mounted) { - setState(() { - _top = _top + 10; - _loadMore = false; - }); - } - } - - int _top = 10; - - Future> getSubHistory() async { - var dbHelper = DBHelper(); - return await dbHelper.getSubHistory(); - } - - TabController _controller; - List list = const [0, 1, 2, 3, 4, 5, 6]; - - Future> getData() async { - var dbHelper = DBHelper(); - var stats = []; - - for (var day in list) { - var mins = await dbHelper.listenMins(7 - day); - stats.add(FlSpot(day.toDouble(), mins)); - } - return stats; - } - - Future recoverSub(BuildContext context, String url) async { - Fluttertoast.showToast( - msg: context.s.toastPodcastRecovering, - gravity: ToastGravity.BOTTOM, - ); - var subscribeWorker = context.watch(); - try { - var options = BaseOptions( - connectTimeout: 10000, - receiveTimeout: 10000, - ); - var response = await Dio(options).get(url); - var p = RssFeed.parse(response.data); - var podcast = OnlinePodcast( - rss: url, - title: p.title, - publisher: p.author, - description: p.description, - image: p.itunes.image.href); - var item = SubscribeItem(podcast.rss, podcast.title, - imgUrl: podcast.image, group: 'Home'); - subscribeWorker.setSubscribeItem(item); - } catch (e) { - developer.log(e.toString(), name: 'Recover podcast error'); - Fluttertoast.showToast( - msg: context.s.toastRecoverFailed, - gravity: ToastGravity.BOTTOM, - ); - } - } - - @override - void initState() { - super.initState(); - _controller = TabController(length: 2, vsync: this); - } - - @override - void dispose() { - _controller.dispose(); - super.dispose(); - } - - double top = 0; - @override - Widget build(BuildContext context) { - final s = context.s; - return AnnotatedRegion( - value: SystemUiOverlayStyle( - statusBarIconBrightness: Theme.of(context).accentColorBrightness, - systemNavigationBarColor: Theme.of(context).primaryColor, - systemNavigationBarIconBrightness: - Theme.of(context).accentColorBrightness, - ), - child: Scaffold( - backgroundColor: context.primaryColor, - body: SafeArea( - child: NestedScrollView( - headerSliverBuilder: (context, innerBoxScrolled) { - return [ - SliverAppBar( - backgroundColor: Theme.of(context).primaryColor, - leading: CustomBackButton(), - elevation: 0, - expandedHeight: 260, - floating: false, - pinned: true, - flexibleSpace: LayoutBuilder( - builder: (context, constraints) { - top = constraints.biggest.height; - return FlexibleSpaceBar( - title: top < 70 + MediaQuery.of(context).padding.top - ? Text( - s.settingsHistory, - ) - : Center(), - background: Padding( - padding: EdgeInsets.only( - top: 50, left: 20, right: 20, bottom: 20), - child: FutureBuilder>( - future: getData(), - builder: (context, snapshot) { - return snapshot.hasData - ? HistoryChart(snapshot.data) - : Center(); - }), - ), - ); - }, - ), - ), - SliverPersistentHeader( - delegate: _SliverAppBarDelegate( - TabBar( - controller: _controller, - indicatorColor: context.accentColor, - labelColor: context.textColor, - labelStyle: context.textTheme.headline6, - tabs: [ - Tab( - child: Text(s.listen), - ), - Tab( - child: Text(s.subscribe), - ) - ], - ), - context.primaryColor), - pinned: true, - ), - ]; - }, - body: TabBarView(controller: _controller, children: [ - FutureBuilder>( - future: _getPlayHistory(_top), - builder: (context, snapshot) { - var width = context.width; - return snapshot.hasData - ? NotificationListener( - onNotification: (scrollInfo) { - if (scrollInfo.metrics.pixels == - scrollInfo.metrics.maxScrollExtent && - snapshot.data.length == _top) { - if (!_loadMore) { - _loadMoreData(); - } - } - return true; - }, - child: ListView.builder( - scrollDirection: Axis.vertical, - itemCount: snapshot.data.length + 1, - itemBuilder: (context, index) { - if (index == snapshot.data.length) { - return SizedBox( - height: 2, - child: _loadMore - ? LinearProgressIndicator() - : Center()); - } else { - var seekValue = - snapshot.data[index].seekValue; - var seconds = snapshot.data[index].seconds; - return Container( - padding: - const EdgeInsets.symmetric(vertical: 5), - color: context.scaffoldBackgroundColor, - child: Column( - children: [ - ListTile( - title: Column( - mainAxisAlignment: - MainAxisAlignment.start, - crossAxisAlignment: - CrossAxisAlignment.start, - children: [ - Text( - DateFormat.yMd() - .add_jm() - .format(snapshot - .data[index].playdate), - style: TextStyle( - color: context.textColor - .withOpacity(0.8), - fontSize: 15, - fontStyle: - FontStyle.italic), - ), - Text( - snapshot.data[index].title, - maxLines: 2, - overflow: TextOverflow.ellipsis, - ), - ], - ), - subtitle: Row( - children: [ - Icon( - Icons.timelapse, - color: Colors.grey[400], - ), - Container( - height: 2, - decoration: BoxDecoration( - border: Border( - bottom: BorderSide( - color: Colors - .grey[400], - width: 2.0))), - width: width * seekValue < - (width - 120) - ? width * seekValue - : width - 120, - ), - Padding( - padding: EdgeInsets.symmetric( - horizontal: 2), - ), - Container( - width: 50, - alignment: Alignment.center, - decoration: BoxDecoration( - color: context.accentColor, - borderRadius: - BorderRadius.all( - Radius.circular( - 10))), - padding: EdgeInsets.all(2), - child: Text( - seconds == 0 && seekValue == 1 - ? s.mark - : seconds.toInt().toTime, - style: TextStyle( - color: Colors.white), - ), - ), - ], - ), - ), - ], - ), - ); - } - }), - ) - : Center( - child: SizedBox( - height: 25, - width: 25, - child: CircularProgressIndicator()), - ); - }, - ), - FutureBuilder>( - future: getSubHistory(), - builder: (context, snapshot) { - return snapshot.hasData - ? ListView.builder( - // shrinkWrap: true, - scrollDirection: Axis.vertical, - itemCount: snapshot.data.length, - itemBuilder: (context, index) { - var _status = snapshot.data[index].status; - return Container( - color: context.scaffoldBackgroundColor, - child: Column( - children: [ - ListTile( - enabled: _status, - title: Column( - mainAxisAlignment: - MainAxisAlignment.start, - crossAxisAlignment: - CrossAxisAlignment.start, - children: [ - Text( - DateFormat.yMd().add_jm().format( - snapshot.data[index].subDate), - style: TextStyle( - color: context.textColor - .withOpacity(0.8), - fontSize: 15, - fontStyle: FontStyle.italic), - ), - Text(snapshot.data[index].title), - ], - ), - subtitle: _status - ? Text(s.daysAgo(DateTime.now() - .difference( - snapshot.data[index].subDate) - .inDays)) - : Text( - s.removedAt(DateFormat.yMd() - .add_jm() - .format(snapshot - .data[index].delDate)), - style: TextStyle(color: Colors.red), - ), - trailing: !_status - ? Material( - color: Colors.transparent, - child: IconButton( - tooltip: s.recoverSubscribe, - icon: Icon(LineIcons - .trash_restore_alt_solid), - onPressed: () => recoverSub( - context, - snapshot.data[index].rssUrl), - ), - ) - : null, - ), - Divider( - height: 2, - ) - ], - ), - ); - }) - : Center( - child: SizedBox( - height: 25, - width: 25, - child: CircularProgressIndicator()), - ); - }, - ), - ]), - ), - ), - ), - ); - } -} - -class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate { - _SliverAppBarDelegate(this._tabBar, this._color); - final Color _color; - final TabBar _tabBar; - - @override - double get minExtent => _tabBar.preferredSize.height; - @override - double get maxExtent => _tabBar.preferredSize.height; - - @override - Widget build( - BuildContext context, double shrinkOffset, bool overlapsContent) { - return Container( - color: _color, - child: _tabBar, - ); - } - - @override - bool shouldRebuild(_SliverAppBarDelegate oldDelegate) { - return true; - } -} - -class HistoryChart extends StatelessWidget { - final List stats; - HistoryChart(this.stats); - @override - Widget build(BuildContext context) { - return SafeArea( - child: LineChart( - LineChartData( - backgroundColor: Colors.transparent, - gridData: FlGridData( - show: true, - drawHorizontalLine: false, - getDrawingHorizontalLine: (value) { - return value % 1000 == 0 - ? FlLine( - color: context.brightness == Brightness.light - ? Colors.grey[400] - : Colors.grey[700], - strokeWidth: 0, - ) - : FlLine(color: Colors.transparent); - }, - ), - titlesData: FlTitlesData( - show: true, - bottomTitles: SideTitles( - getTextStyles: (i) => TextStyle( - color: const Color(0xff67727d), - fontWeight: FontWeight.bold, - fontSize: 12, - ), - showTitles: true, - reservedSize: 10, - getTitles: (value) { - return DateFormat.E().format(DateTime.now() - .subtract(Duration(days: (7 - value.toInt())))); - }, - margin: 5, - ), - leftTitles: SideTitles( - showTitles: true, - getTextStyles: (s) => TextStyle( - color: const Color(0xff67727d), - fontWeight: FontWeight.bold, - fontSize: 12, - ), - getTitles: (value) { - return value % 60 == 0 && value > 0 ? '${value ~/ 60}h' : ''; - }, - reservedSize: 20, - margin: 5, - ), - ), - borderData: FlBorderData( - show: false, - border: Border( - left: BorderSide(color: Colors.red, width: 2), - )), - lineTouchData: LineTouchData( - enabled: true, - touchTooltipData: LineTouchTooltipData( - tooltipBgColor: context.scaffoldBackgroundColor, - fitInsideHorizontally: true, - getTooltipItems: (touchedBarSpots) { - return touchedBarSpots.map((barSpot) { - return LineTooltipItem(context.s.minsCount(barSpot.y.toInt()), - context.textTheme.subtitle1); - }).toList(); - }, - ), - getTouchedSpotIndicator: (barData, spotIndexes) { - return spotIndexes.map((spotIndex) { - return TouchedSpotIndicatorData( - FlLine(color: Colors.transparent), - FlDotData( - show: true, - getDotPainter: (spot, percent, barData, index) { - return FlDotCirclePainter( - radius: 3, - color: context.accentColor, - strokeWidth: 4, - strokeColor: context.primaryColor); - })); - }).toList(); - }, - ), - lineBarsData: [ - LineChartBarData( - spots: stats, - isCurved: true, - colors: [context.accentColor], - preventCurveOverShooting: true, - barWidth: 3, - isStrokeCapRound: true, - belowBarData: BarAreaData( - show: true, - gradientFrom: Offset(0, 0), - gradientTo: Offset(0, 1), - gradientColorStops: [ - 0.3, - 0.8, - 0.99 - ], - colors: [ - context.accentColor.withOpacity(0.6), - context.accentColor.withOpacity(0.1), - context.accentColor.withOpacity(0) - ]), - dotData: FlDotData( - show: true, - getDotPainter: (spot, percent, barData, index) { - return FlDotCirclePainter( - radius: 2, - color: context.primaryColor, - strokeWidth: 3, - strokeColor: context.accentColor); - }), - ), - ], - ), - ), - ); - } -} +import 'dart:developer' as developer; + +import 'package:dio/dio.dart'; +import 'package:fl_chart/fl_chart.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:intl/intl.dart'; +import 'package:line_icons/line_icons.dart'; +import 'package:provider/provider.dart'; +import 'package:webfeed/webfeed.dart'; + +import '../local_storage/sqflite_localpodcast.dart'; +import '../state/podcast_group.dart'; +import '../type/play_histroy.dart'; +import '../type/search_api/searchpodcast.dart'; +import '../type/sub_history.dart'; +import '../util/custom_widget.dart'; +import '../util/extension_helper.dart'; + +class PlayedHistory extends StatefulWidget { + @override + _PlayedHistoryState createState() => _PlayedHistoryState(); +} + +class _PlayedHistoryState extends State + with SingleTickerProviderStateMixin { + /// Get play history. + Future> _getPlayHistory(int top) async { + var dbHelper = DBHelper(); + List playHistory; + playHistory = await dbHelper.getPlayHistory(top); + for (var record in playHistory) { + await record.getEpisode(); + } + return playHistory; + } + + bool _loadMore = false; + + Future _loadMoreData() async { + if (mounted) { + setState(() { + _loadMore = true; + }); + } + await Future.delayed(Duration(milliseconds: 500)); + if (mounted) { + setState(() { + _top = _top + 10; + _loadMore = false; + }); + } + } + + int _top = 10; + + Future> getSubHistory() async { + var dbHelper = DBHelper(); + return await dbHelper.getSubHistory(); + } + + TabController _controller; + List list = const [0, 1, 2, 3, 4, 5, 6]; + + Future> getData() async { + var dbHelper = DBHelper(); + var stats = []; + + for (var day in list) { + var mins = await dbHelper.listenMins(7 - day); + stats.add(FlSpot(day.toDouble(), mins)); + } + return stats; + } + + Future recoverSub(BuildContext context, String url) async { + Fluttertoast.showToast( + msg: context.s.toastPodcastRecovering, + gravity: ToastGravity.BOTTOM, + ); + var subscribeWorker = context.watch(); + try { + var options = BaseOptions( + connectTimeout: 10000, + receiveTimeout: 10000, + ); + var response = await Dio(options).get(url); + var p = RssFeed.parse(response.data); + var podcast = OnlinePodcast( + rss: url, + title: p.title, + publisher: p.author, + description: p.description, + image: p.itunes.image.href); + var item = SubscribeItem(podcast.rss, podcast.title, + imgUrl: podcast.image, group: 'Home'); + subscribeWorker.setSubscribeItem(item); + } catch (e) { + developer.log(e.toString(), name: 'Recover podcast error'); + Fluttertoast.showToast( + msg: context.s.toastRecoverFailed, + gravity: ToastGravity.BOTTOM, + ); + } + } + + @override + void initState() { + super.initState(); + _controller = TabController(length: 2, vsync: this); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + double top = 0; + @override + Widget build(BuildContext context) { + final s = context.s; + return AnnotatedRegion( + value: SystemUiOverlayStyle( + statusBarIconBrightness: Theme.of(context).accentColorBrightness, + systemNavigationBarColor: Theme.of(context).primaryColor, + systemNavigationBarIconBrightness: + Theme.of(context).accentColorBrightness, + ), + child: Scaffold( + backgroundColor: context.primaryColor, + body: SafeArea( + child: NestedScrollView( + headerSliverBuilder: (context, innerBoxScrolled) { + return [ + SliverAppBar( + backgroundColor: Theme.of(context).primaryColor, + leading: CustomBackButton(), + elevation: 0, + expandedHeight: 260, + floating: false, + pinned: true, + flexibleSpace: LayoutBuilder( + builder: (context, constraints) { + top = constraints.biggest.height; + return FlexibleSpaceBar( + title: top < 70 + MediaQuery.of(context).padding.top + ? Text( + s.settingsHistory, + ) + : Center(), + background: Padding( + padding: EdgeInsets.only( + top: 50, left: 20, right: 20, bottom: 20), + child: FutureBuilder>( + future: getData(), + builder: (context, snapshot) { + return snapshot.hasData + ? HistoryChart(snapshot.data) + : Center(); + }), + ), + ); + }, + ), + ), + SliverPersistentHeader( + delegate: _SliverAppBarDelegate( + TabBar( + controller: _controller, + indicatorColor: context.accentColor, + labelColor: context.textColor, + labelStyle: context.textTheme.headline6, + tabs: [ + Tab( + child: Text(s.listen), + ), + Tab( + child: Text(s.subscribe), + ) + ], + ), + context.primaryColor), + pinned: true, + ), + ]; + }, + body: TabBarView(controller: _controller, children: [ + FutureBuilder>( + future: _getPlayHistory(_top), + builder: (context, snapshot) { + var width = context.width; + return snapshot.hasData + ? NotificationListener( + onNotification: (scrollInfo) { + if (scrollInfo.metrics.pixels == + scrollInfo.metrics.maxScrollExtent && + snapshot.data.length == _top) { + if (!_loadMore) { + _loadMoreData(); + } + } + return true; + }, + child: ListView.builder( + scrollDirection: Axis.vertical, + itemCount: snapshot.data.length + 1, + itemBuilder: (context, index) { + if (index == snapshot.data.length) { + return SizedBox( + height: 2, + child: _loadMore + ? LinearProgressIndicator() + : Center()); + } else { + var seekValue = + snapshot.data[index].seekValue; + var seconds = snapshot.data[index].seconds; + return Container( + padding: + const EdgeInsets.symmetric(vertical: 5), + color: context.scaffoldBackgroundColor, + child: Column( + children: [ + ListTile( + title: Column( + mainAxisAlignment: + MainAxisAlignment.start, + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text( + DateFormat.yMd() + .add_jm() + .format(snapshot + .data[index].playdate), + style: TextStyle( + color: context.textColor + .withOpacity(0.8), + fontSize: 15, + fontStyle: + FontStyle.italic), + ), + Text( + snapshot.data[index].title, + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + ], + ), + subtitle: Row( + children: [ + Icon( + Icons.timelapse, + color: Colors.grey[400], + ), + Container( + height: 2, + decoration: BoxDecoration( + border: Border( + bottom: BorderSide( + color: Colors + .grey[400], + width: 2.0))), + width: width * seekValue < + (width - 120) + ? width * seekValue + : width - 120, + ), + Padding( + padding: EdgeInsets.symmetric( + horizontal: 2), + ), + Container( + width: 50, + alignment: Alignment.center, + decoration: BoxDecoration( + color: context.accentColor, + borderRadius: + BorderRadius.all( + Radius.circular( + 10))), + padding: EdgeInsets.all(2), + child: Text( + seconds == 0 && seekValue == 1 + ? s.mark + : seconds.toInt().toTime, + style: TextStyle( + color: Colors.white), + ), + ), + ], + ), + ), + ], + ), + ); + } + }), + ) + : Center( + child: SizedBox( + height: 25, + width: 25, + child: CircularProgressIndicator()), + ); + }, + ), + FutureBuilder>( + future: getSubHistory(), + builder: (context, snapshot) { + return snapshot.hasData + ? ListView.builder( + // shrinkWrap: true, + scrollDirection: Axis.vertical, + itemCount: snapshot.data.length, + itemBuilder: (context, index) { + var _status = snapshot.data[index].status; + return Container( + color: context.scaffoldBackgroundColor, + child: Column( + children: [ + ListTile( + enabled: _status, + title: Column( + mainAxisAlignment: + MainAxisAlignment.start, + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text( + DateFormat.yMd().add_jm().format( + snapshot.data[index].subDate), + style: TextStyle( + color: context.textColor + .withOpacity(0.8), + fontSize: 15, + fontStyle: FontStyle.italic), + ), + Text(snapshot.data[index].title), + ], + ), + subtitle: _status + ? Text(s.daysAgo(DateTime.now() + .difference( + snapshot.data[index].subDate) + .inDays)) + : Text( + s.removedAt(DateFormat.yMd() + .add_jm() + .format(snapshot + .data[index].delDate)), + style: TextStyle(color: Colors.red), + ), + trailing: !_status + ? Material( + color: Colors.transparent, + child: IconButton( + tooltip: s.recoverSubscribe, + icon: Icon(LineIcons + .trash_restore_alt_solid), + onPressed: () => recoverSub( + context, + snapshot.data[index].rssUrl), + ), + ) + : null, + ), + Divider( + height: 2, + ) + ], + ), + ); + }) + : Center( + child: SizedBox( + height: 25, + width: 25, + child: CircularProgressIndicator()), + ); + }, + ), + ]), + ), + ), + ), + ); + } +} + +class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate { + _SliverAppBarDelegate(this._tabBar, this._color); + final Color _color; + final TabBar _tabBar; + + @override + double get minExtent => _tabBar.preferredSize.height; + @override + double get maxExtent => _tabBar.preferredSize.height; + + @override + Widget build( + BuildContext context, double shrinkOffset, bool overlapsContent) { + return Container( + color: _color, + child: _tabBar, + ); + } + + @override + bool shouldRebuild(_SliverAppBarDelegate oldDelegate) { + return true; + } +} + +class HistoryChart extends StatelessWidget { + final List stats; + HistoryChart(this.stats); + @override + Widget build(BuildContext context) { + return SafeArea( + child: LineChart( + LineChartData( + backgroundColor: Colors.transparent, + gridData: FlGridData( + show: true, + drawHorizontalLine: false, + getDrawingHorizontalLine: (value) { + return value % 1000 == 0 + ? FlLine( + color: context.brightness == Brightness.light + ? Colors.grey[400] + : Colors.grey[700], + strokeWidth: 0, + ) + : FlLine(color: Colors.transparent); + }, + ), + titlesData: FlTitlesData( + show: true, + bottomTitles: SideTitles( + getTextStyles: (i) => TextStyle( + color: const Color(0xff67727d), + fontWeight: FontWeight.bold, + fontSize: 12, + ), + showTitles: true, + reservedSize: 10, + getTitles: (value) { + return DateFormat.E().format(DateTime.now() + .subtract(Duration(days: (7 - value.toInt())))); + }, + margin: 5, + ), + leftTitles: SideTitles( + showTitles: true, + getTextStyles: (s) => TextStyle( + color: const Color(0xff67727d), + fontWeight: FontWeight.bold, + fontSize: 12, + ), + getTitles: (value) { + return value % 60 == 0 && value > 0 ? '${value ~/ 60}h' : ''; + }, + reservedSize: 20, + margin: 5, + ), + ), + borderData: FlBorderData( + show: false, + border: Border( + left: BorderSide(color: Colors.red, width: 2), + )), + lineTouchData: LineTouchData( + enabled: true, + touchTooltipData: LineTouchTooltipData( + tooltipBgColor: context.scaffoldBackgroundColor, + fitInsideHorizontally: true, + getTooltipItems: (touchedBarSpots) { + return touchedBarSpots.map((barSpot) { + return LineTooltipItem(context.s.minsCount(barSpot.y.toInt()), + context.textTheme.subtitle1); + }).toList(); + }, + ), + getTouchedSpotIndicator: (barData, spotIndexes) { + return spotIndexes.map((spotIndex) { + return TouchedSpotIndicatorData( + FlLine(color: Colors.transparent), + FlDotData( + show: true, + getDotPainter: (spot, percent, barData, index) { + return FlDotCirclePainter( + radius: 3, + color: context.accentColor, + strokeWidth: 4, + strokeColor: context.primaryColor); + })); + }).toList(); + }, + ), + lineBarsData: [ + LineChartBarData( + spots: stats, + isCurved: true, + colors: [context.accentColor], + preventCurveOverShooting: true, + barWidth: 3, + isStrokeCapRound: true, + belowBarData: BarAreaData( + show: true, + gradientFrom: Offset(0, 0), + gradientTo: Offset(0, 1), + gradientColorStops: [ + 0.3, + 0.8, + 0.99 + ], + colors: [ + context.accentColor.withOpacity(0.6), + context.accentColor.withOpacity(0.1), + context.accentColor.withOpacity(0) + ]), + dotData: FlDotData( + show: true, + getDotPainter: (spot, percent, barData, index) { + return FlDotCirclePainter( + radius: 2, + color: context.primaryColor, + strokeWidth: 3, + strokeColor: context.accentColor); + }), + ), + ], + ), + ), + ); + } +} diff --git a/lib/settings/languages.dart b/lib/settings/languages.dart index 52fadd1..bcb6c34 100644 --- a/lib/settings/languages.dart +++ b/lib/settings/languages.dart @@ -1,148 +1,148 @@ -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:intl/intl.dart'; -import 'package:intl/intl_standalone.dart'; - -import '../generated/l10n.dart'; -import '../local_storage/key_value_storage.dart'; -import '../util/extension_helper.dart'; - -class LanguagesSetting extends StatefulWidget { - const LanguagesSetting({Key key}) : super(key: key); - - @override - _LanguagesSettingState createState() => _LanguagesSettingState(); -} - -class _LanguagesSettingState extends State { - _setLocale(Locale locale, {bool systemDefault = false}) async { - var localeStorage = KeyValueStorage(localeKey); - if (systemDefault) { - await localeStorage.saveStringList([]); - await findSystemLocale(); - var systemLanCode; - final list = Intl.systemLocale.split('_'); - if (list.length == 2) { - systemLanCode = list.first; - } else if (list.length == 3) { - systemLanCode = '${list[0]}_${list[1]}'; - } else { - systemLanCode = 'en'; - } - await S.load(Locale(systemLanCode)); - if (mounted) { - setState(() {}); - } - } else { - await localeStorage - .saveStringList([locale.languageCode, locale.countryCode]); - await S.load(locale); - if (mounted) { - setState(() {}); - } - } - } - - @override - void initState() { - super.initState(); - findSystemLocale(); - } - - @override - Widget build(BuildContext context) { - final s = context.s; - return Column( - children: [ - ListTile( - title: Text( - s.systemDefault, - style: TextStyle( - color: Intl.systemLocale.contains(Intl.getCurrentLocale()) - ? context.accentColor - : null), - ), - onTap: () => - _setLocale(Locale(Intl.systemLocale), systemDefault: true), - contentPadding: const EdgeInsets.only(left: 20, right: 20), - ), - Divider(height: 1), - ListTile( - title: Text('English'), - onTap: () => _setLocale(Locale('en')), - contentPadding: const EdgeInsets.only(left: 20, right: 20), - trailing: Radio( - value: Locale('en'), - groupValue: Locale(Intl.getCurrentLocale()), - onChanged: _setLocale)), - Divider(height: 1), - ListTile( - title: Text('简体中文'), - onTap: () => _setLocale(Locale('zh_Hans')), - contentPadding: const EdgeInsets.only(left: 20, right: 20), - trailing: Radio( - value: Locale('zh_Hans'), - groupValue: Locale(Intl.getCurrentLocale()), - onChanged: _setLocale, - )), - Divider(height: 1), - ListTile( - title: Text('Français'), - onTap: () => _setLocale(Locale('fr')), - contentPadding: const EdgeInsets.only(left: 20, right: 20), - trailing: Radio( - value: Locale('fr'), - groupValue: Locale(Intl.getCurrentLocale()), - onChanged: _setLocale), - ), - Divider(height: 1), - ListTile( - title: Text('Español'), - onTap: () => _setLocale(Locale('es')), - contentPadding: const EdgeInsets.only(left: 20, right: 20), - trailing: Radio( - value: Locale('es'), - groupValue: Locale(Intl.getCurrentLocale()), - onChanged: _setLocale), - ), - Divider(height: 1), - ListTile( - title: Text('Português'), - onTap: () => _setLocale(Locale('pt')), - contentPadding: const EdgeInsets.only(left: 20, right: 20), - trailing: Radio( - value: Locale('pt'), - groupValue: Locale(Intl.getCurrentLocale()), - onChanged: _setLocale), - ), - Divider(height: 1), - ListTile( - title: Text('Italiano'), - onTap: () => _setLocale(Locale('it')), - contentPadding: const EdgeInsets.only(left: 20, right: 20), - trailing: Radio( - value: Locale('it'), - groupValue: Locale(Intl.getCurrentLocale()), - onChanged: _setLocale), - ), - Divider(height: 1), - ListTile( - onTap: () => - 'mailto:?subject=Tsacdop localization project' - .launchUrl, - contentPadding: const EdgeInsets.only(left: 20, right: 20), - title: Align( - alignment: Alignment.centerLeft, - child: Image( - image: Theme.of(context).brightness == Brightness.light - ? AssetImage('assets/localizely_logo.png') - : AssetImage('assets/localizely_logo_light.png'), - height: 20), - ), - subtitle: Text( - "If you'd like to contribute to localization project, please contact me."), - ), - ], - ); - } -} +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:intl/intl.dart'; +import 'package:intl/intl_standalone.dart'; + +import '../generated/l10n.dart'; +import '../local_storage/key_value_storage.dart'; +import '../util/extension_helper.dart'; + +class LanguagesSetting extends StatefulWidget { + const LanguagesSetting({Key key}) : super(key: key); + + @override + _LanguagesSettingState createState() => _LanguagesSettingState(); +} + +class _LanguagesSettingState extends State { + _setLocale(Locale locale, {bool systemDefault = false}) async { + var localeStorage = KeyValueStorage(localeKey); + if (systemDefault) { + await localeStorage.saveStringList([]); + await findSystemLocale(); + var systemLanCode; + final list = Intl.systemLocale.split('_'); + if (list.length == 2) { + systemLanCode = list.first; + } else if (list.length == 3) { + systemLanCode = '${list[0]}_${list[1]}'; + } else { + systemLanCode = 'en'; + } + await S.load(Locale(systemLanCode)); + if (mounted) { + setState(() {}); + } + } else { + await localeStorage + .saveStringList([locale.languageCode, locale.countryCode]); + await S.load(locale); + if (mounted) { + setState(() {}); + } + } + } + + @override + void initState() { + super.initState(); + findSystemLocale(); + } + + @override + Widget build(BuildContext context) { + final s = context.s; + return Column( + children: [ + ListTile( + title: Text( + s.systemDefault, + style: TextStyle( + color: Intl.systemLocale.contains(Intl.getCurrentLocale()) + ? context.accentColor + : null), + ), + onTap: () => + _setLocale(Locale(Intl.systemLocale), systemDefault: true), + contentPadding: const EdgeInsets.only(left: 20, right: 20), + ), + Divider(height: 1), + ListTile( + title: Text('English'), + onTap: () => _setLocale(Locale('en')), + contentPadding: const EdgeInsets.only(left: 20, right: 20), + trailing: Radio( + value: Locale('en'), + groupValue: Locale(Intl.getCurrentLocale()), + onChanged: _setLocale)), + Divider(height: 1), + ListTile( + title: Text('简体中文'), + onTap: () => _setLocale(Locale('zh_Hans')), + contentPadding: const EdgeInsets.only(left: 20, right: 20), + trailing: Radio( + value: Locale('zh_Hans'), + groupValue: Locale(Intl.getCurrentLocale()), + onChanged: _setLocale, + )), + Divider(height: 1), + ListTile( + title: Text('Français'), + onTap: () => _setLocale(Locale('fr')), + contentPadding: const EdgeInsets.only(left: 20, right: 20), + trailing: Radio( + value: Locale('fr'), + groupValue: Locale(Intl.getCurrentLocale()), + onChanged: _setLocale), + ), + Divider(height: 1), + ListTile( + title: Text('Español'), + onTap: () => _setLocale(Locale('es')), + contentPadding: const EdgeInsets.only(left: 20, right: 20), + trailing: Radio( + value: Locale('es'), + groupValue: Locale(Intl.getCurrentLocale()), + onChanged: _setLocale), + ), + Divider(height: 1), + ListTile( + title: Text('Português'), + onTap: () => _setLocale(Locale('pt')), + contentPadding: const EdgeInsets.only(left: 20, right: 20), + trailing: Radio( + value: Locale('pt'), + groupValue: Locale(Intl.getCurrentLocale()), + onChanged: _setLocale), + ), + Divider(height: 1), + ListTile( + title: Text('Italiano'), + onTap: () => _setLocale(Locale('it')), + contentPadding: const EdgeInsets.only(left: 20, right: 20), + trailing: Radio( + value: Locale('it'), + groupValue: Locale(Intl.getCurrentLocale()), + onChanged: _setLocale), + ), + Divider(height: 1), + ListTile( + onTap: () => + 'mailto:?subject=Tsacdop localization project' + .launchUrl, + contentPadding: const EdgeInsets.only(left: 20, right: 20), + title: Align( + alignment: Alignment.centerLeft, + child: Image( + image: Theme.of(context).brightness == Brightness.light + ? AssetImage('assets/localizely_logo.png') + : AssetImage('assets/localizely_logo_light.png'), + height: 20), + ), + subtitle: Text( + "If you'd like to contribute to localization project, please contact me."), + ), + ], + ); + } +} diff --git a/lib/settings/layouts.dart b/lib/settings/layouts.dart index 01efa54..cf35383 100644 --- a/lib/settings/layouts.dart +++ b/lib/settings/layouts.dart @@ -1,366 +1,366 @@ -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:provider/provider.dart'; - -import '../local_storage/key_value_storage.dart'; -import '../service/search_api.dart'; -import '../state/audio_state.dart'; -import '../util/custom_dropdown.dart'; -import '../util/custom_widget.dart'; -import '../util/episodegrid.dart'; -import '../util/extension_helper.dart'; -import 'popup_menu.dart'; - -class LayoutSetting extends StatefulWidget { - const LayoutSetting({Key key}) : super(key: key); - - @override - _LayoutSettingState createState() => _LayoutSettingState(); -} - -class _LayoutSettingState extends State { - final _hideDiscoveyStorage = KeyValueStorage(hidePodcastDiscoveryKey); - Future _getLayout(String key) async { - var keyValueStorage = KeyValueStorage(key); - var layout = await keyValueStorage.getInt(); - return Layout.values[layout]; - } - - Future _getHideDiscovery() async { - return await _hideDiscoveyStorage.getBool(defaultValue: false); - } - - Future _saveHideDiscovery(bool boo) async { - await _hideDiscoveyStorage.saveBool(boo); - if (mounted) setState(() {}); - } - - Future _hideListened() async { - var hideListenedStorage = KeyValueStorage(hideListenedKey); - var hideListened = await hideListenedStorage.getBool(defaultValue: false); - return hideListened; - } - - Future _saveHideListened(bool boo) async { - var hideListenedStorage = KeyValueStorage(hideListenedKey); - await hideListenedStorage.saveBool(boo); - if (mounted) setState(() {}); - } - - Future _getSearchEngine() async { - final storage = KeyValueStorage(searchEngineKey); - final index = await storage.getInt(); - return SearchEngine.values[index]; - } - - Future _saveSearchEngine(SearchEngine engine) async { - final storage = KeyValueStorage(searchEngineKey); - await storage.saveInt(engine.index); - if (mounted) setState(() {}); - } - - String _getHeightString(PlayerHeight mode) { - final s = context.s; - switch (mode) { - case PlayerHeight.short: - return s.playerHeightShort; - break; - case PlayerHeight.mid: - return s.playerHeightMed; - break; - case PlayerHeight.tall: - return s.playerHeightTall; - break; - default: - return ''; - } - } - - Widget _gridOptions(BuildContext context, - {String key, - Layout layout, - Layout option, - double scale, - BorderRadiusGeometry borderRadius}) => - Padding( - padding: const EdgeInsets.only(top: 10.0, bottom: 10.0), - child: InkWell( - onTap: () async { - var storage = KeyValueStorage(key); - await storage.saveInt(option.index); - setState(() {}); - }, - borderRadius: borderRadius, - child: AnimatedContainer( - duration: Duration(milliseconds: 400), - height: 30, - width: 50, - decoration: BoxDecoration( - borderRadius: borderRadius, - color: layout == option - ? context.accentColor - : context.primaryColorDark, - ), - alignment: Alignment.center, - child: SizedBox( - height: 10, - width: 30, - child: CustomPaint( - painter: LayoutPainter( - scale, - layout == option - ? Colors.white - : context.textTheme.bodyText1.color), - ), - ), - ), - ), - ); - - Widget _setDefaultGrid(BuildContext context, {String key}) { - return FutureBuilder( - future: _getLayout(key), - builder: (context, snapshot) { - return snapshot.hasData - ? Row( - mainAxisAlignment: MainAxisAlignment.start, - children: [ - _gridOptions( - context, - key: key, - layout: snapshot.data, - option: Layout.one, - scale: 4, - borderRadius: BorderRadius.only( - bottomLeft: Radius.circular(5), - topLeft: Radius.circular(5)), - ), - _gridOptions( - context, - key: key, - layout: snapshot.data, - option: Layout.two, - scale: 1, - ), - _gridOptions(context, - key: key, - layout: snapshot.data, - option: Layout.three, - scale: 0, - borderRadius: BorderRadius.only( - bottomRight: Radius.circular(5), - topRight: Radius.circular(5))), - ], - ) - : Center(); - }); - } - - Widget _setDefaultGridView(BuildContext context, {String text, String key}) { - return Padding( - padding: EdgeInsets.only(left: 70.0, right: 20, bottom: 10), - child: context.width > 360 - ? Row( - children: [ - Text( - text, - ), - Spacer(), - _setDefaultGrid(context, key: key), - ], - ) - : Column( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - text, - ), - _setDefaultGrid(context, key: key), - ], - ), - ); - } - - @override - Widget build(BuildContext context) { - final s = context.s; - var audio = Provider.of(context, listen: false); - return AnnotatedRegion( - value: SystemUiOverlayStyle( - statusBarIconBrightness: Theme.of(context).accentColorBrightness, - systemNavigationBarColor: context.primaryColor, - systemNavigationBarIconBrightness: - Theme.of(context).accentColorBrightness, - ), - child: Scaffold( - appBar: AppBar( - title: Text(s.settingsLayout), - leading: CustomBackButton(), - elevation: 0, - backgroundColor: context.primaryColor, - ), - body: SingleChildScrollView( - child: Column( - mainAxisAlignment: MainAxisAlignment.start, - children: [ - Padding( - padding: EdgeInsets.all(10.0), - ), - Container( - height: 30.0, - padding: const EdgeInsets.symmetric(horizontal: 70), - alignment: Alignment.centerLeft, - child: Text(s.settingsPopupMenu, - style: context.textTheme.bodyText1 - .copyWith(color: context.accentColor)), - ), - ListTile( - onTap: () => Navigator.push( - context, - MaterialPageRoute( - builder: (context) => PopupMenuSetting())), - contentPadding: EdgeInsets.only(left: 70.0, right: 20), - title: Text(s.settingsPopupMenu), - subtitle: Text(s.settingsPopupMenuDes), - ), - Divider(height: 1), - Padding( - padding: EdgeInsets.all(10.0), - ), - Container( - height: 30.0, - padding: EdgeInsets.symmetric(horizontal: 70), - alignment: Alignment.centerLeft, - child: Text(s.player, - style: Theme.of(context) - .textTheme - .bodyText1 - .copyWith(color: Theme.of(context).accentColor)), - ), - ListTile( - contentPadding: EdgeInsets.fromLTRB(70, 10, 10, 10), - title: Text(s.settingsPlayerHeight), - subtitle: Text(s.settingsPlayerHeightDes), - trailing: Selector( - selector: (_, audio) => audio.playerHeight, - builder: (_, data, __) => MyDropdownButton( - hint: Text(_getHeightString(data)), - underline: Center(), - elevation: 1, - value: data.index, - items: [0, 1, 2].map>((e) { - return DropdownMenuItem( - value: e, - child: Text( - _getHeightString(PlayerHeight.values[e]))); - }).toList(), - onChanged: (index) => - audio.setPlayerHeight = PlayerHeight.values[index]), - ), - ), - Divider(height: 1), - Padding( - padding: EdgeInsets.all(10.0), - ), - Container( - height: 30.0, - padding: EdgeInsets.symmetric(horizontal: 70), - alignment: Alignment.centerLeft, - child: Text(s.search, - style: context.textTheme.bodyText1 - .copyWith(color: context.accentColor)), - ), - FutureBuilder( - future: _getHideDiscovery(), - initialData: false, - builder: (context, snapshot) => ListTile( - contentPadding: EdgeInsets.fromLTRB(70, 10, 10, 10), - onTap: () => _saveHideDiscovery(!snapshot.data), - title: Text(s.hidePodcastDiscovery), - subtitle: Text(s.hidePodcastDiscoveryDes), - trailing: Transform.scale( - scale: 0.9, - child: Switch( - value: snapshot.data, onChanged: _saveHideDiscovery), - ), - ), - ), - FutureBuilder( - future: _getSearchEngine(), - initialData: SearchEngine.listenNotes, - builder: (context, snapshot) => ListTile( - contentPadding: EdgeInsets.fromLTRB(70, 10, 10, 10), - title: Text(s.defaultSearchEngine), - subtitle: Text(s.defaultSearchEngineDes), - trailing: MyDropdownButton( - hint: Text(''), - underline: Center(), - elevation: 1, - value: snapshot.data, - items: [ - DropdownMenuItem( - value: SearchEngine.podcastIndex, - child: Text('Podcastindex')), - DropdownMenuItem( - value: SearchEngine.listenNotes, - child: Text('ListenNotes')), - ], - onChanged: (value) => _saveSearchEngine(value)), - ), - ), - Divider(height: 1), - Padding( - padding: EdgeInsets.all(10.0), - ), - Container( - height: 30.0, - padding: EdgeInsets.symmetric(horizontal: 70), - alignment: Alignment.centerLeft, - child: Text(s.settingsDefaultGrid, - style: Theme.of(context) - .textTheme - .bodyText1 - .copyWith(color: Theme.of(context).accentColor)), - ), - ListView( - physics: const NeverScrollableScrollPhysics(), - shrinkWrap: true, - scrollDirection: Axis.vertical, - children: [ - FutureBuilder( - future: _hideListened(), - initialData: false, - builder: (context, snapshot) => ListTile( - contentPadding: EdgeInsets.only(left: 70, right: 10), - onTap: () => _saveHideListened(!snapshot.data), - title: Text('Hide listened'), - subtitle: Text('Hide listened episodes by default'), - trailing: Transform.scale( - scale: 0.9, - child: Switch( - value: snapshot.data, - onChanged: _saveHideListened), - ), - ), - ), - _setDefaultGridView(context, - text: s.settingsDefaultGridPodcast, - key: podcastLayoutKey), - _setDefaultGridView(context, - text: s.settingsDefaultGridRecent, - key: recentLayoutKey), - _setDefaultGridView(context, - text: s.settingsDefaultGridFavorite, - key: favLayoutKey), - _setDefaultGridView(context, - text: s.settingsDefaultGridDownload, - key: downloadLayoutKey), - ]), - Divider(height: 1), - ], - ), - )), - ); - } -} +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; + +import '../local_storage/key_value_storage.dart'; +import '../service/search_api.dart'; +import '../state/audio_state.dart'; +import '../util/custom_dropdown.dart'; +import '../util/custom_widget.dart'; +import '../util/episodegrid.dart'; +import '../util/extension_helper.dart'; +import 'popup_menu.dart'; + +class LayoutSetting extends StatefulWidget { + const LayoutSetting({Key key}) : super(key: key); + + @override + _LayoutSettingState createState() => _LayoutSettingState(); +} + +class _LayoutSettingState extends State { + final _hideDiscoveyStorage = KeyValueStorage(hidePodcastDiscoveryKey); + Future _getLayout(String key) async { + var keyValueStorage = KeyValueStorage(key); + var layout = await keyValueStorage.getInt(); + return Layout.values[layout]; + } + + Future _getHideDiscovery() async { + return await _hideDiscoveyStorage.getBool(defaultValue: false); + } + + Future _saveHideDiscovery(bool boo) async { + await _hideDiscoveyStorage.saveBool(boo); + if (mounted) setState(() {}); + } + + Future _hideListened() async { + var hideListenedStorage = KeyValueStorage(hideListenedKey); + var hideListened = await hideListenedStorage.getBool(defaultValue: false); + return hideListened; + } + + Future _saveHideListened(bool boo) async { + var hideListenedStorage = KeyValueStorage(hideListenedKey); + await hideListenedStorage.saveBool(boo); + if (mounted) setState(() {}); + } + + Future _getSearchEngine() async { + final storage = KeyValueStorage(searchEngineKey); + final index = await storage.getInt(); + return SearchEngine.values[index]; + } + + Future _saveSearchEngine(SearchEngine engine) async { + final storage = KeyValueStorage(searchEngineKey); + await storage.saveInt(engine.index); + if (mounted) setState(() {}); + } + + String _getHeightString(PlayerHeight mode) { + final s = context.s; + switch (mode) { + case PlayerHeight.short: + return s.playerHeightShort; + break; + case PlayerHeight.mid: + return s.playerHeightMed; + break; + case PlayerHeight.tall: + return s.playerHeightTall; + break; + default: + return ''; + } + } + + Widget _gridOptions(BuildContext context, + {String key, + Layout layout, + Layout option, + double scale, + BorderRadiusGeometry borderRadius}) => + Padding( + padding: const EdgeInsets.only(top: 10.0, bottom: 10.0), + child: InkWell( + onTap: () async { + var storage = KeyValueStorage(key); + await storage.saveInt(option.index); + setState(() {}); + }, + borderRadius: borderRadius, + child: AnimatedContainer( + duration: Duration(milliseconds: 400), + height: 30, + width: 50, + decoration: BoxDecoration( + borderRadius: borderRadius, + color: layout == option + ? context.accentColor + : context.primaryColorDark, + ), + alignment: Alignment.center, + child: SizedBox( + height: 10, + width: 30, + child: CustomPaint( + painter: LayoutPainter( + scale, + layout == option + ? Colors.white + : context.textTheme.bodyText1.color), + ), + ), + ), + ), + ); + + Widget _setDefaultGrid(BuildContext context, {String key}) { + return FutureBuilder( + future: _getLayout(key), + builder: (context, snapshot) { + return snapshot.hasData + ? Row( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + _gridOptions( + context, + key: key, + layout: snapshot.data, + option: Layout.one, + scale: 4, + borderRadius: BorderRadius.only( + bottomLeft: Radius.circular(5), + topLeft: Radius.circular(5)), + ), + _gridOptions( + context, + key: key, + layout: snapshot.data, + option: Layout.two, + scale: 1, + ), + _gridOptions(context, + key: key, + layout: snapshot.data, + option: Layout.three, + scale: 0, + borderRadius: BorderRadius.only( + bottomRight: Radius.circular(5), + topRight: Radius.circular(5))), + ], + ) + : Center(); + }); + } + + Widget _setDefaultGridView(BuildContext context, {String text, String key}) { + return Padding( + padding: EdgeInsets.only(left: 70.0, right: 20, bottom: 10), + child: context.width > 360 + ? Row( + children: [ + Text( + text, + ), + Spacer(), + _setDefaultGrid(context, key: key), + ], + ) + : Column( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + text, + ), + _setDefaultGrid(context, key: key), + ], + ), + ); + } + + @override + Widget build(BuildContext context) { + final s = context.s; + var audio = Provider.of(context, listen: false); + return AnnotatedRegion( + value: SystemUiOverlayStyle( + statusBarIconBrightness: Theme.of(context).accentColorBrightness, + systemNavigationBarColor: context.primaryColor, + systemNavigationBarIconBrightness: + Theme.of(context).accentColorBrightness, + ), + child: Scaffold( + appBar: AppBar( + title: Text(s.settingsLayout), + leading: CustomBackButton(), + elevation: 0, + backgroundColor: context.primaryColor, + ), + body: SingleChildScrollView( + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + Padding( + padding: EdgeInsets.all(10.0), + ), + Container( + height: 30.0, + padding: const EdgeInsets.symmetric(horizontal: 70), + alignment: Alignment.centerLeft, + child: Text(s.settingsPopupMenu, + style: context.textTheme.bodyText1 + .copyWith(color: context.accentColor)), + ), + ListTile( + onTap: () => Navigator.push( + context, + MaterialPageRoute( + builder: (context) => PopupMenuSetting())), + contentPadding: EdgeInsets.only(left: 70.0, right: 20), + title: Text(s.settingsPopupMenu), + subtitle: Text(s.settingsPopupMenuDes), + ), + Divider(height: 1), + Padding( + padding: EdgeInsets.all(10.0), + ), + Container( + height: 30.0, + padding: EdgeInsets.symmetric(horizontal: 70), + alignment: Alignment.centerLeft, + child: Text(s.player, + style: Theme.of(context) + .textTheme + .bodyText1 + .copyWith(color: Theme.of(context).accentColor)), + ), + ListTile( + contentPadding: EdgeInsets.fromLTRB(70, 10, 10, 10), + title: Text(s.settingsPlayerHeight), + subtitle: Text(s.settingsPlayerHeightDes), + trailing: Selector( + selector: (_, audio) => audio.playerHeight, + builder: (_, data, __) => MyDropdownButton( + hint: Text(_getHeightString(data)), + underline: Center(), + elevation: 1, + value: data.index, + items: [0, 1, 2].map>((e) { + return DropdownMenuItem( + value: e, + child: Text( + _getHeightString(PlayerHeight.values[e]))); + }).toList(), + onChanged: (index) => + audio.setPlayerHeight = PlayerHeight.values[index]), + ), + ), + Divider(height: 1), + Padding( + padding: EdgeInsets.all(10.0), + ), + Container( + height: 30.0, + padding: EdgeInsets.symmetric(horizontal: 70), + alignment: Alignment.centerLeft, + child: Text(s.search, + style: context.textTheme.bodyText1 + .copyWith(color: context.accentColor)), + ), + FutureBuilder( + future: _getHideDiscovery(), + initialData: false, + builder: (context, snapshot) => ListTile( + contentPadding: EdgeInsets.fromLTRB(70, 10, 10, 10), + onTap: () => _saveHideDiscovery(!snapshot.data), + title: Text(s.hidePodcastDiscovery), + subtitle: Text(s.hidePodcastDiscoveryDes), + trailing: Transform.scale( + scale: 0.9, + child: Switch( + value: snapshot.data, onChanged: _saveHideDiscovery), + ), + ), + ), + FutureBuilder( + future: _getSearchEngine(), + initialData: SearchEngine.listenNotes, + builder: (context, snapshot) => ListTile( + contentPadding: EdgeInsets.fromLTRB(70, 10, 10, 10), + title: Text(s.defaultSearchEngine), + subtitle: Text(s.defaultSearchEngineDes), + trailing: MyDropdownButton( + hint: Text(''), + underline: Center(), + elevation: 1, + value: snapshot.data, + items: [ + DropdownMenuItem( + value: SearchEngine.podcastIndex, + child: Text('Podcastindex')), + DropdownMenuItem( + value: SearchEngine.listenNotes, + child: Text('ListenNotes')), + ], + onChanged: (value) => _saveSearchEngine(value)), + ), + ), + Divider(height: 1), + Padding( + padding: EdgeInsets.all(10.0), + ), + Container( + height: 30.0, + padding: EdgeInsets.symmetric(horizontal: 70), + alignment: Alignment.centerLeft, + child: Text(s.settingsDefaultGrid, + style: Theme.of(context) + .textTheme + .bodyText1 + .copyWith(color: Theme.of(context).accentColor)), + ), + ListView( + physics: const NeverScrollableScrollPhysics(), + shrinkWrap: true, + scrollDirection: Axis.vertical, + children: [ + FutureBuilder( + future: _hideListened(), + initialData: false, + builder: (context, snapshot) => ListTile( + contentPadding: EdgeInsets.only(left: 70, right: 10), + onTap: () => _saveHideListened(!snapshot.data), + title: Text('Hide listened'), + subtitle: Text('Hide listened episodes by default'), + trailing: Transform.scale( + scale: 0.9, + child: Switch( + value: snapshot.data, + onChanged: _saveHideListened), + ), + ), + ), + _setDefaultGridView(context, + text: s.settingsDefaultGridPodcast, + key: podcastLayoutKey), + _setDefaultGridView(context, + text: s.settingsDefaultGridRecent, + key: recentLayoutKey), + _setDefaultGridView(context, + text: s.settingsDefaultGridFavorite, + key: favLayoutKey), + _setDefaultGridView(context, + text: s.settingsDefaultGridDownload, + key: downloadLayoutKey), + ]), + Divider(height: 1), + ], + ), + )), + ); + } +} diff --git a/lib/settings/libries.dart b/lib/settings/libries.dart index e563ee4..91e5dce 100644 --- a/lib/settings/libries.dart +++ b/lib/settings/libries.dart @@ -1,122 +1,122 @@ -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:url_launcher/url_launcher.dart'; - -import '../util/custom_widget.dart'; -import '../util/extension_helper.dart'; -import 'licenses.dart'; - -class Libries extends StatelessWidget { - _launchUrl(String url) async { - if (await canLaunch(url)) { - await launch(url); - } else { - throw 'Could not launch $url'; - } - } - - @override - Widget build(BuildContext context) { - return AnnotatedRegion( - value: SystemUiOverlayStyle( - statusBarIconBrightness: Theme.of(context).accentColorBrightness, - systemNavigationBarColor: Theme.of(context).primaryColor, - systemNavigationBarIconBrightness: - Theme.of(context).accentColorBrightness, - ), - child: Scaffold( - appBar: AppBar( - title: Text(context.s.settingsLibraries), - leading: CustomBackButton(), - elevation: 0, - backgroundColor: Theme.of(context).primaryColor, - ), - body: SafeArea( - child: Scrollbar( - child: SingleChildScrollView( - scrollDirection: Axis.vertical, - child: Column( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Padding( - padding: EdgeInsets.all(10.0), - ), - Container( - height: 30.0, - padding: EdgeInsets.symmetric(horizontal: 70), - alignment: Alignment.centerLeft, - child: Text('Google', - style: Theme.of(context) - .textTheme - .bodyText1 - .copyWith(color: Theme.of(context).accentColor)), - ), - Column( - children: google.map( - (e) { - return ListTile( - contentPadding: EdgeInsets.symmetric(horizontal: 80), - onTap: () => _launchUrl(e.link), - title: Text(e.name), - subtitle: Text(e.license), - ); - }, - ).toList(), - ), - Container( - height: 30.0, - padding: EdgeInsets.symmetric(horizontal: 70), - alignment: Alignment.centerLeft, - child: Text(context.s.fonts, - style: Theme.of(context) - .textTheme - .bodyText1 - .copyWith(color: Theme.of(context).accentColor)), - ), - Column( - children: fonts.map( - (e) { - return ListTile( - contentPadding: EdgeInsets.symmetric(horizontal: 80), - onTap: () => _launchUrl(e.link), - title: Text(e.name), - subtitle: Text(e.license), - ); - }, - ).toList(), - ), - Container( - height: 30.0, - padding: EdgeInsets.symmetric(horizontal: 70), - alignment: Alignment.centerLeft, - child: Text(context.s.plugins, - style: Theme.of(context) - .textTheme - .bodyText1 - .copyWith(color: Theme.of(context).accentColor)), - ), - Container( - child: Column( - children: plugins.map( - (e) { - return ListTile( - onTap: () => _launchUrl(e.link), - contentPadding: - EdgeInsets.symmetric(horizontal: 80), - title: Text(e.name), - subtitle: Text(e.license), - ); - }, - ).toList(), - ), - ), - ], - ), - ), - ), - ), - ), - ); - } -} +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:url_launcher/url_launcher.dart'; + +import '../util/custom_widget.dart'; +import '../util/extension_helper.dart'; +import 'licenses.dart'; + +class Libries extends StatelessWidget { + _launchUrl(String url) async { + if (await canLaunch(url)) { + await launch(url); + } else { + throw 'Could not launch $url'; + } + } + + @override + Widget build(BuildContext context) { + return AnnotatedRegion( + value: SystemUiOverlayStyle( + statusBarIconBrightness: Theme.of(context).accentColorBrightness, + systemNavigationBarColor: Theme.of(context).primaryColor, + systemNavigationBarIconBrightness: + Theme.of(context).accentColorBrightness, + ), + child: Scaffold( + appBar: AppBar( + title: Text(context.s.settingsLibraries), + leading: CustomBackButton(), + elevation: 0, + backgroundColor: Theme.of(context).primaryColor, + ), + body: SafeArea( + child: Scrollbar( + child: SingleChildScrollView( + scrollDirection: Axis.vertical, + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Padding( + padding: EdgeInsets.all(10.0), + ), + Container( + height: 30.0, + padding: EdgeInsets.symmetric(horizontal: 70), + alignment: Alignment.centerLeft, + child: Text('Google', + style: Theme.of(context) + .textTheme + .bodyText1 + .copyWith(color: Theme.of(context).accentColor)), + ), + Column( + children: google.map( + (e) { + return ListTile( + contentPadding: EdgeInsets.symmetric(horizontal: 80), + onTap: () => _launchUrl(e.link), + title: Text(e.name), + subtitle: Text(e.license), + ); + }, + ).toList(), + ), + Container( + height: 30.0, + padding: EdgeInsets.symmetric(horizontal: 70), + alignment: Alignment.centerLeft, + child: Text(context.s.fonts, + style: Theme.of(context) + .textTheme + .bodyText1 + .copyWith(color: Theme.of(context).accentColor)), + ), + Column( + children: fonts.map( + (e) { + return ListTile( + contentPadding: EdgeInsets.symmetric(horizontal: 80), + onTap: () => _launchUrl(e.link), + title: Text(e.name), + subtitle: Text(e.license), + ); + }, + ).toList(), + ), + Container( + height: 30.0, + padding: EdgeInsets.symmetric(horizontal: 70), + alignment: Alignment.centerLeft, + child: Text(context.s.plugins, + style: Theme.of(context) + .textTheme + .bodyText1 + .copyWith(color: Theme.of(context).accentColor)), + ), + Container( + child: Column( + children: plugins.map( + (e) { + return ListTile( + onTap: () => _launchUrl(e.link), + contentPadding: + EdgeInsets.symmetric(horizontal: 80), + title: Text(e.name), + subtitle: Text(e.license), + ); + }, + ).toList(), + ), + ), + ], + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/settings/licenses.dart b/lib/settings/licenses.dart index 71da1e8..7ee07be 100644 --- a/lib/settings/licenses.dart +++ b/lib/settings/licenses.dart @@ -1,78 +1,78 @@ -const String apacheLicense = "Apache License 2.0"; -const String mit = "MIT License"; -const String bsd = "BSD 3-Clause"; -const String gpl = "GPL 3.0"; -const String font = "Open Font License"; - -class Libries { - String name; - String license; - String link; - Libries(this.name, this.license, this.link); -} - -List google = [ - Libries('Android X', apacheLicense, - 'https://source.android.com/setup/start/licenses'), - Libries( - 'Flutter', bsd, 'https://github.com/flutter/flutter/blob/master/LICENSE') -]; - -List fonts = [ - Libries('Libre Baskerville', font, - "https://fonts.google.com/specimen/Libre+Baskerville"), - Libries('Teko', font, "https://fonts.google.com/specimen/Teko"), - Libries('Martel', font, "https://fonts.google.com/specimen/Martel"), - Libries('Bitter', font, "https://fonts.google.com/specimen/Bitter") -]; - -List plugins = [ - Libries('webfeed', mit, 'https://pub.dev/packages/webfeed'), - Libries('json_annotation', bsd, 'https://pub.dev/packages/json_annotation'), - Libries('sqflite', mit, 'https://pub.dev/packages/sqflite'), - Libries('flutter_html', mit, 'https://pub.dev/packages/flutter_html'), - Libries('path_provider', bsd, 'https://pub.dev/packages/path_provider'), - Libries('color_thief_flutter', mit, - 'https://pub.dev/packages/color_thief_flutter'), - Libries('provider', mit, 'https://pub.dev/packages/provider'), - Libries( - 'google_fonts', apacheLicense, 'https://pub.dev/packages/google_fonts'), - Libries('dio', mit, 'https://pub.dev/packages/dio'), - Libries('file_picker', mit, 'https://pub.dev/packages/file_picker'), - Libries('xml', mit, 'https://pub.dev/packages/xml'), - Libries('marquee', mit, 'https://pub.dev/packages/marquee'), - Libries( - 'flutter_downloader', bsd, 'https://pub.dev/packages/flutter_downloader'), - Libries( - 'permission_handler', mit, 'https://pub.dev/packages/permission_handler'), - Libries('fluttertoast', mit, 'https://pub.dev/packages/fluttertoast'), - Libries('intl', bsd, 'https://pub.dev/packages/intl'), - Libries('url_launcher', bsd, 'https://pub.dev/packages/url_launcher'), - Libries('image', apacheLicense, 'https://pub.dev/packages/image'), - Libries( - 'shared_preferences', bsd, 'https://pub.dev/packages/shared_preferences'), - Libries('uuid', mit, 'https://pub.dev/packages/uuid'), - Libries('tuple', bsd, 'https://pub.dev/packages/tuple'), - Libries('cached_network_image', mit, - 'https://pub.dev/packages/cached_network_image'), - Libries('workmanager', mit, 'https://pub.dev/packages/workmanager'), - Libries('app_settings', mit, 'https://pub.dev/packages/app_settings'), - Libries('fl_chart', bsd, 'https://pub.dev/packages/fl_chart'), - Libries('audio_service', mit, 'https://pub.dev/packages/audio_service'), - Libries('just_audio', apacheLicense, 'https://pub.dev/packages/just_audio'), - Libries('line_icons', gpl, 'https://pub.dev/packages/line_icons'), - Libries('flutter_file_dialog', bsd, - 'https://pub.dev/packages/flutter_file_dialog'), - Libries('flutter_linkify', mit, 'https://pub.dev/packages/flutter_linkify'), - Libries('extended_nested_scroll_view', mit, - 'https://pub.dev/packages/extended_nested_scroll_view'), - Libries('connectivity', bsd, 'https://pub.dev/packages/connectivity'), - Libries('Rxdart', apacheLicense, 'https://pub.dev/packages/rxdart'), - Libries('flutter_isolate', mit, 'https://pub.dev/packages/flutter_isolate'), - Libries('auto_animated', mit, 'https://pub.dev/packages/auto_animated'), - Libries('wc_flutter_share', apacheLicense, - 'https://pub.dev/packages/wc_flutter_share'), - Libries('flutter_time_picker_spinner', 'unknow', - 'https://pub.dev/packages/flutter_time_picker_spinner'), - Libries('focused_menu', mit, 'https://pub.dev/packages/focused_menu') -]; +const String apacheLicense = "Apache License 2.0"; +const String mit = "MIT License"; +const String bsd = "BSD 3-Clause"; +const String gpl = "GPL 3.0"; +const String font = "Open Font License"; + +class Libries { + String name; + String license; + String link; + Libries(this.name, this.license, this.link); +} + +List google = [ + Libries('Android X', apacheLicense, + 'https://source.android.com/setup/start/licenses'), + Libries( + 'Flutter', bsd, 'https://github.com/flutter/flutter/blob/master/LICENSE') +]; + +List fonts = [ + Libries('Libre Baskerville', font, + "https://fonts.google.com/specimen/Libre+Baskerville"), + Libries('Teko', font, "https://fonts.google.com/specimen/Teko"), + Libries('Martel', font, "https://fonts.google.com/specimen/Martel"), + Libries('Bitter', font, "https://fonts.google.com/specimen/Bitter") +]; + +List plugins = [ + Libries('webfeed', mit, 'https://pub.dev/packages/webfeed'), + Libries('json_annotation', bsd, 'https://pub.dev/packages/json_annotation'), + Libries('sqflite', mit, 'https://pub.dev/packages/sqflite'), + Libries('flutter_html', mit, 'https://pub.dev/packages/flutter_html'), + Libries('path_provider', bsd, 'https://pub.dev/packages/path_provider'), + Libries('color_thief_flutter', mit, + 'https://pub.dev/packages/color_thief_flutter'), + Libries('provider', mit, 'https://pub.dev/packages/provider'), + Libries( + 'google_fonts', apacheLicense, 'https://pub.dev/packages/google_fonts'), + Libries('dio', mit, 'https://pub.dev/packages/dio'), + Libries('file_picker', mit, 'https://pub.dev/packages/file_picker'), + Libries('xml', mit, 'https://pub.dev/packages/xml'), + Libries('marquee', mit, 'https://pub.dev/packages/marquee'), + Libries( + 'flutter_downloader', bsd, 'https://pub.dev/packages/flutter_downloader'), + Libries( + 'permission_handler', mit, 'https://pub.dev/packages/permission_handler'), + Libries('fluttertoast', mit, 'https://pub.dev/packages/fluttertoast'), + Libries('intl', bsd, 'https://pub.dev/packages/intl'), + Libries('url_launcher', bsd, 'https://pub.dev/packages/url_launcher'), + Libries('image', apacheLicense, 'https://pub.dev/packages/image'), + Libries( + 'shared_preferences', bsd, 'https://pub.dev/packages/shared_preferences'), + Libries('uuid', mit, 'https://pub.dev/packages/uuid'), + Libries('tuple', bsd, 'https://pub.dev/packages/tuple'), + Libries('cached_network_image', mit, + 'https://pub.dev/packages/cached_network_image'), + Libries('workmanager', mit, 'https://pub.dev/packages/workmanager'), + Libries('app_settings', mit, 'https://pub.dev/packages/app_settings'), + Libries('fl_chart', bsd, 'https://pub.dev/packages/fl_chart'), + Libries('audio_service', mit, 'https://pub.dev/packages/audio_service'), + Libries('just_audio', apacheLicense, 'https://pub.dev/packages/just_audio'), + Libries('line_icons', gpl, 'https://pub.dev/packages/line_icons'), + Libries('flutter_file_dialog', bsd, + 'https://pub.dev/packages/flutter_file_dialog'), + Libries('flutter_linkify', mit, 'https://pub.dev/packages/flutter_linkify'), + Libries('extended_nested_scroll_view', mit, + 'https://pub.dev/packages/extended_nested_scroll_view'), + Libries('connectivity', bsd, 'https://pub.dev/packages/connectivity'), + Libries('Rxdart', apacheLicense, 'https://pub.dev/packages/rxdart'), + Libries('flutter_isolate', mit, 'https://pub.dev/packages/flutter_isolate'), + Libries('auto_animated', mit, 'https://pub.dev/packages/auto_animated'), + Libries('wc_flutter_share', apacheLicense, + 'https://pub.dev/packages/wc_flutter_share'), + Libries('flutter_time_picker_spinner', 'unknow', + 'https://pub.dev/packages/flutter_time_picker_spinner'), + Libries('focused_menu', mit, 'https://pub.dev/packages/focused_menu') +]; diff --git a/lib/settings/play_setting.dart b/lib/settings/play_setting.dart index 1487c24..778a5ed 100644 --- a/lib/settings/play_setting.dart +++ b/lib/settings/play_setting.dart @@ -1,649 +1,649 @@ -import 'dart:ui'; - -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:fluttertoast/fluttertoast.dart'; -import 'package:provider/provider.dart'; -import 'package:tuple/tuple.dart'; - -import '../home/audioplayer.dart'; -import '../local_storage/key_value_storage.dart'; -import '../state/audio_state.dart'; -import '../state/setting_state.dart'; -import '../util/custom_dropdown.dart'; -import '../util/custom_time_picker.dart'; -import '../util/custom_widget.dart'; -import '../util/extension_helper.dart'; - -const List kSecondsToSelect = [5, 10, 15, 20, 25, 30, 45, 60]; -const List kSpeedToSelect = [ - 0.5, - 0.6, - 0.8, - 0.9, - 1.0, - 1.1, - 1.2, - 1.5, - 2.0, - 2.5, - 3.0, - 3.5, - 4.0, - 4.5, - 5.0 -]; - -class PlaySetting extends StatefulWidget { - @override - _PlaySettingState createState() => _PlaySettingState(); -} - -class _PlaySettingState extends State { - String _volumeEffect(BuildContext context, int i) { - final s = context.s; - if (i == 2000) { - return s.playerHeightShort; - } else if (i == 3000) { - return s.playerHeightMed; - } - return s.playerHeightTall; - } - - Future _getMarkListenedSkip() async { - final storage = KeyValueStorage(markListenedAfterSkipKey); - return storage.getBool(defaultValue: false); - } - - Future _saveMarkListenedSkip(bool boo) async { - final storage = KeyValueStorage(markListenedAfterSkipKey); - await storage.saveBool(boo); - if (mounted) setState(() {}); - } - - Widget _modeWidget(BuildContext context) { - var settings = Provider.of(context, listen: false); - return Selector>( - selector: (_, settings) => - Tuple2(settings.autoSleepTimerMode, settings.defaultSleepTimer), - builder: (_, data, __) => Padding( - padding: const EdgeInsets.symmetric(vertical: 10), - child: Row( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - InkWell( - onTap: () => settings.setAutoSleepTimerMode = 0, - borderRadius: BorderRadius.only( - bottomLeft: Radius.circular(5), topLeft: Radius.circular(5)), - child: Material( - color: Colors.transparent, - child: AnimatedContainer( - duration: Duration(milliseconds: 400), - decoration: BoxDecoration( - color: data.item1 == 0 - ? context.accentColor - : context.primaryColorDark, - borderRadius: BorderRadius.only( - bottomLeft: Radius.circular(5), - topLeft: Radius.circular(5)), - ), - padding: const EdgeInsets.all(8.0), - child: Text(context.s.endOfEpisode, - style: TextStyle( - color: data.item1 == 0 ? Colors.white : null)), - ), - ), - ), - InkWell( - onTap: () => settings.setAutoSleepTimerMode = 1, - borderRadius: BorderRadius.only( - bottomRight: Radius.circular(5), - topRight: Radius.circular(5)), - child: Material( - color: Colors.transparent, - child: AnimatedContainer( - duration: Duration(milliseconds: 400), - decoration: BoxDecoration( - color: data.item1 == 1 - ? context.accentColor - : context.primaryColorDark, - borderRadius: BorderRadius.only( - bottomRight: Radius.circular(5), - topRight: Radius.circular(5)), - ), - padding: const EdgeInsets.all(8.0), - child: Text(context.s.minsCount(data.item2), - style: TextStyle( - color: data.item1 == 1 ? Colors.white : null)), - ), - ), - ), - ], - ), - ), - ); - } - - Widget _scheduleWidget(BuildContext context) { - var settings = Provider.of(context, listen: false); - final s = context.s; - return Selector>( - selector: (_, settings) => - Tuple2(settings.autoSleepTimerStart, settings.autoSleepTimerEnd), - builder: (_, data, __) => Padding( - padding: const EdgeInsets.symmetric(vertical: 10.0), - child: Row( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - InkWell( - onTap: () async { - var startTime = data.item1; - final timeOfDay = await showCustomTimePicker( - context: context, - cancelText: s.cancel, - confirmText: s.confirm, - helpText: '', - initialTime: TimeOfDay( - hour: startTime ~/ 60, minute: startTime % 60)); - if (timeOfDay != null) { - startTime = timeOfDay.hour * 60 + timeOfDay.minute; - if (startTime != data.item2) { - settings.setAutoSleepTimerStart = startTime; - } else { - Fluttertoast.showToast( - msg: s.toastTimeEqualEnd, - gravity: ToastGravity.BOTTOM, - ); - } - } - }, - borderRadius: BorderRadius.only( - bottomLeft: Radius.circular(5), topLeft: Radius.circular(5)), - child: Material( - color: Colors.transparent, - child: Container( - decoration: BoxDecoration( - color: context.primaryColorDark, - borderRadius: BorderRadius.only( - bottomLeft: Radius.circular(5), - topLeft: Radius.circular(5)), - ), - padding: const EdgeInsets.all(8.0), - child: Text(s.from(data.item1.toTime)), - ), - ), - ), - InkWell( - onTap: () async { - var endTime = data.item2; - final timeOfDay = await showCustomTimePicker( - context: context, - cancelText: s.cancel, - confirmText: s.confirm, - helpText: '', - initialTime: - TimeOfDay(hour: endTime ~/ 60, minute: endTime % 60)); - if (timeOfDay != null) { - endTime = timeOfDay.hour * 60 + timeOfDay.minute; - if (endTime != data.item1) { - settings.setAutoSleepTimerEnd = endTime; - } else { - Fluttertoast.showToast( - msg: s.toastTimeEqualStart, - gravity: ToastGravity.BOTTOM, - ); - } - } - }, - borderRadius: BorderRadius.only( - bottomRight: Radius.circular(5), - topRight: Radius.circular(5)), - child: Material( - color: Colors.transparent, - child: Container( - padding: const EdgeInsets.all(8.0), - decoration: BoxDecoration( - color: Colors.black54, - borderRadius: BorderRadius.only( - bottomRight: Radius.circular(5), - topRight: Radius.circular(5))), - child: Text(s.to(data.item2.toTime), - style: TextStyle(color: Colors.white)), - ), - ), - ), - ], - ), - ), - ); - } - - @override - Widget build(BuildContext context) { - var settings = context.watch(); - var audio = context.watch(); - final s = context.s; - return AnnotatedRegion( - value: SystemUiOverlayStyle( - statusBarIconBrightness: Theme.of(context).accentColorBrightness, - systemNavigationBarColor: Theme.of(context).primaryColor, - systemNavigationBarIconBrightness: - Theme.of(context).accentColorBrightness, - ), - child: Scaffold( - appBar: AppBar( - title: Text(s.play), - leading: CustomBackButton(), - elevation: 0, - backgroundColor: context.primaryColor, - ), - body: SingleChildScrollView( - scrollDirection: Axis.vertical, - child: Column( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Container( - height: 60.0, - padding: EdgeInsets.symmetric(horizontal: 40), - alignment: Alignment.center, - child: Text(s.notificationSetting, - style: context.textTheme.bodyText1 - .copyWith(color: context.accentColor)), - ), - _NotificationLayout(), - Divider( - height: 1, - ), - Padding( - padding: const EdgeInsets.all(10.0), - ), - Container( - height: 30.0, - padding: EdgeInsets.symmetric(horizontal: 70), - alignment: Alignment.centerLeft, - child: Text(s.homeMenuPlaylist, - style: Theme.of(context) - .textTheme - .bodyText1 - .copyWith(color: Theme.of(context).accentColor)), - ), - Selector( - selector: (_, settings) => settings.autoPlay, - builder: (_, data, __) => ListTile( - onTap: () => settings.setAutoPlay = !data, - contentPadding: - EdgeInsets.only(left: 70.0, right: 20, bottom: 10), - title: Text(s.settingsMenuAutoPlay), - subtitle: Text(s.settingsAutoPlayDes), - trailing: Transform.scale( - scale: 0.9, - child: Switch( - value: data, - onChanged: (boo) => settings.setAutoPlay = boo), - ), - ), - ), - FutureBuilder( - initialData: false, - future: _getMarkListenedSkip(), - builder: (context, snapshot) => ListTile( - onTap: () => _saveMarkListenedSkip(!snapshot.data), - contentPadding: - EdgeInsets.only(left: 70.0, right: 20, bottom: 10), - title: Text(s.settingsMarkListenedSkip), - subtitle: Text(s.settingsMarkListenedSkipDes), - trailing: Transform.scale( - scale: 0.9, - child: Switch( - value: snapshot.data, onChanged: _saveMarkListenedSkip), - ), - ), - ), - Divider(height: 1), - Padding( - padding: const EdgeInsets.all(10.0), - ), - Container( - height: 30.0, - padding: EdgeInsets.symmetric(horizontal: 70), - alignment: Alignment.centerLeft, - child: Text(s.playback, - style: context.textTheme.bodyText1 - .copyWith(color: context.accentColor)), - ), - ListTile( - contentPadding: - EdgeInsets.only(left: 70.0, right: 20, bottom: 10, top: 10), - title: Text(s.settingsFastForwardSec), - subtitle: Text(s.settingsFastForwardSecDes), - trailing: Selector( - selector: (_, settings) => settings.fastForwardSeconds, - builder: (_, data, __) => MyDropdownButton( - hint: Text(s.secCount(data)), - underline: Center(), - elevation: 1, - displayItemCount: 5, - isDense: true, - value: data, - onChanged: (value) => - settings.setFastForwardSeconds = value, - items: kSecondsToSelect.map>((e) { - return DropdownMenuItem( - value: e, child: Text(s.secCount(e))); - }).toList()), - ), - ), - ListTile( - contentPadding: - EdgeInsets.only(left: 70.0, right: 20, bottom: 10, top: 10), - title: Text(s.settingsRewindSec), - subtitle: Text(s.settingsRewindSecDes), - trailing: Selector( - selector: (_, settings) => settings.rewindSeconds, - builder: (_, data, __) => MyDropdownButton( - hint: Text(s.secCount(data)), - underline: Center(), - elevation: 1, - displayItemCount: 5, - isDense: true, - value: data, - onChanged: (value) => settings.setRewindSeconds = value, - items: kSecondsToSelect.map>((e) { - return DropdownMenuItem( - value: e, child: Text(s.secCount(e))); - }).toList()), - ), - ), - ListTile( - contentPadding: - EdgeInsets.only(left: 70.0, right: 20, bottom: 10, top: 10), - title: Text(s.settingsBoostVolume), - subtitle: Text(s.settingsBoostVolumeDes), - trailing: Selector( - selector: (_, audio) => audio.volumeGain, - builder: (_, volumeGain, __) => MyDropdownButton( - hint: Text(_volumeEffect(context, volumeGain)), - underline: Center(), - elevation: 1, - displayItemCount: 5, - isDense: true, - value: volumeGain, - onChanged: (value) => audio.setVolumeGain = value, - items: [2000, 3000, 4000].map>((e) { - return DropdownMenuItem( - value: e, child: Text(_volumeEffect(context, e))); - }).toList()), - ), - ), - _SpeedList(), - Divider(height: 1), - Padding( - padding: const EdgeInsets.all(10.0), - ), - Container( - height: 30.0, - padding: EdgeInsets.symmetric(horizontal: 70), - alignment: Alignment.centerLeft, - child: Text(s.sleepTimer, - style: context.textTheme.bodyText1 - .copyWith(color: Theme.of(context).accentColor)), - ), - ListView( - physics: const BouncingScrollPhysics(), - shrinkWrap: true, - scrollDirection: Axis.vertical, - children: [ - ListTile( - contentPadding: EdgeInsets.only(left: 70.0, right: 20), - title: Text(s.settingsSTDefaultTime), - subtitle: Text(s.settingsSTDefautTimeDes), - trailing: Selector( - selector: (_, settings) => settings.defaultSleepTimer, - builder: (_, data, __) => MyDropdownButton( - hint: Text(s.minsCount(data)), - underline: Center(), - elevation: 1, - displayItemCount: 5, - isDense: true, - value: data, - onChanged: (value) => - settings.setDefaultSleepTimer = value, - items: kMinsToSelect.map>((e) { - return DropdownMenuItem( - value: e, child: Text(s.minsCount(e))); - }).toList()), - ), - ), - Selector( - selector: (_, settings) => settings.autoSleepTimer, - builder: (_, data, __) => ListTile( - onTap: () => settings.setAutoSleepTimer = !data, - contentPadding: const EdgeInsets.only( - left: 70.0, right: 20.0, bottom: 10.0, top: 10.0), - title: Text(s.settingsSTAuto), - subtitle: Text(s.settingsSTAutoDes), - trailing: Transform.scale( - scale: 0.9, - child: Switch( - value: data, - onChanged: (boo) => - settings.setAutoSleepTimer = boo), - ), - ), - ), - ListTile( - contentPadding: const EdgeInsets.only( - left: 70.0, right: 20.0, bottom: 10.0, top: 10.0), - title: Text(s.settingsSTMode), - subtitle: - context.width > 360 ? null : _modeWidget(context), - trailing: - context.width > 360 ? _modeWidget(context) : null), - ListTile( - contentPadding: EdgeInsets.only(left: 70.0, right: 20), - title: Text(s.schedule), - subtitle: - context.width > 360 ? null : _scheduleWidget(context), - trailing: context.width > 360 - ? _scheduleWidget(context) - : null), - Divider(height: 1) - ], - ), - SizedBox(height: 20) - ], - ), - ), - ), - ); - } -} - -class _NotificationLayout extends StatefulWidget { - _NotificationLayout({Key key}) : super(key: key); - - @override - __NotificationLayoutState createState() => __NotificationLayoutState(); -} - -class __NotificationLayoutState extends State<_NotificationLayout> { - Future _getNotificationLayout() async { - final storage = KeyValueStorage(notificationLayoutKey); - var index = await storage.getInt(defaultValue: 0); - return index; - } - - Future _setNotificationLayout(int index) async { - final storage = KeyValueStorage(notificationLayoutKey); - await storage.saveInt(index); - if (mounted) setState(() {}); - } - - Widget _notificationIcon(Widget icon, String des) { - return LimitedBox( - maxWidth: 60, - child: Column( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - icon, - SizedBox(height: 8), - Text(des, - style: TextStyle( - fontSize: 12, color: context.textColor.withOpacity(0.5)), - textAlign: TextAlign.center, - maxLines: 2, - overflow: TextOverflow.clip), - ], - ), - ); - } - - Widget _notificationOptions(int index, {int selected}) { - final s = context.s; - return InkWell( - borderRadius: BorderRadius.circular(10.0), - onTap: () => _setNotificationLayout(index), - child: Container( - padding: EdgeInsets.symmetric(vertical: 10), - decoration: BoxDecoration( - border: Border.all( - color: index == selected - ? context.accentColor.withAlpha(70) - : context.primaryColorDark, - ), - borderRadius: BorderRadius.circular(10), - color: index == selected - ? context.accentColor.withAlpha(70) - : Colors.transparent, - ), - child: index == 0 - ? Row( - mainAxisAlignment: MainAxisAlignment.spaceAround, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - _notificationIcon( - Icon(Icons.pause_circle_filled), '${s.play}| ${s.pause}'), - _notificationIcon(Icon(Icons.fast_forward), s.fastForward), - _notificationIcon(Icon(Icons.skip_next), s.skipToNext), - _notificationIcon(Icon(Icons.close), s.stop), - ], - ) - : index == 1 - ? Row( - mainAxisAlignment: MainAxisAlignment.spaceAround, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - _notificationIcon(Icon(Icons.pause_circle_filled), - '${s.play}| ${s.pause}'), - _notificationIcon( - Icon(Icons.fast_rewind), s.fastRewind), - _notificationIcon(Icon(Icons.skip_next), s.skipToNext), - _notificationIcon(Icon(Icons.close), s.stop), - ]) - : Row( - mainAxisAlignment: MainAxisAlignment.spaceAround, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - _notificationIcon(Icon(Icons.fast_rewind), s.fastRewind), - _notificationIcon(Icon(Icons.pause_circle_filled), - '${s.play}| ${s.pause}'), - _notificationIcon( - Icon(Icons.fast_forward), s.fastForward), - _notificationIcon(Icon(Icons.close), s.stop), - ], - ), - ), - ); - } - - @override - Widget build(BuildContext context) { - return Padding( - padding: EdgeInsets.fromLTRB(40, 0, 40, 30), - child: FutureBuilder( - future: _getNotificationLayout(), - initialData: 0, - builder: (context, snapshot) => Column( - children: [ - _notificationOptions(0, selected: snapshot.data), - SizedBox(height: 20), - _notificationOptions(1, selected: snapshot.data), - SizedBox(height: 20), - _notificationOptions(2, selected: snapshot.data), - ], - ), - ), - ); - } -} - -class _SpeedList extends StatefulWidget { - _SpeedList({Key key}) : super(key: key); - - @override - __SpeedListState createState() => __SpeedListState(); -} - -class __SpeedListState extends State<_SpeedList> { - Future> _getSpeedList() async { - var storage = KeyValueStorage('speedListKey'); - return await storage.getSpeedList(); - } - - Future _saveSpeedList(List list) async { - var storage = KeyValueStorage('speedListKey'); - await storage.saveSpeedList(list); - } - - @override - Widget build(BuildContext context) { - final s = context.s; - return ListTile( - contentPadding: - EdgeInsets.only(left: 70.0, right: 20, bottom: 10, top: 10), - title: Text(s.settingsSpeeds), - subtitle: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(s.settingsSpeedsDes), - FutureBuilder>( - future: _getSpeedList(), - initialData: [], - builder: (context, snapshot) { - var speedSelected = snapshot.data; - return Wrap( - children: kSpeedToSelect - .map((e) => Padding( - padding: const EdgeInsets.only(right: 8.0), - child: FilterChip( - key: ValueKey(e.toString()), - label: Text('X ${e.toStringAsFixed(1)}'), - selectedColor: context.accentColor, - labelStyle: TextStyle( - color: snapshot.data.contains(e) - ? Colors.white - : context.textColor), - elevation: 0, - showCheckmark: false, - selected: snapshot.data.contains(e), - onSelected: (value) async { - if (!value) { - speedSelected.remove(e); - } else { - speedSelected.add(e); - } - await _saveSpeedList(speedSelected); - setState(() {}); - }, - ), - )) - .toList()); - }), - ], - ), - ); - } -} +import 'dart:ui'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:provider/provider.dart'; +import 'package:tuple/tuple.dart'; + +import '../home/audioplayer.dart'; +import '../local_storage/key_value_storage.dart'; +import '../state/audio_state.dart'; +import '../state/setting_state.dart'; +import '../util/custom_dropdown.dart'; +import '../util/custom_time_picker.dart'; +import '../util/custom_widget.dart'; +import '../util/extension_helper.dart'; + +const List kSecondsToSelect = [5, 10, 15, 20, 25, 30, 45, 60]; +const List kSpeedToSelect = [ + 0.5, + 0.6, + 0.8, + 0.9, + 1.0, + 1.1, + 1.2, + 1.5, + 2.0, + 2.5, + 3.0, + 3.5, + 4.0, + 4.5, + 5.0 +]; + +class PlaySetting extends StatefulWidget { + @override + _PlaySettingState createState() => _PlaySettingState(); +} + +class _PlaySettingState extends State { + String _volumeEffect(BuildContext context, int i) { + final s = context.s; + if (i == 2000) { + return s.playerHeightShort; + } else if (i == 3000) { + return s.playerHeightMed; + } + return s.playerHeightTall; + } + + Future _getMarkListenedSkip() async { + final storage = KeyValueStorage(markListenedAfterSkipKey); + return storage.getBool(defaultValue: false); + } + + Future _saveMarkListenedSkip(bool boo) async { + final storage = KeyValueStorage(markListenedAfterSkipKey); + await storage.saveBool(boo); + if (mounted) setState(() {}); + } + + Widget _modeWidget(BuildContext context) { + var settings = Provider.of(context, listen: false); + return Selector>( + selector: (_, settings) => + Tuple2(settings.autoSleepTimerMode, settings.defaultSleepTimer), + builder: (_, data, __) => Padding( + padding: const EdgeInsets.symmetric(vertical: 10), + child: Row( + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + InkWell( + onTap: () => settings.setAutoSleepTimerMode = 0, + borderRadius: BorderRadius.only( + bottomLeft: Radius.circular(5), topLeft: Radius.circular(5)), + child: Material( + color: Colors.transparent, + child: AnimatedContainer( + duration: Duration(milliseconds: 400), + decoration: BoxDecoration( + color: data.item1 == 0 + ? context.accentColor + : context.primaryColorDark, + borderRadius: BorderRadius.only( + bottomLeft: Radius.circular(5), + topLeft: Radius.circular(5)), + ), + padding: const EdgeInsets.all(8.0), + child: Text(context.s.endOfEpisode, + style: TextStyle( + color: data.item1 == 0 ? Colors.white : null)), + ), + ), + ), + InkWell( + onTap: () => settings.setAutoSleepTimerMode = 1, + borderRadius: BorderRadius.only( + bottomRight: Radius.circular(5), + topRight: Radius.circular(5)), + child: Material( + color: Colors.transparent, + child: AnimatedContainer( + duration: Duration(milliseconds: 400), + decoration: BoxDecoration( + color: data.item1 == 1 + ? context.accentColor + : context.primaryColorDark, + borderRadius: BorderRadius.only( + bottomRight: Radius.circular(5), + topRight: Radius.circular(5)), + ), + padding: const EdgeInsets.all(8.0), + child: Text(context.s.minsCount(data.item2), + style: TextStyle( + color: data.item1 == 1 ? Colors.white : null)), + ), + ), + ), + ], + ), + ), + ); + } + + Widget _scheduleWidget(BuildContext context) { + var settings = Provider.of(context, listen: false); + final s = context.s; + return Selector>( + selector: (_, settings) => + Tuple2(settings.autoSleepTimerStart, settings.autoSleepTimerEnd), + builder: (_, data, __) => Padding( + padding: const EdgeInsets.symmetric(vertical: 10.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + InkWell( + onTap: () async { + var startTime = data.item1; + final timeOfDay = await showCustomTimePicker( + context: context, + cancelText: s.cancel, + confirmText: s.confirm, + helpText: '', + initialTime: TimeOfDay( + hour: startTime ~/ 60, minute: startTime % 60)); + if (timeOfDay != null) { + startTime = timeOfDay.hour * 60 + timeOfDay.minute; + if (startTime != data.item2) { + settings.setAutoSleepTimerStart = startTime; + } else { + Fluttertoast.showToast( + msg: s.toastTimeEqualEnd, + gravity: ToastGravity.BOTTOM, + ); + } + } + }, + borderRadius: BorderRadius.only( + bottomLeft: Radius.circular(5), topLeft: Radius.circular(5)), + child: Material( + color: Colors.transparent, + child: Container( + decoration: BoxDecoration( + color: context.primaryColorDark, + borderRadius: BorderRadius.only( + bottomLeft: Radius.circular(5), + topLeft: Radius.circular(5)), + ), + padding: const EdgeInsets.all(8.0), + child: Text(s.from(data.item1.toTime)), + ), + ), + ), + InkWell( + onTap: () async { + var endTime = data.item2; + final timeOfDay = await showCustomTimePicker( + context: context, + cancelText: s.cancel, + confirmText: s.confirm, + helpText: '', + initialTime: + TimeOfDay(hour: endTime ~/ 60, minute: endTime % 60)); + if (timeOfDay != null) { + endTime = timeOfDay.hour * 60 + timeOfDay.minute; + if (endTime != data.item1) { + settings.setAutoSleepTimerEnd = endTime; + } else { + Fluttertoast.showToast( + msg: s.toastTimeEqualStart, + gravity: ToastGravity.BOTTOM, + ); + } + } + }, + borderRadius: BorderRadius.only( + bottomRight: Radius.circular(5), + topRight: Radius.circular(5)), + child: Material( + color: Colors.transparent, + child: Container( + padding: const EdgeInsets.all(8.0), + decoration: BoxDecoration( + color: Colors.black54, + borderRadius: BorderRadius.only( + bottomRight: Radius.circular(5), + topRight: Radius.circular(5))), + child: Text(s.to(data.item2.toTime), + style: TextStyle(color: Colors.white)), + ), + ), + ), + ], + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + var settings = context.watch(); + var audio = context.watch(); + final s = context.s; + return AnnotatedRegion( + value: SystemUiOverlayStyle( + statusBarIconBrightness: Theme.of(context).accentColorBrightness, + systemNavigationBarColor: Theme.of(context).primaryColor, + systemNavigationBarIconBrightness: + Theme.of(context).accentColorBrightness, + ), + child: Scaffold( + appBar: AppBar( + title: Text(s.play), + leading: CustomBackButton(), + elevation: 0, + backgroundColor: context.primaryColor, + ), + body: SingleChildScrollView( + scrollDirection: Axis.vertical, + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Container( + height: 60.0, + padding: EdgeInsets.symmetric(horizontal: 40), + alignment: Alignment.center, + child: Text(s.notificationSetting, + style: context.textTheme.bodyText1 + .copyWith(color: context.accentColor)), + ), + _NotificationLayout(), + Divider( + height: 1, + ), + Padding( + padding: const EdgeInsets.all(10.0), + ), + Container( + height: 30.0, + padding: EdgeInsets.symmetric(horizontal: 70), + alignment: Alignment.centerLeft, + child: Text(s.homeMenuPlaylist, + style: Theme.of(context) + .textTheme + .bodyText1 + .copyWith(color: Theme.of(context).accentColor)), + ), + Selector( + selector: (_, settings) => settings.autoPlay, + builder: (_, data, __) => ListTile( + onTap: () => settings.setAutoPlay = !data, + contentPadding: + EdgeInsets.only(left: 70.0, right: 20, bottom: 10), + title: Text(s.settingsMenuAutoPlay), + subtitle: Text(s.settingsAutoPlayDes), + trailing: Transform.scale( + scale: 0.9, + child: Switch( + value: data, + onChanged: (boo) => settings.setAutoPlay = boo), + ), + ), + ), + FutureBuilder( + initialData: false, + future: _getMarkListenedSkip(), + builder: (context, snapshot) => ListTile( + onTap: () => _saveMarkListenedSkip(!snapshot.data), + contentPadding: + EdgeInsets.only(left: 70.0, right: 20, bottom: 10), + title: Text(s.settingsMarkListenedSkip), + subtitle: Text(s.settingsMarkListenedSkipDes), + trailing: Transform.scale( + scale: 0.9, + child: Switch( + value: snapshot.data, onChanged: _saveMarkListenedSkip), + ), + ), + ), + Divider(height: 1), + Padding( + padding: const EdgeInsets.all(10.0), + ), + Container( + height: 30.0, + padding: EdgeInsets.symmetric(horizontal: 70), + alignment: Alignment.centerLeft, + child: Text(s.playback, + style: context.textTheme.bodyText1 + .copyWith(color: context.accentColor)), + ), + ListTile( + contentPadding: + EdgeInsets.only(left: 70.0, right: 20, bottom: 10, top: 10), + title: Text(s.settingsFastForwardSec), + subtitle: Text(s.settingsFastForwardSecDes), + trailing: Selector( + selector: (_, settings) => settings.fastForwardSeconds, + builder: (_, data, __) => MyDropdownButton( + hint: Text(s.secCount(data)), + underline: Center(), + elevation: 1, + displayItemCount: 5, + isDense: true, + value: data, + onChanged: (value) => + settings.setFastForwardSeconds = value, + items: kSecondsToSelect.map>((e) { + return DropdownMenuItem( + value: e, child: Text(s.secCount(e))); + }).toList()), + ), + ), + ListTile( + contentPadding: + EdgeInsets.only(left: 70.0, right: 20, bottom: 10, top: 10), + title: Text(s.settingsRewindSec), + subtitle: Text(s.settingsRewindSecDes), + trailing: Selector( + selector: (_, settings) => settings.rewindSeconds, + builder: (_, data, __) => MyDropdownButton( + hint: Text(s.secCount(data)), + underline: Center(), + elevation: 1, + displayItemCount: 5, + isDense: true, + value: data, + onChanged: (value) => settings.setRewindSeconds = value, + items: kSecondsToSelect.map>((e) { + return DropdownMenuItem( + value: e, child: Text(s.secCount(e))); + }).toList()), + ), + ), + ListTile( + contentPadding: + EdgeInsets.only(left: 70.0, right: 20, bottom: 10, top: 10), + title: Text(s.settingsBoostVolume), + subtitle: Text(s.settingsBoostVolumeDes), + trailing: Selector( + selector: (_, audio) => audio.volumeGain, + builder: (_, volumeGain, __) => MyDropdownButton( + hint: Text(_volumeEffect(context, volumeGain)), + underline: Center(), + elevation: 1, + displayItemCount: 5, + isDense: true, + value: volumeGain, + onChanged: (value) => audio.setVolumeGain = value, + items: [2000, 3000, 4000].map>((e) { + return DropdownMenuItem( + value: e, child: Text(_volumeEffect(context, e))); + }).toList()), + ), + ), + _SpeedList(), + Divider(height: 1), + Padding( + padding: const EdgeInsets.all(10.0), + ), + Container( + height: 30.0, + padding: EdgeInsets.symmetric(horizontal: 70), + alignment: Alignment.centerLeft, + child: Text(s.sleepTimer, + style: context.textTheme.bodyText1 + .copyWith(color: Theme.of(context).accentColor)), + ), + ListView( + physics: const BouncingScrollPhysics(), + shrinkWrap: true, + scrollDirection: Axis.vertical, + children: [ + ListTile( + contentPadding: EdgeInsets.only(left: 70.0, right: 20), + title: Text(s.settingsSTDefaultTime), + subtitle: Text(s.settingsSTDefautTimeDes), + trailing: Selector( + selector: (_, settings) => settings.defaultSleepTimer, + builder: (_, data, __) => MyDropdownButton( + hint: Text(s.minsCount(data)), + underline: Center(), + elevation: 1, + displayItemCount: 5, + isDense: true, + value: data, + onChanged: (value) => + settings.setDefaultSleepTimer = value, + items: kMinsToSelect.map>((e) { + return DropdownMenuItem( + value: e, child: Text(s.minsCount(e))); + }).toList()), + ), + ), + Selector( + selector: (_, settings) => settings.autoSleepTimer, + builder: (_, data, __) => ListTile( + onTap: () => settings.setAutoSleepTimer = !data, + contentPadding: const EdgeInsets.only( + left: 70.0, right: 20.0, bottom: 10.0, top: 10.0), + title: Text(s.settingsSTAuto), + subtitle: Text(s.settingsSTAutoDes), + trailing: Transform.scale( + scale: 0.9, + child: Switch( + value: data, + onChanged: (boo) => + settings.setAutoSleepTimer = boo), + ), + ), + ), + ListTile( + contentPadding: const EdgeInsets.only( + left: 70.0, right: 20.0, bottom: 10.0, top: 10.0), + title: Text(s.settingsSTMode), + subtitle: + context.width > 360 ? null : _modeWidget(context), + trailing: + context.width > 360 ? _modeWidget(context) : null), + ListTile( + contentPadding: EdgeInsets.only(left: 70.0, right: 20), + title: Text(s.schedule), + subtitle: + context.width > 360 ? null : _scheduleWidget(context), + trailing: context.width > 360 + ? _scheduleWidget(context) + : null), + Divider(height: 1) + ], + ), + SizedBox(height: 20) + ], + ), + ), + ), + ); + } +} + +class _NotificationLayout extends StatefulWidget { + _NotificationLayout({Key key}) : super(key: key); + + @override + __NotificationLayoutState createState() => __NotificationLayoutState(); +} + +class __NotificationLayoutState extends State<_NotificationLayout> { + Future _getNotificationLayout() async { + final storage = KeyValueStorage(notificationLayoutKey); + var index = await storage.getInt(defaultValue: 0); + return index; + } + + Future _setNotificationLayout(int index) async { + final storage = KeyValueStorage(notificationLayoutKey); + await storage.saveInt(index); + if (mounted) setState(() {}); + } + + Widget _notificationIcon(Widget icon, String des) { + return LimitedBox( + maxWidth: 60, + child: Column( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + icon, + SizedBox(height: 8), + Text(des, + style: TextStyle( + fontSize: 12, color: context.textColor.withOpacity(0.5)), + textAlign: TextAlign.center, + maxLines: 2, + overflow: TextOverflow.clip), + ], + ), + ); + } + + Widget _notificationOptions(int index, {int selected}) { + final s = context.s; + return InkWell( + borderRadius: BorderRadius.circular(10.0), + onTap: () => _setNotificationLayout(index), + child: Container( + padding: EdgeInsets.symmetric(vertical: 10), + decoration: BoxDecoration( + border: Border.all( + color: index == selected + ? context.accentColor.withAlpha(70) + : context.primaryColorDark, + ), + borderRadius: BorderRadius.circular(10), + color: index == selected + ? context.accentColor.withAlpha(70) + : Colors.transparent, + ), + child: index == 0 + ? Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _notificationIcon( + Icon(Icons.pause_circle_filled), '${s.play}| ${s.pause}'), + _notificationIcon(Icon(Icons.fast_forward), s.fastForward), + _notificationIcon(Icon(Icons.skip_next), s.skipToNext), + _notificationIcon(Icon(Icons.close), s.stop), + ], + ) + : index == 1 + ? Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _notificationIcon(Icon(Icons.pause_circle_filled), + '${s.play}| ${s.pause}'), + _notificationIcon( + Icon(Icons.fast_rewind), s.fastRewind), + _notificationIcon(Icon(Icons.skip_next), s.skipToNext), + _notificationIcon(Icon(Icons.close), s.stop), + ]) + : Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _notificationIcon(Icon(Icons.fast_rewind), s.fastRewind), + _notificationIcon(Icon(Icons.pause_circle_filled), + '${s.play}| ${s.pause}'), + _notificationIcon( + Icon(Icons.fast_forward), s.fastForward), + _notificationIcon(Icon(Icons.close), s.stop), + ], + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + return Padding( + padding: EdgeInsets.fromLTRB(40, 0, 40, 30), + child: FutureBuilder( + future: _getNotificationLayout(), + initialData: 0, + builder: (context, snapshot) => Column( + children: [ + _notificationOptions(0, selected: snapshot.data), + SizedBox(height: 20), + _notificationOptions(1, selected: snapshot.data), + SizedBox(height: 20), + _notificationOptions(2, selected: snapshot.data), + ], + ), + ), + ); + } +} + +class _SpeedList extends StatefulWidget { + _SpeedList({Key key}) : super(key: key); + + @override + __SpeedListState createState() => __SpeedListState(); +} + +class __SpeedListState extends State<_SpeedList> { + Future> _getSpeedList() async { + var storage = KeyValueStorage('speedListKey'); + return await storage.getSpeedList(); + } + + Future _saveSpeedList(List list) async { + var storage = KeyValueStorage('speedListKey'); + await storage.saveSpeedList(list); + } + + @override + Widget build(BuildContext context) { + final s = context.s; + return ListTile( + contentPadding: + EdgeInsets.only(left: 70.0, right: 20, bottom: 10, top: 10), + title: Text(s.settingsSpeeds), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(s.settingsSpeedsDes), + FutureBuilder>( + future: _getSpeedList(), + initialData: [], + builder: (context, snapshot) { + var speedSelected = snapshot.data; + return Wrap( + children: kSpeedToSelect + .map((e) => Padding( + padding: const EdgeInsets.only(right: 8.0), + child: FilterChip( + key: ValueKey(e.toString()), + label: Text('X ${e.toStringAsFixed(1)}'), + selectedColor: context.accentColor, + labelStyle: TextStyle( + color: snapshot.data.contains(e) + ? Colors.white + : context.textColor), + elevation: 0, + showCheckmark: false, + selected: snapshot.data.contains(e), + onSelected: (value) async { + if (!value) { + speedSelected.remove(e); + } else { + speedSelected.add(e); + } + await _saveSpeedList(speedSelected); + setState(() {}); + }, + ), + )) + .toList()); + }), + ], + ), + ); + } +} diff --git a/lib/settings/popup_menu.dart b/lib/settings/popup_menu.dart index 1a8e608..28f2410 100644 --- a/lib/settings/popup_menu.dart +++ b/lib/settings/popup_menu.dart @@ -1,222 +1,222 @@ -import 'package:flare_flutter/flare_actor.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:line_icons/line_icons.dart'; - -import '../local_storage/key_value_storage.dart'; -import '../util/custom_widget.dart'; -import '../util/extension_helper.dart'; - -class PopupMenuSetting extends StatefulWidget { - const PopupMenuSetting({Key key}) : super(key: key); - - @override - _PopupMenuSettingState createState() => _PopupMenuSettingState(); -} - -class _PopupMenuSettingState extends State { - Future> _getEpisodeMenu() async { - var popupMenuStorage = KeyValueStorage(episodePopupMenuKey); - var list = await popupMenuStorage.getMenu(); - return list; - } - - Future _getTapToOpenPopupMenu() async { - var tapToOpenPopupMenuStorage = KeyValueStorage(tapToOpenPopupMenuKey); - var boo = await tapToOpenPopupMenuStorage.getBool(defaultValue: false); - return boo; - } - - _saveEpisodeMene(List list) async { - var popupMenuStorage = KeyValueStorage(episodePopupMenuKey); - await popupMenuStorage.saveMenu(list); - if (mounted) setState(() {}); - } - - _saveTapToOpenPopupMenu(bool boo) async { - var tapToOpenPopupMenuStorage = KeyValueStorage(tapToOpenPopupMenuKey); - await tapToOpenPopupMenuStorage.saveBool(boo); - if (mounted) setState(() {}); - } - - Widget _popupMenuItem(List menu, int e, - {Widget icon, - String text, - String description = '', - bool enable = false}) { - return Padding( - key: ObjectKey(text), - padding: EdgeInsets.only(left: 60.0, right: 20), - child: ListTile( - leading: icon, - title: Text(text), - subtitle: Text(description), - onTap: e == 0 - ? null - : () { - if (e >= 10) { - var index = menu.indexOf(e); - menu.remove(e); - menu.insert(index, e - 10); - _saveEpisodeMene(menu); - } else if (e < 10) { - var index = menu.indexOf(e); - menu.remove(e); - menu.insert(index, e + 10); - _saveEpisodeMene(menu); - } - }, - trailing: Checkbox( - value: e < 10, - onChanged: e == 0 - ? null - : (boo) { - if (boo && e >= 10) { - var index = menu.indexOf(e); - menu.remove(e); - menu.insert(index, e - 10); - _saveEpisodeMene(menu); - } else if (e < 10) { - var index = menu.indexOf(e); - menu.remove(e); - menu.insert(index, e + 10); - _saveEpisodeMene(menu); - } - })), - ); - } - - @override - Widget build(BuildContext context) { - final s = context.s; - return AnnotatedRegion( - value: SystemUiOverlayStyle( - statusBarIconBrightness: Theme.of(context).accentColorBrightness, - systemNavigationBarColor: context.primaryColor, - systemNavigationBarIconBrightness: - Theme.of(context).accentColorBrightness, - ), - child: Scaffold( - appBar: AppBar( - elevation: 0, - leading: CustomBackButton(), - backgroundColor: context.primaryColor, - ), - body: Column( - mainAxisAlignment: MainAxisAlignment.start, - children: [ - Container( - color: context.primaryColor, - height: 200, - // color: Colors.red, - child: FlareActor( - 'assets/longtap.flr', - alignment: Alignment.center, - animation: 'longtap', - fit: BoxFit.cover, - )), - FutureBuilder>( - future: _getEpisodeMenu(), - initialData: [0, 1, 12, 13, 14], - builder: (context, snapshot) { - var menu = snapshot.data; - return Expanded( - child: ListView( - shrinkWrap: true, - children: [ - Padding( - padding: EdgeInsets.symmetric(vertical: 10), - ), - Container( - height: 30.0, - padding: EdgeInsets.symmetric(horizontal: 80), - alignment: Alignment.centerLeft, - child: Text(s.settingsPopupMenu, - style: Theme.of(context) - .textTheme - .bodyText1 - .copyWith( - color: Theme.of(context).accentColor)), - ), - FutureBuilder( - future: _getTapToOpenPopupMenu(), - initialData: false, - builder: (context, snapshot) => ListTile( - contentPadding: EdgeInsets.only( - left: 80, top: 10, bottom: 10, right: 30), - onTap: () => - _saveTapToOpenPopupMenu(!snapshot.data), - title: Text(s.settingsTapToOpenPopupMenu), - subtitle: Text(s.settingsTapToOpenPopupMenuDes), - trailing: Transform.scale( - scale: 0.9, - child: Switch( - value: snapshot.data, - onChanged: _saveTapToOpenPopupMenu), - ), - ), - ), - ...menu.map((e) { - var i = e % 10; - switch (i) { - case 0: - return _popupMenuItem(menu, e, - icon: Icon( - LineIcons.play_circle_solid, - color: context.accentColor, - ), - text: s.play, - description: s.popupMenuPlayDes); - break; - case 1: - return _popupMenuItem(menu, e, - icon: Icon( - LineIcons.clock_solid, - color: Colors.cyan, - ), - text: s.later, - description: s.popupMenuLaterDes); - break; - case 2: - return _popupMenuItem(menu, e, - icon: Icon(LineIcons.heart, - color: Colors.red, size: 21), - text: s.like, - description: s.popupMenuLikeDes); - break; - case 3: - return _popupMenuItem(menu, e, - icon: SizedBox( - width: 23, - height: 23, - child: CustomPaint( - painter: ListenedAllPainter( - Colors.blue, - stroke: 1.5)), - ), - text: s.markListened, - description: s.popupMenuMarkDes); - break; - case 4: - return _popupMenuItem(menu, e, - icon: Icon( - LineIcons.download_solid, - color: Colors.green, - ), - text: s.download, - description: s.popupMenuDownloadDes); - break; - default: - return Text('Text'); - break; - } - }).toList(), - ], - ), - ); - }), - ], - )), - ); - } -} +import 'package:flare_flutter/flare_actor.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:line_icons/line_icons.dart'; + +import '../local_storage/key_value_storage.dart'; +import '../util/custom_widget.dart'; +import '../util/extension_helper.dart'; + +class PopupMenuSetting extends StatefulWidget { + const PopupMenuSetting({Key key}) : super(key: key); + + @override + _PopupMenuSettingState createState() => _PopupMenuSettingState(); +} + +class _PopupMenuSettingState extends State { + Future> _getEpisodeMenu() async { + var popupMenuStorage = KeyValueStorage(episodePopupMenuKey); + var list = await popupMenuStorage.getMenu(); + return list; + } + + Future _getTapToOpenPopupMenu() async { + var tapToOpenPopupMenuStorage = KeyValueStorage(tapToOpenPopupMenuKey); + var boo = await tapToOpenPopupMenuStorage.getBool(defaultValue: false); + return boo; + } + + _saveEpisodeMene(List list) async { + var popupMenuStorage = KeyValueStorage(episodePopupMenuKey); + await popupMenuStorage.saveMenu(list); + if (mounted) setState(() {}); + } + + _saveTapToOpenPopupMenu(bool boo) async { + var tapToOpenPopupMenuStorage = KeyValueStorage(tapToOpenPopupMenuKey); + await tapToOpenPopupMenuStorage.saveBool(boo); + if (mounted) setState(() {}); + } + + Widget _popupMenuItem(List menu, int e, + {Widget icon, + String text, + String description = '', + bool enable = false}) { + return Padding( + key: ObjectKey(text), + padding: EdgeInsets.only(left: 60.0, right: 20), + child: ListTile( + leading: icon, + title: Text(text), + subtitle: Text(description), + onTap: e == 0 + ? null + : () { + if (e >= 10) { + var index = menu.indexOf(e); + menu.remove(e); + menu.insert(index, e - 10); + _saveEpisodeMene(menu); + } else if (e < 10) { + var index = menu.indexOf(e); + menu.remove(e); + menu.insert(index, e + 10); + _saveEpisodeMene(menu); + } + }, + trailing: Checkbox( + value: e < 10, + onChanged: e == 0 + ? null + : (boo) { + if (boo && e >= 10) { + var index = menu.indexOf(e); + menu.remove(e); + menu.insert(index, e - 10); + _saveEpisodeMene(menu); + } else if (e < 10) { + var index = menu.indexOf(e); + menu.remove(e); + menu.insert(index, e + 10); + _saveEpisodeMene(menu); + } + })), + ); + } + + @override + Widget build(BuildContext context) { + final s = context.s; + return AnnotatedRegion( + value: SystemUiOverlayStyle( + statusBarIconBrightness: Theme.of(context).accentColorBrightness, + systemNavigationBarColor: context.primaryColor, + systemNavigationBarIconBrightness: + Theme.of(context).accentColorBrightness, + ), + child: Scaffold( + appBar: AppBar( + elevation: 0, + leading: CustomBackButton(), + backgroundColor: context.primaryColor, + ), + body: Column( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + Container( + color: context.primaryColor, + height: 200, + // color: Colors.red, + child: FlareActor( + 'assets/longtap.flr', + alignment: Alignment.center, + animation: 'longtap', + fit: BoxFit.cover, + )), + FutureBuilder>( + future: _getEpisodeMenu(), + initialData: [0, 1, 12, 13, 14], + builder: (context, snapshot) { + var menu = snapshot.data; + return Expanded( + child: ListView( + shrinkWrap: true, + children: [ + Padding( + padding: EdgeInsets.symmetric(vertical: 10), + ), + Container( + height: 30.0, + padding: EdgeInsets.symmetric(horizontal: 80), + alignment: Alignment.centerLeft, + child: Text(s.settingsPopupMenu, + style: Theme.of(context) + .textTheme + .bodyText1 + .copyWith( + color: Theme.of(context).accentColor)), + ), + FutureBuilder( + future: _getTapToOpenPopupMenu(), + initialData: false, + builder: (context, snapshot) => ListTile( + contentPadding: EdgeInsets.only( + left: 80, top: 10, bottom: 10, right: 30), + onTap: () => + _saveTapToOpenPopupMenu(!snapshot.data), + title: Text(s.settingsTapToOpenPopupMenu), + subtitle: Text(s.settingsTapToOpenPopupMenuDes), + trailing: Transform.scale( + scale: 0.9, + child: Switch( + value: snapshot.data, + onChanged: _saveTapToOpenPopupMenu), + ), + ), + ), + ...menu.map((e) { + var i = e % 10; + switch (i) { + case 0: + return _popupMenuItem(menu, e, + icon: Icon( + LineIcons.play_circle_solid, + color: context.accentColor, + ), + text: s.play, + description: s.popupMenuPlayDes); + break; + case 1: + return _popupMenuItem(menu, e, + icon: Icon( + LineIcons.clock_solid, + color: Colors.cyan, + ), + text: s.later, + description: s.popupMenuLaterDes); + break; + case 2: + return _popupMenuItem(menu, e, + icon: Icon(LineIcons.heart, + color: Colors.red, size: 21), + text: s.like, + description: s.popupMenuLikeDes); + break; + case 3: + return _popupMenuItem(menu, e, + icon: SizedBox( + width: 23, + height: 23, + child: CustomPaint( + painter: ListenedAllPainter( + Colors.blue, + stroke: 1.5)), + ), + text: s.markListened, + description: s.popupMenuMarkDes); + break; + case 4: + return _popupMenuItem(menu, e, + icon: Icon( + LineIcons.download_solid, + color: Colors.green, + ), + text: s.download, + description: s.popupMenuDownloadDes); + break; + default: + return Text('Text'); + break; + } + }).toList(), + ], + ), + ); + }), + ], + )), + ); + } +} diff --git a/lib/settings/settting.dart b/lib/settings/settting.dart index 39dae19..42de7f5 100644 --- a/lib/settings/settting.dart +++ b/lib/settings/settting.dart @@ -1,265 +1,265 @@ -import 'package:feature_discovery/feature_discovery.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:fluttertoast/fluttertoast.dart'; -import 'package:line_icons/line_icons.dart'; - -import '../home/home.dart'; -import '../intro_slider/app_intro.dart'; -import '../podcasts/podcast_manage.dart'; -import '../util/custom_widget.dart'; -import '../util/extension_helper.dart'; -import '../util/general_dialog.dart'; -import 'data_backup.dart'; -import 'history.dart'; -import 'languages.dart'; -import 'layouts.dart'; -import 'libries.dart'; -import 'play_setting.dart'; -import 'storage.dart'; -import 'syncing.dart'; -import 'theme.dart'; - -class Settings extends StatefulWidget { - @override - _SettingsState createState() => _SettingsState(); -} - -class _SettingsState extends State { - Widget _feedbackItem(IconData icon, String name, String url) => ListTile( - onTap: () { - url.launchUrl; - Navigator.pop(context); - }, - leading: Icon( - icon, - size: 20, - ), - title: Text( - name, - maxLines: 2, - ), - ); - - @override - Widget build(BuildContext context) { - final s = context.s; - return AnnotatedRegion( - value: SystemUiOverlayStyle( - statusBarIconBrightness: Theme.of(context).accentColorBrightness, - systemNavigationBarColor: Theme.of(context).primaryColor, - systemNavigationBarIconBrightness: - Theme.of(context).accentColorBrightness, - ), - child: Scaffold( - appBar: AppBar( - title: Text(s.settings), - leading: CustomBackButton(), - elevation: 0, - backgroundColor: context.primaryColor, - ), - body: SafeArea( - child: SingleChildScrollView( - scrollDirection: Axis.vertical, - child: Column( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Padding( - padding: EdgeInsets.all(10.0), - ), - Container( - height: 30.0, - padding: EdgeInsets.symmetric(horizontal: 70), - alignment: Alignment.centerLeft, - child: Text(s.settingsPrefrence, - style: context.textTheme.bodyText1 - .copyWith(color: context.accentColor)), - ), - ListTile( - onTap: () => Navigator.push(context, - MaterialPageRoute(builder: (context) => ThemeSetting())), - contentPadding: EdgeInsets.symmetric(horizontal: 25.0), - leading: - Icon(LineIcons.adjust_solid, color: context.accentColor), - title: Text(s.settingsAppearance), - subtitle: Text(s.settingsAppearanceDes), - ), - Divider(height: 1), - ListTile( - onTap: () => Navigator.push(context, - MaterialPageRoute(builder: (context) => LayoutSetting())), - contentPadding: EdgeInsets.symmetric(horizontal: 25.0), - leading: Icon(LineIcons.stop_circle_solid, - color: Colors.blueAccent), - title: Text(s.settingsLayout), - subtitle: Text(s.settingsLayoutDes), - ), - Divider(height: 1), - ListTile( - onTap: () => Navigator.push(context, - MaterialPageRoute(builder: (context) => PlaySetting())), - contentPadding: EdgeInsets.symmetric(horizontal: 25.0), - leading: Icon(LineIcons.play_circle, color: Colors.redAccent), - title: Text(s.play), - subtitle: Text(s.settingsPlayDes), - ), - Divider(height: 1), - ListTile( - onTap: () => Navigator.push( - context, - MaterialPageRoute( - builder: (context) => SyncingSetting())), - contentPadding: EdgeInsets.symmetric(horizontal: 25.0), - leading: Icon(LineIcons.cloud_download_alt_solid, - color: Colors.yellow[700]), - title: Text(s.settingsSyncing), - subtitle: Text(s.settingsSyncingDes)), - Divider(height: 1), - ListTile( - onTap: () => Navigator.push( - context, - MaterialPageRoute( - builder: (context) => StorageSetting())), - contentPadding: EdgeInsets.symmetric(horizontal: 25.0), - leading: Icon(LineIcons.save, color: Colors.green[700]), - title: Text(s.settingStorage), - subtitle: Text(s.settingsStorageDes), - ), - Divider(height: 1), - ListTile( - onTap: () => Navigator.push(context, - MaterialPageRoute(builder: (context) => PlayedHistory())), - contentPadding: EdgeInsets.symmetric(horizontal: 25.0), - leading: Icon(Icons.update, color: Colors.indigo[700]), - title: Text(s.settingsHistory), - subtitle: Text(s.settingsHistoryDes), - ), - Divider(height: 1), - ListTile( - onTap: () => generalSheet(context, - title: s.settingsLanguages, child: LanguagesSetting()) - .then((value) => setState(() {})), - contentPadding: EdgeInsets.symmetric(horizontal: 25.0), - leading: Icon(LineIcons.language_solid, - color: Colors.purpleAccent), - title: Text(s.settingsLanguages), - subtitle: Text(s.settingsLanguagesDes), - ), - Divider(height: 1), - ListTile( - onTap: () { - //_exportOmpl(context); - Navigator.push(context, - MaterialPageRoute(builder: (context) => DataBackup())); - }, - contentPadding: EdgeInsets.symmetric(horizontal: 25.0), - leading: Icon(LineIcons.file_code_solid, - color: Colors.lightGreen[700]), - title: Text(s.settingsBackup), - subtitle: Text(s.settingsBackupDes), - ), - Divider(height: 1), - Padding( - padding: EdgeInsets.all(10.0), - ), - Container( - height: 30.0, - padding: EdgeInsets.symmetric(horizontal: 70), - alignment: Alignment.centerLeft, - child: Text(s.settingsInfo, - style: Theme.of(context) - .textTheme - .bodyText1 - .copyWith(color: Theme.of(context).accentColor)), - ), - ListTile( - onTap: () => Navigator.push(context, - MaterialPageRoute(builder: (context) => Libries())), - contentPadding: EdgeInsets.symmetric(horizontal: 25.0), - leading: Icon(LineIcons.book_open_solid, - color: Colors.purple[700]), - title: Text(s.settingsLibraries), - subtitle: Text(s.settingsLibrariesDes), - ), - Divider(height: 1), - ListTile( - onTap: () => generalSheet( - context, - title: s.settingsFeedback, - child: Column( - mainAxisSize: MainAxisSize.min, - mainAxisAlignment: MainAxisAlignment.start, - children: [ - _feedbackItem(LineIcons.github, s.feedbackGithub, - 'https://github.com/stonega/tsacdop/issues'), - Divider(height: 1), - _feedbackItem(LineIcons.telegram, s.feedbackTelegram, - 'https://t.me/joinchat/Bk3LkRpTHy40QYC78PK7Qg'), - Divider(height: 1), - _feedbackItem( - LineIcons.envelope_open_text_solid, - s.feedbackEmail, - 'mailto:?subject=Tsacdop Feedback'), - Divider(height: 1), - _feedbackItem(LineIcons.google_play, s.feedbackPlay, - 'https://play.google.com/store/apps/details?id=com.stonegate.tsacdop'), - Divider(height: 1), - ], - ), - ), - contentPadding: EdgeInsets.symmetric(horizontal: 25.0), - leading: Icon(LineIcons.bug_solid, color: Colors.pink[700]), - title: Text(s.settingsFeedback), - subtitle: Text(s.settingsFeedbackDes), - ), - Divider( - height: 2, - ), - ListTile( - onTap: () { - FeatureDiscovery.clearPreferences(context, const { - addFeature, - menuFeature, - playlistFeature, - groupsFeature, - addGroupFeature, - configureGroup, - configurePodcast, - podcastFeature - }); - Fluttertoast.showToast( - msg: s.toastDiscovery, - gravity: ToastGravity.BOTTOM, - ); - }, - contentPadding: EdgeInsets.symmetric(horizontal: 25.0), - leading: - Icon(LineIcons.capsules_solid, color: Colors.pinkAccent), - title: Text(s.settingsDiscovery), - ), - Divider(height: 1), - ListTile( - onTap: () => Navigator.push( - context, - MaterialPageRoute( - builder: (context) => - SlideIntro(goto: Goto.settings))), - contentPadding: EdgeInsets.symmetric(horizontal: 25.0), - leading: - Icon(LineIcons.columns_solid, color: Colors.blueGrey), - title: Text(s.settingsAppIntro), - ), - Divider(height: 1), - Padding( - padding: EdgeInsets.all(10.0), - ), - ], - ), - ), - ), - ), - ); - } -} +import 'package:feature_discovery/feature_discovery.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:line_icons/line_icons.dart'; + +import '../home/home.dart'; +import '../intro_slider/app_intro.dart'; +import '../podcasts/podcast_manage.dart'; +import '../util/custom_widget.dart'; +import '../util/extension_helper.dart'; +import '../util/general_dialog.dart'; +import 'data_backup.dart'; +import 'history.dart'; +import 'languages.dart'; +import 'layouts.dart'; +import 'libries.dart'; +import 'play_setting.dart'; +import 'storage.dart'; +import 'syncing.dart'; +import 'theme.dart'; + +class Settings extends StatefulWidget { + @override + _SettingsState createState() => _SettingsState(); +} + +class _SettingsState extends State { + Widget _feedbackItem(IconData icon, String name, String url) => ListTile( + onTap: () { + url.launchUrl; + Navigator.pop(context); + }, + leading: Icon( + icon, + size: 20, + ), + title: Text( + name, + maxLines: 2, + ), + ); + + @override + Widget build(BuildContext context) { + final s = context.s; + return AnnotatedRegion( + value: SystemUiOverlayStyle( + statusBarIconBrightness: Theme.of(context).accentColorBrightness, + systemNavigationBarColor: Theme.of(context).primaryColor, + systemNavigationBarIconBrightness: + Theme.of(context).accentColorBrightness, + ), + child: Scaffold( + appBar: AppBar( + title: Text(s.settings), + leading: CustomBackButton(), + elevation: 0, + backgroundColor: context.primaryColor, + ), + body: SafeArea( + child: SingleChildScrollView( + scrollDirection: Axis.vertical, + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: EdgeInsets.all(10.0), + ), + Container( + height: 30.0, + padding: EdgeInsets.symmetric(horizontal: 70), + alignment: Alignment.centerLeft, + child: Text(s.settingsPrefrence, + style: context.textTheme.bodyText1 + .copyWith(color: context.accentColor)), + ), + ListTile( + onTap: () => Navigator.push(context, + MaterialPageRoute(builder: (context) => ThemeSetting())), + contentPadding: EdgeInsets.symmetric(horizontal: 25.0), + leading: + Icon(LineIcons.adjust_solid, color: context.accentColor), + title: Text(s.settingsAppearance), + subtitle: Text(s.settingsAppearanceDes), + ), + Divider(height: 1), + ListTile( + onTap: () => Navigator.push(context, + MaterialPageRoute(builder: (context) => LayoutSetting())), + contentPadding: EdgeInsets.symmetric(horizontal: 25.0), + leading: Icon(LineIcons.stop_circle_solid, + color: Colors.blueAccent), + title: Text(s.settingsLayout), + subtitle: Text(s.settingsLayoutDes), + ), + Divider(height: 1), + ListTile( + onTap: () => Navigator.push(context, + MaterialPageRoute(builder: (context) => PlaySetting())), + contentPadding: EdgeInsets.symmetric(horizontal: 25.0), + leading: Icon(LineIcons.play_circle, color: Colors.redAccent), + title: Text(s.play), + subtitle: Text(s.settingsPlayDes), + ), + Divider(height: 1), + ListTile( + onTap: () => Navigator.push( + context, + MaterialPageRoute( + builder: (context) => SyncingSetting())), + contentPadding: EdgeInsets.symmetric(horizontal: 25.0), + leading: Icon(LineIcons.cloud_download_alt_solid, + color: Colors.yellow[700]), + title: Text(s.settingsSyncing), + subtitle: Text(s.settingsSyncingDes)), + Divider(height: 1), + ListTile( + onTap: () => Navigator.push( + context, + MaterialPageRoute( + builder: (context) => StorageSetting())), + contentPadding: EdgeInsets.symmetric(horizontal: 25.0), + leading: Icon(LineIcons.save, color: Colors.green[700]), + title: Text(s.settingStorage), + subtitle: Text(s.settingsStorageDes), + ), + Divider(height: 1), + ListTile( + onTap: () => Navigator.push(context, + MaterialPageRoute(builder: (context) => PlayedHistory())), + contentPadding: EdgeInsets.symmetric(horizontal: 25.0), + leading: Icon(Icons.update, color: Colors.indigo[700]), + title: Text(s.settingsHistory), + subtitle: Text(s.settingsHistoryDes), + ), + Divider(height: 1), + ListTile( + onTap: () => generalSheet(context, + title: s.settingsLanguages, child: LanguagesSetting()) + .then((value) => setState(() {})), + contentPadding: EdgeInsets.symmetric(horizontal: 25.0), + leading: Icon(LineIcons.language_solid, + color: Colors.purpleAccent), + title: Text(s.settingsLanguages), + subtitle: Text(s.settingsLanguagesDes), + ), + Divider(height: 1), + ListTile( + onTap: () { + //_exportOmpl(context); + Navigator.push(context, + MaterialPageRoute(builder: (context) => DataBackup())); + }, + contentPadding: EdgeInsets.symmetric(horizontal: 25.0), + leading: Icon(LineIcons.file_code_solid, + color: Colors.lightGreen[700]), + title: Text(s.settingsBackup), + subtitle: Text(s.settingsBackupDes), + ), + Divider(height: 1), + Padding( + padding: EdgeInsets.all(10.0), + ), + Container( + height: 30.0, + padding: EdgeInsets.symmetric(horizontal: 70), + alignment: Alignment.centerLeft, + child: Text(s.settingsInfo, + style: Theme.of(context) + .textTheme + .bodyText1 + .copyWith(color: Theme.of(context).accentColor)), + ), + ListTile( + onTap: () => Navigator.push(context, + MaterialPageRoute(builder: (context) => Libries())), + contentPadding: EdgeInsets.symmetric(horizontal: 25.0), + leading: Icon(LineIcons.book_open_solid, + color: Colors.purple[700]), + title: Text(s.settingsLibraries), + subtitle: Text(s.settingsLibrariesDes), + ), + Divider(height: 1), + ListTile( + onTap: () => generalSheet( + context, + title: s.settingsFeedback, + child: Column( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.start, + children: [ + _feedbackItem(LineIcons.github, s.feedbackGithub, + 'https://github.com/stonega/tsacdop/issues'), + Divider(height: 1), + _feedbackItem(LineIcons.telegram, s.feedbackTelegram, + 'https://t.me/joinchat/Bk3LkRpTHy40QYC78PK7Qg'), + Divider(height: 1), + _feedbackItem( + LineIcons.envelope_open_text_solid, + s.feedbackEmail, + 'mailto:?subject=Tsacdop Feedback'), + Divider(height: 1), + _feedbackItem(LineIcons.google_play, s.feedbackPlay, + 'https://play.google.com/store/apps/details?id=com.stonegate.tsacdop'), + Divider(height: 1), + ], + ), + ), + contentPadding: EdgeInsets.symmetric(horizontal: 25.0), + leading: Icon(LineIcons.bug_solid, color: Colors.pink[700]), + title: Text(s.settingsFeedback), + subtitle: Text(s.settingsFeedbackDes), + ), + Divider( + height: 2, + ), + ListTile( + onTap: () { + FeatureDiscovery.clearPreferences(context, const { + addFeature, + menuFeature, + playlistFeature, + groupsFeature, + addGroupFeature, + configureGroup, + configurePodcast, + podcastFeature + }); + Fluttertoast.showToast( + msg: s.toastDiscovery, + gravity: ToastGravity.BOTTOM, + ); + }, + contentPadding: EdgeInsets.symmetric(horizontal: 25.0), + leading: + Icon(LineIcons.capsules_solid, color: Colors.pinkAccent), + title: Text(s.settingsDiscovery), + ), + Divider(height: 1), + ListTile( + onTap: () => Navigator.push( + context, + MaterialPageRoute( + builder: (context) => + SlideIntro(goto: Goto.settings))), + contentPadding: EdgeInsets.symmetric(horizontal: 25.0), + leading: + Icon(LineIcons.columns_solid, color: Colors.blueGrey), + title: Text(s.settingsAppIntro), + ), + Divider(height: 1), + Padding( + padding: EdgeInsets.all(10.0), + ), + ], + ), + ), + ), + ), + ); + } +} diff --git a/lib/settings/storage.dart b/lib/settings/storage.dart index 2d33331..42327f8 100644 --- a/lib/settings/storage.dart +++ b/lib/settings/storage.dart @@ -1,348 +1,348 @@ -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:google_fonts/google_fonts.dart'; -import 'package:path_provider/path_provider.dart'; -import 'package:provider/provider.dart'; -import 'package:tsacdop/util/general_dialog.dart'; - -import '../local_storage/key_value_storage.dart'; -import '../settings/downloads_manage.dart'; -import '../state/setting_state.dart'; -import '../util/custom_dropdown.dart'; -import '../util/custom_widget.dart'; -import '../util/extension_helper.dart'; - -class StorageSetting extends StatefulWidget { - @override - _StorageSettingState createState() => _StorageSettingState(); -} - -class _StorageSettingState extends State - with SingleTickerProviderStateMixin { - final KeyValueStorage cacheStorage = KeyValueStorage(cacheMaxKey); - AnimationController _controller; - Animation _animation; - List _dirs; - Future _getCacheMax() async { - var cache = - await cacheStorage.getInt(defaultValue: (200 * 1024 * 1024).toInt()); - if (cache == 0) { - await cacheStorage.saveInt((200 * 1024 * 1024).toInt()); - cache = 200 * 1024 * 1024; - } - var value = cache ~/ (1024 * 1024); - if (value > 100) { - _controller = AnimationController( - vsync: this, duration: Duration(milliseconds: value * 2)); - _animation = Tween(begin: 100, end: value.toDouble()).animate( - CurvedAnimation(curve: Curves.easeOutQuart, parent: _controller)) - ..addListener(() { - setState(() => _value = _animation.value); - }); - _controller.forward(); - } - } - - Future _getAutoDownloadNetwork() async { - var storage = KeyValueStorage(autoDownloadNetworkKey); - var value = await storage.getBool(defaultValue: false); - return value; - } - - Future _getAutoDeleteDays() async { - var storage = KeyValueStorage(autoDeleteKey); - var days = await storage.getInt(); - if (days == 0) { - storage.saveInt(30); - return 30; - } - return days; - } - - Future _getDownloadPasition() async { - final storage = KeyValueStorage(downloadPositionKey); - final index = await storage.getInt(); - final externalDirs = await getExternalStorageDirectories(); - _dirs = [for (var dir in externalDirs) dir.path]; - return index; - } - - Future _getDelteAfterPlayed() async { - final storage = KeyValueStorage(deleteAfterPlayedKey); - return await storage.getBool(defaultValue: false); - } - - Future _setAutoDeleteDays(int days) async { - var storage = KeyValueStorage(autoDeleteKey); - await storage.saveInt(days); - setState(() {}); - } - - Future _setAudtDownloadNetwork(bool boo) async { - var storage = KeyValueStorage(autoDownloadNetworkKey); - await storage.saveBool(boo); - } - - Future _setDownloadPosition(int index) async { - final storage = KeyValueStorage(downloadPositionKey); - await storage.saveInt(index); - } - - Future _setDeleteAfterPlayed(bool boo) async { - final storage = KeyValueStorage(deleteAfterPlayedKey); - await storage.saveBool(boo); - } - - double _value; - - @override - void initState() { - super.initState(); - _value = 100; - _getCacheMax(); - } - - @override - void dispose() { - _controller?.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - final s = context.s; - var settings = Provider.of(context, listen: false); - return AnnotatedRegion( - value: SystemUiOverlayStyle( - statusBarIconBrightness: Theme.of(context).accentColorBrightness, - systemNavigationBarColor: Theme.of(context).primaryColor, - systemNavigationBarIconBrightness: - Theme.of(context).accentColorBrightness, - ), - child: Scaffold( - appBar: AppBar( - title: Text(s.settingStorage), - leading: CustomBackButton(), - elevation: 0, - backgroundColor: Theme.of(context).primaryColor, - ), - body: SafeArea( - child: SingleChildScrollView( - child: Column( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Padding( - padding: EdgeInsets.all(10.0), - ), - Container( - height: 30.0, - padding: EdgeInsets.symmetric(horizontal: 70), - alignment: Alignment.centerLeft, - child: Text(s.network, - style: context.textTheme.bodyText1 - .copyWith(color: context.accentColor)), - ), - Selector( - selector: (_, settings) => settings.downloadUsingData, - builder: (_, data, __) { - return ListTile( - onTap: () => settings.downloadUsingData = !data, - contentPadding: EdgeInsets.only( - left: 70.0, right: 25, bottom: 10, top: 10), - title: Text(s.settingsNetworkCellular), - subtitle: Text(s.settingsNetworkCellularDes), - trailing: Transform.scale( - scale: 0.9, - child: Switch( - value: data, - onChanged: (value) => - settings.downloadUsingData = value, - ), - ), - ); - }, - ), - FutureBuilder( - future: _getAutoDownloadNetwork(), - initialData: false, - builder: (context, snapshot) { - return ListTile( - onTap: () async { - _setAudtDownloadNetwork(!snapshot.data); - setState(() {}); - }, - contentPadding: EdgeInsets.only( - left: 70.0, right: 25, bottom: 10, top: 10), - title: Text(s.settingsNetworkCellularAuto), - subtitle: Text(s.settingsNetworkCellularAutoDes), - trailing: Transform.scale( - scale: 0.9, - child: Switch( - value: snapshot.data, - onChanged: (value) async { - await _setAudtDownloadNetwork(value); - setState(() {}); - }, - ), - ), - ); - }), - Divider(height: 1), - Padding( - padding: EdgeInsets.all(10.0), - ), - Container( - height: 30.0, - padding: EdgeInsets.symmetric(horizontal: 70), - alignment: Alignment.centerLeft, - child: Text(s.settingStorage, - style: context.textTheme.bodyText1 - .copyWith(color: context.accentColor)), - ), - ListTile( - onTap: () => Navigator.push( - context, - MaterialPageRoute( - builder: (context) => DownloadsManage())), - contentPadding: EdgeInsets.symmetric(horizontal: 70.0), - title: Text(s.download), - subtitle: Text(s.settingsManageDownloadDes), - ), - FutureBuilder( - future: _getDownloadPasition(), - initialData: 0, - builder: (context, snapshot) { - return ListTile( - contentPadding: EdgeInsets.fromLTRB(70, 10, 20, 10), - title: Text(s.settingsDownloadPosition), - subtitle: Text( - _dirs == null ? '' : _dirs[snapshot.data], - maxLines: 2, - overflow: TextOverflow.ellipsis), - onTap: () => generalSheet( - context, - title: s.settingsDownloadPosition, - child: Column(children: [ - SizedBox( - height: 10, - ), - for (var dir in _dirs) - ListTile( - title: Text(dir), - onTap: () => - _setDownloadPosition(_dirs.indexOf(dir)), - trailing: Radio( - value: _dirs.indexOf(dir), - groupValue: snapshot.data, - onChanged: _setDownloadPosition), - ), - SizedBox( - height: 30, - ) - ]), - ), - ); - }), - FutureBuilder( - future: _getAutoDeleteDays(), - initialData: 30, - builder: (context, snapshot) { - return ListTile( - contentPadding: EdgeInsets.only(left: 70.0, right: 20), - title: Text(s.settingsAutoDelete), - subtitle: Text(s.settingsAutoDeleteDes), - trailing: MyDropdownButton( - hint: snapshot.data == -1 - ? Text(s.daysCount(0)) - : Text(s.daysCount(snapshot.data)), - underline: Center(), - elevation: 1, - value: snapshot.data, - onChanged: (value) async { - await _setAutoDeleteDays(value); - }, - items: [-1, 5, 10, 15, 30] - .map>((e) { - return DropdownMenuItem( - value: e, - child: e == -1 - ? Text(s.daysCount(0)) - : Text(s.daysCount(e))); - }).toList()), - ); - }, - ), - FutureBuilder( - future: _getDelteAfterPlayed(), - initialData: false, - builder: (context, snapshot) { - return ListTile( - onTap: () async { - _setDeleteAfterPlayed(snapshot.data); - setState(() {}); - }, - contentPadding: EdgeInsets.only(left: 70.0, right: 25), - title: Text('Delete download after played'), - subtitle: Text('Delete after played'), - trailing: Transform.scale( - scale: 0.9, - child: Switch( - value: snapshot.data, - onChanged: (value) async { - await _setDeleteAfterPlayed(value); - setState(() {}); - }, - ), - ), - ); - }), - ListTile( - contentPadding: EdgeInsets.only(left: 70.0, right: 25), - // leading: Icon(Icons.colorize), - title: Text(s.settingsAudioCache), - subtitle: Text(s.settingsAudioCacheDes), - trailing: Text.rich(TextSpan( - text: '${(_value ~/ 100) * 100}', - style: GoogleFonts.teko( - textStyle: context.textTheme.headline6 - .copyWith(color: context.accentColor)), - children: [ - TextSpan( - text: ' Mb', style: context.textTheme.subtitle2), - ])), - ), - Padding( - padding: - EdgeInsets.only(left: 50.0, right: 20.0, bottom: 10.0), - child: SliderTheme( - data: Theme.of(context).sliderTheme.copyWith( - showValueIndicator: ShowValueIndicator.always, - trackHeight: 2, - thumbShape: - RoundSliderThumbShape(enabledThumbRadius: 6)), - child: Slider( - label: '${_value ~/ 100 * 100} Mb', - activeColor: context.accentColor, - inactiveColor: context.primaryColorDark, - value: _value, - min: 100, - max: 1000, - divisions: 9, - onChanged: (val) { - setState(() { - _value = val; - }); - cacheStorage.saveInt((val * 1024 * 1024).toInt()); - }), - ), - ), - Divider(height: 1), - ], - ), - ), - ), - ), - ); - } -} +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:path_provider/path_provider.dart'; +import 'package:provider/provider.dart'; + +import '../local_storage/key_value_storage.dart'; +import '../settings/downloads_manage.dart'; +import '../state/setting_state.dart'; +import '../util/custom_dropdown.dart'; +import '../util/custom_widget.dart'; +import '../util/extension_helper.dart'; +import '../util/general_dialog.dart'; + +class StorageSetting extends StatefulWidget { + @override + _StorageSettingState createState() => _StorageSettingState(); +} + +class _StorageSettingState extends State + with SingleTickerProviderStateMixin { + final KeyValueStorage cacheStorage = KeyValueStorage(cacheMaxKey); + AnimationController _controller; + Animation _animation; + List _dirs; + Future _getCacheMax() async { + var cache = + await cacheStorage.getInt(defaultValue: (200 * 1024 * 1024).toInt()); + if (cache == 0) { + await cacheStorage.saveInt((200 * 1024 * 1024).toInt()); + cache = 200 * 1024 * 1024; + } + var value = cache ~/ (1024 * 1024); + if (value > 100) { + _controller = AnimationController( + vsync: this, duration: Duration(milliseconds: value * 2)); + _animation = Tween(begin: 100, end: value.toDouble()).animate( + CurvedAnimation(curve: Curves.easeOutQuart, parent: _controller)) + ..addListener(() { + setState(() => _value = _animation.value); + }); + _controller.forward(); + } + } + + Future _getAutoDownloadNetwork() async { + var storage = KeyValueStorage(autoDownloadNetworkKey); + var value = await storage.getBool(defaultValue: false); + return value; + } + + Future _getAutoDeleteDays() async { + var storage = KeyValueStorage(autoDeleteKey); + var days = await storage.getInt(); + if (days == 0) { + storage.saveInt(30); + return 30; + } + return days; + } + + Future _getDownloadPasition() async { + final storage = KeyValueStorage(downloadPositionKey); + final index = await storage.getInt(); + final externalDirs = await getExternalStorageDirectories(); + _dirs = [for (var dir in externalDirs) dir.path]; + return index; + } + + Future _getDelteAfterPlayed() async { + final storage = KeyValueStorage(deleteAfterPlayedKey); + return await storage.getBool(defaultValue: false); + } + + Future _setAutoDeleteDays(int days) async { + var storage = KeyValueStorage(autoDeleteKey); + await storage.saveInt(days); + setState(() {}); + } + + Future _setAudtDownloadNetwork(bool boo) async { + var storage = KeyValueStorage(autoDownloadNetworkKey); + await storage.saveBool(boo); + } + + Future _setDownloadPosition(int index) async { + final storage = KeyValueStorage(downloadPositionKey); + await storage.saveInt(index); + } + + Future _setDeleteAfterPlayed(bool boo) async { + final storage = KeyValueStorage(deleteAfterPlayedKey); + await storage.saveBool(boo); + } + + double _value; + + @override + void initState() { + super.initState(); + _value = 100; + _getCacheMax(); + } + + @override + void dispose() { + _controller?.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final s = context.s; + var settings = Provider.of(context, listen: false); + return AnnotatedRegion( + value: SystemUiOverlayStyle( + statusBarIconBrightness: Theme.of(context).accentColorBrightness, + systemNavigationBarColor: Theme.of(context).primaryColor, + systemNavigationBarIconBrightness: + Theme.of(context).accentColorBrightness, + ), + child: Scaffold( + appBar: AppBar( + title: Text(s.settingStorage), + leading: CustomBackButton(), + elevation: 0, + backgroundColor: Theme.of(context).primaryColor, + ), + body: SafeArea( + child: SingleChildScrollView( + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Padding( + padding: EdgeInsets.all(10.0), + ), + Container( + height: 30.0, + padding: EdgeInsets.symmetric(horizontal: 70), + alignment: Alignment.centerLeft, + child: Text(s.network, + style: context.textTheme.bodyText1 + .copyWith(color: context.accentColor)), + ), + Selector( + selector: (_, settings) => settings.downloadUsingData, + builder: (_, data, __) { + return ListTile( + onTap: () => settings.downloadUsingData = !data, + contentPadding: EdgeInsets.only( + left: 70.0, right: 25, bottom: 10, top: 10), + title: Text(s.settingsNetworkCellular), + subtitle: Text(s.settingsNetworkCellularDes), + trailing: Transform.scale( + scale: 0.9, + child: Switch( + value: data, + onChanged: (value) => + settings.downloadUsingData = value, + ), + ), + ); + }, + ), + FutureBuilder( + future: _getAutoDownloadNetwork(), + initialData: false, + builder: (context, snapshot) { + return ListTile( + onTap: () async { + _setAudtDownloadNetwork(!snapshot.data); + setState(() {}); + }, + contentPadding: EdgeInsets.only( + left: 70.0, right: 25, bottom: 10, top: 10), + title: Text(s.settingsNetworkCellularAuto), + subtitle: Text(s.settingsNetworkCellularAutoDes), + trailing: Transform.scale( + scale: 0.9, + child: Switch( + value: snapshot.data, + onChanged: (value) async { + await _setAudtDownloadNetwork(value); + setState(() {}); + }, + ), + ), + ); + }), + Divider(height: 1), + Padding( + padding: EdgeInsets.all(10.0), + ), + Container( + height: 30.0, + padding: EdgeInsets.symmetric(horizontal: 70), + alignment: Alignment.centerLeft, + child: Text(s.settingStorage, + style: context.textTheme.bodyText1 + .copyWith(color: context.accentColor)), + ), + ListTile( + onTap: () => Navigator.push( + context, + MaterialPageRoute( + builder: (context) => DownloadsManage())), + contentPadding: EdgeInsets.symmetric(horizontal: 70.0), + title: Text(s.download), + subtitle: Text(s.settingsManageDownloadDes), + ), + FutureBuilder( + future: _getDownloadPasition(), + initialData: 0, + builder: (context, snapshot) { + return ListTile( + contentPadding: EdgeInsets.fromLTRB(70, 10, 20, 10), + title: Text(s.settingsDownloadPosition), + subtitle: Text( + _dirs == null ? '' : _dirs[snapshot.data], + maxLines: 2, + overflow: TextOverflow.ellipsis), + onTap: () => generalSheet( + context, + title: s.settingsDownloadPosition, + child: Column(children: [ + SizedBox( + height: 10, + ), + for (var dir in _dirs) + ListTile( + title: Text(dir), + onTap: () => + _setDownloadPosition(_dirs.indexOf(dir)), + trailing: Radio( + value: _dirs.indexOf(dir), + groupValue: snapshot.data, + onChanged: _setDownloadPosition), + ), + SizedBox( + height: 30, + ) + ]), + ), + ); + }), + FutureBuilder( + future: _getAutoDeleteDays(), + initialData: 30, + builder: (context, snapshot) { + return ListTile( + contentPadding: EdgeInsets.only(left: 70.0, right: 20), + title: Text(s.settingsAutoDelete), + subtitle: Text(s.settingsAutoDeleteDes), + trailing: MyDropdownButton( + hint: snapshot.data == -1 + ? Text(s.daysCount(0)) + : Text(s.daysCount(snapshot.data)), + underline: Center(), + elevation: 1, + value: snapshot.data, + onChanged: (value) async { + await _setAutoDeleteDays(value); + }, + items: [-1, 5, 10, 15, 30] + .map>((e) { + return DropdownMenuItem( + value: e, + child: e == -1 + ? Text(s.daysCount(0)) + : Text(s.daysCount(e))); + }).toList()), + ); + }, + ), + FutureBuilder( + future: _getDelteAfterPlayed(), + initialData: false, + builder: (context, snapshot) { + return ListTile( + onTap: () async { + _setDeleteAfterPlayed(snapshot.data); + setState(() {}); + }, + contentPadding: EdgeInsets.only(left: 70.0, right: 25), + title: Text('Delete download after played'), + subtitle: Text('Delete after played'), + trailing: Transform.scale( + scale: 0.9, + child: Switch( + value: snapshot.data, + onChanged: (value) async { + await _setDeleteAfterPlayed(value); + setState(() {}); + }, + ), + ), + ); + }), + ListTile( + contentPadding: EdgeInsets.only(left: 70.0, right: 25), + // leading: Icon(Icons.colorize), + title: Text(s.settingsAudioCache), + subtitle: Text(s.settingsAudioCacheDes), + trailing: Text.rich(TextSpan( + text: '${(_value ~/ 100) * 100}', + style: GoogleFonts.teko( + textStyle: context.textTheme.headline6 + .copyWith(color: context.accentColor)), + children: [ + TextSpan( + text: ' Mb', style: context.textTheme.subtitle2), + ])), + ), + Padding( + padding: + EdgeInsets.only(left: 50.0, right: 20.0, bottom: 10.0), + child: SliderTheme( + data: Theme.of(context).sliderTheme.copyWith( + showValueIndicator: ShowValueIndicator.always, + trackHeight: 2, + thumbShape: + RoundSliderThumbShape(enabledThumbRadius: 6)), + child: Slider( + label: '${_value ~/ 100 * 100} Mb', + activeColor: context.accentColor, + inactiveColor: context.primaryColorDark, + value: _value, + min: 100, + max: 1000, + divisions: 9, + onChanged: (val) { + setState(() { + _value = val; + }); + cacheStorage.saveInt((val * 1024 * 1024).toInt()); + }), + ), + ), + Divider(height: 1), + ], + ), + ), + ), + ), + ); + } +} diff --git a/lib/settings/syncing.dart b/lib/settings/syncing.dart index 651aa74..865a7b1 100644 --- a/lib/settings/syncing.dart +++ b/lib/settings/syncing.dart @@ -1,103 +1,103 @@ -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:provider/provider.dart'; -import 'package:tuple/tuple.dart'; - -import '../state/setting_state.dart'; -import '../util/custom_dropdown.dart'; -import '../util/custom_widget.dart'; -import '../util/extension_helper.dart'; - -class SyncingSetting extends StatelessWidget { - @override - Widget build(BuildContext context) { - final s = context.s; - var settings = Provider.of(context, listen: false); - return AnnotatedRegion( - value: SystemUiOverlayStyle( - statusBarIconBrightness: Theme.of(context).accentColorBrightness, - systemNavigationBarColor: Theme.of(context).primaryColor, - systemNavigationBarIconBrightness: - Theme.of(context).accentColorBrightness, - ), - child: Scaffold( - appBar: AppBar( - title: Text(s.settingsSyncing), - leading: CustomBackButton(), - elevation: 0, - backgroundColor: Theme.of(context).primaryColor, - ), - body: SingleChildScrollView( - child: Selector>( - selector: (_, settings) => - Tuple2(settings.autoUpdate, settings.updateInterval), - builder: (_, data, __) => Column( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Padding( - padding: const EdgeInsets.fromLTRB(70, 20, 70, 10), - child: Text(s.settingsSyncing, - style: context.textTheme.bodyText1 - .copyWith(color: context.accentColor)), - ), - ListTile( - onTap: () { - if (settings.autoUpdate) { - settings.autoUpdate = false; - settings.cancelWork(); - } else { - settings.autoUpdate = true; - settings.setWorkManager(data.item2); - } - }, - contentPadding: - const EdgeInsets.only(left: 70.0, right: 20, bottom: 10), - title: Text(s.settingsEnableSyncing), - subtitle: Text(s.settingsEnableSyncingDes), - trailing: Transform.scale( - scale: 0.9, - child: Switch( - value: data.item1, - onChanged: (boo) async { - settings.autoUpdate = boo; - if (boo) { - settings.setWorkManager(data.item2); - } else { - settings.cancelWork(); - } - }), - ), - ), - ListTile( - contentPadding: const EdgeInsets.only(left: 70.0, right: 20), - title: Text(s.settingsUpdateInterval), - subtitle: Text(s.settingsUpdateIntervalDes), - trailing: MyDropdownButton( - hint: Text(s.hoursCount(data.item2)), - underline: Center(), - elevation: 1, - displayItemCount: 5, - value: data.item2, - onChanged: data.item1 - ? (value) async { - await settings.cancelWork(); - settings.setWorkManager(value); - } - : null, - items: [1, 2, 4, 8, 24, 48] - .map>((e) { - return DropdownMenuItem( - value: e, child: Text(s.hoursCount(e))); - }).toList()), - ), - Divider(height: 1), - ], - ), - ), - ), - ), - ); - } -} +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; +import 'package:tuple/tuple.dart'; + +import '../state/setting_state.dart'; +import '../util/custom_dropdown.dart'; +import '../util/custom_widget.dart'; +import '../util/extension_helper.dart'; + +class SyncingSetting extends StatelessWidget { + @override + Widget build(BuildContext context) { + final s = context.s; + var settings = Provider.of(context, listen: false); + return AnnotatedRegion( + value: SystemUiOverlayStyle( + statusBarIconBrightness: Theme.of(context).accentColorBrightness, + systemNavigationBarColor: Theme.of(context).primaryColor, + systemNavigationBarIconBrightness: + Theme.of(context).accentColorBrightness, + ), + child: Scaffold( + appBar: AppBar( + title: Text(s.settingsSyncing), + leading: CustomBackButton(), + elevation: 0, + backgroundColor: Theme.of(context).primaryColor, + ), + body: SingleChildScrollView( + child: Selector>( + selector: (_, settings) => + Tuple2(settings.autoUpdate, settings.updateInterval), + builder: (_, data, __) => Column( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(70, 20, 70, 10), + child: Text(s.settingsSyncing, + style: context.textTheme.bodyText1 + .copyWith(color: context.accentColor)), + ), + ListTile( + onTap: () { + if (settings.autoUpdate) { + settings.autoUpdate = false; + settings.cancelWork(); + } else { + settings.autoUpdate = true; + settings.setWorkManager(data.item2); + } + }, + contentPadding: + const EdgeInsets.only(left: 70.0, right: 20, bottom: 10), + title: Text(s.settingsEnableSyncing), + subtitle: Text(s.settingsEnableSyncingDes), + trailing: Transform.scale( + scale: 0.9, + child: Switch( + value: data.item1, + onChanged: (boo) async { + settings.autoUpdate = boo; + if (boo) { + settings.setWorkManager(data.item2); + } else { + settings.cancelWork(); + } + }), + ), + ), + ListTile( + contentPadding: const EdgeInsets.only(left: 70.0, right: 20), + title: Text(s.settingsUpdateInterval), + subtitle: Text(s.settingsUpdateIntervalDes), + trailing: MyDropdownButton( + hint: Text(s.hoursCount(data.item2)), + underline: Center(), + elevation: 1, + displayItemCount: 5, + value: data.item2, + onChanged: data.item1 + ? (value) async { + await settings.cancelWork(); + settings.setWorkManager(value); + } + : null, + items: [1, 2, 4, 8, 24, 48] + .map>((e) { + return DropdownMenuItem( + value: e, child: Text(s.hoursCount(e))); + }).toList()), + ), + Divider(height: 1), + ], + ), + ), + ), + ), + ); + } +} diff --git a/lib/settings/theme.dart b/lib/settings/theme.dart index 596665b..c5a4fe7 100644 --- a/lib/settings/theme.dart +++ b/lib/settings/theme.dart @@ -1,404 +1,404 @@ -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:provider/provider.dart'; - -import '../state/setting_state.dart'; -import '../util/custom_widget.dart'; -import '../util/extension_helper.dart'; -import '../util/general_dialog.dart'; - -class ThemeSetting extends StatelessWidget { - @override - Widget build(BuildContext context) { - final s = context.s; - var settings = Provider.of(context, listen: false); - return AnnotatedRegion( - value: SystemUiOverlayStyle( - statusBarIconBrightness: Theme.of(context).accentColorBrightness, - systemNavigationBarColor: Theme.of(context).primaryColor, - systemNavigationBarIconBrightness: - Theme.of(context).accentColorBrightness, - ), - child: Scaffold( - appBar: AppBar( - title: Text(s.settingsAppearance), - leading: CustomBackButton(), - elevation: 0, - backgroundColor: Theme.of(context).primaryColor, - ), - body: Column( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Padding( - padding: EdgeInsets.all(10.0), - ), - Container( - height: 30.0, - padding: EdgeInsets.symmetric(horizontal: 70), - alignment: Alignment.centerLeft, - child: Text(s.settingsInterface, - style: Theme.of(context) - .textTheme - .bodyText1 - .copyWith(color: Theme.of(context).accentColor)), - ), - ListTile( - onTap: () => showGeneralDialog( - context: context, - barrierDismissible: true, - barrierLabel: MaterialLocalizations.of(context) - .modalBarrierDismissLabel, - barrierColor: Colors.black54, - transitionDuration: const Duration(milliseconds: 200), - pageBuilder: (context, animaiton, secondaryAnimation) => - AnnotatedRegion( - value: SystemUiOverlayStyle( - statusBarIconBrightness: Brightness.light, - systemNavigationBarColor: - Theme.of(context).brightness == Brightness.light - ? Color.fromRGBO(113, 113, 113, 1) - : Color.fromRGBO(15, 15, 15, 1), - ), - child: AlertDialog( - titlePadding: EdgeInsets.only( - top: 20, - left: 40, - right: context.width / 3, - ), - elevation: 1, - shape: RoundedRectangleBorder( - borderRadius: - BorderRadius.all(Radius.circular(10.0))), - title: Text(s.settingsTheme), - content: SingleChildScrollView( - scrollDirection: Axis.vertical, - child: Column( - mainAxisSize: MainAxisSize.min, - mainAxisAlignment: MainAxisAlignment.start, - children: [ - ClipRRect( - borderRadius: - BorderRadius.all(Radius.circular(5)), - child: Material( - color: Colors.transparent, - child: RadioListTile( - title: Text(s.systemDefault), - value: ThemeMode.system, - groupValue: settings.theme, - onChanged: (value) { - settings.setTheme = value; - Navigator.of(context).pop(); - }), - ), - ), - ClipRRect( - borderRadius: - BorderRadius.all(Radius.circular(5)), - child: Material( - color: Colors.transparent, - child: RadioListTile( - title: Text(s.darkMode), - value: ThemeMode.dark, - groupValue: settings.theme, - onChanged: (value) { - settings.setTheme = value; - Navigator.of(context).pop(); - }), - ), - ), - ClipRRect( - borderRadius: - BorderRadius.all(Radius.circular(5)), - child: Material( - color: Colors.transparent, - child: RadioListTile( - title: Text(s.lightMode), - value: ThemeMode.light, - groupValue: settings.theme, - onChanged: (value) { - settings.setTheme = value; - Navigator.of(context).pop(); - }), - ), - ), - ], - ), - ), - ), - )), - contentPadding: EdgeInsets.symmetric(horizontal: 70.0), - // leading: Icon(Icons.colorize), - title: Text(s.settingsTheme), - subtitle: Text(s.systemDefault), - ), - Selector( - selector: (_, setting) => setting.realDark, - builder: (_, data, __) => ListTile( - onTap: () => settings.setRealDark = !data, - contentPadding: const EdgeInsets.only( - left: 70.0, right: 20, bottom: 10, top: 10), - // leading: Icon(Icons.colorize), - title: Text( - s.settingsRealDark, - ), - subtitle: Text(s.settingsRealDarkDes), - trailing: Transform.scale( - scale: 0.9, - child: Switch( - value: data, - onChanged: (boo) async { - settings.setRealDark = boo; - }), - ), - ), - ), - ListTile( - onTap: () => generalDialog( - context, - title: Text.rich(TextSpan(text: s.chooseA, children: [ - TextSpan( - text: ' ${s.color}', - style: TextStyle( - fontWeight: FontWeight.bold, - color: context.accentColor)) - ])), - content: _ColorPicker( - onColorChanged: (value) => settings.setAccentColor = value, - ), - ), - contentPadding: EdgeInsets.only(left: 70.0, right: 35), - title: Text(s.settingsAccentColor), - subtitle: Text(s.settingsAccentColorDes), - trailing: Container( - height: 25, - width: 25, - decoration: BoxDecoration( - shape: BoxShape.circle, color: context.accentColor), - ), - ), - Divider(height: 1), - Padding( - padding: EdgeInsets.all(10.0), - ), - Container( - height: 30.0, - padding: EdgeInsets.symmetric(horizontal: 70), - alignment: Alignment.centerLeft, - child: Text(s.fontStyle, - style: context.textTheme.bodyText1 - .copyWith(color: context.accentColor)), - ), - Selector( - selector: (_, setting) => setting.showNotesFontIndex, - builder: (_, data, __) => ListTile( - contentPadding: const EdgeInsets.only( - left: 70.0, right: 20, bottom: 10, top: 10), - title: Text(s.showNotesFonts), - subtitle: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: showNotesFontStyles.map((textStyle) { - final index = showNotesFontStyles.indexOf(textStyle); - return Padding( - padding: const EdgeInsets.symmetric(vertical: 10), - child: InkWell( - onTap: () => settings.setShowNoteFontStyle = index, - borderRadius: BorderRadius.circular(10.0), - child: Container( - height: 60, - width: 80, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(10), - border: Border.all( - color: data == index - ? context.accentColor.withAlpha(70) - : context.primaryColorDark), - color: data == index - ? context.accentColor.withAlpha(70) - : Colors.transparent), - alignment: Alignment.center, - child: Text( - 'Show notes', - textAlign: TextAlign.center, - style: textStyle, - ), - ), - ), - ); - }).toList(), - ), - ), - ), - Divider(height: 1) - ], - ), - ), - ); - } -} - -class _ColorPicker extends StatefulWidget { - final ValueChanged onColorChanged; - _ColorPicker({Key key, this.onColorChanged}) : super(key: key); - @override - __ColorPickerState createState() => __ColorPickerState(); -} - -class __ColorPickerState extends State<_ColorPicker> - with SingleTickerProviderStateMixin { - TabController _controller; - int _index; - @override - void initState() { - super.initState(); - _index = 0; - _controller = TabController(length: Colors.primaries.length, vsync: this) - ..addListener(() { - setState(() => _index = _controller.index); - }); - } - - Widget _colorCircle(Color color) => Material( - color: Colors.transparent, - child: InkWell( - borderRadius: BorderRadius.all(Radius.circular(10)), - onTap: () => widget.onColorChanged(color), - child: Container( - decoration: BoxDecoration( - border: color == context.accentColor - ? Border.all(color: Colors.grey[400], width: 4) - : null, - borderRadius: BorderRadius.all(Radius.circular(10)), - color: color), - ), - ), - ); - - List _accentList(MaterialAccentColor color) => [ - _colorCircle(color.shade100), - _colorCircle(color.shade200), - _colorCircle(color.shade400), - _colorCircle(color.shade700) - ]; - - @override - Widget build(BuildContext context) { - return Container( - width: 400, - height: 400, - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Container( - height: 40, - color: Theme.of(context).dialogBackgroundColor, - child: TabBar( - labelPadding: EdgeInsets.symmetric(horizontal: 10), - controller: _controller, - indicatorColor: Colors.transparent, - indicatorSize: TabBarIndicatorSize.tab, - isScrollable: true, - tabs: Colors.primaries - .map((color) => Tab( - child: Container( - height: 20, - width: 40, - decoration: BoxDecoration( - border: Colors.primaries.indexOf(color) == _index - ? Border.all( - color: Colors.grey[400], width: 2) - : null, - borderRadius: - BorderRadius.all(Radius.circular(10)), - color: color), - ), - )) - .toList(), - ), - ), - Expanded( - child: TabBarView( - physics: const ClampingScrollPhysics(), - key: UniqueKey(), - controller: _controller, - children: Colors.primaries - .map((color) => ScrollConfiguration( - behavior: NoGrowBehavior(), - child: GridView.count( - primary: false, - padding: const EdgeInsets.fromLTRB(2, 10, 2, 10), - crossAxisSpacing: 4, - mainAxisSpacing: 4, - crossAxisCount: 3, - children: [ - _colorCircle(color.shade100), - _colorCircle(color.shade200), - _colorCircle(color.shade300), - _colorCircle(color.shade400), - _colorCircle(color.shade500), - _colorCircle(color.shade600), - _colorCircle(color.shade700), - _colorCircle(color.shade800), - _colorCircle(color.shade900), - ...color == Colors.red - ? _accentList(Colors.redAccent) - : color == Colors.pink - ? _accentList(Colors.pinkAccent) - : color == Colors.deepOrange - ? _accentList(Colors.deepOrangeAccent) - : color == Colors.orange - ? _accentList(Colors.orangeAccent) - : color == Colors.amber - ? _accentList( - Colors.amberAccent) - : color == Colors.yellow - ? _accentList( - Colors.yellowAccent) - : color == Colors.lime - ? _accentList( - Colors.limeAccent) - : color == - Colors - .lightGreen - ? _accentList(Colors - .lightGreenAccent) - : color == - Colors.green - ? _accentList(Colors - .greenAccent) - : color == - Colors - .teal - ? _accentList( - Colors - .tealAccent) - : color == - Colors - .cyan - ? _accentList(Colors - .cyanAccent) - : color == - Colors.lightBlue - ? _accentList(Colors.lightBlueAccent) - : color == Colors.blue - ? _accentList(Colors.blueAccent) - : color == Colors.indigo - ? _accentList(Colors.indigoAccent) - : color == Colors.purple - ? _accentList(Colors.purpleAccent) - : color == Colors.deepPurple - ? _accentList(Colors.deepPurpleAccent) - : [] - ], - ), - )) - .toList(), - ), - ), - ], - ), - ); - } -} +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; + +import '../state/setting_state.dart'; +import '../util/custom_widget.dart'; +import '../util/extension_helper.dart'; +import '../util/general_dialog.dart'; + +class ThemeSetting extends StatelessWidget { + @override + Widget build(BuildContext context) { + final s = context.s; + var settings = Provider.of(context, listen: false); + return AnnotatedRegion( + value: SystemUiOverlayStyle( + statusBarIconBrightness: Theme.of(context).accentColorBrightness, + systemNavigationBarColor: Theme.of(context).primaryColor, + systemNavigationBarIconBrightness: + Theme.of(context).accentColorBrightness, + ), + child: Scaffold( + appBar: AppBar( + title: Text(s.settingsAppearance), + leading: CustomBackButton(), + elevation: 0, + backgroundColor: Theme.of(context).primaryColor, + ), + body: Column( + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Padding( + padding: EdgeInsets.all(10.0), + ), + Container( + height: 30.0, + padding: EdgeInsets.symmetric(horizontal: 70), + alignment: Alignment.centerLeft, + child: Text(s.settingsInterface, + style: Theme.of(context) + .textTheme + .bodyText1 + .copyWith(color: Theme.of(context).accentColor)), + ), + ListTile( + onTap: () => showGeneralDialog( + context: context, + barrierDismissible: true, + barrierLabel: MaterialLocalizations.of(context) + .modalBarrierDismissLabel, + barrierColor: Colors.black54, + transitionDuration: const Duration(milliseconds: 200), + pageBuilder: (context, animaiton, secondaryAnimation) => + AnnotatedRegion( + value: SystemUiOverlayStyle( + statusBarIconBrightness: Brightness.light, + systemNavigationBarColor: + Theme.of(context).brightness == Brightness.light + ? Color.fromRGBO(113, 113, 113, 1) + : Color.fromRGBO(15, 15, 15, 1), + ), + child: AlertDialog( + titlePadding: EdgeInsets.only( + top: 20, + left: 40, + right: context.width / 3, + ), + elevation: 1, + shape: RoundedRectangleBorder( + borderRadius: + BorderRadius.all(Radius.circular(10.0))), + title: Text(s.settingsTheme), + content: SingleChildScrollView( + scrollDirection: Axis.vertical, + child: Column( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.start, + children: [ + ClipRRect( + borderRadius: + BorderRadius.all(Radius.circular(5)), + child: Material( + color: Colors.transparent, + child: RadioListTile( + title: Text(s.systemDefault), + value: ThemeMode.system, + groupValue: settings.theme, + onChanged: (value) { + settings.setTheme = value; + Navigator.of(context).pop(); + }), + ), + ), + ClipRRect( + borderRadius: + BorderRadius.all(Radius.circular(5)), + child: Material( + color: Colors.transparent, + child: RadioListTile( + title: Text(s.darkMode), + value: ThemeMode.dark, + groupValue: settings.theme, + onChanged: (value) { + settings.setTheme = value; + Navigator.of(context).pop(); + }), + ), + ), + ClipRRect( + borderRadius: + BorderRadius.all(Radius.circular(5)), + child: Material( + color: Colors.transparent, + child: RadioListTile( + title: Text(s.lightMode), + value: ThemeMode.light, + groupValue: settings.theme, + onChanged: (value) { + settings.setTheme = value; + Navigator.of(context).pop(); + }), + ), + ), + ], + ), + ), + ), + )), + contentPadding: EdgeInsets.symmetric(horizontal: 70.0), + // leading: Icon(Icons.colorize), + title: Text(s.settingsTheme), + subtitle: Text(s.systemDefault), + ), + Selector( + selector: (_, setting) => setting.realDark, + builder: (_, data, __) => ListTile( + onTap: () => settings.setRealDark = !data, + contentPadding: const EdgeInsets.only( + left: 70.0, right: 20, bottom: 10, top: 10), + // leading: Icon(Icons.colorize), + title: Text( + s.settingsRealDark, + ), + subtitle: Text(s.settingsRealDarkDes), + trailing: Transform.scale( + scale: 0.9, + child: Switch( + value: data, + onChanged: (boo) async { + settings.setRealDark = boo; + }), + ), + ), + ), + ListTile( + onTap: () => generalDialog( + context, + title: Text.rich(TextSpan(text: s.chooseA, children: [ + TextSpan( + text: ' ${s.color}', + style: TextStyle( + fontWeight: FontWeight.bold, + color: context.accentColor)) + ])), + content: _ColorPicker( + onColorChanged: (value) => settings.setAccentColor = value, + ), + ), + contentPadding: EdgeInsets.only(left: 70.0, right: 35), + title: Text(s.settingsAccentColor), + subtitle: Text(s.settingsAccentColorDes), + trailing: Container( + height: 25, + width: 25, + decoration: BoxDecoration( + shape: BoxShape.circle, color: context.accentColor), + ), + ), + Divider(height: 1), + Padding( + padding: EdgeInsets.all(10.0), + ), + Container( + height: 30.0, + padding: EdgeInsets.symmetric(horizontal: 70), + alignment: Alignment.centerLeft, + child: Text(s.fontStyle, + style: context.textTheme.bodyText1 + .copyWith(color: context.accentColor)), + ), + Selector( + selector: (_, setting) => setting.showNotesFontIndex, + builder: (_, data, __) => ListTile( + contentPadding: const EdgeInsets.only( + left: 70.0, right: 20, bottom: 10, top: 10), + title: Text(s.showNotesFonts), + subtitle: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: showNotesFontStyles.map((textStyle) { + final index = showNotesFontStyles.indexOf(textStyle); + return Padding( + padding: const EdgeInsets.symmetric(vertical: 10), + child: InkWell( + onTap: () => settings.setShowNoteFontStyle = index, + borderRadius: BorderRadius.circular(10.0), + child: Container( + height: 60, + width: 80, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(10), + border: Border.all( + color: data == index + ? context.accentColor.withAlpha(70) + : context.primaryColorDark), + color: data == index + ? context.accentColor.withAlpha(70) + : Colors.transparent), + alignment: Alignment.center, + child: Text( + 'Show notes', + textAlign: TextAlign.center, + style: textStyle, + ), + ), + ), + ); + }).toList(), + ), + ), + ), + Divider(height: 1) + ], + ), + ), + ); + } +} + +class _ColorPicker extends StatefulWidget { + final ValueChanged onColorChanged; + _ColorPicker({Key key, this.onColorChanged}) : super(key: key); + @override + __ColorPickerState createState() => __ColorPickerState(); +} + +class __ColorPickerState extends State<_ColorPicker> + with SingleTickerProviderStateMixin { + TabController _controller; + int _index; + @override + void initState() { + super.initState(); + _index = 0; + _controller = TabController(length: Colors.primaries.length, vsync: this) + ..addListener(() { + setState(() => _index = _controller.index); + }); + } + + Widget _colorCircle(Color color) => Material( + color: Colors.transparent, + child: InkWell( + borderRadius: BorderRadius.all(Radius.circular(10)), + onTap: () => widget.onColorChanged(color), + child: Container( + decoration: BoxDecoration( + border: color == context.accentColor + ? Border.all(color: Colors.grey[400], width: 4) + : null, + borderRadius: BorderRadius.all(Radius.circular(10)), + color: color), + ), + ), + ); + + List _accentList(MaterialAccentColor color) => [ + _colorCircle(color.shade100), + _colorCircle(color.shade200), + _colorCircle(color.shade400), + _colorCircle(color.shade700) + ]; + + @override + Widget build(BuildContext context) { + return Container( + width: 400, + height: 400, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Container( + height: 40, + color: Theme.of(context).dialogBackgroundColor, + child: TabBar( + labelPadding: EdgeInsets.symmetric(horizontal: 10), + controller: _controller, + indicatorColor: Colors.transparent, + indicatorSize: TabBarIndicatorSize.tab, + isScrollable: true, + tabs: Colors.primaries + .map((color) => Tab( + child: Container( + height: 20, + width: 40, + decoration: BoxDecoration( + border: Colors.primaries.indexOf(color) == _index + ? Border.all( + color: Colors.grey[400], width: 2) + : null, + borderRadius: + BorderRadius.all(Radius.circular(10)), + color: color), + ), + )) + .toList(), + ), + ), + Expanded( + child: TabBarView( + physics: const ClampingScrollPhysics(), + key: UniqueKey(), + controller: _controller, + children: Colors.primaries + .map((color) => ScrollConfiguration( + behavior: NoGrowBehavior(), + child: GridView.count( + primary: false, + padding: const EdgeInsets.fromLTRB(2, 10, 2, 10), + crossAxisSpacing: 4, + mainAxisSpacing: 4, + crossAxisCount: 3, + children: [ + _colorCircle(color.shade100), + _colorCircle(color.shade200), + _colorCircle(color.shade300), + _colorCircle(color.shade400), + _colorCircle(color.shade500), + _colorCircle(color.shade600), + _colorCircle(color.shade700), + _colorCircle(color.shade800), + _colorCircle(color.shade900), + ...color == Colors.red + ? _accentList(Colors.redAccent) + : color == Colors.pink + ? _accentList(Colors.pinkAccent) + : color == Colors.deepOrange + ? _accentList(Colors.deepOrangeAccent) + : color == Colors.orange + ? _accentList(Colors.orangeAccent) + : color == Colors.amber + ? _accentList( + Colors.amberAccent) + : color == Colors.yellow + ? _accentList( + Colors.yellowAccent) + : color == Colors.lime + ? _accentList( + Colors.limeAccent) + : color == + Colors + .lightGreen + ? _accentList(Colors + .lightGreenAccent) + : color == + Colors.green + ? _accentList(Colors + .greenAccent) + : color == + Colors + .teal + ? _accentList( + Colors + .tealAccent) + : color == + Colors + .cyan + ? _accentList(Colors + .cyanAccent) + : color == + Colors.lightBlue + ? _accentList(Colors.lightBlueAccent) + : color == Colors.blue + ? _accentList(Colors.blueAccent) + : color == Colors.indigo + ? _accentList(Colors.indigoAccent) + : color == Colors.purple + ? _accentList(Colors.purpleAccent) + : color == Colors.deepPurple + ? _accentList(Colors.deepPurpleAccent) + : [] + ], + ), + )) + .toList(), + ), + ), + ], + ), + ); + } +} diff --git a/lib/state/audio_state.dart b/lib/state/audio_state.dart index 241e24e..71fdd13 100644 --- a/lib/state/audio_state.dart +++ b/lib/state/audio_state.dart @@ -1,1142 +1,1142 @@ -import 'dart:async'; -import 'dart:math' as math; - -import 'package:audio_service/audio_service.dart'; -import 'package:audio_session/audio_session.dart'; -import 'package:dio/dio.dart'; -import 'package:flutter/foundation.dart'; -import 'package:just_audio/just_audio.dart'; - -import '../local_storage/key_value_storage.dart'; -import '../local_storage/sqflite_localpodcast.dart'; -import '../type/episodebrief.dart'; -import '../type/play_histroy.dart'; -import '../type/playlist.dart'; - -MediaControl playControl = MediaControl( - androidIcon: 'drawable/ic_stat_play_circle_filled', - label: 'Play', - action: MediaAction.play, -); -MediaControl pauseControl = MediaControl( - androidIcon: 'drawable/ic_stat_pause_circle_filled', - label: 'Pause', - action: MediaAction.pause, -); -MediaControl skipToNextControl = MediaControl( - androidIcon: 'drawable/baseline_skip_next_white_24', - label: 'Next', - action: MediaAction.skipToNext, -); -MediaControl skipToPreviousControl = MediaControl( - androidIcon: 'drawable/ic_action_skip_previous', - label: 'Previous', - action: MediaAction.skipToPrevious, -); -MediaControl stopControl = MediaControl( - androidIcon: 'drawable/baseline_close_white_24', - label: 'Stop', - action: MediaAction.stop, -); -MediaControl forward = MediaControl( - androidIcon: 'drawable/baseline_fast_forward_white_24', - label: 'forward', - action: MediaAction.fastForward, -); - -MediaControl rewind = MediaControl( - androidIcon: 'drawable/baseline_fast_rewind_white_24', - label: 'rewind', - action: MediaAction.rewind, -); - -void _audioPlayerTaskEntrypoint() async { - AudioServiceBackground.run(() => AudioPlayerTask()); -} - -/// Sleep timer mode. -enum SleepTimerMode { endOfEpisode, timer, undefined } -enum PlayerHeight { short, mid, tall } -//enum ShareStatus { generate, download, complete, undefined, error } - -class AudioPlayerNotifier extends ChangeNotifier { - DBHelper dbHelper = DBHelper(); - final _positionStorage = KeyValueStorage(audioPositionKey); - final _autoPlayStorage = KeyValueStorage(autoPlayKey); - final _autoSleepTimerStorage = KeyValueStorage(autoSleepTimerKey); - final _defaultSleepTimerStorage = KeyValueStorage(defaultSleepTimerKey); - final _autoSleepTimerModeStorage = KeyValueStorage(autoSleepTimerModeKey); - final _autoSleepTimerStartStorage = KeyValueStorage(autoSleepTimerStartKey); - final _autoSleepTimerEndStorage = KeyValueStorage(autoSleepTimerEndKey); - final _fastForwardSecondsStorage = KeyValueStorage(fastForwardSecondsKey); - final _rewindSecondsStorage = KeyValueStorage(rewindSecondsKey); - final _playerHeightStorage = KeyValueStorage(playerHeightKey); - final _speedStorage = KeyValueStorage(speedKey); - final _skipSilenceStorage = KeyValueStorage(skipSilenceKey); - final _boostVolumeStorage = KeyValueStorage(boostVolumeKey); - final _volumeGainStorage = KeyValueStorage(volumeGainKey); - final _markListenedAfterSkipStorage = - KeyValueStorage(markListenedAfterSkipKey); - - /// Current playing episdoe. - EpisodeBrief _episode; - - /// Current playlist. - Playlist _queue; - - /// Notifier for playlist change. - bool _queueUpdate = false; - - /// Player state. - AudioProcessingState _audioState = AudioProcessingState.none; - - /// Player playing. - bool _playing = false; - - /// Fastforward second. - int _fastForwardSeconds = 0; - - /// Rewind seconds. - int _rewindSeconds = 0; - - /// No slide, set true if slide on seekbar. - bool _noSlide = true; - - /// Current episode duration. - int _backgroundAudioDuration = 0; - - /// Current episode positin. - int _backgroundAudioPosition = 0; - - /// Erroe maeesage. - String _remoteErrorMessage; - - /// Seekbar value, min 0, max 1.0. - double _seekSliderValue = 0.0; - - /// Record plyaer position. - int _lastPostion = 0; - - /// Set true if sleep timer mode is end of episode. - bool _stopOnComplete = false; - - /// Sleep timer timer. - Timer _stopTimer; - - /// Sleep timer time left. - int _timeLeft = 0; - - /// Start sleep timer. - bool _startSleepTimer = false; - - /// Control sleep timer anamation. - double _switchValue = 0; - - /// Sleep timer mode. - SleepTimerMode _sleepTimerMode = SleepTimerMode.undefined; - - //Auto stop at the end of episode when you start play at scheduled time. - bool _autoSleepTimer; - - //set autoplay episode in playlist - bool _autoPlay; - - /// Datetime now. - DateTime _current; - - /// Current position. - int _currentPosition; - - /// Current speed. - double _currentSpeed = 1; - - ///Update episode card when setting changed - bool _episodeState = false; - - /// Player height. - PlayerHeight _playerHeight; - - /// Player skip silence. - bool _skipSilence; - - /// Boost volumn - bool _boostVolume; - - /// Boost volume gain. - int _volumeGain; - - // ignore: prefer_final_fields - bool _playerRunning = false; - - bool _markListened; - - AudioProcessingState get audioState => _audioState; - int get backgroundAudioDuration => _backgroundAudioDuration; - int get backgroundAudioPosition => _backgroundAudioPosition; - double get seekSliderValue => _seekSliderValue; - String get remoteErrorMessage => _remoteErrorMessage; - bool get playerRunning => _playerRunning; - bool get buffering => _audioState != AudioProcessingState.ready; - int get lastPositin => _lastPostion; - Playlist get queue => _queue; - bool get playing => _playing; - bool get queueUpdate => _queueUpdate; - EpisodeBrief get episode => _episode; - bool get stopOnComplete => _stopOnComplete; - bool get startSleepTimer => _startSleepTimer; - SleepTimerMode get sleepTimerMode => _sleepTimerMode; - int get timeLeft => _timeLeft; - double get switchValue => _switchValue; - double get currentSpeed => _currentSpeed; - bool get episodeState => _episodeState; - bool get autoSleepTimer => _autoSleepTimer; - int get fastForwardSeconds => _fastForwardSeconds; - int get rewindSeconds => _rewindSeconds; - PlayerHeight get playerHeight => _playerHeight; - bool get skipSilence => _skipSilence; - bool get boostVolume => _boostVolume; - int get volumeGain => _volumeGain; - - set setSwitchValue(double value) { - _switchValue = value; - notifyListeners(); - } - - set setEpisodeState(bool boo) { - _episodeState = !_episodeState; - notifyListeners(); - } - - set setPlayerHeight(PlayerHeight mode) { - _playerHeight = mode; - notifyListeners(); - _savePlayerHeight(); - } - - set setVolumeGain(int volumeGain) { - _volumeGain = volumeGain; - if (_playerRunning && _boostVolume) { - setBoostVolume(boostVolume: _boostVolume, gain: _volumeGain); - } - notifyListeners(); - _volumeGainStorage.saveInt(volumeGain); - } - - Future _initAudioData() async { - var index = await _playerHeightStorage.getInt(defaultValue: 0); - _playerHeight = PlayerHeight.values[index]; - _currentSpeed = await _speedStorage.getDoubel(defaultValue: 1.0); - _skipSilence = await _skipSilenceStorage.getBool(defaultValue: false); - _boostVolume = await _boostVolumeStorage.getBool(defaultValue: false); - _volumeGain = await _volumeGainStorage.getInt(defaultValue: 3000); - } - - Future _savePlayerHeight() async { - await _playerHeightStorage.saveInt(_playerHeight.index); - } - - Future _getAutoPlay() async { - var i = await _autoPlayStorage.getInt(); - _autoPlay = i == 0; - } - - Future _getAutoSleepTimer() async { - var i = await _autoSleepTimerStorage.getInt(); - _autoSleepTimer = i == 1; - } - - set setSleepTimerMode(SleepTimerMode timer) { - _sleepTimerMode = timer; - notifyListeners(); - } - - @override - void addListener(VoidCallback listener) { - super.addListener(listener); - _initAudioData(); - AudioService.connect(); - var running = AudioService.running; - if (running) {} - } - - Future loadPlaylist() async { - _queue = Playlist(); - await _queue.getPlaylist(); - await _getAutoPlay(); - _lastPostion = await _positionStorage.getInt(); - if (_lastPostion > 0 && _queue.playlist.length > 0) { - final episode = _queue.playlist.first; - final duration = episode.duration * 1000; - final seekValue = duration != 0 ? _lastPostion / duration : 1.0; - final history = PlayHistory( - episode.title, episode.enclosureUrl, _lastPostion ~/ 1000, seekValue); - await dbHelper.saveHistory(history); - } - var lastWorkStorage = KeyValueStorage(lastWorkKey); - await lastWorkStorage.saveInt(0); - } - - Future playlistLoad() async { - await _queue.getPlaylist(); - _backgroundAudioDuration = 0; - _backgroundAudioPosition = 0; - _seekSliderValue = 0; - _episode = _queue.playlist.first; - _queueUpdate = !_queueUpdate; - _audioState = AudioProcessingState.none; - _playerRunning = true; - notifyListeners(); - _startAudioService(_lastPostion ?? 0, _queue.playlist.first.enclosureUrl); - } - - Future episodeLoad(EpisodeBrief episode, - {int startPosition = 0}) async { - final episodeNew = await dbHelper.getRssItemWithUrl(episode.enclosureUrl); - //TODO load episode from last position when player running - if (playerRunning) { - final history = PlayHistory(_episode.title, _episode.enclosureUrl, - backgroundAudioPosition ~/ 1000, seekSliderValue); - await dbHelper.saveHistory(history); - await AudioService.addQueueItemAt(episodeNew.toMediaItem(), 0); - if (startPosition > 0) { - await AudioService.seekTo(Duration(milliseconds: startPosition)); - } - _queue.playlist.removeAt(0); - _queue.playlist.removeWhere((item) => item == episode); - _queue.playlist.insert(0, episodeNew); - _queueUpdate != _queueUpdate; - _remoteErrorMessage = null; - notifyListeners(); - await _queue.savePlaylist(); - if (episodeNew.isNew == 1) { - await dbHelper.removeEpisodeNewMark(episodeNew.enclosureUrl); - } - } else { - await _queue.getPlaylist(); - await _queue.addToPlayListAt(episodeNew, 0); - _backgroundAudioDuration = 0; - _backgroundAudioPosition = 0; - _seekSliderValue = 0; - _episode = episodeNew; - _playerRunning = true; - notifyListeners(); - _startAudioService(startPosition, episodeNew.enclosureUrl); - } - } - - Future _startAudioService(int position, String url) async { - _stopOnComplete = false; - _sleepTimerMode = SleepTimerMode.undefined; - _switchValue = 0; - - /// Connect to audio service. - if (!AudioService.connected) { - await AudioService.connect(); - } - - /// Get fastword and rewind seconds. - _fastForwardSeconds = - await _fastForwardSecondsStorage.getInt(defaultValue: 30); - _rewindSeconds = await _rewindSecondsStorage.getInt(defaultValue: 10); - - /// Get if auto mark listened after skip - _markListened = - await _markListenedAfterSkipStorage.getBool(defaultValue: false); - - /// Start audio service. - await AudioService.start( - backgroundTaskEntrypoint: _audioPlayerTaskEntrypoint, - androidNotificationChannelName: 'Tsacdop', - androidNotificationColor: 0xFF4d91be, - androidNotificationIcon: 'drawable/ic_notification', - androidEnableQueue: true, - androidStopForegroundOnPause: true, - fastForwardInterval: Duration(seconds: _fastForwardSeconds), - rewindInterval: Duration(seconds: _rewindSeconds)); - - //Check autoplay setting, if true only add one episode, else add playlist. - await _getAutoPlay(); - if (_autoPlay) { - for (var episode in _queue.playlist) { - await AudioService.addQueueItem(episode.toMediaItem()); - } - } else { - await AudioService.addQueueItem(_queue.playlist.first.toMediaItem()); - } - //Check auto sleep timer setting - await _getAutoSleepTimer(); - if (_autoSleepTimer) { - var startTime = - await _autoSleepTimerStartStorage.getInt(defaultValue: 1380); - var endTime = await _autoSleepTimerEndStorage.getInt(defaultValue: 360); - var currentTime = DateTime.now().hour * 60 + DateTime.now().minute; - if ((startTime > endTime && - (currentTime > startTime || currentTime < endTime)) || - ((startTime < endTime) && - (currentTime > startTime && currentTime < endTime))) { - var mode = await _autoSleepTimerModeStorage.getInt(); - _sleepTimerMode = SleepTimerMode.values[mode]; - var defaultTimer = - await _defaultSleepTimerStorage.getInt(defaultValue: 30); - sleepTimer(defaultTimer); - } - } - - /// Set player speed. - if (_currentSpeed != 1.0) { - await AudioService.customAction('setSpeed', _currentSpeed); - } - - /// Set slipsilence. - if (_skipSilence) { - await AudioService.customAction('setSkipSilence', skipSilence); - } - - /// Set boostValome. - if (_boostVolume) { - await AudioService.customAction( - 'setBoostVolume', [_boostVolume, _volumeGain]); - } - - await AudioService.play(); - - AudioService.currentMediaItemStream - .where((event) => event != null) - .listen((item) async { - var episode = await dbHelper.getRssItemWithMediaId(item.id); - - _backgroundAudioDuration = item.duration?.inMilliseconds ?? 0; - if (episode != null) { - _episode = episode; - _backgroundAudioDuration = item.duration.inMilliseconds ?? 0; - if (position > 0 && - _backgroundAudioDuration > 0 && - _episode.enclosureUrl == url) { - await AudioService.seekTo(Duration(milliseconds: position)); - position = 0; - } - notifyListeners(); - } else { - // _queue.playlist.removeAt(0); - AudioService.skipToNext(); - } - }); - AudioService.playbackStateStream - .distinct() - .where((event) => event != null) - .listen((event) async { - _current = DateTime.now(); - _audioState = event.processingState; - _playing = event?.playing; - _currentSpeed = event.speed; - _currentPosition = event.currentPosition.inMilliseconds ?? 0; - - if (_audioState == AudioProcessingState.stopped) { - if (_switchValue > 0) _switchValue = 0; - } - - /// Get error state. - if (_audioState == AudioProcessingState.error) { - _remoteErrorMessage = 'Network Error'; - } - - /// Reset error state. - if (_audioState != AudioProcessingState.error) { - _remoteErrorMessage = null; - } - notifyListeners(); - }); - - AudioService.customEventStream.distinct().listen((event) async { - if (event is String && - _queue.playlist.isNotEmpty && - _queue.playlist.first.title == event) { - _queue.delFromPlaylist(_episode); - _lastPostion = 0; - notifyListeners(); - await _positionStorage.saveInt(_lastPostion); - var history; - if (_markListened) { - history = PlayHistory(_episode.title, _episode.enclosureUrl, - _backgroundAudioPosition ~/ 1000, 1); - } else { - history = PlayHistory(_episode.title, _episode.enclosureUrl, - _backgroundAudioPosition ~/ 1000, _seekSliderValue); - } - await dbHelper.saveHistory(history); - } - if (event is Map && event['playerRunning'] == false && _playerRunning) { - _playerRunning = false; - notifyListeners(); - if (_lastPostion > 0) { - final history = PlayHistory(_episode.title, _episode.enclosureUrl, - _lastPostion ~/ 1000, _seekSliderValue); - await dbHelper.saveHistory(history); - } - _episode = null; - } - }); - - //double s = _currentSpeed ?? 1.0; - var getPosition = 0; - Timer.periodic(Duration(milliseconds: 500), (timer) { - var s = _currentSpeed ?? 1.0; - if (_noSlide) { - if (_playing && !buffering) { - getPosition = _currentPosition + - ((DateTime.now().difference(_current).inMilliseconds) * s) - .toInt(); - _backgroundAudioPosition = - math.min(getPosition, _backgroundAudioDuration); - } else { - _backgroundAudioPosition = _currentPosition ?? 0; - } - - if (_backgroundAudioDuration != null && - _backgroundAudioDuration != 0 && - _backgroundAudioPosition != null) { - _seekSliderValue = - _backgroundAudioPosition / _backgroundAudioDuration ?? 0; - } else { - _seekSliderValue = 0; - } - - if (_backgroundAudioPosition > 0 && - _backgroundAudioPosition < _backgroundAudioDuration) { - _lastPostion = _backgroundAudioPosition; - _positionStorage.saveInt(_lastPostion); - } - notifyListeners(); - } - if (_audioState == AudioProcessingState.stopped) { - timer.cancel(); - } - }); - } - - Future playNext() async { - _remoteErrorMessage = null; - await AudioService.skipToNext(); - _queueUpdate = !_queueUpdate; - notifyListeners(); - } - - Future addToPlaylist(EpisodeBrief episode) async { - var episodeNew = await dbHelper.getRssItemWithUrl(episode.enclosureUrl); - if (!_queue.playlist.contains(episodeNew)) { - if (playerRunning) { - await AudioService.addQueueItem(episodeNew.toMediaItem()); - } - await _queue.addToPlayList(episodeNew); - _queueUpdate = !_queueUpdate; - notifyListeners(); - } - } - - Future addToPlaylistAt(EpisodeBrief episode, int index) async { - var episodeNew = await dbHelper.getRssItemWithUrl(episode.enclosureUrl); - if (playerRunning) { - await AudioService.addQueueItemAt(episodeNew.toMediaItem(), index); - } - await _queue.addToPlayListAt(episodeNew, index); - _queueUpdate = !_queueUpdate; - notifyListeners(); - } - - Future addNewEpisode(List group) async { - var newEpisodes = []; - if (group.isEmpty) { - newEpisodes = await dbHelper.getRecentNewRssItem(); - } else { - newEpisodes = await dbHelper.getGroupNewRssItem(group); - } - if (newEpisodes.length > 0 && newEpisodes.length < 100) { - for (var episode in newEpisodes) { - await addToPlaylist(episode); - } - } - if (group.isEmpty) { - await dbHelper.removeAllNewMark(); - } else { - await dbHelper.removeGroupNewMark(group); - } - } - - Future updateMediaItem(EpisodeBrief episode) async { - if (episode.enclosureUrl == episode.mediaId) { - var index = _queue.playlist - .indexWhere((item) => item.enclosureUrl == episode.enclosureUrl); - if (index > 0) { - var episodeNew = await dbHelper.getRssItemWithUrl(episode.enclosureUrl); - await delFromPlaylist(episode); - await addToPlaylistAt(episodeNew, index); - } - } - } - - Future delFromPlaylist(EpisodeBrief episode) async { - var episodeNew = await dbHelper.getRssItemWithUrl(episode.enclosureUrl); - if (playerRunning) { - await AudioService.removeQueueItem(episodeNew.toMediaItem()); - } - var index = await _queue.delFromPlaylist(episodeNew); - if (index == 0) { - _lastPostion = 0; - await _positionStorage.saveInt(0); - } - _queueUpdate = !_queueUpdate; - notifyListeners(); - return index; - } - - Future reorderPlaylist(int oldIndex, int newIndex) async { - var episode = _queue.playlist[oldIndex]; - if (playerRunning) { - await AudioService.removeQueueItem(episode.toMediaItem()); - await AudioService.addQueueItemAt(episode.toMediaItem(), newIndex); - } - await _queue.addToPlayListAt(episode, newIndex); - if (newIndex == 0) { - _lastPostion = 0; - await _positionStorage.saveInt(0); - } - } - - Future moveToTop(EpisodeBrief episode) async { - await delFromPlaylist(episode); - if (playerRunning) { - await AudioService.addQueueItemAt(episode.toMediaItem(), 1); - await _queue.addToPlayListAt(episode, 1, existed: false); - } else { - await _queue.addToPlayListAt(episode, 0, existed: false); - _lastPostion = 0; - _positionStorage.saveInt(_lastPostion); - } - _queueUpdate = !_queueUpdate; - notifyListeners(); - return true; - } - - Future pauseAduio() async { - await AudioService.pause(); - } - - Future resumeAudio() async { - _remoteErrorMessage = null; - notifyListeners(); - if (_audioState != AudioProcessingState.connecting && - _audioState != AudioProcessingState.none) { - AudioService.play(); - } - } - - Future forwardAudio(int s) async { - var pos = _backgroundAudioPosition + s * 1000; - await AudioService.seekTo(Duration(milliseconds: pos)); - } - - Future fastForward() async { - await AudioService.fastForward(); - } - - Future rewind() async { - await AudioService.rewind(); - } - - Future seekTo(int position) async { - if (_audioState != AudioProcessingState.connecting && - _audioState != AudioProcessingState.none) { - await AudioService.seekTo(Duration(milliseconds: position)); - } - } - - Future sliderSeek(double val) async { - if (_audioState != AudioProcessingState.connecting && - _audioState != AudioProcessingState.none) { - _noSlide = false; - _seekSliderValue = val; - notifyListeners(); - _currentPosition = (val * _backgroundAudioDuration).toInt(); - await AudioService.seekTo(Duration(milliseconds: _currentPosition)); - _noSlide = true; - } - } - - /// Set player speed. - Future setSpeed(double speed) async { - await AudioService.customAction('setSpeed', speed); - _currentSpeed = speed; - await _speedStorage.saveDouble(_currentSpeed); - notifyListeners(); - } - - Future setSkipSilence({@required bool skipSilence}) async { - await AudioService.customAction('setSkipSilence', skipSilence); - _skipSilence = skipSilence; - await _skipSilenceStorage.saveBool(_skipSilence); - notifyListeners(); - } - - Future setBoostVolume({@required bool boostVolume, int gain}) async { - await AudioService.customAction( - 'setBoostVolume', [boostVolume, _volumeGain]); - _boostVolume = boostVolume; - notifyListeners(); - await _boostVolumeStorage.saveBool(boostVolume); - } - - //Set sleep timer - void sleepTimer(int mins) { - if (_sleepTimerMode == SleepTimerMode.timer) { - _startSleepTimer = true; - _switchValue = 1; - notifyListeners(); - _timeLeft = mins * 60; - Timer.periodic(Duration(seconds: 1), (timer) { - if (_timeLeft == 0) { - timer.cancel(); - notifyListeners(); - } else { - _timeLeft = _timeLeft - 1; - notifyListeners(); - } - }); - _stopTimer = Timer(Duration(minutes: mins), () { - _stopOnComplete = false; - _startSleepTimer = false; - _switchValue = 0; - if (_playerRunning) { - AudioService.stop(); - } - notifyListeners(); - // AudioService.disconnect(); - }); - } else if (_sleepTimerMode == SleepTimerMode.endOfEpisode) { - _stopOnComplete = true; - _switchValue = 1; - notifyListeners(); - if (_queue.playlist.length > 1 && _autoPlay) { - AudioService.customAction('stopAtEnd'); - } - } - } - -//Cancel sleep timer - void cancelTimer() { - if (_sleepTimerMode == SleepTimerMode.timer) { - _stopTimer.cancel(); - _timeLeft = 0; - _startSleepTimer = false; - _switchValue = 0; - notifyListeners(); - } else if (_sleepTimerMode == SleepTimerMode.endOfEpisode) { - AudioService.customAction('cancelStopAtEnd'); - _switchValue = 0; - _stopOnComplete = false; - notifyListeners(); - } - } - - @override - void dispose() async { - await AudioService.disconnect(); - super.dispose(); - } -} - -class AudioPlayerTask extends BackgroundAudioTask { - final cacheStorage = KeyValueStorage(cacheMaxKey); - final layoutStorage = KeyValueStorage(notificationLayoutKey); - final List _queue = []; - final AudioPlayer _audioPlayer = AudioPlayer(); - AudioSession _session; - AudioProcessingState _skipState; - bool _playing; - bool _interrupted = false; - bool _stopAtEnd; - int _cacheMax; - bool get hasNext => _queue.length > 0; - - MediaItem get mediaItem => _queue.length > 0 ? _queue.first : null; - - StreamSubscription _playerStateSubscription; - StreamSubscription _eventSubscription; - - @override - Future onStart(Map params) async { - _stopAtEnd = false; - _session = await AudioSession.instance; - await _session.configure(AudioSessionConfiguration.speech()); - _handleInterruption(_session); - _playerStateSubscription = _audioPlayer.playbackStateStream - .where((state) => state == AudioPlaybackState.completed) - .listen((state) { - _handlePlaybackCompleted(); - }); - - _eventSubscription = _audioPlayer.playbackEventStream.listen((event) { - if (event.playbackError != null) { - _playing = false; - _setState(processingState: _skipState ?? AudioProcessingState.error); - } - final bufferingState = - event.buffering ? AudioProcessingState.buffering : null; - switch (event.state) { - case AudioPlaybackState.paused: - _setState( - processingState: bufferingState ?? AudioProcessingState.ready, - position: event.position, - ); - break; - case AudioPlaybackState.playing: - _setState( - processingState: bufferingState ?? AudioProcessingState.ready, - position: event.position, - ); - break; - case AudioPlaybackState.connecting: - _setState( - processingState: _skipState ?? AudioProcessingState.connecting, - position: event.position, - ); - break; - default: - break; - } - }); - } - - void _handlePlaybackCompleted() async { - if (hasNext) { - onSkipToNext(); - } else { - _audioPlayer.stop(); - _queue.removeAt(0); - await AudioServiceBackground.setQueue(_queue); - onStop(); - } - } - - void _handleInterruption(AudioSession session) async { - session.interruptionEventStream.listen((event) { - if (event.begin) { - switch (event.type) { - case AudioInterruptionType.pause: - if (_playing) { - onPause(); - _interrupted = true; - } - break; - case AudioInterruptionType.duck: - if (_playing) { - onPause(); - _interrupted = true; - } - break; - case AudioInterruptionType.unknown: - if (_playing) { - onPause(); - _interrupted = true; - } - break; - } - } else { - switch (event.type) { - case AudioInterruptionType.pause: - if (!_playing && _interrupted) { - onPlay(); - } - break; - case AudioInterruptionType.duck: - if (!_playing && _interrupted) { - onPlay(); - } - break; - case AudioInterruptionType.unknown: - break; - } - _interrupted = false; - } - }); - session.becomingNoisyEventStream.listen((_) { - if (_playing) onPause(); - }); - } - - void playPause() { - if (AudioServiceBackground.state.playing) { - onPause(); - } else { - onPlay(); - } - } - - @override - Future onSkipToNext() async { - _skipState = AudioProcessingState.skippingToNext; - _playing = false; - await _audioPlayer.stop(); - if (_queue.length > 0) { - AudioServiceBackground.sendCustomEvent(_queue.first.title); - _queue.removeAt(0); - } - await AudioServiceBackground.setQueue(_queue); - if (_queue.length == 0 || _stopAtEnd) { - _skipState = null; - await Future.delayed(Duration(milliseconds: 200)); - await onStop(); - } else { - await AudioServiceBackground.setQueue(_queue); - await AudioServiceBackground.setMediaItem(mediaItem); - await _audioPlayer.setUrl(mediaItem.id, cacheMax: _cacheMax); - var duration = await _audioPlayer.durationFuture; - if (duration != null) { - await AudioServiceBackground.setMediaItem( - mediaItem.copyWith(duration: duration)); - } - _skipState = null; - _playFromStart(); - } - } - - @override - Future onPlay() async { - if (_skipState == null) { - if (_playing == null) { - _playing = true; - _cacheMax = await cacheStorage.getInt( - defaultValue: (200 * 1024 * 1024).toInt()); - if (_cacheMax == 0) { - await cacheStorage.saveInt((200 * 1024 * 1024).toInt()); - _cacheMax = 200 * 1024 * 1024; - } - await _audioPlayer.setUrl(mediaItem.id, cacheMax: _cacheMax); - var duration = await _audioPlayer.durationFuture; - if (duration != null) { - await AudioServiceBackground.setMediaItem( - mediaItem.copyWith(duration: duration)); - } - _playFromStart(); - } else { - _playing = true; - _session.setActive(true); - if (_audioPlayer.playbackEvent.state != AudioPlaybackState.connecting || - _audioPlayer.playbackEvent.state != AudioPlaybackState.none) { - await _audioPlayer.play(); - await _seekRelative(Duration(seconds: -3)); - } - } - } - } - - Future _playFromStart() async { - _playing = true; - _session.setActive(true); - if (mediaItem.extras['skipSecondsStart'] > 0 || - mediaItem.extras['skipSecondsEnd'] > 0) { - _audioPlayer - .seek(Duration(seconds: mediaItem.extras['skipSecondsStart'])); - } - if (_audioPlayer.playbackEvent.state != AudioPlaybackState.connecting || - _audioPlayer.playbackEvent.state != AudioPlaybackState.none) { - try { - _audioPlayer.play(); - } catch (e) { - _setState(processingState: AudioProcessingState.error); - } - } - } - - @override - Future onPause() async { - if (_skipState == null) { - if (_playing == null) { - } else if (_playing) { - _playing = false; - _audioPlayer.pause(); - } - } - } - - @override - Future onSeekTo(Duration position) async { - if (_audioPlayer.playbackEvent.state != AudioPlaybackState.connecting || - _audioPlayer.playbackEvent.state != AudioPlaybackState.none) { - await _audioPlayer.seek(position); - } - } - - @override - Future onClick(MediaButton button) async { - switch (button) { - case MediaButton.media: - if (AudioServiceBackground.state?.playing == true) { - await onPause(); - } else { - await onPlay(); - } - break; - case MediaButton.next: - await onFastForward(); - break; - case MediaButton.previous: - await onRewind(); - break; - } - } - - Future _seekRelative(Duration offset) async { - var newPosition = _audioPlayer.playbackEvent.position + offset; - if (newPosition < Duration.zero) newPosition = Duration.zero; - onSeekTo(newPosition); - } - - @override - Future onStop() async { - await _audioPlayer.stop(); - await _audioPlayer.dispose(); - _playing = false; - _playerStateSubscription.cancel(); - _eventSubscription.cancel(); - await _setState(processingState: AudioProcessingState.none); - AudioServiceBackground.sendCustomEvent({'playerRunning': false}); - await super.onStop(); - } - - @override - Future onTaskRemoved() async { - await onStop(); - } - - @override - Future onAddQueueItem(MediaItem mediaItem) async { - _queue.add(mediaItem); - await AudioServiceBackground.setQueue(_queue); - } - - @override - Future onRemoveQueueItem(MediaItem mediaItem) async { - _queue.removeWhere((item) => item.id == mediaItem.id); - await AudioServiceBackground.setQueue(_queue); - } - - @override - Future onAddQueueItemAt(MediaItem mediaItem, int index) async { - if (index == 0) { - await _audioPlayer.stop(); - _queue.removeAt(0); - _queue.removeWhere((item) => item.id == mediaItem.id); - _queue.insert(0, mediaItem); - await AudioServiceBackground.setQueue(_queue); - await AudioServiceBackground.setMediaItem(mediaItem); - await _audioPlayer.setUrl(mediaItem.id, cacheMax: _cacheMax); - var duration = await _audioPlayer.durationFuture ?? Duration.zero; - AudioServiceBackground.setMediaItem( - mediaItem.copyWith(duration: duration)); - _playFromStart(); - //onPlay(); - } else { - _queue.insert(index, mediaItem); - await AudioServiceBackground.setQueue(_queue); - } - } - - @override - Future onFastForward() async { - await _seekRelative(fastForwardInterval); - } - - @override - Future onRewind() async { - await _seekRelative(-rewindInterval); - } - - @override - Future onCustomAction(funtion, argument) async { - switch (funtion) { - case 'stopAtEnd': - _stopAtEnd = true; - break; - case 'cancelStopAtEnd': - _stopAtEnd = false; - break; - case 'setSpeed': - await _audioPlayer.setSpeed(argument); - break; - case 'setSkipSilence': - await _setSkipSilence(argument); - break; - case 'setBoostVolume': - await _setBoostVolume(argument[0], argument[1]); - break; - } - } - - Future _setSkipSilence(bool boo) async { - await _audioPlayer.setSkipSilence(boo); - var duration = await _audioPlayer.durationFuture ?? Duration.zero; - AudioServiceBackground.setMediaItem(mediaItem.copyWith(duration: duration)); - } - - Future _setBoostVolume(bool boo, int gain) async { - await _audioPlayer.setBoostVolume(boo, gain: gain); - } - - Future _setState({ - AudioProcessingState processingState, - Duration position, - Duration bufferedPosition, - }) async { - if (position == null) { - position = _audioPlayer.playbackEvent.position; - } - final index = await layoutStorage.getInt(defaultValue: 0); - await AudioServiceBackground.setState( - controls: _getControls(index), - systemActions: [ - MediaAction.seekTo, - MediaAction.seekForward, - MediaAction.seekBackward, - ], - processingState: - processingState ?? AudioServiceBackground.state.processingState, - playing: _playing ?? false, - position: position, - bufferedPosition: bufferedPosition ?? position, - speed: _audioPlayer.speed, - ); - } - - List _getControls(int index) { - switch (index) { - case 0: - if (_playing) { - return [pauseControl, forward, skipToNextControl, stopControl]; - } else { - return [playControl, forward, skipToNextControl, stopControl]; - } - break; - case 1: - if (_playing) { - return [pauseControl, rewind, skipToNextControl, stopControl]; - } else { - return [playControl, rewind, skipToNextControl, stopControl]; - } - break; - case 2: - if (_playing) { - return [rewind, pauseControl, forward, stopControl]; - } else { - return [rewind, playControl, forward, stopControl]; - } - break; - default: - if (_playing) { - return [pauseControl, forward, skipToNextControl, stopControl]; - } else { - return [playControl, forward, skipToNextControl, stopControl]; - } - break; - } - } -} +import 'dart:async'; +import 'dart:math' as math; + +import 'package:audio_service/audio_service.dart'; +import 'package:audio_session/audio_session.dart'; +import 'package:dio/dio.dart'; +import 'package:flutter/foundation.dart'; +import 'package:just_audio/just_audio.dart'; + +import '../local_storage/key_value_storage.dart'; +import '../local_storage/sqflite_localpodcast.dart'; +import '../type/episodebrief.dart'; +import '../type/play_histroy.dart'; +import '../type/playlist.dart'; + +MediaControl playControl = MediaControl( + androidIcon: 'drawable/ic_stat_play_circle_filled', + label: 'Play', + action: MediaAction.play, +); +MediaControl pauseControl = MediaControl( + androidIcon: 'drawable/ic_stat_pause_circle_filled', + label: 'Pause', + action: MediaAction.pause, +); +MediaControl skipToNextControl = MediaControl( + androidIcon: 'drawable/baseline_skip_next_white_24', + label: 'Next', + action: MediaAction.skipToNext, +); +MediaControl skipToPreviousControl = MediaControl( + androidIcon: 'drawable/ic_action_skip_previous', + label: 'Previous', + action: MediaAction.skipToPrevious, +); +MediaControl stopControl = MediaControl( + androidIcon: 'drawable/baseline_close_white_24', + label: 'Stop', + action: MediaAction.stop, +); +MediaControl forward = MediaControl( + androidIcon: 'drawable/baseline_fast_forward_white_24', + label: 'forward', + action: MediaAction.fastForward, +); + +MediaControl rewind = MediaControl( + androidIcon: 'drawable/baseline_fast_rewind_white_24', + label: 'rewind', + action: MediaAction.rewind, +); + +void _audioPlayerTaskEntrypoint() async { + AudioServiceBackground.run(() => AudioPlayerTask()); +} + +/// Sleep timer mode. +enum SleepTimerMode { endOfEpisode, timer, undefined } +enum PlayerHeight { short, mid, tall } +//enum ShareStatus { generate, download, complete, undefined, error } + +class AudioPlayerNotifier extends ChangeNotifier { + DBHelper dbHelper = DBHelper(); + final _positionStorage = KeyValueStorage(audioPositionKey); + final _autoPlayStorage = KeyValueStorage(autoPlayKey); + final _autoSleepTimerStorage = KeyValueStorage(autoSleepTimerKey); + final _defaultSleepTimerStorage = KeyValueStorage(defaultSleepTimerKey); + final _autoSleepTimerModeStorage = KeyValueStorage(autoSleepTimerModeKey); + final _autoSleepTimerStartStorage = KeyValueStorage(autoSleepTimerStartKey); + final _autoSleepTimerEndStorage = KeyValueStorage(autoSleepTimerEndKey); + final _fastForwardSecondsStorage = KeyValueStorage(fastForwardSecondsKey); + final _rewindSecondsStorage = KeyValueStorage(rewindSecondsKey); + final _playerHeightStorage = KeyValueStorage(playerHeightKey); + final _speedStorage = KeyValueStorage(speedKey); + final _skipSilenceStorage = KeyValueStorage(skipSilenceKey); + final _boostVolumeStorage = KeyValueStorage(boostVolumeKey); + final _volumeGainStorage = KeyValueStorage(volumeGainKey); + final _markListenedAfterSkipStorage = + KeyValueStorage(markListenedAfterSkipKey); + + /// Current playing episdoe. + EpisodeBrief _episode; + + /// Current playlist. + Playlist _queue; + + /// Notifier for playlist change. + bool _queueUpdate = false; + + /// Player state. + AudioProcessingState _audioState = AudioProcessingState.none; + + /// Player playing. + bool _playing = false; + + /// Fastforward second. + int _fastForwardSeconds = 0; + + /// Rewind seconds. + int _rewindSeconds = 0; + + /// No slide, set true if slide on seekbar. + bool _noSlide = true; + + /// Current episode duration. + int _backgroundAudioDuration = 0; + + /// Current episode positin. + int _backgroundAudioPosition = 0; + + /// Erroe maeesage. + String _remoteErrorMessage; + + /// Seekbar value, min 0, max 1.0. + double _seekSliderValue = 0.0; + + /// Record plyaer position. + int _lastPostion = 0; + + /// Set true if sleep timer mode is end of episode. + bool _stopOnComplete = false; + + /// Sleep timer timer. + Timer _stopTimer; + + /// Sleep timer time left. + int _timeLeft = 0; + + /// Start sleep timer. + bool _startSleepTimer = false; + + /// Control sleep timer anamation. + double _switchValue = 0; + + /// Sleep timer mode. + SleepTimerMode _sleepTimerMode = SleepTimerMode.undefined; + + //Auto stop at the end of episode when you start play at scheduled time. + bool _autoSleepTimer; + + //set autoplay episode in playlist + bool _autoPlay; + + /// Datetime now. + DateTime _current; + + /// Current position. + int _currentPosition; + + /// Current speed. + double _currentSpeed = 1; + + ///Update episode card when setting changed + bool _episodeState = false; + + /// Player height. + PlayerHeight _playerHeight; + + /// Player skip silence. + bool _skipSilence; + + /// Boost volumn + bool _boostVolume; + + /// Boost volume gain. + int _volumeGain; + + // ignore: prefer_final_fields + bool _playerRunning = false; + + bool _markListened; + + AudioProcessingState get audioState => _audioState; + int get backgroundAudioDuration => _backgroundAudioDuration; + int get backgroundAudioPosition => _backgroundAudioPosition; + double get seekSliderValue => _seekSliderValue; + String get remoteErrorMessage => _remoteErrorMessage; + bool get playerRunning => _playerRunning; + bool get buffering => _audioState != AudioProcessingState.ready; + int get lastPositin => _lastPostion; + Playlist get queue => _queue; + bool get playing => _playing; + bool get queueUpdate => _queueUpdate; + EpisodeBrief get episode => _episode; + bool get stopOnComplete => _stopOnComplete; + bool get startSleepTimer => _startSleepTimer; + SleepTimerMode get sleepTimerMode => _sleepTimerMode; + int get timeLeft => _timeLeft; + double get switchValue => _switchValue; + double get currentSpeed => _currentSpeed; + bool get episodeState => _episodeState; + bool get autoSleepTimer => _autoSleepTimer; + int get fastForwardSeconds => _fastForwardSeconds; + int get rewindSeconds => _rewindSeconds; + PlayerHeight get playerHeight => _playerHeight; + bool get skipSilence => _skipSilence; + bool get boostVolume => _boostVolume; + int get volumeGain => _volumeGain; + + set setSwitchValue(double value) { + _switchValue = value; + notifyListeners(); + } + + set setEpisodeState(bool boo) { + _episodeState = !_episodeState; + notifyListeners(); + } + + set setPlayerHeight(PlayerHeight mode) { + _playerHeight = mode; + notifyListeners(); + _savePlayerHeight(); + } + + set setVolumeGain(int volumeGain) { + _volumeGain = volumeGain; + if (_playerRunning && _boostVolume) { + setBoostVolume(boostVolume: _boostVolume, gain: _volumeGain); + } + notifyListeners(); + _volumeGainStorage.saveInt(volumeGain); + } + + Future _initAudioData() async { + var index = await _playerHeightStorage.getInt(defaultValue: 0); + _playerHeight = PlayerHeight.values[index]; + _currentSpeed = await _speedStorage.getDoubel(defaultValue: 1.0); + _skipSilence = await _skipSilenceStorage.getBool(defaultValue: false); + _boostVolume = await _boostVolumeStorage.getBool(defaultValue: false); + _volumeGain = await _volumeGainStorage.getInt(defaultValue: 3000); + } + + Future _savePlayerHeight() async { + await _playerHeightStorage.saveInt(_playerHeight.index); + } + + Future _getAutoPlay() async { + var i = await _autoPlayStorage.getInt(); + _autoPlay = i == 0; + } + + Future _getAutoSleepTimer() async { + var i = await _autoSleepTimerStorage.getInt(); + _autoSleepTimer = i == 1; + } + + set setSleepTimerMode(SleepTimerMode timer) { + _sleepTimerMode = timer; + notifyListeners(); + } + + @override + void addListener(VoidCallback listener) { + super.addListener(listener); + _initAudioData(); + AudioService.connect(); + var running = AudioService.running; + if (running) {} + } + + Future loadPlaylist() async { + _queue = Playlist(); + await _queue.getPlaylist(); + await _getAutoPlay(); + _lastPostion = await _positionStorage.getInt(); + if (_lastPostion > 0 && _queue.playlist.length > 0) { + final episode = _queue.playlist.first; + final duration = episode.duration * 1000; + final seekValue = duration != 0 ? _lastPostion / duration : 1.0; + final history = PlayHistory( + episode.title, episode.enclosureUrl, _lastPostion ~/ 1000, seekValue); + await dbHelper.saveHistory(history); + } + var lastWorkStorage = KeyValueStorage(lastWorkKey); + await lastWorkStorage.saveInt(0); + } + + Future playlistLoad() async { + await _queue.getPlaylist(); + _backgroundAudioDuration = 0; + _backgroundAudioPosition = 0; + _seekSliderValue = 0; + _episode = _queue.playlist.first; + _queueUpdate = !_queueUpdate; + _audioState = AudioProcessingState.none; + _playerRunning = true; + notifyListeners(); + _startAudioService(_lastPostion ?? 0, _queue.playlist.first.enclosureUrl); + } + + Future episodeLoad(EpisodeBrief episode, + {int startPosition = 0}) async { + final episodeNew = await dbHelper.getRssItemWithUrl(episode.enclosureUrl); + //TODO load episode from last position when player running + if (playerRunning) { + final history = PlayHistory(_episode.title, _episode.enclosureUrl, + backgroundAudioPosition ~/ 1000, seekSliderValue); + await dbHelper.saveHistory(history); + await AudioService.addQueueItemAt(episodeNew.toMediaItem(), 0); + if (startPosition > 0) { + await AudioService.seekTo(Duration(milliseconds: startPosition)); + } + _queue.playlist.removeAt(0); + _queue.playlist.removeWhere((item) => item == episode); + _queue.playlist.insert(0, episodeNew); + _queueUpdate != _queueUpdate; + _remoteErrorMessage = null; + notifyListeners(); + await _queue.savePlaylist(); + if (episodeNew.isNew == 1) { + await dbHelper.removeEpisodeNewMark(episodeNew.enclosureUrl); + } + } else { + await _queue.getPlaylist(); + await _queue.addToPlayListAt(episodeNew, 0); + _backgroundAudioDuration = 0; + _backgroundAudioPosition = 0; + _seekSliderValue = 0; + _episode = episodeNew; + _playerRunning = true; + notifyListeners(); + _startAudioService(startPosition, episodeNew.enclosureUrl); + } + } + + Future _startAudioService(int position, String url) async { + _stopOnComplete = false; + _sleepTimerMode = SleepTimerMode.undefined; + _switchValue = 0; + + /// Connect to audio service. + if (!AudioService.connected) { + await AudioService.connect(); + } + + /// Get fastword and rewind seconds. + _fastForwardSeconds = + await _fastForwardSecondsStorage.getInt(defaultValue: 30); + _rewindSeconds = await _rewindSecondsStorage.getInt(defaultValue: 10); + + /// Get if auto mark listened after skip + _markListened = + await _markListenedAfterSkipStorage.getBool(defaultValue: false); + + /// Start audio service. + await AudioService.start( + backgroundTaskEntrypoint: _audioPlayerTaskEntrypoint, + androidNotificationChannelName: 'Tsacdop', + androidNotificationColor: 0xFF4d91be, + androidNotificationIcon: 'drawable/ic_notification', + androidEnableQueue: true, + androidStopForegroundOnPause: true, + fastForwardInterval: Duration(seconds: _fastForwardSeconds), + rewindInterval: Duration(seconds: _rewindSeconds)); + + //Check autoplay setting, if true only add one episode, else add playlist. + await _getAutoPlay(); + if (_autoPlay) { + for (var episode in _queue.playlist) { + await AudioService.addQueueItem(episode.toMediaItem()); + } + } else { + await AudioService.addQueueItem(_queue.playlist.first.toMediaItem()); + } + //Check auto sleep timer setting + await _getAutoSleepTimer(); + if (_autoSleepTimer) { + var startTime = + await _autoSleepTimerStartStorage.getInt(defaultValue: 1380); + var endTime = await _autoSleepTimerEndStorage.getInt(defaultValue: 360); + var currentTime = DateTime.now().hour * 60 + DateTime.now().minute; + if ((startTime > endTime && + (currentTime > startTime || currentTime < endTime)) || + ((startTime < endTime) && + (currentTime > startTime && currentTime < endTime))) { + var mode = await _autoSleepTimerModeStorage.getInt(); + _sleepTimerMode = SleepTimerMode.values[mode]; + var defaultTimer = + await _defaultSleepTimerStorage.getInt(defaultValue: 30); + sleepTimer(defaultTimer); + } + } + + /// Set player speed. + if (_currentSpeed != 1.0) { + await AudioService.customAction('setSpeed', _currentSpeed); + } + + /// Set slipsilence. + if (_skipSilence) { + await AudioService.customAction('setSkipSilence', skipSilence); + } + + /// Set boostValome. + if (_boostVolume) { + await AudioService.customAction( + 'setBoostVolume', [_boostVolume, _volumeGain]); + } + + await AudioService.play(); + + AudioService.currentMediaItemStream + .where((event) => event != null) + .listen((item) async { + var episode = await dbHelper.getRssItemWithMediaId(item.id); + + _backgroundAudioDuration = item.duration?.inMilliseconds ?? 0; + if (episode != null) { + _episode = episode; + _backgroundAudioDuration = item.duration.inMilliseconds ?? 0; + if (position > 0 && + _backgroundAudioDuration > 0 && + _episode.enclosureUrl == url) { + await AudioService.seekTo(Duration(milliseconds: position)); + position = 0; + } + notifyListeners(); + } else { + // _queue.playlist.removeAt(0); + AudioService.skipToNext(); + } + }); + AudioService.playbackStateStream + .distinct() + .where((event) => event != null) + .listen((event) async { + _current = DateTime.now(); + _audioState = event.processingState; + _playing = event?.playing; + _currentSpeed = event.speed; + _currentPosition = event.currentPosition.inMilliseconds ?? 0; + + if (_audioState == AudioProcessingState.stopped) { + if (_switchValue > 0) _switchValue = 0; + } + + /// Get error state. + if (_audioState == AudioProcessingState.error) { + _remoteErrorMessage = 'Network Error'; + } + + /// Reset error state. + if (_audioState != AudioProcessingState.error) { + _remoteErrorMessage = null; + } + notifyListeners(); + }); + + AudioService.customEventStream.distinct().listen((event) async { + if (event is String && + _queue.playlist.isNotEmpty && + _queue.playlist.first.title == event) { + _queue.delFromPlaylist(_episode); + _lastPostion = 0; + notifyListeners(); + await _positionStorage.saveInt(_lastPostion); + var history; + if (_markListened) { + history = PlayHistory(_episode.title, _episode.enclosureUrl, + _backgroundAudioPosition ~/ 1000, 1); + } else { + history = PlayHistory(_episode.title, _episode.enclosureUrl, + _backgroundAudioPosition ~/ 1000, _seekSliderValue); + } + await dbHelper.saveHistory(history); + } + if (event is Map && event['playerRunning'] == false && _playerRunning) { + _playerRunning = false; + notifyListeners(); + if (_lastPostion > 0) { + final history = PlayHistory(_episode.title, _episode.enclosureUrl, + _lastPostion ~/ 1000, _seekSliderValue); + await dbHelper.saveHistory(history); + } + _episode = null; + } + }); + + //double s = _currentSpeed ?? 1.0; + var getPosition = 0; + Timer.periodic(Duration(milliseconds: 500), (timer) { + var s = _currentSpeed ?? 1.0; + if (_noSlide) { + if (_playing && !buffering) { + getPosition = _currentPosition + + ((DateTime.now().difference(_current).inMilliseconds) * s) + .toInt(); + _backgroundAudioPosition = + math.min(getPosition, _backgroundAudioDuration); + } else { + _backgroundAudioPosition = _currentPosition ?? 0; + } + + if (_backgroundAudioDuration != null && + _backgroundAudioDuration != 0 && + _backgroundAudioPosition != null) { + _seekSliderValue = + _backgroundAudioPosition / _backgroundAudioDuration ?? 0; + } else { + _seekSliderValue = 0; + } + + if (_backgroundAudioPosition > 0 && + _backgroundAudioPosition < _backgroundAudioDuration) { + _lastPostion = _backgroundAudioPosition; + _positionStorage.saveInt(_lastPostion); + } + notifyListeners(); + } + if (_audioState == AudioProcessingState.stopped) { + timer.cancel(); + } + }); + } + + Future playNext() async { + _remoteErrorMessage = null; + await AudioService.skipToNext(); + _queueUpdate = !_queueUpdate; + notifyListeners(); + } + + Future addToPlaylist(EpisodeBrief episode) async { + var episodeNew = await dbHelper.getRssItemWithUrl(episode.enclosureUrl); + if (!_queue.playlist.contains(episodeNew)) { + if (playerRunning) { + await AudioService.addQueueItem(episodeNew.toMediaItem()); + } + await _queue.addToPlayList(episodeNew); + _queueUpdate = !_queueUpdate; + notifyListeners(); + } + } + + Future addToPlaylistAt(EpisodeBrief episode, int index) async { + var episodeNew = await dbHelper.getRssItemWithUrl(episode.enclosureUrl); + if (playerRunning) { + await AudioService.addQueueItemAt(episodeNew.toMediaItem(), index); + } + await _queue.addToPlayListAt(episodeNew, index); + _queueUpdate = !_queueUpdate; + notifyListeners(); + } + + Future addNewEpisode(List group) async { + var newEpisodes = []; + if (group.isEmpty) { + newEpisodes = await dbHelper.getRecentNewRssItem(); + } else { + newEpisodes = await dbHelper.getGroupNewRssItem(group); + } + if (newEpisodes.length > 0 && newEpisodes.length < 100) { + for (var episode in newEpisodes) { + await addToPlaylist(episode); + } + } + if (group.isEmpty) { + await dbHelper.removeAllNewMark(); + } else { + await dbHelper.removeGroupNewMark(group); + } + } + + Future updateMediaItem(EpisodeBrief episode) async { + if (episode.enclosureUrl == episode.mediaId) { + var index = _queue.playlist + .indexWhere((item) => item.enclosureUrl == episode.enclosureUrl); + if (index > 0) { + var episodeNew = await dbHelper.getRssItemWithUrl(episode.enclosureUrl); + await delFromPlaylist(episode); + await addToPlaylistAt(episodeNew, index); + } + } + } + + Future delFromPlaylist(EpisodeBrief episode) async { + var episodeNew = await dbHelper.getRssItemWithUrl(episode.enclosureUrl); + if (playerRunning) { + await AudioService.removeQueueItem(episodeNew.toMediaItem()); + } + var index = await _queue.delFromPlaylist(episodeNew); + if (index == 0) { + _lastPostion = 0; + await _positionStorage.saveInt(0); + } + _queueUpdate = !_queueUpdate; + notifyListeners(); + return index; + } + + Future reorderPlaylist(int oldIndex, int newIndex) async { + var episode = _queue.playlist[oldIndex]; + if (playerRunning) { + await AudioService.removeQueueItem(episode.toMediaItem()); + await AudioService.addQueueItemAt(episode.toMediaItem(), newIndex); + } + await _queue.addToPlayListAt(episode, newIndex); + if (newIndex == 0) { + _lastPostion = 0; + await _positionStorage.saveInt(0); + } + } + + Future moveToTop(EpisodeBrief episode) async { + await delFromPlaylist(episode); + if (playerRunning) { + await AudioService.addQueueItemAt(episode.toMediaItem(), 1); + await _queue.addToPlayListAt(episode, 1, existed: false); + } else { + await _queue.addToPlayListAt(episode, 0, existed: false); + _lastPostion = 0; + _positionStorage.saveInt(_lastPostion); + } + _queueUpdate = !_queueUpdate; + notifyListeners(); + return true; + } + + Future pauseAduio() async { + await AudioService.pause(); + } + + Future resumeAudio() async { + _remoteErrorMessage = null; + notifyListeners(); + if (_audioState != AudioProcessingState.connecting && + _audioState != AudioProcessingState.none) { + AudioService.play(); + } + } + + Future forwardAudio(int s) async { + var pos = _backgroundAudioPosition + s * 1000; + await AudioService.seekTo(Duration(milliseconds: pos)); + } + + Future fastForward() async { + await AudioService.fastForward(); + } + + Future rewind() async { + await AudioService.rewind(); + } + + Future seekTo(int position) async { + if (_audioState != AudioProcessingState.connecting && + _audioState != AudioProcessingState.none) { + await AudioService.seekTo(Duration(milliseconds: position)); + } + } + + Future sliderSeek(double val) async { + if (_audioState != AudioProcessingState.connecting && + _audioState != AudioProcessingState.none) { + _noSlide = false; + _seekSliderValue = val; + notifyListeners(); + _currentPosition = (val * _backgroundAudioDuration).toInt(); + await AudioService.seekTo(Duration(milliseconds: _currentPosition)); + _noSlide = true; + } + } + + /// Set player speed. + Future setSpeed(double speed) async { + await AudioService.customAction('setSpeed', speed); + _currentSpeed = speed; + await _speedStorage.saveDouble(_currentSpeed); + notifyListeners(); + } + + Future setSkipSilence({@required bool skipSilence}) async { + await AudioService.customAction('setSkipSilence', skipSilence); + _skipSilence = skipSilence; + await _skipSilenceStorage.saveBool(_skipSilence); + notifyListeners(); + } + + Future setBoostVolume({@required bool boostVolume, int gain}) async { + await AudioService.customAction( + 'setBoostVolume', [boostVolume, _volumeGain]); + _boostVolume = boostVolume; + notifyListeners(); + await _boostVolumeStorage.saveBool(boostVolume); + } + + //Set sleep timer + void sleepTimer(int mins) { + if (_sleepTimerMode == SleepTimerMode.timer) { + _startSleepTimer = true; + _switchValue = 1; + notifyListeners(); + _timeLeft = mins * 60; + Timer.periodic(Duration(seconds: 1), (timer) { + if (_timeLeft == 0) { + timer.cancel(); + notifyListeners(); + } else { + _timeLeft = _timeLeft - 1; + notifyListeners(); + } + }); + _stopTimer = Timer(Duration(minutes: mins), () { + _stopOnComplete = false; + _startSleepTimer = false; + _switchValue = 0; + if (_playerRunning) { + AudioService.stop(); + } + notifyListeners(); + // AudioService.disconnect(); + }); + } else if (_sleepTimerMode == SleepTimerMode.endOfEpisode) { + _stopOnComplete = true; + _switchValue = 1; + notifyListeners(); + if (_queue.playlist.length > 1 && _autoPlay) { + AudioService.customAction('stopAtEnd'); + } + } + } + +//Cancel sleep timer + void cancelTimer() { + if (_sleepTimerMode == SleepTimerMode.timer) { + _stopTimer.cancel(); + _timeLeft = 0; + _startSleepTimer = false; + _switchValue = 0; + notifyListeners(); + } else if (_sleepTimerMode == SleepTimerMode.endOfEpisode) { + AudioService.customAction('cancelStopAtEnd'); + _switchValue = 0; + _stopOnComplete = false; + notifyListeners(); + } + } + + @override + void dispose() async { + await AudioService.disconnect(); + super.dispose(); + } +} + +class AudioPlayerTask extends BackgroundAudioTask { + final cacheStorage = KeyValueStorage(cacheMaxKey); + final layoutStorage = KeyValueStorage(notificationLayoutKey); + final List _queue = []; + final AudioPlayer _audioPlayer = AudioPlayer(); + AudioSession _session; + AudioProcessingState _skipState; + bool _playing; + bool _interrupted = false; + bool _stopAtEnd; + int _cacheMax; + bool get hasNext => _queue.length > 0; + + MediaItem get mediaItem => _queue.length > 0 ? _queue.first : null; + + StreamSubscription _playerStateSubscription; + StreamSubscription _eventSubscription; + + @override + Future onStart(Map params) async { + _stopAtEnd = false; + _session = await AudioSession.instance; + await _session.configure(AudioSessionConfiguration.speech()); + _handleInterruption(_session); + _playerStateSubscription = _audioPlayer.playbackStateStream + .where((state) => state == AudioPlaybackState.completed) + .listen((state) { + _handlePlaybackCompleted(); + }); + + _eventSubscription = _audioPlayer.playbackEventStream.listen((event) { + if (event.playbackError != null) { + _playing = false; + _setState(processingState: _skipState ?? AudioProcessingState.error); + } + final bufferingState = + event.buffering ? AudioProcessingState.buffering : null; + switch (event.state) { + case AudioPlaybackState.paused: + _setState( + processingState: bufferingState ?? AudioProcessingState.ready, + position: event.position, + ); + break; + case AudioPlaybackState.playing: + _setState( + processingState: bufferingState ?? AudioProcessingState.ready, + position: event.position, + ); + break; + case AudioPlaybackState.connecting: + _setState( + processingState: _skipState ?? AudioProcessingState.connecting, + position: event.position, + ); + break; + default: + break; + } + }); + } + + void _handlePlaybackCompleted() async { + if (hasNext) { + onSkipToNext(); + } else { + _audioPlayer.stop(); + _queue.removeAt(0); + await AudioServiceBackground.setQueue(_queue); + onStop(); + } + } + + void _handleInterruption(AudioSession session) async { + session.interruptionEventStream.listen((event) { + if (event.begin) { + switch (event.type) { + case AudioInterruptionType.pause: + if (_playing) { + onPause(); + _interrupted = true; + } + break; + case AudioInterruptionType.duck: + if (_playing) { + onPause(); + _interrupted = true; + } + break; + case AudioInterruptionType.unknown: + if (_playing) { + onPause(); + _interrupted = true; + } + break; + } + } else { + switch (event.type) { + case AudioInterruptionType.pause: + if (!_playing && _interrupted) { + onPlay(); + } + break; + case AudioInterruptionType.duck: + if (!_playing && _interrupted) { + onPlay(); + } + break; + case AudioInterruptionType.unknown: + break; + } + _interrupted = false; + } + }); + session.becomingNoisyEventStream.listen((_) { + if (_playing) onPause(); + }); + } + + void playPause() { + if (AudioServiceBackground.state.playing) { + onPause(); + } else { + onPlay(); + } + } + + @override + Future onSkipToNext() async { + _skipState = AudioProcessingState.skippingToNext; + _playing = false; + await _audioPlayer.stop(); + if (_queue.length > 0) { + AudioServiceBackground.sendCustomEvent(_queue.first.title); + _queue.removeAt(0); + } + await AudioServiceBackground.setQueue(_queue); + if (_queue.length == 0 || _stopAtEnd) { + _skipState = null; + await Future.delayed(Duration(milliseconds: 200)); + await onStop(); + } else { + await AudioServiceBackground.setQueue(_queue); + await AudioServiceBackground.setMediaItem(mediaItem); + await _audioPlayer.setUrl(mediaItem.id, cacheMax: _cacheMax); + var duration = await _audioPlayer.durationFuture; + if (duration != null) { + await AudioServiceBackground.setMediaItem( + mediaItem.copyWith(duration: duration)); + } + _skipState = null; + _playFromStart(); + } + } + + @override + Future onPlay() async { + if (_skipState == null) { + if (_playing == null) { + _playing = true; + _cacheMax = await cacheStorage.getInt( + defaultValue: (200 * 1024 * 1024).toInt()); + if (_cacheMax == 0) { + await cacheStorage.saveInt((200 * 1024 * 1024).toInt()); + _cacheMax = 200 * 1024 * 1024; + } + await _audioPlayer.setUrl(mediaItem.id, cacheMax: _cacheMax); + var duration = await _audioPlayer.durationFuture; + if (duration != null) { + await AudioServiceBackground.setMediaItem( + mediaItem.copyWith(duration: duration)); + } + _playFromStart(); + } else { + _playing = true; + _session.setActive(true); + if (_audioPlayer.playbackEvent.state != AudioPlaybackState.connecting || + _audioPlayer.playbackEvent.state != AudioPlaybackState.none) { + await _audioPlayer.play(); + await _seekRelative(Duration(seconds: -3)); + } + } + } + } + + Future _playFromStart() async { + _playing = true; + _session.setActive(true); + if (mediaItem.extras['skipSecondsStart'] > 0 || + mediaItem.extras['skipSecondsEnd'] > 0) { + _audioPlayer + .seek(Duration(seconds: mediaItem.extras['skipSecondsStart'])); + } + if (_audioPlayer.playbackEvent.state != AudioPlaybackState.connecting || + _audioPlayer.playbackEvent.state != AudioPlaybackState.none) { + try { + _audioPlayer.play(); + } catch (e) { + _setState(processingState: AudioProcessingState.error); + } + } + } + + @override + Future onPause() async { + if (_skipState == null) { + if (_playing == null) { + } else if (_playing) { + _playing = false; + _audioPlayer.pause(); + } + } + } + + @override + Future onSeekTo(Duration position) async { + if (_audioPlayer.playbackEvent.state != AudioPlaybackState.connecting || + _audioPlayer.playbackEvent.state != AudioPlaybackState.none) { + await _audioPlayer.seek(position); + } + } + + @override + Future onClick(MediaButton button) async { + switch (button) { + case MediaButton.media: + if (AudioServiceBackground.state?.playing == true) { + await onPause(); + } else { + await onPlay(); + } + break; + case MediaButton.next: + await onFastForward(); + break; + case MediaButton.previous: + await onRewind(); + break; + } + } + + Future _seekRelative(Duration offset) async { + var newPosition = _audioPlayer.playbackEvent.position + offset; + if (newPosition < Duration.zero) newPosition = Duration.zero; + onSeekTo(newPosition); + } + + @override + Future onStop() async { + await _audioPlayer.stop(); + await _audioPlayer.dispose(); + _playing = false; + _playerStateSubscription.cancel(); + _eventSubscription.cancel(); + await _setState(processingState: AudioProcessingState.none); + AudioServiceBackground.sendCustomEvent({'playerRunning': false}); + await super.onStop(); + } + + @override + Future onTaskRemoved() async { + await onStop(); + } + + @override + Future onAddQueueItem(MediaItem mediaItem) async { + _queue.add(mediaItem); + await AudioServiceBackground.setQueue(_queue); + } + + @override + Future onRemoveQueueItem(MediaItem mediaItem) async { + _queue.removeWhere((item) => item.id == mediaItem.id); + await AudioServiceBackground.setQueue(_queue); + } + + @override + Future onAddQueueItemAt(MediaItem mediaItem, int index) async { + if (index == 0) { + await _audioPlayer.stop(); + _queue.removeAt(0); + _queue.removeWhere((item) => item.id == mediaItem.id); + _queue.insert(0, mediaItem); + await AudioServiceBackground.setQueue(_queue); + await AudioServiceBackground.setMediaItem(mediaItem); + await _audioPlayer.setUrl(mediaItem.id, cacheMax: _cacheMax); + var duration = await _audioPlayer.durationFuture ?? Duration.zero; + AudioServiceBackground.setMediaItem( + mediaItem.copyWith(duration: duration)); + _playFromStart(); + //onPlay(); + } else { + _queue.insert(index, mediaItem); + await AudioServiceBackground.setQueue(_queue); + } + } + + @override + Future onFastForward() async { + await _seekRelative(fastForwardInterval); + } + + @override + Future onRewind() async { + await _seekRelative(-rewindInterval); + } + + @override + Future onCustomAction(funtion, argument) async { + switch (funtion) { + case 'stopAtEnd': + _stopAtEnd = true; + break; + case 'cancelStopAtEnd': + _stopAtEnd = false; + break; + case 'setSpeed': + await _audioPlayer.setSpeed(argument); + break; + case 'setSkipSilence': + await _setSkipSilence(argument); + break; + case 'setBoostVolume': + await _setBoostVolume(argument[0], argument[1]); + break; + } + } + + Future _setSkipSilence(bool boo) async { + await _audioPlayer.setSkipSilence(boo); + var duration = await _audioPlayer.durationFuture ?? Duration.zero; + AudioServiceBackground.setMediaItem(mediaItem.copyWith(duration: duration)); + } + + Future _setBoostVolume(bool boo, int gain) async { + await _audioPlayer.setBoostVolume(boo, gain: gain); + } + + Future _setState({ + AudioProcessingState processingState, + Duration position, + Duration bufferedPosition, + }) async { + if (position == null) { + position = _audioPlayer.playbackEvent.position; + } + final index = await layoutStorage.getInt(defaultValue: 0); + await AudioServiceBackground.setState( + controls: _getControls(index), + systemActions: [ + MediaAction.seekTo, + MediaAction.seekForward, + MediaAction.seekBackward, + ], + processingState: + processingState ?? AudioServiceBackground.state.processingState, + playing: _playing ?? false, + position: position, + bufferedPosition: bufferedPosition ?? position, + speed: _audioPlayer.speed, + ); + } + + List _getControls(int index) { + switch (index) { + case 0: + if (_playing) { + return [pauseControl, forward, skipToNextControl, stopControl]; + } else { + return [playControl, forward, skipToNextControl, stopControl]; + } + break; + case 1: + if (_playing) { + return [pauseControl, rewind, skipToNextControl, stopControl]; + } else { + return [playControl, rewind, skipToNextControl, stopControl]; + } + break; + case 2: + if (_playing) { + return [rewind, pauseControl, forward, stopControl]; + } else { + return [rewind, playControl, forward, stopControl]; + } + break; + default: + if (_playing) { + return [pauseControl, forward, skipToNextControl, stopControl]; + } else { + return [playControl, forward, skipToNextControl, stopControl]; + } + break; + } + } +} diff --git a/lib/state/download_state.dart b/lib/state/download_state.dart index 363d487..232f5f4 100644 --- a/lib/state/download_state.dart +++ b/lib/state/download_state.dart @@ -1,386 +1,386 @@ -import 'dart:async'; -import 'dart:developer' as developer; -import 'dart:io'; -import 'dart:isolate'; -import 'dart:ui'; - -import 'package:flutter/material.dart'; -import 'package:flutter/rendering.dart'; -import 'package:flutter_downloader/flutter_downloader.dart'; -import 'package:path/path.dart' as path; -import 'package:path_provider/path_provider.dart'; - -import '../local_storage/key_value_storage.dart'; -import '../local_storage/sqflite_localpodcast.dart'; -import '../type/episode_task.dart'; -import '../type/episodebrief.dart'; - -void downloadCallback(String id, DownloadTaskStatus status, int progress) { - developer.log('Homepage callback task in $id status ($status) $progress'); - final send = IsolateNameServer.lookupPortByName('downloader_send_port'); - send.send([id, status, progress]); -} - -void autoDownloadCallback(String id, DownloadTaskStatus status, int progress) { - developer - .log('Autodownload callback task in $id status ($status) $progress'); - final send = IsolateNameServer.lookupPortByName('auto_downloader_send_port'); - send.send([id, status, progress]); -} - -//For background auto downlaod -class AutoDownloader { - DBHelper dbHelper = DBHelper(); - final List _episodeTasks = []; - final Completer _completer = Completer(); - AutoDownloader() { - FlutterDownloader.registerCallback(autoDownloadCallback); - } - - bindBackgroundIsolate() { - var _port = ReceivePort(); - var isSuccess = IsolateNameServer.registerPortWithName( - _port.sendPort, 'auto_downloader_send_port'); - if (!isSuccess) { - IsolateNameServer.removePortNameMapping('auto_downloader_send_port'); - bindBackgroundIsolate(); - return; - } - _port.listen((dynamic data) { - String id = data[0]; - DownloadTaskStatus status = data[1]; - int progress = data[2]; - - for (var episodeTask in _episodeTasks) { - if (episodeTask.taskId == id) { - episodeTask.status = status; - episodeTask.progress = progress; - if (status == DownloadTaskStatus.complete) { - _saveMediaId(episodeTask); - } else if (status == DownloadTaskStatus.failed) { - _episodeTasks.removeWhere((element) => - element.episode.enclosureUrl == - episodeTask.episode.enclosureUrl); - if (_episodeTasks.length == 0) _unbindBackgroundIsolate(); - } - } - } - }); - } - - void _unbindBackgroundIsolate() { - IsolateNameServer.removePortNameMapping('auto_downloader_send_port'); - _completer?.complete(); - } - - Future _getDownloadDirectory() async { - final storage = KeyValueStorage(downloadPositionKey); - final index = await storage.getInt(); - final externalDirs = await getExternalStorageDirectories(); - return externalDirs[index]; - } - - Future _saveMediaId(EpisodeTask episodeTask) async { - final completeTask = await FlutterDownloader.loadTasksWithRawQuery( - query: "SELECT * FROM task WHERE task_id = '${episodeTask.taskId}'"); - var filePath = - 'file://${path.join(completeTask.first.savedDir, Uri.encodeComponent(completeTask.first.filename))}'; - var fileStat = await File( - path.join(completeTask.first.savedDir, completeTask.first.filename)) - .stat(); - await dbHelper.saveMediaId(episodeTask.episode.enclosureUrl, filePath, - episodeTask.taskId, fileStat.size); - _episodeTasks.removeWhere((element) => - element.episode.enclosureUrl == episodeTask.episode.enclosureUrl); - if (_episodeTasks.length == 0) _unbindBackgroundIsolate(); - } - - Future startTask(List episodes, - {bool showNotification = false}) async { - for (var episode in episodes) { - final dir = await _getDownloadDirectory(); - var localPath = path.join(dir.path, episode.feedTitle); - final saveDir = Directory(localPath); - var hasExisted = await saveDir.exists(); - if (!hasExisted) { - saveDir.create(); - } - var now = DateTime.now(); - var datePlus = now.year.toString() + - now.month.toString() + - now.day.toString() + - now.second.toString(); - var fileName = - '${episode.title}$datePlus.${episode.enclosureUrl.split('/').last.split('.').last}'; - if (fileName.length > 100) { - fileName = fileName.substring(fileName.length - 100); - } - var taskId = await FlutterDownloader.enqueue( - fileName: fileName, - url: episode.enclosureUrl, - savedDir: localPath, - showNotification: showNotification, - openFileFromNotification: false, - ); - _episodeTasks.add(EpisodeTask(episode, taskId)); - var dbHelper = DBHelper(); - await dbHelper.saveDownloaded(episode.enclosureUrl, taskId); - } - await _completer.future; - return; - } -} - -//For download episode inside app -class DownloadState extends ChangeNotifier { - DBHelper dbHelper = DBHelper(); - List _episodeTasks = []; - List get episodeTasks => _episodeTasks; - - DownloadState() { - _autoDelete(); - _bindBackgroundIsolate(); - FlutterDownloader.registerCallback(downloadCallback); - } - - @override - void addListener(VoidCallback listener) async { - _loadTasks(); - super.addListener(listener); - } - - Future _loadTasks() async { - _episodeTasks = []; - var dbHelper = DBHelper(); - var tasks = await FlutterDownloader.loadTasks(); - if (tasks.length != 0) { - for (var task in tasks) { - var episode = await dbHelper.getRssItemWithUrl(task.url); - if (episode == null) { - await FlutterDownloader.remove( - taskId: task.taskId, shouldDeleteContent: true); - } else { - if (task.status == DownloadTaskStatus.complete) { - var exist = - await File(path.join(task.savedDir, task.filename)).exists(); - if (!exist) { - await FlutterDownloader.remove( - taskId: task.taskId, shouldDeleteContent: true); - await dbHelper.delDownloaded(episode.enclosureUrl); - } else { - if (episode.enclosureUrl == episode.mediaId) { - var filePath = - 'file://${path.join(task.savedDir, Uri.encodeComponent(task.filename))}'; - var fileStat = - await File(path.join(task.savedDir, task.filename)).stat(); - await dbHelper.saveMediaId( - episode.enclosureUrl, filePath, task.taskId, fileStat.size); - } - _episodeTasks.add(EpisodeTask(episode, task.taskId, - progress: task.progress, status: task.status)); - } - } else { - _episodeTasks.add(EpisodeTask(episode, task.taskId, - progress: task.progress, status: task.status)); - } - } - } - } - notifyListeners(); - } - - Future _getDownloadDirectory() async { - final storage = KeyValueStorage(downloadPositionKey); - final index = await storage.getInt(); - final externalDirs = await getExternalStorageDirectories(); - return externalDirs[index]; - } - - void _bindBackgroundIsolate() { - var _port = ReceivePort(); - var isSuccess = IsolateNameServer.registerPortWithName( - _port.sendPort, 'downloader_send_port'); - if (!isSuccess) { - _unbindBackgroundIsolate(); - _bindBackgroundIsolate(); - return; - } - - _port.listen((dynamic data) { - String id = data[0]; - DownloadTaskStatus status = data[1]; - int progress = data[2]; - - for (var episodeTask in _episodeTasks) { - if (episodeTask.taskId == id) { - episodeTask.status = status; - episodeTask.progress = progress; - if (status == DownloadTaskStatus.complete) { - _saveMediaId(episodeTask).then((value) { - notifyListeners(); - }); - } else { - notifyListeners(); - } - } - } - }); - } - - Future _saveMediaId(EpisodeTask episodeTask) async { - episodeTask.status = DownloadTaskStatus.complete; - final completeTask = await FlutterDownloader.loadTasksWithRawQuery( - query: "SELECT * FROM task WHERE task_id = '${episodeTask.taskId}'"); - var filePath = - 'file://${path.join(completeTask.first.savedDir, Uri.encodeComponent(completeTask.first.filename))}'; - var fileStat = await File( - path.join(completeTask.first.savedDir, completeTask.first.filename)) - .stat(); - dbHelper.saveMediaId(episodeTask.episode.enclosureUrl, filePath, - episodeTask.taskId, fileStat.size); - var episode = - await dbHelper.getRssItemWithUrl(episodeTask.episode.enclosureUrl); - _removeTask(episodeTask.episode); - _episodeTasks.add(EpisodeTask(episode, episodeTask.taskId, - progress: 100, status: DownloadTaskStatus.complete)); - } - - void _unbindBackgroundIsolate() { - IsolateNameServer.removePortNameMapping('downloader_send_port'); - } - - EpisodeTask episodeToTask(EpisodeBrief episode) { - return _episodeTasks - .firstWhere((task) => task.episode.enclosureUrl == episode.enclosureUrl, - orElse: () { - return EpisodeTask( - episode, - '', - ); - }); - } - - @override - void dispose() { - _unbindBackgroundIsolate(); - super.dispose(); - } - - Future startTask(EpisodeBrief episode, {bool showNotification = true}) async { - var dbHelper = DBHelper(); - var isDownloaded = await dbHelper.isDownloaded(episode.enclosureUrl); - if (!isDownloaded) { - final dir = await _getDownloadDirectory(); - var localPath = - path.join(dir.path, episode.feedTitle?.replaceAll('/', '')); - final saveDir = Directory(localPath); - var hasExisted = await saveDir.exists(); - if (!hasExisted) { - await saveDir.create(); - } - var now = DateTime.now(); - var datePlus = now.year.toString() + - now.month.toString() + - now.day.toString() + - now.second.toString(); - var fileName = - '${episode.title}$datePlus.${episode.enclosureUrl.split('/').last.split('.').last}'; - if (fileName.length > 100) { - fileName = fileName.substring(fileName.length - 100); - } - var taskId = await FlutterDownloader.enqueue( - fileName: fileName, - url: episode.enclosureUrl, - savedDir: localPath, - showNotification: showNotification, - openFileFromNotification: false, - ); - _episodeTasks.add(EpisodeTask(episode, taskId)); - await dbHelper.saveDownloaded(episode.enclosureUrl, taskId); - notifyListeners(); - } - } - - Future pauseTask(EpisodeBrief episode) async { - var task = episodeToTask(episode); - if (task.progress > 0) { - await FlutterDownloader.pause(taskId: task.taskId); - } - notifyListeners(); - } - - Future resumeTask(EpisodeBrief episode) async { - var task = episodeToTask(episode); - var newTaskId = await FlutterDownloader.resume(taskId: task.taskId); - await FlutterDownloader.remove(taskId: task.taskId); - var index = _episodeTasks.indexOf(task); - _episodeTasks[index] = task.copyWith(taskId: newTaskId); - notifyListeners(); - await dbHelper.saveDownloaded(episode.enclosureUrl, newTaskId); - } - - Future retryTask(EpisodeBrief episode) async { - var task = episodeToTask(episode); - var newTaskId = await FlutterDownloader.retry(taskId: task.taskId); - await FlutterDownloader.remove(taskId: task.taskId); - var index = _episodeTasks.indexOf(task); - _episodeTasks[index] = task.copyWith(taskId: newTaskId); - notifyListeners(); - await dbHelper.saveDownloaded(episode.enclosureUrl, newTaskId); - } - - Future removeTask(EpisodeBrief episode) async { - var task = episodeToTask(episode); - await FlutterDownloader.remove( - taskId: task.taskId, shouldDeleteContent: false); - } - - Future delTask(EpisodeBrief episode) async { - var task = episodeToTask(episode); - await FlutterDownloader.remove( - taskId: task.taskId, shouldDeleteContent: true); - await dbHelper.delDownloaded(episode.enclosureUrl); - - for (var episodeTask in _episodeTasks) { - if (episodeTask.taskId == task.taskId) { - episodeTask.status = DownloadTaskStatus.undefined; - } - notifyListeners(); - } - _removeTask(episode); - } - - void _removeTask(EpisodeBrief episode) { - _episodeTasks.removeWhere((element) => element.episode == episode); - notifyListeners(); - } - - Future _autoDelete() async { - developer.log('Start auto delete outdated episodes'); - final autoDeleteStorage = KeyValueStorage(autoDeleteKey); - final deletePlayedStorage = KeyValueStorage(deleteAfterPlayedKey); - final autoDelete = await autoDeleteStorage.getInt(); - final deletePlayed = await deletePlayedStorage.getBool(defaultValue: false); - if (autoDelete == 0) { - await autoDeleteStorage.saveInt(30); - } else if (autoDelete > 0) { - var deadline = DateTime.now() - .subtract(Duration(days: autoDelete)) - .millisecondsSinceEpoch; - var episodes = await dbHelper.getOutdatedEpisode(deadline, - deletePlayed: deletePlayed); - if (episodes.isNotEmpty) { - for (var episode in episodes) { - await delTask(episode); - } - } - final tasks = await FlutterDownloader.loadTasksWithRawQuery( - query: - 'SELECT * FROM task WHERE time_created < $deadline AND status = 3'); - for (var task in tasks) { - FlutterDownloader.remove( - taskId: task.taskId, shouldDeleteContent: true); - } - } - } -} +import 'dart:async'; +import 'dart:developer' as developer; +import 'dart:io'; +import 'dart:isolate'; +import 'dart:ui'; + +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_downloader/flutter_downloader.dart'; +import 'package:path/path.dart' as path; +import 'package:path_provider/path_provider.dart'; + +import '../local_storage/key_value_storage.dart'; +import '../local_storage/sqflite_localpodcast.dart'; +import '../type/episode_task.dart'; +import '../type/episodebrief.dart'; + +void downloadCallback(String id, DownloadTaskStatus status, int progress) { + developer.log('Homepage callback task in $id status ($status) $progress'); + final send = IsolateNameServer.lookupPortByName('downloader_send_port'); + send.send([id, status, progress]); +} + +void autoDownloadCallback(String id, DownloadTaskStatus status, int progress) { + developer + .log('Autodownload callback task in $id status ($status) $progress'); + final send = IsolateNameServer.lookupPortByName('auto_downloader_send_port'); + send.send([id, status, progress]); +} + +//For background auto downlaod +class AutoDownloader { + DBHelper dbHelper = DBHelper(); + final List _episodeTasks = []; + final Completer _completer = Completer(); + AutoDownloader() { + FlutterDownloader.registerCallback(autoDownloadCallback); + } + + bindBackgroundIsolate() { + var _port = ReceivePort(); + var isSuccess = IsolateNameServer.registerPortWithName( + _port.sendPort, 'auto_downloader_send_port'); + if (!isSuccess) { + IsolateNameServer.removePortNameMapping('auto_downloader_send_port'); + bindBackgroundIsolate(); + return; + } + _port.listen((dynamic data) { + String id = data[0]; + DownloadTaskStatus status = data[1]; + int progress = data[2]; + + for (var episodeTask in _episodeTasks) { + if (episodeTask.taskId == id) { + episodeTask.status = status; + episodeTask.progress = progress; + if (status == DownloadTaskStatus.complete) { + _saveMediaId(episodeTask); + } else if (status == DownloadTaskStatus.failed) { + _episodeTasks.removeWhere((element) => + element.episode.enclosureUrl == + episodeTask.episode.enclosureUrl); + if (_episodeTasks.length == 0) _unbindBackgroundIsolate(); + } + } + } + }); + } + + void _unbindBackgroundIsolate() { + IsolateNameServer.removePortNameMapping('auto_downloader_send_port'); + _completer?.complete(); + } + + Future _getDownloadDirectory() async { + final storage = KeyValueStorage(downloadPositionKey); + final index = await storage.getInt(); + final externalDirs = await getExternalStorageDirectories(); + return externalDirs[index]; + } + + Future _saveMediaId(EpisodeTask episodeTask) async { + final completeTask = await FlutterDownloader.loadTasksWithRawQuery( + query: "SELECT * FROM task WHERE task_id = '${episodeTask.taskId}'"); + var filePath = + 'file://${path.join(completeTask.first.savedDir, Uri.encodeComponent(completeTask.first.filename))}'; + var fileStat = await File( + path.join(completeTask.first.savedDir, completeTask.first.filename)) + .stat(); + await dbHelper.saveMediaId(episodeTask.episode.enclosureUrl, filePath, + episodeTask.taskId, fileStat.size); + _episodeTasks.removeWhere((element) => + element.episode.enclosureUrl == episodeTask.episode.enclosureUrl); + if (_episodeTasks.length == 0) _unbindBackgroundIsolate(); + } + + Future startTask(List episodes, + {bool showNotification = false}) async { + for (var episode in episodes) { + final dir = await _getDownloadDirectory(); + var localPath = path.join(dir.path, episode.feedTitle); + final saveDir = Directory(localPath); + var hasExisted = await saveDir.exists(); + if (!hasExisted) { + saveDir.create(); + } + var now = DateTime.now(); + var datePlus = now.year.toString() + + now.month.toString() + + now.day.toString() + + now.second.toString(); + var fileName = + '${episode.title}$datePlus.${episode.enclosureUrl.split('/').last.split('.').last}'; + if (fileName.length > 100) { + fileName = fileName.substring(fileName.length - 100); + } + var taskId = await FlutterDownloader.enqueue( + fileName: fileName, + url: episode.enclosureUrl, + savedDir: localPath, + showNotification: showNotification, + openFileFromNotification: false, + ); + _episodeTasks.add(EpisodeTask(episode, taskId)); + var dbHelper = DBHelper(); + await dbHelper.saveDownloaded(episode.enclosureUrl, taskId); + } + await _completer.future; + return; + } +} + +//For download episode inside app +class DownloadState extends ChangeNotifier { + DBHelper dbHelper = DBHelper(); + List _episodeTasks = []; + List get episodeTasks => _episodeTasks; + + DownloadState() { + _autoDelete(); + _bindBackgroundIsolate(); + FlutterDownloader.registerCallback(downloadCallback); + } + + @override + void addListener(VoidCallback listener) async { + _loadTasks(); + super.addListener(listener); + } + + Future _loadTasks() async { + _episodeTasks = []; + var dbHelper = DBHelper(); + var tasks = await FlutterDownloader.loadTasks(); + if (tasks.length != 0) { + for (var task in tasks) { + var episode = await dbHelper.getRssItemWithUrl(task.url); + if (episode == null) { + await FlutterDownloader.remove( + taskId: task.taskId, shouldDeleteContent: true); + } else { + if (task.status == DownloadTaskStatus.complete) { + var exist = + await File(path.join(task.savedDir, task.filename)).exists(); + if (!exist) { + await FlutterDownloader.remove( + taskId: task.taskId, shouldDeleteContent: true); + await dbHelper.delDownloaded(episode.enclosureUrl); + } else { + if (episode.enclosureUrl == episode.mediaId) { + var filePath = + 'file://${path.join(task.savedDir, Uri.encodeComponent(task.filename))}'; + var fileStat = + await File(path.join(task.savedDir, task.filename)).stat(); + await dbHelper.saveMediaId( + episode.enclosureUrl, filePath, task.taskId, fileStat.size); + } + _episodeTasks.add(EpisodeTask(episode, task.taskId, + progress: task.progress, status: task.status)); + } + } else { + _episodeTasks.add(EpisodeTask(episode, task.taskId, + progress: task.progress, status: task.status)); + } + } + } + } + notifyListeners(); + } + + Future _getDownloadDirectory() async { + final storage = KeyValueStorage(downloadPositionKey); + final index = await storage.getInt(); + final externalDirs = await getExternalStorageDirectories(); + return externalDirs[index]; + } + + void _bindBackgroundIsolate() { + var _port = ReceivePort(); + var isSuccess = IsolateNameServer.registerPortWithName( + _port.sendPort, 'downloader_send_port'); + if (!isSuccess) { + _unbindBackgroundIsolate(); + _bindBackgroundIsolate(); + return; + } + + _port.listen((dynamic data) { + String id = data[0]; + DownloadTaskStatus status = data[1]; + int progress = data[2]; + + for (var episodeTask in _episodeTasks) { + if (episodeTask.taskId == id) { + episodeTask.status = status; + episodeTask.progress = progress; + if (status == DownloadTaskStatus.complete) { + _saveMediaId(episodeTask).then((value) { + notifyListeners(); + }); + } else { + notifyListeners(); + } + } + } + }); + } + + Future _saveMediaId(EpisodeTask episodeTask) async { + episodeTask.status = DownloadTaskStatus.complete; + final completeTask = await FlutterDownloader.loadTasksWithRawQuery( + query: "SELECT * FROM task WHERE task_id = '${episodeTask.taskId}'"); + var filePath = + 'file://${path.join(completeTask.first.savedDir, Uri.encodeComponent(completeTask.first.filename))}'; + var fileStat = await File( + path.join(completeTask.first.savedDir, completeTask.first.filename)) + .stat(); + dbHelper.saveMediaId(episodeTask.episode.enclosureUrl, filePath, + episodeTask.taskId, fileStat.size); + var episode = + await dbHelper.getRssItemWithUrl(episodeTask.episode.enclosureUrl); + _removeTask(episodeTask.episode); + _episodeTasks.add(EpisodeTask(episode, episodeTask.taskId, + progress: 100, status: DownloadTaskStatus.complete)); + } + + void _unbindBackgroundIsolate() { + IsolateNameServer.removePortNameMapping('downloader_send_port'); + } + + EpisodeTask episodeToTask(EpisodeBrief episode) { + return _episodeTasks + .firstWhere((task) => task.episode.enclosureUrl == episode.enclosureUrl, + orElse: () { + return EpisodeTask( + episode, + '', + ); + }); + } + + @override + void dispose() { + _unbindBackgroundIsolate(); + super.dispose(); + } + + Future startTask(EpisodeBrief episode, {bool showNotification = true}) async { + var dbHelper = DBHelper(); + var isDownloaded = await dbHelper.isDownloaded(episode.enclosureUrl); + if (!isDownloaded) { + final dir = await _getDownloadDirectory(); + var localPath = + path.join(dir.path, episode.feedTitle?.replaceAll('/', '')); + final saveDir = Directory(localPath); + var hasExisted = await saveDir.exists(); + if (!hasExisted) { + await saveDir.create(); + } + var now = DateTime.now(); + var datePlus = now.year.toString() + + now.month.toString() + + now.day.toString() + + now.second.toString(); + var fileName = + '${episode.title}$datePlus.${episode.enclosureUrl.split('/').last.split('.').last}'; + if (fileName.length > 100) { + fileName = fileName.substring(fileName.length - 100); + } + var taskId = await FlutterDownloader.enqueue( + fileName: fileName, + url: episode.enclosureUrl, + savedDir: localPath, + showNotification: showNotification, + openFileFromNotification: false, + ); + _episodeTasks.add(EpisodeTask(episode, taskId)); + await dbHelper.saveDownloaded(episode.enclosureUrl, taskId); + notifyListeners(); + } + } + + Future pauseTask(EpisodeBrief episode) async { + var task = episodeToTask(episode); + if (task.progress > 0) { + await FlutterDownloader.pause(taskId: task.taskId); + } + notifyListeners(); + } + + Future resumeTask(EpisodeBrief episode) async { + var task = episodeToTask(episode); + var newTaskId = await FlutterDownloader.resume(taskId: task.taskId); + await FlutterDownloader.remove(taskId: task.taskId); + var index = _episodeTasks.indexOf(task); + _episodeTasks[index] = task.copyWith(taskId: newTaskId); + notifyListeners(); + await dbHelper.saveDownloaded(episode.enclosureUrl, newTaskId); + } + + Future retryTask(EpisodeBrief episode) async { + var task = episodeToTask(episode); + var newTaskId = await FlutterDownloader.retry(taskId: task.taskId); + await FlutterDownloader.remove(taskId: task.taskId); + var index = _episodeTasks.indexOf(task); + _episodeTasks[index] = task.copyWith(taskId: newTaskId); + notifyListeners(); + await dbHelper.saveDownloaded(episode.enclosureUrl, newTaskId); + } + + Future removeTask(EpisodeBrief episode) async { + var task = episodeToTask(episode); + await FlutterDownloader.remove( + taskId: task.taskId, shouldDeleteContent: false); + } + + Future delTask(EpisodeBrief episode) async { + var task = episodeToTask(episode); + await FlutterDownloader.remove( + taskId: task.taskId, shouldDeleteContent: true); + await dbHelper.delDownloaded(episode.enclosureUrl); + + for (var episodeTask in _episodeTasks) { + if (episodeTask.taskId == task.taskId) { + episodeTask.status = DownloadTaskStatus.undefined; + } + notifyListeners(); + } + _removeTask(episode); + } + + void _removeTask(EpisodeBrief episode) { + _episodeTasks.removeWhere((element) => element.episode == episode); + notifyListeners(); + } + + Future _autoDelete() async { + developer.log('Start auto delete outdated episodes'); + final autoDeleteStorage = KeyValueStorage(autoDeleteKey); + final deletePlayedStorage = KeyValueStorage(deleteAfterPlayedKey); + final autoDelete = await autoDeleteStorage.getInt(); + final deletePlayed = await deletePlayedStorage.getBool(defaultValue: false); + if (autoDelete == 0) { + await autoDeleteStorage.saveInt(30); + } else if (autoDelete > 0) { + var deadline = DateTime.now() + .subtract(Duration(days: autoDelete)) + .millisecondsSinceEpoch; + var episodes = await dbHelper.getOutdatedEpisode(deadline, + deletePlayed: deletePlayed); + if (episodes.isNotEmpty) { + for (var episode in episodes) { + await delTask(episode); + } + } + final tasks = await FlutterDownloader.loadTasksWithRawQuery( + query: + 'SELECT * FROM task WHERE time_created < $deadline AND status = 3'); + for (var task in tasks) { + FlutterDownloader.remove( + taskId: task.taskId, shouldDeleteContent: true); + } + } + } +} diff --git a/lib/state/podcast_group.dart b/lib/state/podcast_group.dart index 3a86331..3d56851 100644 --- a/lib/state/podcast_group.dart +++ b/lib/state/podcast_group.dart @@ -1,725 +1,725 @@ -import 'dart:core'; -import 'dart:developer' as developer; -import 'dart:io'; -import 'dart:isolate'; -import 'dart:math' as math; -import 'dart:ui'; - -import 'package:color_thief_flutter/color_thief_flutter.dart'; -import 'package:dio/dio.dart'; -import 'package:equatable/equatable.dart'; -import 'package:flutter/foundation.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_isolate/flutter_isolate.dart'; -import 'package:image/image.dart' as img; -import 'package:path_provider/path_provider.dart'; -import 'package:uuid/uuid.dart'; -import 'package:webfeed/webfeed.dart'; -import 'package:workmanager/workmanager.dart'; - -import '../local_storage/key_value_storage.dart'; -import '../local_storage/sqflite_localpodcast.dart'; -import '../service/gpodder_api.dart'; -import '../type/fireside_data.dart'; -import '../type/podcastlocal.dart'; - -void callbackDispatcher() { - if (Platform.isAndroid) { - Workmanager.executeTask((task, inputData) async { - final gpodder = Gpodder(); - final status = await gpodder.getChanges(); - if (status == 200) { - await gpodder.updateChange(); - developer.log('Gpodder sync successfully'); - } - return Future.value(true); - }); - } -} - -class GroupEntity { - final String name; - final String id; - final String color; - final List podcastList; - - GroupEntity(this.name, this.id, this.color, this.podcastList); - - Map toJson() { - return {'name': name, 'id': id, 'color': color, 'podcastList': podcastList}; - } - - static GroupEntity fromJson(Map json) { - var list = List.from(json['podcastList']); - return GroupEntity(json['name'] as String, json['id'] as String, - json['color'] as String, list); - } -} - -class PodcastGroup extends Equatable { - /// Group name. - final String name; - - final String id; - - /// Group theme color, not used. - final String color; - - /// Id lists of podcasts in group. - List _podcastList; - - List get podcastList => _podcastList; - - set podcastList(list) { - _podcastList = list; - } - - PodcastGroup(this.name, - {this.color = '#000000', String id, List podcastList}) - : id = id ?? Uuid().v4(), - _podcastList = podcastList ?? []; - - Future getPodcasts() async { - var dbHelper = DBHelper(); - if (_podcastList != []) { - try { - _podcasts = await dbHelper.getPodcastLocal(_podcastList); - } catch (e) { - await Future.delayed(Duration(milliseconds: 200)); - try { - _podcasts = await dbHelper.getPodcastLocal(_podcastList); - } catch (e) { - developer.log(e.toString()); - } - } - } - } - - Color getColor() { - if (color != '#000000') { - var colorInt = int.parse('FF${color.toUpperCase()}', radix: 16); - return Color(colorInt).withOpacity(1.0); - } else { - return Colors.blue[400]; - } - } - - ///Podcast in group. - List _podcasts; - List get podcasts => _podcasts; - - ///Ordered podcast list. - List _orderedPodcasts; - List get orderedPodcasts => _orderedPodcasts; - - set orderedPodcasts(list) => _orderedPodcasts = list; - - GroupEntity toEntity() { - return GroupEntity(name, id, color, podcastList); - } - - static PodcastGroup fromEntity(GroupEntity entity) { - return PodcastGroup( - entity.name, - id: entity.id, - color: entity.color, - podcastList: entity.podcastList, - ); - } - - @override - List get props => [id, name]; -} - -enum SubscribeState { none, start, subscribe, fetch, stop, exist, error } - -class SubscribeItem { - ///Rss url. - String url; - - ///Rss title. - String title; - - /// Subscribe status. - SubscribeState subscribeState; - - /// Podcast id. - String id; - - ///Avatar image link. - String imgUrl; - - ///Podcast group, default Home. - String group; - - SubscribeItem( - this.url, - this.title, { - this.subscribeState = SubscribeState.none, - this.id = '', - this.imgUrl = '', - this.group = '', - }); -} - -class GroupList extends ChangeNotifier { - /// List of all gourps. - final List _groups = []; - - List get groups => _groups; - - final DBHelper _dbHelper = DBHelper(); - - /// Groups save in shared_prefrences. - final KeyValueStorage _groupStorage = KeyValueStorage(groupsKey); - - //GroupList({List groups}) : _groups = groups ?? []; - - /// Default false, true during loading groups from storage. - bool _isLoading = false; - - bool get isLoading => _isLoading; - - /// Svae ordered gourps info before saved. - final List _orderChanged = []; - List get orderChanged => _orderChanged; - - /// Subscribe worker isolate - FlutterIsolate subIsolate; - ReceivePort receivePort; - SendPort subSendPort; - - /// Current subsribe item from isolate. - SubscribeItem _currentSubscribeItem = SubscribeItem('', ''); - SubscribeItem get currentSubscribeItem => _currentSubscribeItem; - - bool _created = false; - - /// Default false, true if subscribe isolate is created. - bool get created => _created; - - /// Add subsribe item - SubscribeItem _subscribeItem; - setSubscribeItem(SubscribeItem item, {bool syncGpodder = true}) async { - _subscribeItem = item; - if (syncGpodder) _syncAdd(item.url); - await _start(); - } - - _setCurrentSubscribeItem(SubscribeItem item) { - _currentSubscribeItem = item; - notifyListeners(); - } - - Future _syncAdd(String rssUrl) async { - final check = await _checkGpodderLoggedin(); - if (check) { - await _addStorage.addList([rssUrl]); - } - } - - Future _start() async { - if (!_created) { - await _createIsolate(); - _created = true; - listen(); - } else { - subSendPort.send([ - _subscribeItem.url, - _subscribeItem.title, - _subscribeItem.imgUrl, - _subscribeItem.group, - ]); - } - } - - Future _createIsolate() async { - receivePort = ReceivePort(); - subIsolate = - await FlutterIsolate.spawn(subIsolateEntryPoint, receivePort.sendPort); - } - - /// Isolate listener to get subscrribe status. - void listen() { - receivePort.distinct().listen((message) { - if (message is SendPort) { - subSendPort = message; - subSendPort.send([ - _subscribeItem.url, - _subscribeItem.title, - _subscribeItem.imgUrl, - _subscribeItem.group, - ]); - } else if (message is List) { - _setCurrentSubscribeItem(SubscribeItem( - message[1], - message[0], - subscribeState: SubscribeState.values[message[2]], - )); - if (message.length == 5) { - _subscribeNewPodcast(id: message[3], groupName: message[4]); - } - } else if (message is String && message == "done") { - subIsolate.kill(); - subIsolate = null; - _currentSubscribeItem = SubscribeItem('', ''); - _created = false; - notifyListeners(); - } - }); - } - - ///Set gpodder sync - final _loginInfp = KeyValueStorage(gpodderApiKey); - final _addStorage = KeyValueStorage(gpodderAddKey); - final _removeStorage = KeyValueStorage(gpodderRemoveKey); - final _remoteAddStorage = KeyValueStorage(gpodderRemoteAddKey); - final _remoteRemoveStorage = KeyValueStorage(gpodderRemoteRemoveKey); - - Future _checkGpodderLoggedin() async { - final loginInfo = await _loginInfp.getStringList(); - return loginInfo.isNotEmpty; - } - - Future gpodderSyncNow() async { - final addList = await _remoteAddStorage.getStringList(); - final removeList = await _remoteRemoveStorage.getStringList(); - - if (removeList.isNotEmpty) { - for (var rssLink in removeList) { - final exist = await _dbHelper.checkPodcast(rssLink); - if (exist != '') { - await _unsubscribe(exist); - } - } - await _remoteAddStorage.clearList(); - } - if (addList.isNotEmpty) { - for (var rssLink in addList) { - final exist = await _dbHelper.checkPodcast(rssLink); - if (exist == '') { - var item = SubscribeItem(rssLink, rssLink, group: 'Home'); - _subscribeItem = item; - await _start(); - - await Future.delayed(Duration(milliseconds: 200)); - } - } - await _remoteRemoveStorage.clearList(); - } - } - - void setWorkManager() { - Workmanager.initialize( - callbackDispatcher, - isInDebugMode: false, - ); - Workmanager.registerPeriodicTask("2", "gpodder_sync", - frequency: Duration(hours: 4), - initialDelay: Duration(seconds: 10), - constraints: Constraints( - networkType: NetworkType.connected, - )); - developer.log('work manager init done + (gpodder sync)'); - } - - Future cancelWork() async { - await Workmanager.cancelByUniqueName('2'); - developer.log('work job cancelled'); - } - - void addToOrderChanged(PodcastGroup group) { - _orderChanged.add(group); - notifyListeners(); - } - - void drlFromOrderChanged(String name) { - _orderChanged.removeWhere((group) => group.name == name); - notifyListeners(); - } - - Future clearOrderChanged() async { - if (_orderChanged.length > 0) { - for (var group in _orderChanged) { - await group.getPodcasts(); - } - _orderChanged.clear(); - // notifyListeners(); - } - } - - @override - void addListener(VoidCallback listener) { - loadGroups().then((value) => super.addListener(listener)); - gpodderSyncNow(); - } - - @override - void dispose() { - subIsolate?.kill(); - subIsolate = null; - super.dispose(); - } - - /// Load groups from storage at start. - Future loadGroups() async { - _isLoading = true; - notifyListeners(); - _groupStorage.getGroups().then((loadgroups) async { - _groups.addAll(loadgroups.map(PodcastGroup.fromEntity)); - for (var group in _groups) { - await group.getPodcasts(); - } - _isLoading = false; - notifyListeners(); - }); - } - - /// Update podcasts of each group - Future updateGroups() async { - for (var group in _groups) { - await group.getPodcasts(); - } - notifyListeners(); - } - - /// Add new group. - Future addGroup(PodcastGroup podcastGroup) async { - _isLoading = true; - _groups.add(podcastGroup); - await _saveGroup(); - _isLoading = false; - notifyListeners(); - } - - /// Remove group. - Future delGroup(PodcastGroup podcastGroup) async { - _isLoading = true; - for (var podcast in podcastGroup.podcastList) { - if (!_groups.first.podcastList.contains(podcast)) { - _groups[0].podcastList.insert(0, podcast); - } - } - await _saveGroup(); - _groups.remove(podcastGroup); - await _groups[0].getPodcasts(); - _isLoading = false; - notifyListeners(); - } - - Future updateGroup(PodcastGroup podcastGroup) async { - var oldGroup = _groups.firstWhere((it) => it.id == podcastGroup.id); - var index = _groups.indexOf(oldGroup); - _groups.replaceRange(index, index + 1, [podcastGroup]); - await podcastGroup.getPodcasts(); - notifyListeners(); - _saveGroup(); - } - - Future _saveGroup() async { - await _groupStorage.saveGroup(_groups.map((it) => it.toEntity()).toList()); - } - - /// Subscribe podcast from search result. - Future subscribe(PodcastLocal podcastLocal) async { - _groups[0].podcastList.insert(0, podcastLocal.id); - await _saveGroup(); - await _dbHelper.savePodcastLocal(podcastLocal); - await _groups[0].getPodcasts(); - notifyListeners(); - } - - Future updatePodcast(String id) async { - var counts = await _dbHelper.getPodcastCounts(id); - for (var group in _groups) { - if (group.podcastList.contains(id)) { - group.podcasts.firstWhere((podcast) => podcast.id == id) - ..episodeCount = counts; - notifyListeners(); - } - } - } - - /// Subscribe podcast from OPML. - Future _subscribeNewPodcast( - {String id, String groupName = 'Home'}) async { - //List groupNames = _groups.map((e) => e.name).toList(); - for (var group in _groups) { - if (group.name == groupName) { - if (group.podcastList.contains(id)) { - return true; - } else { - _isLoading = true; - notifyListeners(); - group.podcastList.insert(0, id); - await _saveGroup(); - await group.getPodcasts(); - _isLoading = false; - notifyListeners(); - return true; - } - } - } - _isLoading = true; - notifyListeners(); - _groups.add(PodcastGroup(groupName, podcastList: [id])); - //_groups.last.podcastList.insert(0, id); - await _saveGroup(); - await _groups.last.getPodcasts(); - _isLoading = false; - notifyListeners(); - return true; - } - - List getPodcastGroup(String id) { - var result = []; - for (var group in _groups) { - if (group.podcastList.contains(id)) { - result.add(group); - } - } - return result; - } - - //Change podcast groups - Future changeGroup(String id, List list) async { - _isLoading = true; - notifyListeners(); - - for (var group in getPodcastGroup(id)) { - if (list.contains(group)) { - list.remove(group); - } else { - group.podcastList.remove(id); - } - } - for (var s in list) { - s.podcastList.insert(0, id); - } - await _saveGroup(); - for (var group in _groups) { - await group.getPodcasts(); - } - _isLoading = false; - notifyListeners(); - } - - /// Unsubscribe podcast - Future _syncRemove(String rssUrl) async { - final check = await _checkGpodderLoggedin(); - if (check) { - await _removeStorage.addList([rssUrl]); - } - } - - Future _unsubscribe(String id) async { - _isLoading = true; - notifyListeners(); - for (var group in _groups) { - group.podcastList.remove(id); - } - await _saveGroup(); - await _dbHelper.delPodcastLocal(id); - for (var group in _groups) { - await group.getPodcasts(); - } - _isLoading = false; - notifyListeners(); - } - - Future removePodcast( - PodcastLocal podcast, - ) async { - _syncRemove(podcast.rssUrl); - final id = podcast.id; - await _unsubscribe(id); - } - - Future saveOrder(PodcastGroup group) async { - group.podcastList = group.orderedPodcasts.map((e) => e.id).toList(); - await _saveGroup(); - await group.getPodcasts(); - notifyListeners(); - } -} - -Future subIsolateEntryPoint(SendPort sendPort) async { - var items = []; - var _running = false; - final listColor = [ - '388E3C', - '1976D2', - 'D32F2F', - '00796B', - ]; - var subReceivePort = ReceivePort(); - sendPort.send(subReceivePort.sendPort); - - Future _getColor(File file) async { - final imageProvider = FileImage(file); - var colorImage = await getImageFromProvider(imageProvider); - var color = await getColorFromImage(colorImage); - var primaryColor = color.toString(); - return primaryColor; - } - - Future _subscribe(SubscribeItem item) async { - var dbHelper = DBHelper(); - var rss = item.url; - sendPort.send([item.title, item.url, 1]); - var options = BaseOptions( - connectTimeout: 30000, - receiveTimeout: 90000, - ); - - try { - var response = await Dio(options).get(rss); - RssFeed p; - try { - p = RssFeed.parse(response.data); - } catch (e) { - sendPort.send([item.title, item.url, 6]); - await Future.delayed(Duration(seconds: 2)); - sendPort.send([item.title, item.url, 4]); - items.removeWhere((element) => element.url == item.url); - if (items.isNotEmpty) { - await _subscribe(items.first); - } else { - sendPort.send("done"); - } - } - - var dir = await getApplicationDocumentsDirectory(); - - var realUrl = - response.redirects.isEmpty ? rss : response.realUri.toString(); - - var checkUrl = await dbHelper.checkPodcast(realUrl); - - /// If url not existe in database. - if (checkUrl == '') { - img.Image thumbnail; - String imageUrl; - try { - var imageResponse = await Dio().get>(p.itunes.image.href, - options: Options( - responseType: ResponseType.bytes, - receiveTimeout: 90000, - )); - imageUrl = p.itunes.image.href; - var image = img.decodeImage(imageResponse.data); - thumbnail = img.copyResize(image, width: 300); - } catch (e) { - try { - var imageResponse = await Dio().get>(item.imgUrl, - options: Options( - responseType: ResponseType.bytes, - receiveTimeout: 90000, - )); - imageUrl = item.imgUrl; - var image = img.decodeImage(imageResponse.data); - thumbnail = img.copyResize(image, width: 300); - } catch (e) { - developer.log(e.toString(), name: 'Download image error'); - try { - var index = math.Random().nextInt(3); - var imageResponse = await Dio().get>( - "https://ui-avatars.com/api/?size=300&background=" - "${listColor[index]}&color=fff&name=${item.title}&length=2&bold=true", - options: Options(responseType: ResponseType.bytes)); - imageUrl = "https://ui-avatars.com/api/?size=300&background=" - "${listColor[index]}&color=fff&name=${item.title}&length=2&bold=true"; - thumbnail = img.decodeImage(imageResponse.data); - } catch (e) { - developer.log(e.toString(), name: 'Donwload image error'); - sendPort.send([item.title, item.url, 6]); - await Future.delayed(Duration(seconds: 2)); - sendPort.send([item.title, item.url, 4]); - items.removeWhere((element) => element.url == item.url); - if (items.length > 0) { - await _subscribe(items.first); - } else { - sendPort.send("done"); - } - } - } - } - var uuid = Uuid().v4(); - File("${dir.path}/$uuid.png") - ..writeAsBytesSync(img.encodePng(thumbnail)); - - var imagePath = "${dir.path}/$uuid.png"; - var primaryColor = await _getColor(File("${dir.path}/$uuid.png")); - var author = p.itunes.author ?? p.author ?? ''; - var provider = p.generator ?? ''; - var link = p.link ?? ''; - var podcastLocal = PodcastLocal(p.title, imageUrl, realUrl, - primaryColor, author, uuid, imagePath, provider, link, - description: p.description); - - await dbHelper.savePodcastLocal(podcastLocal); - sendPort.send([item.title, item.url, 2, uuid, item.group]); - if (provider.contains('fireside')) { - var data = FiresideData(uuid, link); - try { - await data.fatchData(); - } catch (e) { - developer.log(e.toString(), name: 'Fatch fireside data error'); - } - } - await dbHelper.savePodcastRss(p, uuid); - - // if (item.syncWithGpodder) { - // final gpodder = Gpodder(); - // await gpodder.updateChange({ - // 'add': [item.url] - // }); - // } - - sendPort.send([item.title, item.url, 3, uuid]); - - await Future.delayed(Duration(seconds: 2)); - - sendPort.send([item.title, item.url, 4]); - items.removeAt(0); - if (items.length > 0) { - await _subscribe(items.first); - } else { - sendPort.send("done"); - } - } else { - sendPort.send([item.title, realUrl, 5, checkUrl, item.group]); - await Future.delayed(Duration(seconds: 2)); - sendPort.send([item.title, item.url, 4]); - items.removeAt(0); - if (items.length > 0) { - await _subscribe(items.first); - } else { - sendPort.send("done"); - } - } - } catch (e) { - developer.log('$e confirm'); - sendPort.send([item.title, item.url, 6]); - await Future.delayed(Duration(seconds: 2)); - sendPort.send([item.title, item.url, 4]); - items.removeWhere((element) => element.url == item.url); - if (items.length > 0) { - await _subscribe(items.first); - } else { - sendPort.send("done"); - } - } - } - - subReceivePort.distinct().listen((message) { - if (message is List) { - items.add(SubscribeItem(message[0], message[1], - imgUrl: message[2], group: message[3])); - if (!_running) { - _subscribe(items.first); - _running = true; - } - } - }); -} +import 'dart:core'; +import 'dart:developer' as developer; +import 'dart:io'; +import 'dart:isolate'; +import 'dart:math' as math; +import 'dart:ui'; + +import 'package:color_thief_flutter/color_thief_flutter.dart'; +import 'package:dio/dio.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_isolate/flutter_isolate.dart'; +import 'package:image/image.dart' as img; +import 'package:path_provider/path_provider.dart'; +import 'package:uuid/uuid.dart'; +import 'package:webfeed/webfeed.dart'; +import 'package:workmanager/workmanager.dart'; + +import '../local_storage/key_value_storage.dart'; +import '../local_storage/sqflite_localpodcast.dart'; +import '../service/gpodder_api.dart'; +import '../type/fireside_data.dart'; +import '../type/podcastlocal.dart'; + +void callbackDispatcher() { + if (Platform.isAndroid) { + Workmanager.executeTask((task, inputData) async { + final gpodder = Gpodder(); + final status = await gpodder.getChanges(); + if (status == 200) { + await gpodder.updateChange(); + developer.log('Gpodder sync successfully'); + } + return Future.value(true); + }); + } +} + +class GroupEntity { + final String name; + final String id; + final String color; + final List podcastList; + + GroupEntity(this.name, this.id, this.color, this.podcastList); + + Map toJson() { + return {'name': name, 'id': id, 'color': color, 'podcastList': podcastList}; + } + + static GroupEntity fromJson(Map json) { + var list = List.from(json['podcastList']); + return GroupEntity(json['name'] as String, json['id'] as String, + json['color'] as String, list); + } +} + +class PodcastGroup extends Equatable { + /// Group name. + final String name; + + final String id; + + /// Group theme color, not used. + final String color; + + /// Id lists of podcasts in group. + List _podcastList; + + List get podcastList => _podcastList; + + set podcastList(list) { + _podcastList = list; + } + + PodcastGroup(this.name, + {this.color = '#000000', String id, List podcastList}) + : id = id ?? Uuid().v4(), + _podcastList = podcastList ?? []; + + Future getPodcasts() async { + var dbHelper = DBHelper(); + if (_podcastList != []) { + try { + _podcasts = await dbHelper.getPodcastLocal(_podcastList); + } catch (e) { + await Future.delayed(Duration(milliseconds: 200)); + try { + _podcasts = await dbHelper.getPodcastLocal(_podcastList); + } catch (e) { + developer.log(e.toString()); + } + } + } + } + + Color getColor() { + if (color != '#000000') { + var colorInt = int.parse('FF${color.toUpperCase()}', radix: 16); + return Color(colorInt).withOpacity(1.0); + } else { + return Colors.blue[400]; + } + } + + ///Podcast in group. + List _podcasts; + List get podcasts => _podcasts; + + ///Ordered podcast list. + List _orderedPodcasts; + List get orderedPodcasts => _orderedPodcasts; + + set orderedPodcasts(list) => _orderedPodcasts = list; + + GroupEntity toEntity() { + return GroupEntity(name, id, color, podcastList); + } + + static PodcastGroup fromEntity(GroupEntity entity) { + return PodcastGroup( + entity.name, + id: entity.id, + color: entity.color, + podcastList: entity.podcastList, + ); + } + + @override + List get props => [id, name]; +} + +enum SubscribeState { none, start, subscribe, fetch, stop, exist, error } + +class SubscribeItem { + ///Rss url. + String url; + + ///Rss title. + String title; + + /// Subscribe status. + SubscribeState subscribeState; + + /// Podcast id. + String id; + + ///Avatar image link. + String imgUrl; + + ///Podcast group, default Home. + String group; + + SubscribeItem( + this.url, + this.title, { + this.subscribeState = SubscribeState.none, + this.id = '', + this.imgUrl = '', + this.group = '', + }); +} + +class GroupList extends ChangeNotifier { + /// List of all gourps. + final List _groups = []; + + List get groups => _groups; + + final DBHelper _dbHelper = DBHelper(); + + /// Groups save in shared_prefrences. + final KeyValueStorage _groupStorage = KeyValueStorage(groupsKey); + + //GroupList({List groups}) : _groups = groups ?? []; + + /// Default false, true during loading groups from storage. + bool _isLoading = false; + + bool get isLoading => _isLoading; + + /// Svae ordered gourps info before saved. + final List _orderChanged = []; + List get orderChanged => _orderChanged; + + /// Subscribe worker isolate + FlutterIsolate subIsolate; + ReceivePort receivePort; + SendPort subSendPort; + + /// Current subsribe item from isolate. + SubscribeItem _currentSubscribeItem = SubscribeItem('', ''); + SubscribeItem get currentSubscribeItem => _currentSubscribeItem; + + bool _created = false; + + /// Default false, true if subscribe isolate is created. + bool get created => _created; + + /// Add subsribe item + SubscribeItem _subscribeItem; + setSubscribeItem(SubscribeItem item, {bool syncGpodder = true}) async { + _subscribeItem = item; + if (syncGpodder) _syncAdd(item.url); + await _start(); + } + + _setCurrentSubscribeItem(SubscribeItem item) { + _currentSubscribeItem = item; + notifyListeners(); + } + + Future _syncAdd(String rssUrl) async { + final check = await _checkGpodderLoggedin(); + if (check) { + await _addStorage.addList([rssUrl]); + } + } + + Future _start() async { + if (!_created) { + await _createIsolate(); + _created = true; + listen(); + } else { + subSendPort.send([ + _subscribeItem.url, + _subscribeItem.title, + _subscribeItem.imgUrl, + _subscribeItem.group, + ]); + } + } + + Future _createIsolate() async { + receivePort = ReceivePort(); + subIsolate = + await FlutterIsolate.spawn(subIsolateEntryPoint, receivePort.sendPort); + } + + /// Isolate listener to get subscrribe status. + void listen() { + receivePort.distinct().listen((message) { + if (message is SendPort) { + subSendPort = message; + subSendPort.send([ + _subscribeItem.url, + _subscribeItem.title, + _subscribeItem.imgUrl, + _subscribeItem.group, + ]); + } else if (message is List) { + _setCurrentSubscribeItem(SubscribeItem( + message[1], + message[0], + subscribeState: SubscribeState.values[message[2]], + )); + if (message.length == 5) { + _subscribeNewPodcast(id: message[3], groupName: message[4]); + } + } else if (message is String && message == "done") { + subIsolate.kill(); + subIsolate = null; + _currentSubscribeItem = SubscribeItem('', ''); + _created = false; + notifyListeners(); + } + }); + } + + ///Set gpodder sync + final _loginInfp = KeyValueStorage(gpodderApiKey); + final _addStorage = KeyValueStorage(gpodderAddKey); + final _removeStorage = KeyValueStorage(gpodderRemoveKey); + final _remoteAddStorage = KeyValueStorage(gpodderRemoteAddKey); + final _remoteRemoveStorage = KeyValueStorage(gpodderRemoteRemoveKey); + + Future _checkGpodderLoggedin() async { + final loginInfo = await _loginInfp.getStringList(); + return loginInfo.isNotEmpty; + } + + Future gpodderSyncNow() async { + final addList = await _remoteAddStorage.getStringList(); + final removeList = await _remoteRemoveStorage.getStringList(); + + if (removeList.isNotEmpty) { + for (var rssLink in removeList) { + final exist = await _dbHelper.checkPodcast(rssLink); + if (exist != '') { + await _unsubscribe(exist); + } + } + await _remoteAddStorage.clearList(); + } + if (addList.isNotEmpty) { + for (var rssLink in addList) { + final exist = await _dbHelper.checkPodcast(rssLink); + if (exist == '') { + var item = SubscribeItem(rssLink, rssLink, group: 'Home'); + _subscribeItem = item; + await _start(); + + await Future.delayed(Duration(milliseconds: 200)); + } + } + await _remoteRemoveStorage.clearList(); + } + } + + void setWorkManager() { + Workmanager.initialize( + callbackDispatcher, + isInDebugMode: false, + ); + Workmanager.registerPeriodicTask("2", "gpodder_sync", + frequency: Duration(hours: 4), + initialDelay: Duration(seconds: 10), + constraints: Constraints( + networkType: NetworkType.connected, + )); + developer.log('work manager init done + (gpodder sync)'); + } + + Future cancelWork() async { + await Workmanager.cancelByUniqueName('2'); + developer.log('work job cancelled'); + } + + void addToOrderChanged(PodcastGroup group) { + _orderChanged.add(group); + notifyListeners(); + } + + void drlFromOrderChanged(String name) { + _orderChanged.removeWhere((group) => group.name == name); + notifyListeners(); + } + + Future clearOrderChanged() async { + if (_orderChanged.length > 0) { + for (var group in _orderChanged) { + await group.getPodcasts(); + } + _orderChanged.clear(); + // notifyListeners(); + } + } + + @override + void addListener(VoidCallback listener) { + loadGroups().then((value) => super.addListener(listener)); + gpodderSyncNow(); + } + + @override + void dispose() { + subIsolate?.kill(); + subIsolate = null; + super.dispose(); + } + + /// Load groups from storage at start. + Future loadGroups() async { + _isLoading = true; + notifyListeners(); + _groupStorage.getGroups().then((loadgroups) async { + _groups.addAll(loadgroups.map(PodcastGroup.fromEntity)); + for (var group in _groups) { + await group.getPodcasts(); + } + _isLoading = false; + notifyListeners(); + }); + } + + /// Update podcasts of each group + Future updateGroups() async { + for (var group in _groups) { + await group.getPodcasts(); + } + notifyListeners(); + } + + /// Add new group. + Future addGroup(PodcastGroup podcastGroup) async { + _isLoading = true; + _groups.add(podcastGroup); + await _saveGroup(); + _isLoading = false; + notifyListeners(); + } + + /// Remove group. + Future delGroup(PodcastGroup podcastGroup) async { + _isLoading = true; + for (var podcast in podcastGroup.podcastList) { + if (!_groups.first.podcastList.contains(podcast)) { + _groups[0].podcastList.insert(0, podcast); + } + } + await _saveGroup(); + _groups.remove(podcastGroup); + await _groups[0].getPodcasts(); + _isLoading = false; + notifyListeners(); + } + + Future updateGroup(PodcastGroup podcastGroup) async { + var oldGroup = _groups.firstWhere((it) => it.id == podcastGroup.id); + var index = _groups.indexOf(oldGroup); + _groups.replaceRange(index, index + 1, [podcastGroup]); + await podcastGroup.getPodcasts(); + notifyListeners(); + _saveGroup(); + } + + Future _saveGroup() async { + await _groupStorage.saveGroup(_groups.map((it) => it.toEntity()).toList()); + } + + /// Subscribe podcast from search result. + Future subscribe(PodcastLocal podcastLocal) async { + _groups[0].podcastList.insert(0, podcastLocal.id); + await _saveGroup(); + await _dbHelper.savePodcastLocal(podcastLocal); + await _groups[0].getPodcasts(); + notifyListeners(); + } + + Future updatePodcast(String id) async { + var counts = await _dbHelper.getPodcastCounts(id); + for (var group in _groups) { + if (group.podcastList.contains(id)) { + group.podcasts.firstWhere((podcast) => podcast.id == id) + ..episodeCount = counts; + notifyListeners(); + } + } + } + + /// Subscribe podcast from OPML. + Future _subscribeNewPodcast( + {String id, String groupName = 'Home'}) async { + //List groupNames = _groups.map((e) => e.name).toList(); + for (var group in _groups) { + if (group.name == groupName) { + if (group.podcastList.contains(id)) { + return true; + } else { + _isLoading = true; + notifyListeners(); + group.podcastList.insert(0, id); + await _saveGroup(); + await group.getPodcasts(); + _isLoading = false; + notifyListeners(); + return true; + } + } + } + _isLoading = true; + notifyListeners(); + _groups.add(PodcastGroup(groupName, podcastList: [id])); + //_groups.last.podcastList.insert(0, id); + await _saveGroup(); + await _groups.last.getPodcasts(); + _isLoading = false; + notifyListeners(); + return true; + } + + List getPodcastGroup(String id) { + var result = []; + for (var group in _groups) { + if (group.podcastList.contains(id)) { + result.add(group); + } + } + return result; + } + + //Change podcast groups + Future changeGroup(String id, List list) async { + _isLoading = true; + notifyListeners(); + + for (var group in getPodcastGroup(id)) { + if (list.contains(group)) { + list.remove(group); + } else { + group.podcastList.remove(id); + } + } + for (var s in list) { + s.podcastList.insert(0, id); + } + await _saveGroup(); + for (var group in _groups) { + await group.getPodcasts(); + } + _isLoading = false; + notifyListeners(); + } + + /// Unsubscribe podcast + Future _syncRemove(String rssUrl) async { + final check = await _checkGpodderLoggedin(); + if (check) { + await _removeStorage.addList([rssUrl]); + } + } + + Future _unsubscribe(String id) async { + _isLoading = true; + notifyListeners(); + for (var group in _groups) { + group.podcastList.remove(id); + } + await _saveGroup(); + await _dbHelper.delPodcastLocal(id); + for (var group in _groups) { + await group.getPodcasts(); + } + _isLoading = false; + notifyListeners(); + } + + Future removePodcast( + PodcastLocal podcast, + ) async { + _syncRemove(podcast.rssUrl); + final id = podcast.id; + await _unsubscribe(id); + } + + Future saveOrder(PodcastGroup group) async { + group.podcastList = group.orderedPodcasts.map((e) => e.id).toList(); + await _saveGroup(); + await group.getPodcasts(); + notifyListeners(); + } +} + +Future subIsolateEntryPoint(SendPort sendPort) async { + var items = []; + var _running = false; + final listColor = [ + '388E3C', + '1976D2', + 'D32F2F', + '00796B', + ]; + var subReceivePort = ReceivePort(); + sendPort.send(subReceivePort.sendPort); + + Future _getColor(File file) async { + final imageProvider = FileImage(file); + var colorImage = await getImageFromProvider(imageProvider); + var color = await getColorFromImage(colorImage); + var primaryColor = color.toString(); + return primaryColor; + } + + Future _subscribe(SubscribeItem item) async { + var dbHelper = DBHelper(); + var rss = item.url; + sendPort.send([item.title, item.url, 1]); + var options = BaseOptions( + connectTimeout: 30000, + receiveTimeout: 90000, + ); + + try { + var response = await Dio(options).get(rss); + RssFeed p; + try { + p = RssFeed.parse(response.data); + } catch (e) { + sendPort.send([item.title, item.url, 6]); + await Future.delayed(Duration(seconds: 2)); + sendPort.send([item.title, item.url, 4]); + items.removeWhere((element) => element.url == item.url); + if (items.isNotEmpty) { + await _subscribe(items.first); + } else { + sendPort.send("done"); + } + } + + var dir = await getApplicationDocumentsDirectory(); + + var realUrl = + response.redirects.isEmpty ? rss : response.realUri.toString(); + + var checkUrl = await dbHelper.checkPodcast(realUrl); + + /// If url not existe in database. + if (checkUrl == '') { + img.Image thumbnail; + String imageUrl; + try { + var imageResponse = await Dio().get>(p.itunes.image.href, + options: Options( + responseType: ResponseType.bytes, + receiveTimeout: 90000, + )); + imageUrl = p.itunes.image.href; + var image = img.decodeImage(imageResponse.data); + thumbnail = img.copyResize(image, width: 300); + } catch (e) { + try { + var imageResponse = await Dio().get>(item.imgUrl, + options: Options( + responseType: ResponseType.bytes, + receiveTimeout: 90000, + )); + imageUrl = item.imgUrl; + var image = img.decodeImage(imageResponse.data); + thumbnail = img.copyResize(image, width: 300); + } catch (e) { + developer.log(e.toString(), name: 'Download image error'); + try { + var index = math.Random().nextInt(3); + var imageResponse = await Dio().get>( + "https://ui-avatars.com/api/?size=300&background=" + "${listColor[index]}&color=fff&name=${item.title}&length=2&bold=true", + options: Options(responseType: ResponseType.bytes)); + imageUrl = "https://ui-avatars.com/api/?size=300&background=" + "${listColor[index]}&color=fff&name=${item.title}&length=2&bold=true"; + thumbnail = img.decodeImage(imageResponse.data); + } catch (e) { + developer.log(e.toString(), name: 'Donwload image error'); + sendPort.send([item.title, item.url, 6]); + await Future.delayed(Duration(seconds: 2)); + sendPort.send([item.title, item.url, 4]); + items.removeWhere((element) => element.url == item.url); + if (items.length > 0) { + await _subscribe(items.first); + } else { + sendPort.send("done"); + } + } + } + } + var uuid = Uuid().v4(); + File("${dir.path}/$uuid.png") + ..writeAsBytesSync(img.encodePng(thumbnail)); + + var imagePath = "${dir.path}/$uuid.png"; + var primaryColor = await _getColor(File("${dir.path}/$uuid.png")); + var author = p.itunes.author ?? p.author ?? ''; + var provider = p.generator ?? ''; + var link = p.link ?? ''; + var podcastLocal = PodcastLocal(p.title, imageUrl, realUrl, + primaryColor, author, uuid, imagePath, provider, link, + description: p.description); + + await dbHelper.savePodcastLocal(podcastLocal); + sendPort.send([item.title, item.url, 2, uuid, item.group]); + if (provider.contains('fireside')) { + var data = FiresideData(uuid, link); + try { + await data.fatchData(); + } catch (e) { + developer.log(e.toString(), name: 'Fatch fireside data error'); + } + } + await dbHelper.savePodcastRss(p, uuid); + + // if (item.syncWithGpodder) { + // final gpodder = Gpodder(); + // await gpodder.updateChange({ + // 'add': [item.url] + // }); + // } + + sendPort.send([item.title, item.url, 3, uuid]); + + await Future.delayed(Duration(seconds: 2)); + + sendPort.send([item.title, item.url, 4]); + items.removeAt(0); + if (items.length > 0) { + await _subscribe(items.first); + } else { + sendPort.send("done"); + } + } else { + sendPort.send([item.title, realUrl, 5, checkUrl, item.group]); + await Future.delayed(Duration(seconds: 2)); + sendPort.send([item.title, item.url, 4]); + items.removeAt(0); + if (items.length > 0) { + await _subscribe(items.first); + } else { + sendPort.send("done"); + } + } + } catch (e) { + developer.log('$e confirm'); + sendPort.send([item.title, item.url, 6]); + await Future.delayed(Duration(seconds: 2)); + sendPort.send([item.title, item.url, 4]); + items.removeWhere((element) => element.url == item.url); + if (items.length > 0) { + await _subscribe(items.first); + } else { + sendPort.send("done"); + } + } + } + + subReceivePort.distinct().listen((message) { + if (message is List) { + items.add(SubscribeItem(message[0], message[1], + imgUrl: message[2], group: message[3])); + if (!_running) { + _subscribe(items.first); + _running = true; + } + } + }); +} diff --git a/lib/state/refresh_podcast.dart b/lib/state/refresh_podcast.dart index 7450c1a..1b8d388 100644 --- a/lib/state/refresh_podcast.dart +++ b/lib/state/refresh_podcast.dart @@ -1,103 +1,103 @@ -import 'dart:developer' as developer; -import 'dart:isolate'; - -import 'package:flutter/material.dart'; -import 'package:flutter_isolate/flutter_isolate.dart'; - -import '../local_storage/key_value_storage.dart'; -import '../local_storage/sqflite_localpodcast.dart'; - -enum RefreshState { none, fetch, error, artwork } - -class RefreshItem { - String title; - RefreshState refreshState; - bool artwork; - RefreshItem(this.title, this.refreshState, {this.artwork = false}); -} - -class RefreshWorker extends ChangeNotifier { - FlutterIsolate refreshIsolate; - ReceivePort receivePort; - SendPort refreshSendPort; - - RefreshItem _currentRefreshItem = RefreshItem('', RefreshState.none); - bool _complete = false; - RefreshItem get currentRefreshItem => _currentRefreshItem; - bool get complete => _complete; - - bool _created = false; - - Future _createIsolate() async { - receivePort = ReceivePort(); - refreshIsolate = await FlutterIsolate.spawn( - refreshIsolateEntryPoint, receivePort.sendPort); - } - - void _listen(List podcasts) { - receivePort.distinct().listen((message) { - if (message is SendPort) { - refreshSendPort = message; - refreshSendPort.send(podcasts); - } - if (message is List) { - _currentRefreshItem = - RefreshItem(message[0], RefreshState.values[message[1]]); - notifyListeners(); - } else if (message is String && message == "done") { - _currentRefreshItem = RefreshItem('', RefreshState.none); - _complete = true; - notifyListeners(); - refreshIsolate?.kill(); - refreshIsolate = null; - _created = false; - } - }); - } - - Future start(List podcasts) async { - if (!_created) { - if (podcasts.isEmpty) { - final refreshstorage = KeyValueStorage(refreshdateKey); - await refreshstorage.saveInt(DateTime.now().millisecondsSinceEpoch); - } - _complete = false; - await _createIsolate(); - _listen(podcasts); - _created = true; - } - } - - void dispose() { - refreshIsolate?.kill(); - refreshIsolate = null; - super.dispose(); - } -} - -Future refreshIsolateEntryPoint(SendPort sendPort) async { - var refreshReceivePort = ReceivePort(); - sendPort.send(refreshReceivePort.sendPort); - var _dbHelper = DBHelper(); - - Future _refreshAll(List podcasts) async { - var podcastList; - if (podcasts.isEmpty) { - podcastList = await _dbHelper.getPodcastLocalAll(updateOnly: true); - } else { - podcastList = await _dbHelper.getPodcastLocal(podcasts, updateOnly: true); - } - for (var podcastLocal in podcastList) { - sendPort.send([podcastLocal.title, 1]); - var updateCount = await _dbHelper.updatePodcastRss(podcastLocal); - developer.log('Refresh ${podcastLocal.title}$updateCount'); - } - sendPort.send("done"); - } - - refreshReceivePort.distinct().listen((message) { - if (message is List) { - _refreshAll(message); - } - }); -} +import 'dart:developer' as developer; +import 'dart:isolate'; + +import 'package:flutter/material.dart'; +import 'package:flutter_isolate/flutter_isolate.dart'; + +import '../local_storage/key_value_storage.dart'; +import '../local_storage/sqflite_localpodcast.dart'; + +enum RefreshState { none, fetch, error, artwork } + +class RefreshItem { + String title; + RefreshState refreshState; + bool artwork; + RefreshItem(this.title, this.refreshState, {this.artwork = false}); +} + +class RefreshWorker extends ChangeNotifier { + FlutterIsolate refreshIsolate; + ReceivePort receivePort; + SendPort refreshSendPort; + + RefreshItem _currentRefreshItem = RefreshItem('', RefreshState.none); + bool _complete = false; + RefreshItem get currentRefreshItem => _currentRefreshItem; + bool get complete => _complete; + + bool _created = false; + + Future _createIsolate() async { + receivePort = ReceivePort(); + refreshIsolate = await FlutterIsolate.spawn( + refreshIsolateEntryPoint, receivePort.sendPort); + } + + void _listen(List podcasts) { + receivePort.distinct().listen((message) { + if (message is SendPort) { + refreshSendPort = message; + refreshSendPort.send(podcasts); + } + if (message is List) { + _currentRefreshItem = + RefreshItem(message[0], RefreshState.values[message[1]]); + notifyListeners(); + } else if (message is String && message == "done") { + _currentRefreshItem = RefreshItem('', RefreshState.none); + _complete = true; + notifyListeners(); + refreshIsolate?.kill(); + refreshIsolate = null; + _created = false; + } + }); + } + + Future start(List podcasts) async { + if (!_created) { + if (podcasts.isEmpty) { + final refreshstorage = KeyValueStorage(refreshdateKey); + await refreshstorage.saveInt(DateTime.now().millisecondsSinceEpoch); + } + _complete = false; + await _createIsolate(); + _listen(podcasts); + _created = true; + } + } + + void dispose() { + refreshIsolate?.kill(); + refreshIsolate = null; + super.dispose(); + } +} + +Future refreshIsolateEntryPoint(SendPort sendPort) async { + var refreshReceivePort = ReceivePort(); + sendPort.send(refreshReceivePort.sendPort); + var _dbHelper = DBHelper(); + + Future _refreshAll(List podcasts) async { + var podcastList; + if (podcasts.isEmpty) { + podcastList = await _dbHelper.getPodcastLocalAll(updateOnly: true); + } else { + podcastList = await _dbHelper.getPodcastLocal(podcasts, updateOnly: true); + } + for (var podcastLocal in podcastList) { + sendPort.send([podcastLocal.title, 1]); + var updateCount = await _dbHelper.updatePodcastRss(podcastLocal); + developer.log('Refresh ${podcastLocal.title}$updateCount'); + } + sendPort.send("done"); + } + + refreshReceivePort.distinct().listen((message) { + if (message is List) { + _refreshAll(message); + } + }); +} diff --git a/lib/state/search_state.dart b/lib/state/search_state.dart index 250df4c..0cf4391 100644 --- a/lib/state/search_state.dart +++ b/lib/state/search_state.dart @@ -1,33 +1,33 @@ -import 'package:flutter/material.dart'; -import '../type/search_api/searchpodcast.dart'; - -class SearchState extends ChangeNotifier { - final List _subscribedList = []; - bool _update = false; - List get subscribedList => _subscribedList; - bool get update => _update; - OnlinePodcast _selectedPodcast; - OnlinePodcast get selectedPodcast => _selectedPodcast; - - set selectedPodcast(OnlinePodcast podcast) { - _selectedPodcast = podcast; - notifyListeners(); - } - - bool isSubscribed(OnlinePodcast podcast) => _subscribedList.contains(podcast); - - void clearSelect() { - _selectedPodcast = null; - notifyListeners(); - } - - void clearList() { - _subscribedList.clear(); - } - - void addPodcast(OnlinePodcast podcast) { - _subscribedList.add(podcast); - _update = !_update; - notifyListeners(); - } -} +import 'package:flutter/material.dart'; +import '../type/search_api/searchpodcast.dart'; + +class SearchState extends ChangeNotifier { + final List _subscribedList = []; + bool _update = false; + List get subscribedList => _subscribedList; + bool get update => _update; + OnlinePodcast _selectedPodcast; + OnlinePodcast get selectedPodcast => _selectedPodcast; + + set selectedPodcast(OnlinePodcast podcast) { + _selectedPodcast = podcast; + notifyListeners(); + } + + bool isSubscribed(OnlinePodcast podcast) => _subscribedList.contains(podcast); + + void clearSelect() { + _selectedPodcast = null; + notifyListeners(); + } + + void clearList() { + _subscribedList.clear(); + } + + void addPodcast(OnlinePodcast podcast) { + _subscribedList.add(podcast); + _update = !_update; + notifyListeners(); + } +} diff --git a/lib/state/setting_state.dart b/lib/state/setting_state.dart index ea2e7c7..43128d7 100644 --- a/lib/state/setting_state.dart +++ b/lib/state/setting_state.dart @@ -1,606 +1,606 @@ -import 'dart:developer' as developer; -import 'dart:io'; -import 'dart:ui'; - -import 'package:connectivity/connectivity.dart'; -import 'package:flutter/foundation.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_downloader/flutter_downloader.dart'; -import 'package:google_fonts/google_fonts.dart'; -import 'package:intl/intl.dart'; -import 'package:intl/intl_standalone.dart'; -import 'package:workmanager/workmanager.dart'; - -import '../generated/l10n.dart'; -import '../local_storage/key_value_storage.dart'; -import '../local_storage/sqflite_localpodcast.dart'; -import '../type/settings_backup.dart'; -import 'download_state.dart'; - -void callbackDispatcher() { - if (Platform.isAndroid) { - Workmanager.executeTask((task, inputData) async { - var dbHelper = DBHelper(); - var podcastList = await dbHelper.getPodcastLocalAll(updateOnly: false); - //lastWork is a indicator for if the app was opened since last backgroundwork - //if the app wes opend,then the old marked new episode would be marked not new. - var lastWorkStorage = KeyValueStorage(lastWorkKey); - var lastWork = await lastWorkStorage.getInt(); - for (var podcastLocal in podcastList) { - await dbHelper.updatePodcastRss(podcastLocal, removeMark: lastWork); - developer.log('Refresh ${podcastLocal.title}'); - } - await FlutterDownloader.initialize(); - var downloader = AutoDownloader(); - - var autoDownloadStorage = KeyValueStorage(autoDownloadNetworkKey); - var autoDownloadNetwork = await autoDownloadStorage.getInt(); - var result = await Connectivity().checkConnectivity(); - if (autoDownloadNetwork == 1) { - var episodes = await dbHelper.getNewEpisodes('all'); - // For safety - if (episodes.length < 100 && episodes.length > 0) { - downloader.bindBackgroundIsolate(); - await downloader.startTask(episodes); - } - } else if (result == ConnectivityResult.wifi) { - var episodes = await dbHelper.getNewEpisodes('all'); - //For safety - if (episodes.length < 100 && episodes.length > 0) { - downloader.bindBackgroundIsolate(); - await downloader.startTask(episodes); - } - } - await lastWorkStorage.saveInt(1); - var refreshstorage = KeyValueStorage(refreshdateKey); - await refreshstorage.saveInt(DateTime.now().millisecondsSinceEpoch); - return Future.value(true); - }); - } -} - -ThemeData lightTheme = ThemeData( - accentColorBrightness: Brightness.dark, - primaryColor: Colors.grey[100], - primaryColorLight: Colors.white, - primaryColorDark: Colors.grey[300], - dialogBackgroundColor: Colors.white, - backgroundColor: Colors.grey[100], - appBarTheme: AppBarTheme( - color: Colors.grey[100], - elevation: 0, - ), - textTheme: TextTheme( - bodyText2: TextStyle(fontSize: 15.0, fontWeight: FontWeight.normal), - ), - tabBarTheme: TabBarTheme( - labelColor: Colors.black, - unselectedLabelColor: Colors.grey[400], - ), - buttonTheme: ButtonThemeData(height: 32), -); - -final showNotesFontStyles = [ - TextStyle( - height: 1.8, - ), - GoogleFonts.martel( - textStyle: TextStyle( - height: 1.8, - )), - GoogleFonts.bitter( - textStyle: TextStyle( - height: 1.8, - )), -]; - -class SettingState extends ChangeNotifier { - var themeStorage = KeyValueStorage(themesKey); - var accentStorage = KeyValueStorage(accentsKey); - var autoupdateStorage = KeyValueStorage(autoUpdateKey); - var intervalStorage = KeyValueStorage(updateIntervalKey); - var downloadUsingDataStorage = KeyValueStorage(downloadUsingDataKey); - var introStorage = KeyValueStorage(introKey); - var realDarkStorage = KeyValueStorage(realDarkKey); - var autoPlayStorage = KeyValueStorage(autoPlayKey); - var defaultSleepTimerStorage = KeyValueStorage(defaultSleepTimerKey); - var autoSleepTimerStorage = KeyValueStorage(autoSleepTimerKey); - var autoSleepTimerModeStorage = KeyValueStorage(autoSleepTimerModeKey); - var autoSleepTimerStartStorage = KeyValueStorage(autoSleepTimerStartKey); - var autoSleepTimerEndStorage = KeyValueStorage(autoSleepTimerEndKey); - var tapToOpenPopupMenuStorage = KeyValueStorage(tapToOpenPopupMenuKey); - var cacheStorage = KeyValueStorage(cacheMaxKey); - var podcastLayoutStorage = KeyValueStorage(podcastLayoutKey); - var favLayoutStorage = KeyValueStorage(favLayoutKey); - var downloadLayoutStorage = KeyValueStorage(downloadLayoutKey); - var recentLayoutStorage = KeyValueStorage(recentLayoutKey); - var autoDeleteStorage = KeyValueStorage(autoDeleteKey); - var autoDownloadStorage = KeyValueStorage(autoDownloadNetworkKey); - var fastForwardSecondsStorage = KeyValueStorage(fastForwardSecondsKey); - var rewindSecondsStorage = KeyValueStorage(rewindSecondsKey); - var localeStorage = KeyValueStorage(localeKey); - var showNotesFontStorage = KeyValueStorage(showNotesFontKey); - - Future initData() async { - await _getTheme(); - await _getAccentSetColor(); - await _getShowIntro(); - await _getRealDark(); - } - - Locale _locale; - - /// Load locale. - Locale get locale => _locale; - - /// Spp thememode. default auto. - ThemeMode _theme; - ThemeMode get theme => _theme; - - set setTheme(ThemeMode mode) { - _theme = mode; - _saveTheme(); - notifyListeners(); - } - - void setWorkManager(int hour) { - _updateInterval = hour; - notifyListeners(); - _saveUpdateInterval(); - Workmanager.initialize( - callbackDispatcher, - isInDebugMode: false, - ); - Workmanager.registerPeriodicTask("1", "update_podcasts", - frequency: Duration(hours: hour), - initialDelay: Duration(seconds: 10), - constraints: Constraints( - networkType: NetworkType.connected, - )); - developer.log('work manager init done + '); - } - - Future cancelWork() async { - await Workmanager.cancelByUniqueName('1'); - developer.log('work job cancelled'); - } - - Color _accentSetColor; - Color get accentSetColor => _accentSetColor; - - set setAccentColor(Color color) { - _accentSetColor = color; - _saveAccentSetColor(); - notifyListeners(); - } - - int _updateInterval; - int get updateInterval => _updateInterval; - - int _initUpdateTag; - - /// Auto syncing podcasts in background, default true. - bool _autoUpdate; - bool get autoUpdate => _autoUpdate; - set autoUpdate(bool boo) { - _autoUpdate = boo; - _saveAutoUpdate(); - notifyListeners(); - } - - /// Confirem before using data to download episode, default true(reverse). - bool _downloadUsingData; - bool get downloadUsingData => _downloadUsingData; - set downloadUsingData(bool boo) { - _downloadUsingData = boo; - _saveDownloadUsingData(); - notifyListeners(); - } - - int _initialShowIntor; - bool _showIntro; - bool get showIntro => _showIntro; - - /// Real dark theme, default false. - bool _realDark; - bool get realDark => _realDark; - set setRealDark(bool boo) { - _realDark = boo; - _setRealDark(); - notifyListeners(); - } - - int _defaultSleepTimer; - int get defaultSleepTimer => _defaultSleepTimer; - set setDefaultSleepTimer(int i) { - _defaultSleepTimer = i; - _setDefaultSleepTimer(); - notifyListeners(); - } - - bool _autoPlay; - bool get autoPlay => _autoPlay; - set setAutoPlay(bool boo) { - _autoPlay = boo; - notifyListeners(); - _saveAutoPlay(); - } - - /// Auto start sleep timer at night. Defualt false. - bool _autoSleepTimer; - bool get autoSleepTimer => _autoSleepTimer; - set setAutoSleepTimer(bool boo) { - _autoSleepTimer = boo; - notifyListeners(); - _saveAutoSleepTimer(); - } - - int _autoSleepTimerMode; - int get autoSleepTimerMode => _autoSleepTimerMode; - set setAutoSleepTimerMode(int mode) { - _autoSleepTimerMode = mode; - notifyListeners(); - _saveAutoSleepTimerMode(); - } - - int _autoSleepTimerStart; - int get autoSleepTimerStart => _autoSleepTimerStart; - set setAutoSleepTimerStart(int start) { - _autoSleepTimerStart = start; - notifyListeners(); - _saveAutoSleepTimerStart(); - } - - int _autoSleepTimerEnd; - int get autoSleepTimerEnd => _autoSleepTimerEnd; - set setAutoSleepTimerEnd(int end) { - _autoSleepTimerEnd = end; - notifyListeners(); - _saveAutoSleepTimerEnd(); - } - - int _fastForwardSeconds; - int get fastForwardSeconds => _fastForwardSeconds; - set setFastForwardSeconds(int sec) { - _fastForwardSeconds = sec; - notifyListeners(); - _saveFastForwardSeconds(); - } - - int _rewindSeconds; - int get rewindSeconds => _rewindSeconds; - set setRewindSeconds(int sec) { - _rewindSeconds = sec; - notifyListeners(); - _saveRewindSeconds(); - } - - int _showNotesFontIndex; - int get showNotesFontIndex => _showNotesFontIndex; - TextStyle get showNoteFontStyle => showNotesFontStyles[_showNotesFontIndex]; - set setShowNoteFontStyle(int index) { - _showNotesFontIndex = index; - notifyListeners(); - _saveShowNotesFonts(); - } - - @override - void addListener(VoidCallback listener) { - super.addListener(listener); - _getLocale(); - _getAutoUpdate(); - _getDownloadUsingData(); - _getSleepTimerData(); - _getPlayerSeconds(); - _getShowNotesFonts(); - _getUpdateInterval().then((value) async { - if (_initUpdateTag == 0) { - setWorkManager(24); - } else if (_autoUpdate && _initialShowIntor == 1) { - await cancelWork(); - setWorkManager(_initUpdateTag); - await saveShowIntro(2); - } - }); - } - - Future _getTheme() async { - var mode = await themeStorage.getInt(); - _theme = ThemeMode.values[mode]; - } - - Future _getAccentSetColor() async { - var colorString = await accentStorage.getString(); - if (colorString.isNotEmpty) { - var color = int.parse('FF${colorString.toUpperCase()}', radix: 16); - _accentSetColor = Color(color).withOpacity(1.0); - } else { - _accentSetColor = Colors.teal[500]; - await _saveAccentSetColor(); - } - } - - Future _getAutoUpdate() async { - _autoUpdate = - await autoupdateStorage.getBool(defaultValue: true, reverse: true); - } - - Future _getUpdateInterval() async { - _initUpdateTag = await intervalStorage.getInt(); - _updateInterval = _initUpdateTag; - } - - Future _getDownloadUsingData() async { - _downloadUsingData = await downloadUsingDataStorage.getBool( - defaultValue: true, reverse: true); - } - - Future _saveDownloadUsingData() async { - await downloadUsingDataStorage.saveBool(_downloadUsingData, reverse: true); - } - - Future _getShowIntro() async { - _initialShowIntor = await introStorage.getInt(); - _showIntro = _initialShowIntor == 0 ? true : false; - } - - Future _getRealDark() async { - _realDark = await realDarkStorage.getBool(defaultValue: false); - } - - Future _getSleepTimerData() async { - _defaultSleepTimer = - await defaultSleepTimerStorage.getInt(defaultValue: 30); - _autoSleepTimer = await autoSleepTimerStorage.getBool(defaultValue: false); - _autoSleepTimerStart = - await autoSleepTimerStartStorage.getInt(defaultValue: 1380); - _autoSleepTimerEnd = - await autoSleepTimerEndStorage.getInt(defaultValue: 360); - _autoPlay = - await autoPlayStorage.getBool(defaultValue: true, reverse: true); - _autoSleepTimerMode = await autoSleepTimerModeStorage.getInt(); - } - - Future _getPlayerSeconds() async { - _rewindSeconds = await rewindSecondsStorage.getInt(defaultValue: 10); - _fastForwardSeconds = - await fastForwardSecondsStorage.getInt(defaultValue: 30); - } - - Future _getLocale() async { - var localeString = await localeStorage.getStringList(); - if (localeString.isEmpty) { - await findSystemLocale(); - var systemLanCode; - final list = Intl.systemLocale.split('_'); - if (list.length == 2) { - systemLanCode = list.first; - } else if (list.length == 3) { - systemLanCode = '${list[0]}_${list[1]}'; - } else { - systemLanCode = 'en'; - } - _locale = Locale(systemLanCode); - } else { - _locale = Locale(localeString.first, localeString[1]); - } - await S.load(_locale); - } - - Future _getShowNotesFonts() async { - _showNotesFontIndex = await showNotesFontStorage.getInt(defaultValue: 1); - } - - Future _saveAccentSetColor() async { - await accentStorage - .saveString(_accentSetColor.toString().substring(10, 16)); - } - - Future _setRealDark() async { - await realDarkStorage.saveBool(_realDark); - } - - Future saveShowIntro(int i) async { - await introStorage.saveInt(i); - } - - Future _saveUpdateInterval() async { - await intervalStorage.saveInt(_updateInterval); - } - - Future _saveTheme() async { - await themeStorage.saveInt(_theme.index); - } - - Future _saveAutoUpdate() async { - await autoupdateStorage.saveBool(_autoUpdate, reverse: true); - } - - Future _saveAutoPlay() async { - await autoPlayStorage.saveBool(_autoPlay, reverse: true); - } - - Future _setDefaultSleepTimer() async { - await defaultSleepTimerStorage.saveInt(_defaultSleepTimer); - } - - Future _saveAutoSleepTimer() async { - await autoSleepTimerStorage.saveBool(_autoSleepTimer); - } - - Future _saveAutoSleepTimerMode() async { - await autoSleepTimerModeStorage.saveInt(_autoSleepTimerMode); - } - - Future _saveAutoSleepTimerStart() async { - await autoSleepTimerStartStorage.saveInt(_autoSleepTimerStart); - } - - Future _saveAutoSleepTimerEnd() async { - await autoSleepTimerEndStorage.saveInt(_autoSleepTimerEnd); - } - - Future _saveFastForwardSeconds() async { - await fastForwardSecondsStorage.saveInt(_fastForwardSeconds); - } - - Future _saveRewindSeconds() async { - await rewindSecondsStorage.saveInt(_rewindSeconds); - } - - Future _saveShowNotesFonts() async { - await showNotesFontStorage.saveInt(_showNotesFontIndex); - } - - Future backup() async { - var theme = await themeStorage.getInt(); - var accentColor = await accentStorage.getString(); - var realDark = await realDarkStorage.getBool(defaultValue: false); - var autoPlay = - await autoPlayStorage.getBool(defaultValue: true, reverse: true); - var autoUpdate = - await autoupdateStorage.getBool(defaultValue: true, reverse: true); - var updateInterval = await intervalStorage.getInt(); - var downloadUsingData = await downloadUsingDataStorage.getBool( - defaultValue: true, reverse: true); - var cacheMax = await cacheStorage.getInt(defaultValue: 500 * 1024 * 1024); - var podcastLayout = await podcastLayoutStorage.getInt(); - var recentLayout = await recentLayoutStorage.getInt(); - var favLayout = await favLayoutStorage.getInt(); - var downloadLayout = await downloadLayoutStorage.getInt(); - var autoDownloadNetwork = - await autoDownloadStorage.getBool(defaultValue: false); - var episodePopupMenu = await KeyValueStorage(episodePopupMenuKey).getMenu(); - var autoDelete = await autoDeleteStorage.getInt(); - var autoSleepTimer = - await autoSleepTimerStorage.getBool(defaultValue: false); - var autoSleepTimerStart = await autoSleepTimerStartStorage.getInt(); - var autoSleepTimerEnd = await autoSleepTimerEndStorage.getInt(); - var autoSleepTimerMode = await autoSleepTimerModeStorage.getInt(); - var defaultSleepTime = await defaultSleepTimerStorage.getInt(); - var tapToOpenPopupMenu = await KeyValueStorage(tapToOpenPopupMenuKey) - .getBool(defaultValue: false); - var fastForwardSeconds = - await fastForwardSecondsStorage.getInt(defaultValue: 30); - var rewindSeconds = await rewindSecondsStorage.getInt(defaultValue: 10); - var playerHeight = - await KeyValueStorage(playerHeightKey).getInt(defaultValue: 0); - var localeList = await localeStorage.getStringList(); - var backupLocale = - localeList.isEmpty ? '' : '${'${localeList.first}-'}${localeList[1]}'; - var hideListened = - await KeyValueStorage(hideListenedKey).getBool(defaultValue: false); - var notificationLayout = - await KeyValueStorage(notificationLayoutKey).getInt(defaultValue: 0); - var showNotesFont = await showNotesFontStorage.getInt(defaultValue: 1); - var speedList = await KeyValueStorage(speedListKey).getStringList(); - var hidePodcastDiscovery = await KeyValueStorage(hidePodcastDiscoveryKey) - .getBool(defaultValue: false); - final markListenedAfterSKip = - await KeyValueStorage(markListenedAfterSkipKey) - .getBool(defaultValue: false); - final deleteAfterPlayed = await KeyValueStorage(deleteAfterPlayedKey) - .getBool(defaultValue: false); - - return SettingsBackup( - theme: theme, - accentColor: accentColor, - realDark: realDark, - autoPlay: autoPlay, - autoUpdate: autoUpdate, - updateInterval: updateInterval, - downloadUsingData: downloadUsingData, - cacheMax: cacheMax, - podcastLayout: podcastLayout, - recentLayout: recentLayout, - favLayout: favLayout, - downloadLayout: downloadLayout, - autoDownloadNetwork: autoDownloadNetwork, - episodePopupMenu: episodePopupMenu.map((e) => e.toString()).toList(), - autoDelete: autoDelete, - autoSleepTimer: autoSleepTimer, - autoSleepTimerStart: autoSleepTimerStart, - autoSleepTimerEnd: autoSleepTimerEnd, - autoSleepTimerMode: autoSleepTimerMode, - defaultSleepTime: defaultSleepTime, - tapToOpenPopupMenu: tapToOpenPopupMenu, - fastForwardSeconds: fastForwardSeconds, - rewindSeconds: rewindSeconds, - playerHeight: playerHeight, - locale: backupLocale, - hideListened: hideListened, - notificationLayout: notificationLayout, - showNotesFont: showNotesFont, - speedList: speedList, - hidePodcastDiscovery: hidePodcastDiscovery, - markListenedAfterSkip: markListenedAfterSKip, - deleteAfterPlayed: deleteAfterPlayed); - } - - Future restore(SettingsBackup backup) async { - await themeStorage.saveInt(backup.theme); - await accentStorage.saveString(backup.accentColor); - await realDarkStorage.saveBool(backup.realDark); - await autoPlayStorage.saveBool(backup.autoPlay, reverse: true); - await autoupdateStorage.saveBool(backup.autoUpdate, reverse: true); - await intervalStorage.saveInt(backup.updateInterval); - await downloadUsingDataStorage.saveBool(backup.downloadUsingData, - reverse: true); - await cacheStorage.saveInt(backup.cacheMax); - await podcastLayoutStorage.saveInt(backup.podcastLayout); - await recentLayoutStorage.saveInt(backup.recentLayout); - await favLayoutStorage.saveInt(backup.favLayout); - await downloadLayoutStorage.saveInt(backup.downloadLayout); - await autoDownloadStorage.saveBool(backup.autoDownloadNetwork); - await KeyValueStorage(episodePopupMenuKey) - .saveStringList(backup.episodePopupMenu); - await autoDeleteStorage.saveInt(backup.autoDelete); - await autoSleepTimerStorage.saveBool(backup.autoSleepTimer); - await autoSleepTimerStartStorage.saveInt(backup.autoSleepTimerStart); - await autoSleepTimerEndStorage.saveInt(backup.autoSleepTimerEnd); - await autoSleepTimerModeStorage.saveInt(backup.autoSleepTimerMode); - await defaultSleepTimerStorage.saveInt(backup.defaultSleepTime); - await fastForwardSecondsStorage.saveInt(backup.fastForwardSeconds); - await rewindSecondsStorage.saveInt(backup.rewindSeconds); - await KeyValueStorage(playerHeightKey).saveInt(backup.playerHeight); - await KeyValueStorage(tapToOpenPopupMenuKey) - .saveBool(backup.tapToOpenPopupMenu); - await KeyValueStorage(hideListenedKey).saveBool(backup.hideListened); - await KeyValueStorage(notificationLayoutKey) - .saveInt(backup.notificationLayout); - await showNotesFontStorage.saveInt(backup.showNotesFont); - await KeyValueStorage(speedListKey).saveStringList(backup.speedList); - await KeyValueStorage(markListenedAfterSkipKey) - .saveBool(backup.markListenedAfterSkip); - await KeyValueStorage(deleteAfterPlayedKey) - .saveBool(backup.deleteAfterPlayed); - - if (backup.locale == '') { - await localeStorage.saveStringList([]); - await S.load(Locale(Intl.systemLocale)); - } else { - var localeList = backup.locale.split('-'); - var backupLocale; - if (localeList[1] == 'null') { - backupLocale = Locale(localeList.first); - } else { - backupLocale = Locale(localeList.first, localeList[1]); - } - await localeStorage.saveStringList( - [backupLocale.languageCode, backupLocale.countryCode]); - await S.load(backupLocale); - } - await initData(); - await _getAutoUpdate(); - await _getDownloadUsingData(); - await _getSleepTimerData(); - await _getShowNotesFonts(); - await _getUpdateInterval().then((value) async { - if (_autoUpdate) { - await cancelWork(); - setWorkManager(_initUpdateTag); - await saveShowIntro(2); - } - }); - } -} +import 'dart:developer' as developer; +import 'dart:io'; +import 'dart:ui'; + +import 'package:connectivity/connectivity.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_downloader/flutter_downloader.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:intl/intl.dart'; +import 'package:intl/intl_standalone.dart'; +import 'package:workmanager/workmanager.dart'; + +import '../generated/l10n.dart'; +import '../local_storage/key_value_storage.dart'; +import '../local_storage/sqflite_localpodcast.dart'; +import '../type/settings_backup.dart'; +import 'download_state.dart'; + +void callbackDispatcher() { + if (Platform.isAndroid) { + Workmanager.executeTask((task, inputData) async { + var dbHelper = DBHelper(); + var podcastList = await dbHelper.getPodcastLocalAll(updateOnly: false); + //lastWork is a indicator for if the app was opened since last backgroundwork + //if the app wes opend,then the old marked new episode would be marked not new. + var lastWorkStorage = KeyValueStorage(lastWorkKey); + var lastWork = await lastWorkStorage.getInt(); + for (var podcastLocal in podcastList) { + await dbHelper.updatePodcastRss(podcastLocal, removeMark: lastWork); + developer.log('Refresh ${podcastLocal.title}'); + } + await FlutterDownloader.initialize(); + var downloader = AutoDownloader(); + + var autoDownloadStorage = KeyValueStorage(autoDownloadNetworkKey); + var autoDownloadNetwork = await autoDownloadStorage.getInt(); + var result = await Connectivity().checkConnectivity(); + if (autoDownloadNetwork == 1) { + var episodes = await dbHelper.getNewEpisodes('all'); + // For safety + if (episodes.length < 100 && episodes.length > 0) { + downloader.bindBackgroundIsolate(); + await downloader.startTask(episodes); + } + } else if (result == ConnectivityResult.wifi) { + var episodes = await dbHelper.getNewEpisodes('all'); + //For safety + if (episodes.length < 100 && episodes.length > 0) { + downloader.bindBackgroundIsolate(); + await downloader.startTask(episodes); + } + } + await lastWorkStorage.saveInt(1); + var refreshstorage = KeyValueStorage(refreshdateKey); + await refreshstorage.saveInt(DateTime.now().millisecondsSinceEpoch); + return Future.value(true); + }); + } +} + +ThemeData lightTheme = ThemeData( + accentColorBrightness: Brightness.dark, + primaryColor: Colors.grey[100], + primaryColorLight: Colors.white, + primaryColorDark: Colors.grey[300], + dialogBackgroundColor: Colors.white, + backgroundColor: Colors.grey[100], + appBarTheme: AppBarTheme( + color: Colors.grey[100], + elevation: 0, + ), + textTheme: TextTheme( + bodyText2: TextStyle(fontSize: 15.0, fontWeight: FontWeight.normal), + ), + tabBarTheme: TabBarTheme( + labelColor: Colors.black, + unselectedLabelColor: Colors.grey[400], + ), + buttonTheme: ButtonThemeData(height: 32), +); + +final showNotesFontStyles = [ + TextStyle( + height: 1.8, + ), + GoogleFonts.martel( + textStyle: TextStyle( + height: 1.8, + )), + GoogleFonts.bitter( + textStyle: TextStyle( + height: 1.8, + )), +]; + +class SettingState extends ChangeNotifier { + var themeStorage = KeyValueStorage(themesKey); + var accentStorage = KeyValueStorage(accentsKey); + var autoupdateStorage = KeyValueStorage(autoUpdateKey); + var intervalStorage = KeyValueStorage(updateIntervalKey); + var downloadUsingDataStorage = KeyValueStorage(downloadUsingDataKey); + var introStorage = KeyValueStorage(introKey); + var realDarkStorage = KeyValueStorage(realDarkKey); + var autoPlayStorage = KeyValueStorage(autoPlayKey); + var defaultSleepTimerStorage = KeyValueStorage(defaultSleepTimerKey); + var autoSleepTimerStorage = KeyValueStorage(autoSleepTimerKey); + var autoSleepTimerModeStorage = KeyValueStorage(autoSleepTimerModeKey); + var autoSleepTimerStartStorage = KeyValueStorage(autoSleepTimerStartKey); + var autoSleepTimerEndStorage = KeyValueStorage(autoSleepTimerEndKey); + var tapToOpenPopupMenuStorage = KeyValueStorage(tapToOpenPopupMenuKey); + var cacheStorage = KeyValueStorage(cacheMaxKey); + var podcastLayoutStorage = KeyValueStorage(podcastLayoutKey); + var favLayoutStorage = KeyValueStorage(favLayoutKey); + var downloadLayoutStorage = KeyValueStorage(downloadLayoutKey); + var recentLayoutStorage = KeyValueStorage(recentLayoutKey); + var autoDeleteStorage = KeyValueStorage(autoDeleteKey); + var autoDownloadStorage = KeyValueStorage(autoDownloadNetworkKey); + var fastForwardSecondsStorage = KeyValueStorage(fastForwardSecondsKey); + var rewindSecondsStorage = KeyValueStorage(rewindSecondsKey); + var localeStorage = KeyValueStorage(localeKey); + var showNotesFontStorage = KeyValueStorage(showNotesFontKey); + + Future initData() async { + await _getTheme(); + await _getAccentSetColor(); + await _getShowIntro(); + await _getRealDark(); + } + + Locale _locale; + + /// Load locale. + Locale get locale => _locale; + + /// Spp thememode. default auto. + ThemeMode _theme; + ThemeMode get theme => _theme; + + set setTheme(ThemeMode mode) { + _theme = mode; + _saveTheme(); + notifyListeners(); + } + + void setWorkManager(int hour) { + _updateInterval = hour; + notifyListeners(); + _saveUpdateInterval(); + Workmanager.initialize( + callbackDispatcher, + isInDebugMode: false, + ); + Workmanager.registerPeriodicTask("1", "update_podcasts", + frequency: Duration(hours: hour), + initialDelay: Duration(seconds: 10), + constraints: Constraints( + networkType: NetworkType.connected, + )); + developer.log('work manager init done + '); + } + + Future cancelWork() async { + await Workmanager.cancelByUniqueName('1'); + developer.log('work job cancelled'); + } + + Color _accentSetColor; + Color get accentSetColor => _accentSetColor; + + set setAccentColor(Color color) { + _accentSetColor = color; + _saveAccentSetColor(); + notifyListeners(); + } + + int _updateInterval; + int get updateInterval => _updateInterval; + + int _initUpdateTag; + + /// Auto syncing podcasts in background, default true. + bool _autoUpdate; + bool get autoUpdate => _autoUpdate; + set autoUpdate(bool boo) { + _autoUpdate = boo; + _saveAutoUpdate(); + notifyListeners(); + } + + /// Confirem before using data to download episode, default true(reverse). + bool _downloadUsingData; + bool get downloadUsingData => _downloadUsingData; + set downloadUsingData(bool boo) { + _downloadUsingData = boo; + _saveDownloadUsingData(); + notifyListeners(); + } + + int _initialShowIntor; + bool _showIntro; + bool get showIntro => _showIntro; + + /// Real dark theme, default false. + bool _realDark; + bool get realDark => _realDark; + set setRealDark(bool boo) { + _realDark = boo; + _setRealDark(); + notifyListeners(); + } + + int _defaultSleepTimer; + int get defaultSleepTimer => _defaultSleepTimer; + set setDefaultSleepTimer(int i) { + _defaultSleepTimer = i; + _setDefaultSleepTimer(); + notifyListeners(); + } + + bool _autoPlay; + bool get autoPlay => _autoPlay; + set setAutoPlay(bool boo) { + _autoPlay = boo; + notifyListeners(); + _saveAutoPlay(); + } + + /// Auto start sleep timer at night. Defualt false. + bool _autoSleepTimer; + bool get autoSleepTimer => _autoSleepTimer; + set setAutoSleepTimer(bool boo) { + _autoSleepTimer = boo; + notifyListeners(); + _saveAutoSleepTimer(); + } + + int _autoSleepTimerMode; + int get autoSleepTimerMode => _autoSleepTimerMode; + set setAutoSleepTimerMode(int mode) { + _autoSleepTimerMode = mode; + notifyListeners(); + _saveAutoSleepTimerMode(); + } + + int _autoSleepTimerStart; + int get autoSleepTimerStart => _autoSleepTimerStart; + set setAutoSleepTimerStart(int start) { + _autoSleepTimerStart = start; + notifyListeners(); + _saveAutoSleepTimerStart(); + } + + int _autoSleepTimerEnd; + int get autoSleepTimerEnd => _autoSleepTimerEnd; + set setAutoSleepTimerEnd(int end) { + _autoSleepTimerEnd = end; + notifyListeners(); + _saveAutoSleepTimerEnd(); + } + + int _fastForwardSeconds; + int get fastForwardSeconds => _fastForwardSeconds; + set setFastForwardSeconds(int sec) { + _fastForwardSeconds = sec; + notifyListeners(); + _saveFastForwardSeconds(); + } + + int _rewindSeconds; + int get rewindSeconds => _rewindSeconds; + set setRewindSeconds(int sec) { + _rewindSeconds = sec; + notifyListeners(); + _saveRewindSeconds(); + } + + int _showNotesFontIndex; + int get showNotesFontIndex => _showNotesFontIndex; + TextStyle get showNoteFontStyle => showNotesFontStyles[_showNotesFontIndex]; + set setShowNoteFontStyle(int index) { + _showNotesFontIndex = index; + notifyListeners(); + _saveShowNotesFonts(); + } + + @override + void addListener(VoidCallback listener) { + super.addListener(listener); + _getLocale(); + _getAutoUpdate(); + _getDownloadUsingData(); + _getSleepTimerData(); + _getPlayerSeconds(); + _getShowNotesFonts(); + _getUpdateInterval().then((value) async { + if (_initUpdateTag == 0) { + setWorkManager(24); + } else if (_autoUpdate && _initialShowIntor == 1) { + await cancelWork(); + setWorkManager(_initUpdateTag); + await saveShowIntro(2); + } + }); + } + + Future _getTheme() async { + var mode = await themeStorage.getInt(); + _theme = ThemeMode.values[mode]; + } + + Future _getAccentSetColor() async { + var colorString = await accentStorage.getString(); + if (colorString.isNotEmpty) { + var color = int.parse('FF${colorString.toUpperCase()}', radix: 16); + _accentSetColor = Color(color).withOpacity(1.0); + } else { + _accentSetColor = Colors.teal[500]; + await _saveAccentSetColor(); + } + } + + Future _getAutoUpdate() async { + _autoUpdate = + await autoupdateStorage.getBool(defaultValue: true, reverse: true); + } + + Future _getUpdateInterval() async { + _initUpdateTag = await intervalStorage.getInt(); + _updateInterval = _initUpdateTag; + } + + Future _getDownloadUsingData() async { + _downloadUsingData = await downloadUsingDataStorage.getBool( + defaultValue: true, reverse: true); + } + + Future _saveDownloadUsingData() async { + await downloadUsingDataStorage.saveBool(_downloadUsingData, reverse: true); + } + + Future _getShowIntro() async { + _initialShowIntor = await introStorage.getInt(); + _showIntro = _initialShowIntor == 0 ? true : false; + } + + Future _getRealDark() async { + _realDark = await realDarkStorage.getBool(defaultValue: false); + } + + Future _getSleepTimerData() async { + _defaultSleepTimer = + await defaultSleepTimerStorage.getInt(defaultValue: 30); + _autoSleepTimer = await autoSleepTimerStorage.getBool(defaultValue: false); + _autoSleepTimerStart = + await autoSleepTimerStartStorage.getInt(defaultValue: 1380); + _autoSleepTimerEnd = + await autoSleepTimerEndStorage.getInt(defaultValue: 360); + _autoPlay = + await autoPlayStorage.getBool(defaultValue: true, reverse: true); + _autoSleepTimerMode = await autoSleepTimerModeStorage.getInt(); + } + + Future _getPlayerSeconds() async { + _rewindSeconds = await rewindSecondsStorage.getInt(defaultValue: 10); + _fastForwardSeconds = + await fastForwardSecondsStorage.getInt(defaultValue: 30); + } + + Future _getLocale() async { + var localeString = await localeStorage.getStringList(); + if (localeString.isEmpty) { + await findSystemLocale(); + var systemLanCode; + final list = Intl.systemLocale.split('_'); + if (list.length == 2) { + systemLanCode = list.first; + } else if (list.length == 3) { + systemLanCode = '${list[0]}_${list[1]}'; + } else { + systemLanCode = 'en'; + } + _locale = Locale(systemLanCode); + } else { + _locale = Locale(localeString.first, localeString[1]); + } + await S.load(_locale); + } + + Future _getShowNotesFonts() async { + _showNotesFontIndex = await showNotesFontStorage.getInt(defaultValue: 1); + } + + Future _saveAccentSetColor() async { + await accentStorage + .saveString(_accentSetColor.toString().substring(10, 16)); + } + + Future _setRealDark() async { + await realDarkStorage.saveBool(_realDark); + } + + Future saveShowIntro(int i) async { + await introStorage.saveInt(i); + } + + Future _saveUpdateInterval() async { + await intervalStorage.saveInt(_updateInterval); + } + + Future _saveTheme() async { + await themeStorage.saveInt(_theme.index); + } + + Future _saveAutoUpdate() async { + await autoupdateStorage.saveBool(_autoUpdate, reverse: true); + } + + Future _saveAutoPlay() async { + await autoPlayStorage.saveBool(_autoPlay, reverse: true); + } + + Future _setDefaultSleepTimer() async { + await defaultSleepTimerStorage.saveInt(_defaultSleepTimer); + } + + Future _saveAutoSleepTimer() async { + await autoSleepTimerStorage.saveBool(_autoSleepTimer); + } + + Future _saveAutoSleepTimerMode() async { + await autoSleepTimerModeStorage.saveInt(_autoSleepTimerMode); + } + + Future _saveAutoSleepTimerStart() async { + await autoSleepTimerStartStorage.saveInt(_autoSleepTimerStart); + } + + Future _saveAutoSleepTimerEnd() async { + await autoSleepTimerEndStorage.saveInt(_autoSleepTimerEnd); + } + + Future _saveFastForwardSeconds() async { + await fastForwardSecondsStorage.saveInt(_fastForwardSeconds); + } + + Future _saveRewindSeconds() async { + await rewindSecondsStorage.saveInt(_rewindSeconds); + } + + Future _saveShowNotesFonts() async { + await showNotesFontStorage.saveInt(_showNotesFontIndex); + } + + Future backup() async { + var theme = await themeStorage.getInt(); + var accentColor = await accentStorage.getString(); + var realDark = await realDarkStorage.getBool(defaultValue: false); + var autoPlay = + await autoPlayStorage.getBool(defaultValue: true, reverse: true); + var autoUpdate = + await autoupdateStorage.getBool(defaultValue: true, reverse: true); + var updateInterval = await intervalStorage.getInt(); + var downloadUsingData = await downloadUsingDataStorage.getBool( + defaultValue: true, reverse: true); + var cacheMax = await cacheStorage.getInt(defaultValue: 500 * 1024 * 1024); + var podcastLayout = await podcastLayoutStorage.getInt(); + var recentLayout = await recentLayoutStorage.getInt(); + var favLayout = await favLayoutStorage.getInt(); + var downloadLayout = await downloadLayoutStorage.getInt(); + var autoDownloadNetwork = + await autoDownloadStorage.getBool(defaultValue: false); + var episodePopupMenu = await KeyValueStorage(episodePopupMenuKey).getMenu(); + var autoDelete = await autoDeleteStorage.getInt(); + var autoSleepTimer = + await autoSleepTimerStorage.getBool(defaultValue: false); + var autoSleepTimerStart = await autoSleepTimerStartStorage.getInt(); + var autoSleepTimerEnd = await autoSleepTimerEndStorage.getInt(); + var autoSleepTimerMode = await autoSleepTimerModeStorage.getInt(); + var defaultSleepTime = await defaultSleepTimerStorage.getInt(); + var tapToOpenPopupMenu = await KeyValueStorage(tapToOpenPopupMenuKey) + .getBool(defaultValue: false); + var fastForwardSeconds = + await fastForwardSecondsStorage.getInt(defaultValue: 30); + var rewindSeconds = await rewindSecondsStorage.getInt(defaultValue: 10); + var playerHeight = + await KeyValueStorage(playerHeightKey).getInt(defaultValue: 0); + var localeList = await localeStorage.getStringList(); + var backupLocale = + localeList.isEmpty ? '' : '${'${localeList.first}-'}${localeList[1]}'; + var hideListened = + await KeyValueStorage(hideListenedKey).getBool(defaultValue: false); + var notificationLayout = + await KeyValueStorage(notificationLayoutKey).getInt(defaultValue: 0); + var showNotesFont = await showNotesFontStorage.getInt(defaultValue: 1); + var speedList = await KeyValueStorage(speedListKey).getStringList(); + var hidePodcastDiscovery = await KeyValueStorage(hidePodcastDiscoveryKey) + .getBool(defaultValue: false); + final markListenedAfterSKip = + await KeyValueStorage(markListenedAfterSkipKey) + .getBool(defaultValue: false); + final deleteAfterPlayed = await KeyValueStorage(deleteAfterPlayedKey) + .getBool(defaultValue: false); + + return SettingsBackup( + theme: theme, + accentColor: accentColor, + realDark: realDark, + autoPlay: autoPlay, + autoUpdate: autoUpdate, + updateInterval: updateInterval, + downloadUsingData: downloadUsingData, + cacheMax: cacheMax, + podcastLayout: podcastLayout, + recentLayout: recentLayout, + favLayout: favLayout, + downloadLayout: downloadLayout, + autoDownloadNetwork: autoDownloadNetwork, + episodePopupMenu: episodePopupMenu.map((e) => e.toString()).toList(), + autoDelete: autoDelete, + autoSleepTimer: autoSleepTimer, + autoSleepTimerStart: autoSleepTimerStart, + autoSleepTimerEnd: autoSleepTimerEnd, + autoSleepTimerMode: autoSleepTimerMode, + defaultSleepTime: defaultSleepTime, + tapToOpenPopupMenu: tapToOpenPopupMenu, + fastForwardSeconds: fastForwardSeconds, + rewindSeconds: rewindSeconds, + playerHeight: playerHeight, + locale: backupLocale, + hideListened: hideListened, + notificationLayout: notificationLayout, + showNotesFont: showNotesFont, + speedList: speedList, + hidePodcastDiscovery: hidePodcastDiscovery, + markListenedAfterSkip: markListenedAfterSKip, + deleteAfterPlayed: deleteAfterPlayed); + } + + Future restore(SettingsBackup backup) async { + await themeStorage.saveInt(backup.theme); + await accentStorage.saveString(backup.accentColor); + await realDarkStorage.saveBool(backup.realDark); + await autoPlayStorage.saveBool(backup.autoPlay, reverse: true); + await autoupdateStorage.saveBool(backup.autoUpdate, reverse: true); + await intervalStorage.saveInt(backup.updateInterval); + await downloadUsingDataStorage.saveBool(backup.downloadUsingData, + reverse: true); + await cacheStorage.saveInt(backup.cacheMax); + await podcastLayoutStorage.saveInt(backup.podcastLayout); + await recentLayoutStorage.saveInt(backup.recentLayout); + await favLayoutStorage.saveInt(backup.favLayout); + await downloadLayoutStorage.saveInt(backup.downloadLayout); + await autoDownloadStorage.saveBool(backup.autoDownloadNetwork); + await KeyValueStorage(episodePopupMenuKey) + .saveStringList(backup.episodePopupMenu); + await autoDeleteStorage.saveInt(backup.autoDelete); + await autoSleepTimerStorage.saveBool(backup.autoSleepTimer); + await autoSleepTimerStartStorage.saveInt(backup.autoSleepTimerStart); + await autoSleepTimerEndStorage.saveInt(backup.autoSleepTimerEnd); + await autoSleepTimerModeStorage.saveInt(backup.autoSleepTimerMode); + await defaultSleepTimerStorage.saveInt(backup.defaultSleepTime); + await fastForwardSecondsStorage.saveInt(backup.fastForwardSeconds); + await rewindSecondsStorage.saveInt(backup.rewindSeconds); + await KeyValueStorage(playerHeightKey).saveInt(backup.playerHeight); + await KeyValueStorage(tapToOpenPopupMenuKey) + .saveBool(backup.tapToOpenPopupMenu); + await KeyValueStorage(hideListenedKey).saveBool(backup.hideListened); + await KeyValueStorage(notificationLayoutKey) + .saveInt(backup.notificationLayout); + await showNotesFontStorage.saveInt(backup.showNotesFont); + await KeyValueStorage(speedListKey).saveStringList(backup.speedList); + await KeyValueStorage(markListenedAfterSkipKey) + .saveBool(backup.markListenedAfterSkip); + await KeyValueStorage(deleteAfterPlayedKey) + .saveBool(backup.deleteAfterPlayed); + + if (backup.locale == '') { + await localeStorage.saveStringList([]); + await S.load(Locale(Intl.systemLocale)); + } else { + var localeList = backup.locale.split('-'); + var backupLocale; + if (localeList[1] == 'null') { + backupLocale = Locale(localeList.first); + } else { + backupLocale = Locale(localeList.first, localeList[1]); + } + await localeStorage.saveStringList( + [backupLocale.languageCode, backupLocale.countryCode]); + await S.load(backupLocale); + } + await initData(); + await _getAutoUpdate(); + await _getDownloadUsingData(); + await _getSleepTimerData(); + await _getShowNotesFonts(); + await _getUpdateInterval().then((value) async { + if (_autoUpdate) { + await cancelWork(); + setWorkManager(_initUpdateTag); + await saveShowIntro(2); + } + }); + } +} diff --git a/lib/type/episode_task.dart b/lib/type/episode_task.dart index 7e30538..ecd4f57 100644 --- a/lib/type/episode_task.dart +++ b/lib/type/episode_task.dart @@ -1,25 +1,25 @@ -import 'package:flutter_downloader/flutter_downloader.dart'; -import 'package:equatable/equatable.dart'; - -import 'episodebrief.dart'; - -class EpisodeTask extends Equatable { - final String taskId; - final EpisodeBrief episode; - int progress; - DownloadTaskStatus status; - EpisodeTask( - this.episode, - this.taskId, { - this.progress = 0, - this.status = DownloadTaskStatus.undefined, - }); - - EpisodeTask copyWith({String taskId}) { - return EpisodeTask(episode, taskId ?? this.taskId, - progress: progress, status: status); - } - - @override - List get props => [taskId]; -} +import 'package:flutter_downloader/flutter_downloader.dart'; +import 'package:equatable/equatable.dart'; + +import 'episodebrief.dart'; + +class EpisodeTask extends Equatable { + final String taskId; + final EpisodeBrief episode; + int progress; + DownloadTaskStatus status; + EpisodeTask( + this.episode, + this.taskId, { + this.progress = 0, + this.status = DownloadTaskStatus.undefined, + }); + + EpisodeTask copyWith({String taskId}) { + return EpisodeTask(episode, taskId ?? this.taskId, + progress: progress, status: status); + } + + @override + List get props => [taskId]; +} diff --git a/lib/type/episodebrief.dart b/lib/type/episodebrief.dart index 1f6f342..ef6754a 100644 --- a/lib/type/episodebrief.dart +++ b/lib/type/episodebrief.dart @@ -1,87 +1,87 @@ -import 'dart:io'; - -import 'package:equatable/equatable.dart'; - -import 'package:audio_service/audio_service.dart'; -import 'package:flutter/material.dart'; -import '../util/extension_helper.dart'; - -class EpisodeBrief extends Equatable { - final String title; - final String description; - final int pubDate; - final int enclosureLength; - final String enclosureUrl; - final String feedTitle; - final String primaryColor; - final int liked; - final String downloaded; - final int duration; - final int explicit; - final String imagePath; - final String mediaId; - final int isNew; - final int skipSecondsStart; - final int skipSecondsEnd; - final int downloadDate; - EpisodeBrief( - this.title, - this.enclosureUrl, - this.enclosureLength, - this.pubDate, - this.feedTitle, - this.primaryColor, - this.duration, - this.explicit, - this.imagePath, - this.isNew, - {this.mediaId, - this.liked, - this.downloaded, - this.skipSecondsStart, - this.skipSecondsEnd, - this.description = '', - this.downloadDate = 0}) - : assert(enclosureUrl != null); - - MediaItem toMediaItem() { - return MediaItem( - id: mediaId, - title: title, - artist: feedTitle, - album: feedTitle, - duration: Duration.zero, - artUri: 'file://$imagePath', - extras: { - 'skipSecondsStart': skipSecondsStart, - 'skipSecondsEnd': skipSecondsEnd - }); - } - - ImageProvider get avatarImage { - return File(imagePath).existsSync() - ? FileImage(File(imagePath)) - : const AssetImage('assets/avatar_backup.png'); - } - - Color backgroudColor(BuildContext context) { - return context.brightness == Brightness.light - ? primaryColor.colorizedark() - : primaryColor.colorizeLight(); - } - - EpisodeBrief copyWith({ - String mediaId, - }) => - EpisodeBrief(title, enclosureUrl, enclosureLength, pubDate, feedTitle, - primaryColor, duration, explicit, imagePath, isNew, - mediaId: mediaId ?? this.mediaId, - downloaded: downloaded, - skipSecondsStart: skipSecondsStart, - skipSecondsEnd: skipSecondsEnd, - description: description, - downloadDate: downloadDate); - - @override - List get props => [enclosureUrl, title]; -} +import 'dart:io'; + +import 'package:equatable/equatable.dart'; + +import 'package:audio_service/audio_service.dart'; +import 'package:flutter/material.dart'; +import '../util/extension_helper.dart'; + +class EpisodeBrief extends Equatable { + final String title; + final String description; + final int pubDate; + final int enclosureLength; + final String enclosureUrl; + final String feedTitle; + final String primaryColor; + final int liked; + final String downloaded; + final int duration; + final int explicit; + final String imagePath; + final String mediaId; + final int isNew; + final int skipSecondsStart; + final int skipSecondsEnd; + final int downloadDate; + EpisodeBrief( + this.title, + this.enclosureUrl, + this.enclosureLength, + this.pubDate, + this.feedTitle, + this.primaryColor, + this.duration, + this.explicit, + this.imagePath, + this.isNew, + {this.mediaId, + this.liked, + this.downloaded, + this.skipSecondsStart, + this.skipSecondsEnd, + this.description = '', + this.downloadDate = 0}) + : assert(enclosureUrl != null); + + MediaItem toMediaItem() { + return MediaItem( + id: mediaId, + title: title, + artist: feedTitle, + album: feedTitle, + duration: Duration.zero, + artUri: 'file://$imagePath', + extras: { + 'skipSecondsStart': skipSecondsStart, + 'skipSecondsEnd': skipSecondsEnd + }); + } + + ImageProvider get avatarImage { + return File(imagePath).existsSync() + ? FileImage(File(imagePath)) + : const AssetImage('assets/avatar_backup.png'); + } + + Color backgroudColor(BuildContext context) { + return context.brightness == Brightness.light + ? primaryColor.colorizedark() + : primaryColor.colorizeLight(); + } + + EpisodeBrief copyWith({ + String mediaId, + }) => + EpisodeBrief(title, enclosureUrl, enclosureLength, pubDate, feedTitle, + primaryColor, duration, explicit, imagePath, isNew, + mediaId: mediaId ?? this.mediaId, + downloaded: downloaded, + skipSecondsStart: skipSecondsStart, + skipSecondsEnd: skipSecondsEnd, + description: description, + downloadDate: downloadDate); + + @override + List get props => [enclosureUrl, title]; +} diff --git a/lib/type/fireside_data.dart b/lib/type/fireside_data.dart index b6f5415..b549bc6 100644 --- a/lib/type/fireside_data.dart +++ b/lib/type/fireside_data.dart @@ -1,93 +1,93 @@ -import 'dart:convert'; - -import 'package:dio/dio.dart'; -import 'package:html/parser.dart'; - -import '../local_storage/sqflite_localpodcast.dart'; - -class FiresideData { - final String id; - final String link; - - String _background; - String get background => _background; - List _hosts; - List get hosts => _hosts; - FiresideData(this.id, this.link); - - final DBHelper _dbHelper = DBHelper(); - - String parseLink(String link) { - if (link == "http://www.shengfm.cn/") { - return "https://guiguzaozhidao.fireside.fm/"; - } else { - return link; - } - } - - Future fatchData() async { - var options = BaseOptions( - connectTimeout: 20000, - receiveTimeout: 20000, - ); - - var response = await Dio(options).get(parseLink(link)); - if (response.statusCode == 200) { - var doc = parse(response.data); - var reg = RegExp(r'https(.+)jpg'); - var backgroundImage = reg.stringMatch(doc.body - .getElementsByClassName('hero-background') - .first - .attributes - .toString()); - var ul = doc.body.getElementsByClassName('episode-hosts').first.children; - var hosts = []; - for (var element in ul) { - PodcastHost host; - var name = element.text.trim(); - var image = element.children.first.children.first.attributes.toString(); - host = PodcastHost( - name, - reg.stringMatch(image) ?? - 'https://fireside.fm/assets/default/avatar_small' - '-170afdc2be97fc6148b283083942d82c101d4c1061f6b28f87c8958b52664af9.jpg'); - - hosts.add(host); - } - var data = [ - id, - backgroundImage, - json.encode({'hosts': hosts.map((host) => host.toJson()).toList()}) - ]; - await _dbHelper.saveFiresideData(data); - } - } - - Future getData() async { - var data = await _dbHelper.getFiresideData(id); - _background = data[0]; - if (data[1] != '') { - _hosts = json - .decode(data[1])['hosts'] - .cast>() - .map(PodcastHost.fromJson) - .toList(); - } else { - _hosts = null; - } - } -} - -class PodcastHost { - final String image; - final String name; - PodcastHost(this.name, this.image); - - Map toJson() { - return {'name': name, 'image': image}; - } - - static PodcastHost fromJson(Map json) { - return PodcastHost(json['name'] as String, json['image'] as String); - } -} +import 'dart:convert'; + +import 'package:dio/dio.dart'; +import 'package:html/parser.dart'; + +import '../local_storage/sqflite_localpodcast.dart'; + +class FiresideData { + final String id; + final String link; + + String _background; + String get background => _background; + List _hosts; + List get hosts => _hosts; + FiresideData(this.id, this.link); + + final DBHelper _dbHelper = DBHelper(); + + String parseLink(String link) { + if (link == "http://www.shengfm.cn/") { + return "https://guiguzaozhidao.fireside.fm/"; + } else { + return link; + } + } + + Future fatchData() async { + var options = BaseOptions( + connectTimeout: 20000, + receiveTimeout: 20000, + ); + + var response = await Dio(options).get(parseLink(link)); + if (response.statusCode == 200) { + var doc = parse(response.data); + var reg = RegExp(r'https(.+)jpg'); + var backgroundImage = reg.stringMatch(doc.body + .getElementsByClassName('hero-background') + .first + .attributes + .toString()); + var ul = doc.body.getElementsByClassName('episode-hosts').first.children; + var hosts = []; + for (var element in ul) { + PodcastHost host; + var name = element.text.trim(); + var image = element.children.first.children.first.attributes.toString(); + host = PodcastHost( + name, + reg.stringMatch(image) ?? + 'https://fireside.fm/assets/default/avatar_small' + '-170afdc2be97fc6148b283083942d82c101d4c1061f6b28f87c8958b52664af9.jpg'); + + hosts.add(host); + } + var data = [ + id, + backgroundImage, + json.encode({'hosts': hosts.map((host) => host.toJson()).toList()}) + ]; + await _dbHelper.saveFiresideData(data); + } + } + + Future getData() async { + var data = await _dbHelper.getFiresideData(id); + _background = data[0]; + if (data[1] != '') { + _hosts = json + .decode(data[1])['hosts'] + .cast>() + .map(PodcastHost.fromJson) + .toList(); + } else { + _hosts = null; + } + } +} + +class PodcastHost { + final String image; + final String name; + PodcastHost(this.name, this.image); + + Map toJson() { + return {'name': name, 'image': image}; + } + + static PodcastHost fromJson(Map json) { + return PodcastHost(json['name'] as String, json['image'] as String); + } +} diff --git a/lib/type/play_histroy.dart b/lib/type/play_histroy.dart index d6e5dd5..d699092 100644 --- a/lib/type/play_histroy.dart +++ b/lib/type/play_histroy.dart @@ -1,31 +1,31 @@ -import '../local_storage/sqflite_localpodcast.dart'; -import 'episodebrief.dart'; - -class PlayHistory { - final DBHelper _dbHelper = DBHelper(); - - /// Episdoe title. - String title; - - /// Episode url - String url; - - /// Play record seconds. - int seconds; - - /// Play record count, - double seekValue; - - /// Listened date. - DateTime playdate; - - PlayHistory(this.title, this.url, this.seconds, this.seekValue, - {this.playdate}); - - EpisodeBrief _episode; - EpisodeBrief get episode => _episode; - - Future getEpisode() async { - _episode = await _dbHelper.getRssItemWithUrl(url); - } -} +import '../local_storage/sqflite_localpodcast.dart'; +import 'episodebrief.dart'; + +class PlayHistory { + final DBHelper _dbHelper = DBHelper(); + + /// Episdoe title. + String title; + + /// Episode url + String url; + + /// Play record seconds. + int seconds; + + /// Play record count, + double seekValue; + + /// Listened date. + DateTime playdate; + + PlayHistory(this.title, this.url, this.seconds, this.seekValue, + {this.playdate}); + + EpisodeBrief _episode; + EpisodeBrief get episode => _episode; + + Future getEpisode() async { + _episode = await _dbHelper.getRssItemWithUrl(url); + } +} diff --git a/lib/type/playlist.dart b/lib/type/playlist.dart index 433bd5a..99c1be8 100644 --- a/lib/type/playlist.dart +++ b/lib/type/playlist.dart @@ -1,61 +1,61 @@ -import '../local_storage/key_value_storage.dart'; -import '../local_storage/sqflite_localpodcast.dart'; -import 'episodebrief.dart'; - -class Playlist { - String name; - final DBHelper _dbHelper = DBHelper(); - List _playlist; - List get playlist => _playlist; - final KeyValueStorage _playlistStorage = KeyValueStorage(playlistKey); - - Future getPlaylist() async { - var urls = await _playlistStorage.getStringList(); - if (urls.length == 0) { - _playlist = []; - } else { - _playlist = []; - for (var url in urls) { - var episode = await _dbHelper.getRssItemWithUrl(url); - if (episode != null) _playlist.add(episode); - } - } - } - - Future savePlaylist() async { - var urls = []; - urls.addAll(_playlist.map((e) => e.enclosureUrl)); - await _playlistStorage.saveStringList(urls.toSet().toList()); - } - - Future addToPlayList(EpisodeBrief episodeBrief) async { - if (!_playlist.contains(episodeBrief)) { - _playlist.add(episodeBrief); - await savePlaylist(); - if (episodeBrief.isNew == 1) { - await _dbHelper.removeEpisodeNewMark(episodeBrief.enclosureUrl); - } - } - } - - Future addToPlayListAt(EpisodeBrief episodeBrief, int index, - {bool existed = true}) async { - if (existed) { - _playlist.removeWhere( - (episode) => episode.enclosureUrl == episodeBrief.enclosureUrl); - if (episodeBrief.isNew == 1) { - await _dbHelper.removeEpisodeNewMark(episodeBrief.enclosureUrl); - } - } - _playlist.insert(index, episodeBrief); - await savePlaylist(); - } - - Future delFromPlaylist(EpisodeBrief episodeBrief) async { - var index = _playlist.indexOf(episodeBrief); - _playlist.removeWhere( - (episode) => episode.enclosureUrl == episodeBrief.enclosureUrl); - await savePlaylist(); - return index; - } -} +import '../local_storage/key_value_storage.dart'; +import '../local_storage/sqflite_localpodcast.dart'; +import 'episodebrief.dart'; + +class Playlist { + String name; + final DBHelper _dbHelper = DBHelper(); + List _playlist; + List get playlist => _playlist; + final KeyValueStorage _playlistStorage = KeyValueStorage(playlistKey); + + Future getPlaylist() async { + var urls = await _playlistStorage.getStringList(); + if (urls.length == 0) { + _playlist = []; + } else { + _playlist = []; + for (var url in urls) { + var episode = await _dbHelper.getRssItemWithUrl(url); + if (episode != null) _playlist.add(episode); + } + } + } + + Future savePlaylist() async { + var urls = []; + urls.addAll(_playlist.map((e) => e.enclosureUrl)); + await _playlistStorage.saveStringList(urls.toSet().toList()); + } + + Future addToPlayList(EpisodeBrief episodeBrief) async { + if (!_playlist.contains(episodeBrief)) { + _playlist.add(episodeBrief); + await savePlaylist(); + if (episodeBrief.isNew == 1) { + await _dbHelper.removeEpisodeNewMark(episodeBrief.enclosureUrl); + } + } + } + + Future addToPlayListAt(EpisodeBrief episodeBrief, int index, + {bool existed = true}) async { + if (existed) { + _playlist.removeWhere( + (episode) => episode.enclosureUrl == episodeBrief.enclosureUrl); + if (episodeBrief.isNew == 1) { + await _dbHelper.removeEpisodeNewMark(episodeBrief.enclosureUrl); + } + } + _playlist.insert(index, episodeBrief); + await savePlaylist(); + } + + Future delFromPlaylist(EpisodeBrief episodeBrief) async { + var index = _playlist.indexOf(episodeBrief); + _playlist.removeWhere( + (episode) => episode.enclosureUrl == episodeBrief.enclosureUrl); + await savePlaylist(); + return index; + } +} diff --git a/lib/type/podcastlocal.dart b/lib/type/podcastlocal.dart index d07ed31..5e56720 100644 --- a/lib/type/podcastlocal.dart +++ b/lib/type/podcastlocal.dart @@ -1,51 +1,51 @@ -import 'dart:io'; - -import 'package:equatable/equatable.dart'; -import 'package:flutter/material.dart'; - -import '../util/extension_helper.dart'; - -class PodcastLocal extends Equatable { - final String title; - final String imageUrl; - final String rssUrl; - final String author; - - final String primaryColor; - final String id; - final String imagePath; - final String provider; - final String link; - - final String description; - - int _upateCount; - int get updateCount => _upateCount; - set updateCount(i) => _upateCount = i; - - int _episodeCount; - int get episodeCount => _episodeCount; - set episodeCount(i) => _episodeCount = i; - - PodcastLocal(this.title, this.imageUrl, this.rssUrl, this.primaryColor, - this.author, this.id, this.imagePath, this.provider, this.link, - {this.description = '', int upateCount, int episodeCount}) - : assert(rssUrl != null), - _episodeCount = episodeCount ?? 0, - _upateCount = upateCount ?? 0; - - ImageProvider get avatarImage { - return File(imagePath).existsSync() - ? FileImage(File(imagePath)) - : const AssetImage('assets/avatar_backup.png'); - } - - Color backgroudColor(BuildContext context) { - return context.brightness == Brightness.light - ? primaryColor.colorizedark() - : primaryColor.colorizeLight(); - } - - @override - List get props => [id, rssUrl]; -} +import 'dart:io'; + +import 'package:equatable/equatable.dart'; +import 'package:flutter/material.dart'; + +import '../util/extension_helper.dart'; + +class PodcastLocal extends Equatable { + final String title; + final String imageUrl; + final String rssUrl; + final String author; + + final String primaryColor; + final String id; + final String imagePath; + final String provider; + final String link; + + final String description; + + int _upateCount; + int get updateCount => _upateCount; + set updateCount(i) => _upateCount = i; + + int _episodeCount; + int get episodeCount => _episodeCount; + set episodeCount(i) => _episodeCount = i; + + PodcastLocal(this.title, this.imageUrl, this.rssUrl, this.primaryColor, + this.author, this.id, this.imagePath, this.provider, this.link, + {this.description = '', int upateCount, int episodeCount}) + : assert(rssUrl != null), + _episodeCount = episodeCount ?? 0, + _upateCount = upateCount ?? 0; + + ImageProvider get avatarImage { + return File(imagePath).existsSync() + ? FileImage(File(imagePath)) + : const AssetImage('assets/avatar_backup.png'); + } + + Color backgroudColor(BuildContext context) { + return context.brightness == Brightness.light + ? primaryColor.colorizedark() + : primaryColor.colorizeLight(); + } + + @override + List get props => [id, rssUrl]; +} diff --git a/lib/type/search_api/index_episode.dart b/lib/type/search_api/index_episode.dart index fec0f96..3f42415 100644 --- a/lib/type/search_api/index_episode.dart +++ b/lib/type/search_api/index_episode.dart @@ -1,51 +1,51 @@ -import 'package:json_annotation/json_annotation.dart'; -import 'package:tsacdop/type/search_api/searchepisodes.dart'; - -part 'index_episode.g.dart'; - -@JsonSerializable() -class IndexEpisodeResult

{ - @_ConvertP() - final List

items; - final String status; - final int count; - IndexEpisodeResult({this.items, this.status, this.count}); - factory IndexEpisodeResult.fromJson(Map json) => - _$IndexEpisodeResultFromJson

(json); - Map toJson() => _$IndexEpisodeResultToJson(this); -} - -class _ConvertP

implements JsonConverter { - const _ConvertP(); - @override - P fromJson(Object json) { - return IndexEpisode.fromJson(json) as P; - } - - @override - Object toJson(P object) { - return object; - } -} - -@JsonSerializable() -class IndexEpisode { - final String title; - final String description; - final int datePublished; - final String enclosureUrl; - final int enclosureLength; - IndexEpisode( - {this.title, - this.description, - this.datePublished, - this.enclosureLength, - this.enclosureUrl}); - - factory IndexEpisode.fromJson(Map json) => - _$IndexEpisodeFromJson(json); - Map toJson() => _$IndexEpisodeToJson(this); - - OnlineEpisode get toOnlineWEpisode => - OnlineEpisode(title: title, pubDate: datePublished * 1000, length: 0); -} +import 'package:json_annotation/json_annotation.dart'; +import 'package:tsacdop/type/search_api/searchepisodes.dart'; + +part 'index_episode.g.dart'; + +@JsonSerializable() +class IndexEpisodeResult

{ + @_ConvertP() + final List

items; + final String status; + final int count; + IndexEpisodeResult({this.items, this.status, this.count}); + factory IndexEpisodeResult.fromJson(Map json) => + _$IndexEpisodeResultFromJson

(json); + Map toJson() => _$IndexEpisodeResultToJson(this); +} + +class _ConvertP

implements JsonConverter { + const _ConvertP(); + @override + P fromJson(Object json) { + return IndexEpisode.fromJson(json) as P; + } + + @override + Object toJson(P object) { + return object; + } +} + +@JsonSerializable() +class IndexEpisode { + final String title; + final String description; + final int datePublished; + final String enclosureUrl; + final int enclosureLength; + IndexEpisode( + {this.title, + this.description, + this.datePublished, + this.enclosureLength, + this.enclosureUrl}); + + factory IndexEpisode.fromJson(Map json) => + _$IndexEpisodeFromJson(json); + Map toJson() => _$IndexEpisodeToJson(this); + + OnlineEpisode get toOnlineWEpisode => + OnlineEpisode(title: title, pubDate: datePublished * 1000, length: 0); +} diff --git a/lib/type/search_api/index_podcast.dart b/lib/type/search_api/index_podcast.dart index e66a77d..e8a9a9b 100644 --- a/lib/type/search_api/index_podcast.dart +++ b/lib/type/search_api/index_podcast.dart @@ -1,68 +1,68 @@ -import 'package:json_annotation/json_annotation.dart'; - -import 'searchpodcast.dart'; - -part 'index_podcast.g.dart'; - -@JsonSerializable() -class PodcastIndexSearchResult

{ - @_ConvertP() - final List

feeds; - final String status; - final int count; - PodcastIndexSearchResult({this.feeds, this.status, this.count}); - - factory PodcastIndexSearchResult.fromJson(Map json) => - _$PodcastIndexSearchResultFromJson

(json); - Map toJson() => _$PodcastIndexSearchResultToJson(this); -} - -class _ConvertP

implements JsonConverter { - const _ConvertP(); - @override - P fromJson(Object json) { - return IndexPodcast.fromJson(json) as P; - } - - @override - Object toJson(P object) { - return object; - } -} - -@JsonSerializable() -class IndexPodcast { - final int id; - final String title; - final String url; - final String link; - final String description; - final String author; - final String image; - final int lastUpdateTime; - final int itunesId; - IndexPodcast( - {this.id, - this.title, - this.url, - this.link, - this.description, - this.author, - this.image, - this.lastUpdateTime, - this.itunesId}); - factory IndexPodcast.fromJson(Map json) => - _$IndexPodcastFromJson(json); - Map toJson() => _$IndexPodcastToJson(this); - - OnlinePodcast get toOnlinePodcast => OnlinePodcast( - earliestPubDate: 0, - title: title, - count: 0, - description: description, - image: image, - latestPubDate: lastUpdateTime * 1000, - rss: url, - publisher: author, - id: itunesId.toString()); -} +import 'package:json_annotation/json_annotation.dart'; + +import 'searchpodcast.dart'; + +part 'index_podcast.g.dart'; + +@JsonSerializable() +class PodcastIndexSearchResult

{ + @_ConvertP() + final List

feeds; + final String status; + final int count; + PodcastIndexSearchResult({this.feeds, this.status, this.count}); + + factory PodcastIndexSearchResult.fromJson(Map json) => + _$PodcastIndexSearchResultFromJson

(json); + Map toJson() => _$PodcastIndexSearchResultToJson(this); +} + +class _ConvertP

implements JsonConverter { + const _ConvertP(); + @override + P fromJson(Object json) { + return IndexPodcast.fromJson(json) as P; + } + + @override + Object toJson(P object) { + return object; + } +} + +@JsonSerializable() +class IndexPodcast { + final int id; + final String title; + final String url; + final String link; + final String description; + final String author; + final String image; + final int lastUpdateTime; + final int itunesId; + IndexPodcast( + {this.id, + this.title, + this.url, + this.link, + this.description, + this.author, + this.image, + this.lastUpdateTime, + this.itunesId}); + factory IndexPodcast.fromJson(Map json) => + _$IndexPodcastFromJson(json); + Map toJson() => _$IndexPodcastToJson(this); + + OnlinePodcast get toOnlinePodcast => OnlinePodcast( + earliestPubDate: 0, + title: title, + count: 0, + description: description, + image: image, + latestPubDate: lastUpdateTime * 1000, + rss: url, + publisher: author, + id: itunesId.toString()); +} diff --git a/lib/type/search_api/itunes_podcast.dart b/lib/type/search_api/itunes_podcast.dart index 9b54065..31cd370 100644 --- a/lib/type/search_api/itunes_podcast.dart +++ b/lib/type/search_api/itunes_podcast.dart @@ -1,67 +1,67 @@ -import 'package:intl/intl.dart'; -import 'package:json_annotation/json_annotation.dart'; - -import 'searchpodcast.dart'; - -part 'itunes_podcast.g.dart'; - -@JsonSerializable() -class ItunesSearchResult

{ - @_ConvertP() - final List

results; - final int resultCount; - ItunesSearchResult({this.resultCount, this.results}); - - factory ItunesSearchResult.fromJson(Map json) => - _$ItunesSearchResultFromJson

(json); - Map toJson() => _$ItunesSearchResultToJson(this); -} - -class _ConvertP

implements JsonConverter { - const _ConvertP(); - @override - P fromJson(Object json) { - return ItunesPodcast.fromJson(json) as P; - } - - @override - Object toJson(P object) { - return object; - } -} - -@JsonSerializable() -class ItunesPodcast { - final String artistName; - final String collectionName; - final String feedUrl; - final String artworkUrl600; - final String releaseDate; - final int collectionId; - - ItunesPodcast( - {this.artistName, - this.collectionName, - this.feedUrl, - this.artworkUrl600, - this.releaseDate, - this.collectionId}); - - factory ItunesPodcast.fromJson(Map json) => - _$ItunesPodcastFromJson(json); - Map toJson() => _$ItunesPodcastToJson(this); - - int get latestPubDate => DateFormat('yyyy-MM-DDTHH:MM:SSZ', 'en_US') - .parse(releaseDate) - .millisecondsSinceEpoch; - OnlinePodcast get toOnlinePodcast => OnlinePodcast( - earliestPubDate: 0, - title: collectionName, - count: 0, - description: '', - image: artworkUrl600, - latestPubDate: latestPubDate, - rss: feedUrl, - publisher: artistName, - id: collectionId.toString()); -} +import 'package:intl/intl.dart'; +import 'package:json_annotation/json_annotation.dart'; + +import 'searchpodcast.dart'; + +part 'itunes_podcast.g.dart'; + +@JsonSerializable() +class ItunesSearchResult

{ + @_ConvertP() + final List

results; + final int resultCount; + ItunesSearchResult({this.resultCount, this.results}); + + factory ItunesSearchResult.fromJson(Map json) => + _$ItunesSearchResultFromJson

(json); + Map toJson() => _$ItunesSearchResultToJson(this); +} + +class _ConvertP

implements JsonConverter { + const _ConvertP(); + @override + P fromJson(Object json) { + return ItunesPodcast.fromJson(json) as P; + } + + @override + Object toJson(P object) { + return object; + } +} + +@JsonSerializable() +class ItunesPodcast { + final String artistName; + final String collectionName; + final String feedUrl; + final String artworkUrl600; + final String releaseDate; + final int collectionId; + + ItunesPodcast( + {this.artistName, + this.collectionName, + this.feedUrl, + this.artworkUrl600, + this.releaseDate, + this.collectionId}); + + factory ItunesPodcast.fromJson(Map json) => + _$ItunesPodcastFromJson(json); + Map toJson() => _$ItunesPodcastToJson(this); + + int get latestPubDate => DateFormat('yyyy-MM-DDTHH:MM:SSZ', 'en_US') + .parse(releaseDate) + .millisecondsSinceEpoch; + OnlinePodcast get toOnlinePodcast => OnlinePodcast( + earliestPubDate: 0, + title: collectionName, + count: 0, + description: '', + image: artworkUrl600, + latestPubDate: latestPubDate, + rss: feedUrl, + publisher: artistName, + id: collectionId.toString()); +} diff --git a/lib/type/search_api/search_genre.dart b/lib/type/search_api/search_genre.dart index 87ef91b..d3e23b3 100644 --- a/lib/type/search_api/search_genre.dart +++ b/lib/type/search_api/search_genre.dart @@ -1,29 +1,29 @@ -class Genre { - String id; - String name; - Genre({this.id, this.name}); -} - -var genres = [ - Genre(id: '100', name: 'Arts'), - Genre(id: '99', name: 'News'), - Genre(id: '144', name: 'Personal Finance'), - Genre(id: '151', name: 'Locally Focused'), - Genre(id: '107', name: 'Science'), - Genre(id: '77', name: 'Sports'), - Genre(id: '134', name: 'Music'), - Genre(id: '125', name: 'History'), - Genre(id: '68', name: 'TV & Film'), - Genre(id: '127', name: 'Technology'), - Genre(id: '135', name: 'True Crime'), - Genre(id: '93', name: 'Business'), - Genre(id: '67', name: 'Comedy'), - Genre(id: '111', name: 'Education'), - Genre(id: '168', name: 'Fiction'), - Genre(id: '88', name: 'Health & Fitness'), - Genre(id: '132', name: 'Kids & Family'), - Genre(id: '82', name: 'Leisure'), - Genre(id: '69', name: 'Religion & Spirituality'), - Genre(id: '122', name: 'Society & Culture'), - Genre(id: '117', name: 'Government'), -]; +class Genre { + String id; + String name; + Genre({this.id, this.name}); +} + +var genres = [ + Genre(id: '100', name: 'Arts'), + Genre(id: '99', name: 'News'), + Genre(id: '144', name: 'Personal Finance'), + Genre(id: '151', name: 'Locally Focused'), + Genre(id: '107', name: 'Science'), + Genre(id: '77', name: 'Sports'), + Genre(id: '134', name: 'Music'), + Genre(id: '125', name: 'History'), + Genre(id: '68', name: 'TV & Film'), + Genre(id: '127', name: 'Technology'), + Genre(id: '135', name: 'True Crime'), + Genre(id: '93', name: 'Business'), + Genre(id: '67', name: 'Comedy'), + Genre(id: '111', name: 'Education'), + Genre(id: '168', name: 'Fiction'), + Genre(id: '88', name: 'Health & Fitness'), + Genre(id: '132', name: 'Kids & Family'), + Genre(id: '82', name: 'Leisure'), + Genre(id: '69', name: 'Religion & Spirituality'), + Genre(id: '122', name: 'Society & Culture'), + Genre(id: '117', name: 'Government'), +]; diff --git a/lib/type/search_api/search_top_podcast.dart b/lib/type/search_api/search_top_podcast.dart index 2edb41e..60c0452 100644 --- a/lib/type/search_api/search_top_podcast.dart +++ b/lib/type/search_api/search_top_podcast.dart @@ -1,76 +1,76 @@ -import 'package:json_annotation/json_annotation.dart'; -import 'searchpodcast.dart'; -part 'search_top_podcast.g.dart'; - -@JsonSerializable() -class SearchTopPodcast { - @_ConvertT() - final List podcasts; - final int id; - final int page; - final int total; - @JsonKey(name: 'has_next') - final bool hasNext; - SearchTopPodcast( - {this.podcasts, this.id, this.total, this.hasNext, this.page}); - - factory SearchTopPodcast.fromJson(Map json) => - _$SearchTopPodcastFromJson(json); - Map toJson() => _$SearchTopPodcastToJson(this); -} - -class _ConvertT implements JsonConverter { - const _ConvertT(); - @override - T fromJson(Object json) { - return OnlineTopPodcast.fromJson(json) as T; - } - - @override - Object toJson(T object) { - return object; - } -} - -@JsonSerializable() -class OnlineTopPodcast { - @JsonKey(name: 'earliest_pub_date_ms') - final int earliestPubDate; - @JsonKey(name: 'title') - final String title; - final String rss; - @JsonKey(name: 'latest_pub_date_ms') - final int latestPubDate; - @JsonKey(name: 'description') - final String description; - @JsonKey(name: 'total_episodes') - final int count; - final String image; - @JsonKey(name: 'publisher') - final String publisher; - final String id; - OnlineTopPodcast( - {this.earliestPubDate, - this.title, - this.count, - this.description, - this.image, - this.latestPubDate, - this.rss, - this.publisher, - this.id}); - factory OnlineTopPodcast.fromJson(Map json) => - _$OnlineTopPodcastFromJson(json); - Map toJson() => _$OnlineTopPodcastToJson(this); - - OnlinePodcast get toOnlinePodcast => OnlinePodcast( - earliestPubDate: earliestPubDate, - title: title, - count: count, - description: description, - image: image, - latestPubDate: latestPubDate, - rss: rss, - publisher: publisher, - id: id); -} +import 'package:json_annotation/json_annotation.dart'; +import 'searchpodcast.dart'; +part 'search_top_podcast.g.dart'; + +@JsonSerializable() +class SearchTopPodcast { + @_ConvertT() + final List podcasts; + final int id; + final int page; + final int total; + @JsonKey(name: 'has_next') + final bool hasNext; + SearchTopPodcast( + {this.podcasts, this.id, this.total, this.hasNext, this.page}); + + factory SearchTopPodcast.fromJson(Map json) => + _$SearchTopPodcastFromJson(json); + Map toJson() => _$SearchTopPodcastToJson(this); +} + +class _ConvertT implements JsonConverter { + const _ConvertT(); + @override + T fromJson(Object json) { + return OnlineTopPodcast.fromJson(json) as T; + } + + @override + Object toJson(T object) { + return object; + } +} + +@JsonSerializable() +class OnlineTopPodcast { + @JsonKey(name: 'earliest_pub_date_ms') + final int earliestPubDate; + @JsonKey(name: 'title') + final String title; + final String rss; + @JsonKey(name: 'latest_pub_date_ms') + final int latestPubDate; + @JsonKey(name: 'description') + final String description; + @JsonKey(name: 'total_episodes') + final int count; + final String image; + @JsonKey(name: 'publisher') + final String publisher; + final String id; + OnlineTopPodcast( + {this.earliestPubDate, + this.title, + this.count, + this.description, + this.image, + this.latestPubDate, + this.rss, + this.publisher, + this.id}); + factory OnlineTopPodcast.fromJson(Map json) => + _$OnlineTopPodcastFromJson(json); + Map toJson() => _$OnlineTopPodcastToJson(this); + + OnlinePodcast get toOnlinePodcast => OnlinePodcast( + earliestPubDate: earliestPubDate, + title: title, + count: count, + description: description, + image: image, + latestPubDate: latestPubDate, + rss: rss, + publisher: publisher, + id: id); +} diff --git a/lib/type/search_api/searchepisodes.dart b/lib/type/search_api/searchepisodes.dart index 128f4b1..edd2900 100644 --- a/lib/type/search_api/searchepisodes.dart +++ b/lib/type/search_api/searchepisodes.dart @@ -1,40 +1,40 @@ -import 'package:json_annotation/json_annotation.dart'; -part 'searchepisodes.g.dart'; - -@JsonSerializable() -class SearchEpisodes { - @_ConvertE() - final List episodes; - @JsonKey(name: 'next_episode_pub_date') - final int nextEpisodeDate; - SearchEpisodes({this.episodes, this.nextEpisodeDate}); - factory SearchEpisodes.fromJson(Map json) => - _$SearchEpisodesFromJson(json); - Map toJson() => _$SearchEpisodesToJson(this); -} - -class _ConvertE implements JsonConverter { - const _ConvertE(); - @override - E fromJson(Object json) { - return OnlineEpisode.fromJson(json) as E; - } - - @override - Object toJson(E object) { - return object; - } -} - -@JsonSerializable() -class OnlineEpisode { - final String title; - @JsonKey(name: 'pub_date_ms') - final int pubDate; - @JsonKey(name: 'audio_length_sec') - final int length; - OnlineEpisode({this.title, this.pubDate, this.length}); - factory OnlineEpisode.fromJson(Map json) => - _$OnlineEpisodeFromJson(json); - Map toJson() => _$OnlineEpisodeToJson(this); -} +import 'package:json_annotation/json_annotation.dart'; +part 'searchepisodes.g.dart'; + +@JsonSerializable() +class SearchEpisodes { + @_ConvertE() + final List episodes; + @JsonKey(name: 'next_episode_pub_date') + final int nextEpisodeDate; + SearchEpisodes({this.episodes, this.nextEpisodeDate}); + factory SearchEpisodes.fromJson(Map json) => + _$SearchEpisodesFromJson(json); + Map toJson() => _$SearchEpisodesToJson(this); +} + +class _ConvertE implements JsonConverter { + const _ConvertE(); + @override + E fromJson(Object json) { + return OnlineEpisode.fromJson(json) as E; + } + + @override + Object toJson(E object) { + return object; + } +} + +@JsonSerializable() +class OnlineEpisode { + final String title; + @JsonKey(name: 'pub_date_ms') + final int pubDate; + @JsonKey(name: 'audio_length_sec') + final int length; + OnlineEpisode({this.title, this.pubDate, this.length}); + factory OnlineEpisode.fromJson(Map json) => + _$OnlineEpisodeFromJson(json); + Map toJson() => _$OnlineEpisodeToJson(this); +} diff --git a/lib/type/search_api/searchpodcast.dart b/lib/type/search_api/searchpodcast.dart index 1197241..71e2a42 100644 --- a/lib/type/search_api/searchpodcast.dart +++ b/lib/type/search_api/searchpodcast.dart @@ -1,78 +1,78 @@ -import 'dart:ui'; - -import 'package:json_annotation/json_annotation.dart'; -part 'searchpodcast.g.dart'; - -@JsonSerializable() -class SearchPodcast

{ - @_ConvertP() - final List

results; - @JsonKey(name: 'next_offset') - final int nextOffset; - final int total; - final int count; - SearchPodcast({this.results, this.nextOffset, this.total, this.count}); - factory SearchPodcast.fromJson(Map json) => - _$SearchPodcastFromJson

(json); - Map toJson() => _$SearchPodcastToJson(this); -} - -class _ConvertP

implements JsonConverter { - const _ConvertP(); - @override - P fromJson(Object json) { - return OnlinePodcast.fromJson(json) as P; - } - - @override - Object toJson(P object) { - return object; - } -} - -@JsonSerializable() -class OnlinePodcast { - @JsonKey(name: 'earliest_pub_date_ms') - final int earliestPubDate; - @JsonKey(name: 'title_original') - final String title; - final String rss; - @JsonKey(name: 'latest_pub_date_ms') - final int latestPubDate; - @JsonKey(name: 'description_original') - final String description; - @JsonKey(name: 'total_episodes') - final int count; - final String image; - @JsonKey(name: 'publisher_original') - final String publisher; - final String id; - OnlinePodcast( - {this.earliestPubDate, - this.title, - this.count, - this.description, - this.image, - this.latestPubDate, - this.rss, - this.publisher, - this.id}); - factory OnlinePodcast.fromJson(Map json) => - _$OnlinePodcastFromJson(json); - Map toJson() => _$OnlinePodcastToJson(this); - - @override - bool operator ==(Object onlinePodcast) => - onlinePodcast is OnlinePodcast && onlinePodcast.id == id; - - @override - int get hashCode => hashValues(id, title); - - int get interval { - if (count < 1) { - // ignore: avoid_returning_null - return null; - } - return (latestPubDate - earliestPubDate) ~/ count; - } -} +import 'dart:ui'; + +import 'package:json_annotation/json_annotation.dart'; +part 'searchpodcast.g.dart'; + +@JsonSerializable() +class SearchPodcast

{ + @_ConvertP() + final List

results; + @JsonKey(name: 'next_offset') + final int nextOffset; + final int total; + final int count; + SearchPodcast({this.results, this.nextOffset, this.total, this.count}); + factory SearchPodcast.fromJson(Map json) => + _$SearchPodcastFromJson

(json); + Map toJson() => _$SearchPodcastToJson(this); +} + +class _ConvertP

implements JsonConverter { + const _ConvertP(); + @override + P fromJson(Object json) { + return OnlinePodcast.fromJson(json) as P; + } + + @override + Object toJson(P object) { + return object; + } +} + +@JsonSerializable() +class OnlinePodcast { + @JsonKey(name: 'earliest_pub_date_ms') + final int earliestPubDate; + @JsonKey(name: 'title_original') + final String title; + final String rss; + @JsonKey(name: 'latest_pub_date_ms') + final int latestPubDate; + @JsonKey(name: 'description_original') + final String description; + @JsonKey(name: 'total_episodes') + final int count; + final String image; + @JsonKey(name: 'publisher_original') + final String publisher; + final String id; + OnlinePodcast( + {this.earliestPubDate, + this.title, + this.count, + this.description, + this.image, + this.latestPubDate, + this.rss, + this.publisher, + this.id}); + factory OnlinePodcast.fromJson(Map json) => + _$OnlinePodcastFromJson(json); + Map toJson() => _$OnlinePodcastToJson(this); + + @override + bool operator ==(Object onlinePodcast) => + onlinePodcast is OnlinePodcast && onlinePodcast.id == id; + + @override + int get hashCode => hashValues(id, title); + + int get interval { + if (count < 1) { + // ignore: avoid_returning_null + return null; + } + return (latestPubDate - earliestPubDate) ~/ count; + } +} diff --git a/lib/type/settings_backup.dart b/lib/type/settings_backup.dart index aa240a1..1ba4949 100644 --- a/lib/type/settings_backup.dart +++ b/lib/type/settings_backup.dart @@ -1,141 +1,141 @@ -class SettingsBackup { - final int theme; - final String accentColor; - final bool realDark; - final bool autoPlay; - final bool autoUpdate; - final int updateInterval; - final bool downloadUsingData; - final int cacheMax; - final int podcastLayout; - final int recentLayout; - final int favLayout; - final int downloadLayout; - final bool autoDownloadNetwork; - final List episodePopupMenu; - final int autoDelete; - final bool autoSleepTimer; - final int autoSleepTimerStart; - final int autoSleepTimerEnd; - final int defaultSleepTime; - final int autoSleepTimerMode; - final bool tapToOpenPopupMenu; - final int fastForwardSeconds; - final int rewindSeconds; - final int playerHeight; - final String locale; - final bool hideListened; - final int notificationLayout; - final int showNotesFont; - final List speedList; - final bool hidePodcastDiscovery; - final bool markListenedAfterSkip; - final bool deleteAfterPlayed; - - SettingsBackup( - {this.theme, - this.accentColor, - this.realDark, - this.autoPlay, - this.autoUpdate, - this.updateInterval, - this.downloadUsingData, - this.cacheMax, - this.podcastLayout, - this.recentLayout, - this.favLayout, - this.downloadLayout, - this.autoDownloadNetwork, - this.episodePopupMenu, - this.autoDelete, - this.autoSleepTimer, - this.autoSleepTimerStart, - this.autoSleepTimerEnd, - this.defaultSleepTime, - this.autoSleepTimerMode, - this.tapToOpenPopupMenu, - this.fastForwardSeconds, - this.rewindSeconds, - this.playerHeight, - this.locale, - this.hideListened, - this.notificationLayout, - this.showNotesFont, - this.speedList, - this.hidePodcastDiscovery, - this.markListenedAfterSkip, - this.deleteAfterPlayed}); - - Map toJson() { - return { - 'theme': theme, - 'accentColor': accentColor, - 'realDark': realDark, - 'autoPlay': autoPlay, - 'autoUpdate': autoUpdate, - 'updateInterval': updateInterval, - 'downloadUsingData': downloadUsingData, - 'cacheMax': cacheMax, - 'podcastLayout': podcastLayout, - 'recentLayout': recentLayout, - 'favLayout': favLayout, - 'downloadLayout': downloadLayout, - 'autoDownloadNetwork': autoDownloadNetwork, - 'episodePopupMenu': episodePopupMenu, - 'autoDelete': autoDelete, - 'autoSleepTimer': autoSleepTimer, - 'autoSleepTimerStart': autoSleepTimerStart, - 'autoSleepTimerEnd': autoSleepTimerEnd, - 'autoSleepTimerMode': autoSleepTimerMode, - 'tapToOpenPopupMenu': tapToOpenPopupMenu, - 'fastForwardSeconds': fastForwardSeconds, - 'rewindSeconds': rewindSeconds, - 'playerHeight': playerHeight, - 'locale': locale, - 'hideListened': hideListened, - 'notificationLayout': notificationLayout, - 'showNotesFont': showNotesFont, - 'speedList': speedList, - 'hidePodcastDiscovery': hidePodcastDiscovery, - 'markListenedAfterSkip': markListenedAfterSkip, - 'deleteAfterPlayed': deleteAfterPlayed - }; - } - - static SettingsBackup fromJson(Map json) { - final menuList = List.from(json['episodePopupMenu']); - final speedList = List.from(json['speedList']); - return SettingsBackup( - theme: json['theme'] as int, - accentColor: json['accentColor'] as String, - realDark: json['realDark'] as bool, - autoPlay: json['autoPlay'] as bool, - autoUpdate: json['autoUpdate'] as bool, - updateInterval: json['updateInterval'] as int, - downloadUsingData: json['downloadUsingData'] as bool, - cacheMax: json['cacheMax'] as int, - podcastLayout: json['podcastLayout'] as int, - recentLayout: json['recentLayout'] as int, - favLayout: json['favLayout'] as int, - downloadLayout: json['downloadLayout'] as int, - autoDownloadNetwork: json['autoDownloadNetwork'] as bool, - episodePopupMenu: menuList, - autoDelete: json['autoDelete'] as int, - autoSleepTimer: json['autoSleepTimer'] as bool, - autoSleepTimerStart: json['autoSleepeTimerStart'] as int, - autoSleepTimerEnd: json['autoSleepTimerEnd'] as int, - autoSleepTimerMode: json['autoSleepTimerMode'] as int, - tapToOpenPopupMenu: json['tapToOpenPopupMenu'] as bool, - fastForwardSeconds: json['fastForwardSeconds'] as int, - rewindSeconds: json['rewindSeconds'] as int, - playerHeight: json['playerHeight'] as int, - locale: json['locale'] as String, - hideListened: json['hideListened'] as bool, - notificationLayout: json['notificationLayout'] as int, - showNotesFont: json['showNotesFont'] as int, - speedList: speedList, - hidePodcastDiscovery: json['hidePodcastDiscovery'] as bool, - markListenedAfterSkip: json['markListenedAfterSkip'] as bool, - deleteAfterPlayed: json['deleteAfterPlayed'] as bool); - } -} +class SettingsBackup { + final int theme; + final String accentColor; + final bool realDark; + final bool autoPlay; + final bool autoUpdate; + final int updateInterval; + final bool downloadUsingData; + final int cacheMax; + final int podcastLayout; + final int recentLayout; + final int favLayout; + final int downloadLayout; + final bool autoDownloadNetwork; + final List episodePopupMenu; + final int autoDelete; + final bool autoSleepTimer; + final int autoSleepTimerStart; + final int autoSleepTimerEnd; + final int defaultSleepTime; + final int autoSleepTimerMode; + final bool tapToOpenPopupMenu; + final int fastForwardSeconds; + final int rewindSeconds; + final int playerHeight; + final String locale; + final bool hideListened; + final int notificationLayout; + final int showNotesFont; + final List speedList; + final bool hidePodcastDiscovery; + final bool markListenedAfterSkip; + final bool deleteAfterPlayed; + + SettingsBackup( + {this.theme, + this.accentColor, + this.realDark, + this.autoPlay, + this.autoUpdate, + this.updateInterval, + this.downloadUsingData, + this.cacheMax, + this.podcastLayout, + this.recentLayout, + this.favLayout, + this.downloadLayout, + this.autoDownloadNetwork, + this.episodePopupMenu, + this.autoDelete, + this.autoSleepTimer, + this.autoSleepTimerStart, + this.autoSleepTimerEnd, + this.defaultSleepTime, + this.autoSleepTimerMode, + this.tapToOpenPopupMenu, + this.fastForwardSeconds, + this.rewindSeconds, + this.playerHeight, + this.locale, + this.hideListened, + this.notificationLayout, + this.showNotesFont, + this.speedList, + this.hidePodcastDiscovery, + this.markListenedAfterSkip, + this.deleteAfterPlayed}); + + Map toJson() { + return { + 'theme': theme, + 'accentColor': accentColor, + 'realDark': realDark, + 'autoPlay': autoPlay, + 'autoUpdate': autoUpdate, + 'updateInterval': updateInterval, + 'downloadUsingData': downloadUsingData, + 'cacheMax': cacheMax, + 'podcastLayout': podcastLayout, + 'recentLayout': recentLayout, + 'favLayout': favLayout, + 'downloadLayout': downloadLayout, + 'autoDownloadNetwork': autoDownloadNetwork, + 'episodePopupMenu': episodePopupMenu, + 'autoDelete': autoDelete, + 'autoSleepTimer': autoSleepTimer, + 'autoSleepTimerStart': autoSleepTimerStart, + 'autoSleepTimerEnd': autoSleepTimerEnd, + 'autoSleepTimerMode': autoSleepTimerMode, + 'tapToOpenPopupMenu': tapToOpenPopupMenu, + 'fastForwardSeconds': fastForwardSeconds, + 'rewindSeconds': rewindSeconds, + 'playerHeight': playerHeight, + 'locale': locale, + 'hideListened': hideListened, + 'notificationLayout': notificationLayout, + 'showNotesFont': showNotesFont, + 'speedList': speedList, + 'hidePodcastDiscovery': hidePodcastDiscovery, + 'markListenedAfterSkip': markListenedAfterSkip, + 'deleteAfterPlayed': deleteAfterPlayed + }; + } + + static SettingsBackup fromJson(Map json) { + final menuList = List.from(json['episodePopupMenu']); + final speedList = List.from(json['speedList']); + return SettingsBackup( + theme: json['theme'] as int, + accentColor: json['accentColor'] as String, + realDark: json['realDark'] as bool, + autoPlay: json['autoPlay'] as bool, + autoUpdate: json['autoUpdate'] as bool, + updateInterval: json['updateInterval'] as int, + downloadUsingData: json['downloadUsingData'] as bool, + cacheMax: json['cacheMax'] as int, + podcastLayout: json['podcastLayout'] as int, + recentLayout: json['recentLayout'] as int, + favLayout: json['favLayout'] as int, + downloadLayout: json['downloadLayout'] as int, + autoDownloadNetwork: json['autoDownloadNetwork'] as bool, + episodePopupMenu: menuList, + autoDelete: json['autoDelete'] as int, + autoSleepTimer: json['autoSleepTimer'] as bool, + autoSleepTimerStart: json['autoSleepeTimerStart'] as int, + autoSleepTimerEnd: json['autoSleepTimerEnd'] as int, + autoSleepTimerMode: json['autoSleepTimerMode'] as int, + tapToOpenPopupMenu: json['tapToOpenPopupMenu'] as bool, + fastForwardSeconds: json['fastForwardSeconds'] as int, + rewindSeconds: json['rewindSeconds'] as int, + playerHeight: json['playerHeight'] as int, + locale: json['locale'] as String, + hideListened: json['hideListened'] as bool, + notificationLayout: json['notificationLayout'] as int, + showNotesFont: json['showNotesFont'] as int, + speedList: speedList, + hidePodcastDiscovery: json['hidePodcastDiscovery'] as bool, + markListenedAfterSkip: json['markListenedAfterSkip'] as bool, + deleteAfterPlayed: json['deleteAfterPlayed'] as bool); + } +} diff --git a/lib/type/sub_history.dart b/lib/type/sub_history.dart index fe69590..40a4dee 100644 --- a/lib/type/sub_history.dart +++ b/lib/type/sub_history.dart @@ -1,18 +1,18 @@ -class SubHistory { - /// POdcast subscribe date. - DateTime subDate; - - /// Podcast remove date. - DateTime delDate; - - /// If podcast still on user device. - bool status; - - /// POdcast title. - String title; - - /// POdcast rss link. - String rssUrl; - - SubHistory(this.status, this.delDate, this.subDate, this.rssUrl, this.title); -} +class SubHistory { + /// POdcast subscribe date. + DateTime subDate; + + /// Podcast remove date. + DateTime delDate; + + /// If podcast still on user device. + bool status; + + /// POdcast title. + String title; + + /// POdcast rss link. + String rssUrl; + + SubHistory(this.status, this.delDate, this.subDate, this.rssUrl, this.title); +} diff --git a/lib/util/audiopanel.dart b/lib/util/audiopanel.dart index a00ae1c..51fbbe1 100644 --- a/lib/util/audiopanel.dart +++ b/lib/util/audiopanel.dart @@ -1,334 +1,334 @@ -import 'dart:math' as math; - -import 'package:flutter/material.dart'; - -import 'extension_helper.dart'; - -enum SlideDirection { up, down } - -class AudioPanel extends StatefulWidget { - final Widget miniPanel; - final Widget expandedPanel; - final Widget optionPanel; - final double minHeight; - final double maxHeight; - - AudioPanel( - {@required this.miniPanel, - @required this.expandedPanel, - this.optionPanel, - this.minHeight = 70, - this.maxHeight = 300, - Key key}) - : super(key: key); - @override - AudioPanelState createState() => AudioPanelState(); -} - -class AudioPanelState extends State with TickerProviderStateMixin { - double initSize; - double _startdy; - double _move = 0; - AnimationController _controller; - AnimationController _slowController; - Animation _animation; - SlideDirection _slideDirection; - double _expandHeight; - - @override - void initState() { - initSize = widget.minHeight; - _controller = - AnimationController(vsync: this, duration: Duration(milliseconds: 50)) - ..addListener(() { - if (mounted) setState(() {}); - }); - _slowController = - AnimationController(vsync: this, duration: Duration(milliseconds: 200)) - ..addListener(() { - if (mounted) setState(() {}); - }); - _animation = - Tween(begin: 0, end: initSize).animate(_slowController); - _controller.forward(); - _slideDirection = SlideDirection.up; - super.initState(); - _expandHeight = widget.maxHeight + 300; - } - - @override - void dispose() { - _controller.dispose(); - _slowController.dispose(); - super.dispose(); - } - - @override - void didUpdateWidget(AudioPanel oldWidget) { - if (oldWidget.maxHeight != widget.maxHeight) { - setState(() { - _expandHeight = widget.maxHeight + 300; - }); - } - super.didUpdateWidget(oldWidget); - } - - double _getHeight() { - if (_animation.value >= _expandHeight) { - return _expandHeight; - } else if (_animation.value <= widget.minHeight) { - return widget.minHeight; - } else { - return _animation.value; - } - } - - @override - Widget build(BuildContext context) { - return Stack(children: [ - Container( - child: (_animation.value > widget.minHeight + 30) - ? Positioned.fill( - child: GestureDetector( - onTap: backToMini, - child: Container( - color: Theme.of(context) - .scaffoldBackgroundColor - .withOpacity(0.9 * - math.min(_animation.value / widget.maxHeight, 1)), - ), - ), - ) - : Center(), - ), - Align( - alignment: Alignment.bottomCenter, - child: GestureDetector( - onVerticalDragStart: _start, - onVerticalDragUpdate: _update, - onVerticalDragEnd: (event) => _end(), - child: Container( - height: _getHeight(), - child: _animation.value < widget.minHeight + 30 - ? Container( - color: Theme.of(context).primaryColor, - child: Opacity( - opacity: _animation.value > widget.minHeight - ? (widget.minHeight + 30 - _animation.value) / 40 - : 1, - child: widget.miniPanel, - ), - ) - : Container( - decoration: BoxDecoration( - color: context.primaryColor, - // borderRadius: BorderRadius.only( - // topLeft: Radius.circular(20.0), - // topRight: Radius.circular(20.0)), - - boxShadow: [ - BoxShadow( - offset: Offset(0, -1), - blurRadius: 1, - color: context.brightness == Brightness.light - ? Colors.grey[400].withOpacity(0.5) - : Colors.grey[800], - ), - ], - ), - child: SingleChildScrollView( - physics: const NeverScrollableScrollPhysics(), - child: Opacity( - opacity: _animation.value < (widget.maxHeight - 50) - ? (_animation.value - widget.minHeight) / - (widget.maxHeight - widget.minHeight - 50) - : 1, - child: SizedBox( - height: math.max(widget.maxHeight, - math.min(_animation.value, _expandHeight)), - child: widget.expandedPanel, - ), - ), - ), - ), - ), - ), - ), - ]); - } - - backToMini() { - setState(() { - _animation = Tween(begin: initSize, end: widget.minHeight) - .animate(_slowController); - initSize = widget.minHeight; - }); - _slowController.forward(); - } - - scrollToTop() { - setState(() { - _animation = Tween(begin: initSize, end: _expandHeight) - .animate(_slowController); - initSize = _expandHeight; - }); - _slowController.forward(); - } - - _start(DragStartDetails event) { - setState(() { - _startdy = event.localPosition.dy; - _animation = - Tween(begin: initSize, end: initSize).animate(_controller); - }); - _controller.forward(); - } - - _update(DragUpdateDetails event) { - setState(() { - _move = _startdy - event.localPosition.dy; - _animation = Tween(begin: initSize, end: initSize + _move) - .animate(_controller); - _slideDirection = _move > 0 ? SlideDirection.up : SlideDirection.down; - }); - _controller.forward(); - } - - _end() async { - if (_slideDirection == SlideDirection.up) { - if (_move > 50) { - if (_animation.value > widget.maxHeight + 20) { - setState(() { - _animation = - Tween(begin: _animation.value, end: _expandHeight) - .animate(_slowController); - initSize = _expandHeight; - }); - _slowController.forward(); - } else { - setState(() { - _animation = - Tween(begin: widget.maxHeight, end: widget.maxHeight) - .animate(_controller); - initSize = widget.maxHeight; - }); - _controller.forward(); - } - } else { - setState(() { - _animation = - Tween(begin: _animation.value, end: widget.minHeight) - .animate(_controller); - initSize = widget.minHeight; - }); - _controller.forward(); - } - } else if (_slideDirection == SlideDirection.down) { - if (_move > -50) { - if (_animation.value > widget.maxHeight) { - setState(() { - _animation = - Tween(begin: _animation.value, end: _expandHeight) - .animate(_slowController); - initSize = _expandHeight; - }); - } else { - setState(() { - _animation = - Tween(begin: _animation.value, end: widget.maxHeight) - .animate(_slowController); - initSize = widget.maxHeight; - }); - } - _slowController.forward(); - } else { - if (_animation.value > widget.maxHeight) { - setState(() { - _animation = - Tween(begin: _animation.value, end: widget.maxHeight) - .animate(_slowController); - initSize = widget.maxHeight; - }); - } else { - setState(() { - _animation = - Tween(begin: _animation.value, end: widget.minHeight) - .animate(_controller); - initSize = widget.minHeight; - }); - } - _controller.forward(); - } - } - if (_animation.value >= _expandHeight) { - setState(() { - initSize = _expandHeight; - }); - } else if (_animation.value < widget.minHeight) { - setState(() { - initSize = widget.minHeight; - }); - } - } -} - -class _AudioPanelRoute extends StatefulWidget { - _AudioPanelRoute({this.expandPanel, this.height, Key key}) : super(key: key); - final Widget expandPanel; - final double height; - @override - __AudioPanelRouteState createState() => __AudioPanelRouteState(); -} - -class __AudioPanelRouteState extends State<_AudioPanelRoute> { - @override - Widget build(BuildContext context) { - return MediaQuery.removePadding( - context: context, - removeTop: true, - child: Scaffold( - body: Stack(children: [ - Container( - child: Positioned.fill( - child: GestureDetector( - onTap: () => Navigator.pop(context), - // child: - // Container( - // color: Theme.of(context) - // .scaffoldBackgroundColor - // .withOpacity(0.8), - // - //), - ), - ), - ), - Align( - alignment: Alignment.bottomCenter, - child: Container( - height: widget.height, - decoration: BoxDecoration( - color: context.primaryColor, - boxShadow: [ - BoxShadow( - offset: Offset(0, -1), - blurRadius: 1, - color: context.brightness == Brightness.light - ? Colors.grey[400].withOpacity(0.5) - : Colors.grey[800], - ), - ], - ), - child: SingleChildScrollView( - physics: const NeverScrollableScrollPhysics(), - child: SizedBox( - height: 300, - child: widget.expandPanel, - ), - ), - ), - ), - ]), - ), - ); - } -} +import 'dart:math' as math; + +import 'package:flutter/material.dart'; + +import 'extension_helper.dart'; + +enum SlideDirection { up, down } + +class AudioPanel extends StatefulWidget { + final Widget miniPanel; + final Widget expandedPanel; + final Widget optionPanel; + final double minHeight; + final double maxHeight; + + AudioPanel( + {@required this.miniPanel, + @required this.expandedPanel, + this.optionPanel, + this.minHeight = 70, + this.maxHeight = 300, + Key key}) + : super(key: key); + @override + AudioPanelState createState() => AudioPanelState(); +} + +class AudioPanelState extends State with TickerProviderStateMixin { + double initSize; + double _startdy; + double _move = 0; + AnimationController _controller; + AnimationController _slowController; + Animation _animation; + SlideDirection _slideDirection; + double _expandHeight; + + @override + void initState() { + initSize = widget.minHeight; + _controller = + AnimationController(vsync: this, duration: Duration(milliseconds: 50)) + ..addListener(() { + if (mounted) setState(() {}); + }); + _slowController = + AnimationController(vsync: this, duration: Duration(milliseconds: 200)) + ..addListener(() { + if (mounted) setState(() {}); + }); + _animation = + Tween(begin: 0, end: initSize).animate(_slowController); + _controller.forward(); + _slideDirection = SlideDirection.up; + super.initState(); + _expandHeight = widget.maxHeight + 300; + } + + @override + void dispose() { + _controller.dispose(); + _slowController.dispose(); + super.dispose(); + } + + @override + void didUpdateWidget(AudioPanel oldWidget) { + if (oldWidget.maxHeight != widget.maxHeight) { + setState(() { + _expandHeight = widget.maxHeight + 300; + }); + } + super.didUpdateWidget(oldWidget); + } + + double _getHeight() { + if (_animation.value >= _expandHeight) { + return _expandHeight; + } else if (_animation.value <= widget.minHeight) { + return widget.minHeight; + } else { + return _animation.value; + } + } + + @override + Widget build(BuildContext context) { + return Stack(children: [ + Container( + child: (_animation.value > widget.minHeight + 30) + ? Positioned.fill( + child: GestureDetector( + onTap: backToMini, + child: Container( + color: Theme.of(context) + .scaffoldBackgroundColor + .withOpacity(0.9 * + math.min(_animation.value / widget.maxHeight, 1)), + ), + ), + ) + : Center(), + ), + Align( + alignment: Alignment.bottomCenter, + child: GestureDetector( + onVerticalDragStart: _start, + onVerticalDragUpdate: _update, + onVerticalDragEnd: (event) => _end(), + child: Container( + height: _getHeight(), + child: _animation.value < widget.minHeight + 30 + ? Container( + color: Theme.of(context).primaryColor, + child: Opacity( + opacity: _animation.value > widget.minHeight + ? (widget.minHeight + 30 - _animation.value) / 40 + : 1, + child: widget.miniPanel, + ), + ) + : Container( + decoration: BoxDecoration( + color: context.primaryColor, + // borderRadius: BorderRadius.only( + // topLeft: Radius.circular(20.0), + // topRight: Radius.circular(20.0)), + + boxShadow: [ + BoxShadow( + offset: Offset(0, -1), + blurRadius: 1, + color: context.brightness == Brightness.light + ? Colors.grey[400].withOpacity(0.5) + : Colors.grey[800], + ), + ], + ), + child: SingleChildScrollView( + physics: const NeverScrollableScrollPhysics(), + child: Opacity( + opacity: _animation.value < (widget.maxHeight - 50) + ? (_animation.value - widget.minHeight) / + (widget.maxHeight - widget.minHeight - 50) + : 1, + child: SizedBox( + height: math.max(widget.maxHeight, + math.min(_animation.value, _expandHeight)), + child: widget.expandedPanel, + ), + ), + ), + ), + ), + ), + ), + ]); + } + + backToMini() { + setState(() { + _animation = Tween(begin: initSize, end: widget.minHeight) + .animate(_slowController); + initSize = widget.minHeight; + }); + _slowController.forward(); + } + + scrollToTop() { + setState(() { + _animation = Tween(begin: initSize, end: _expandHeight) + .animate(_slowController); + initSize = _expandHeight; + }); + _slowController.forward(); + } + + _start(DragStartDetails event) { + setState(() { + _startdy = event.localPosition.dy; + _animation = + Tween(begin: initSize, end: initSize).animate(_controller); + }); + _controller.forward(); + } + + _update(DragUpdateDetails event) { + setState(() { + _move = _startdy - event.localPosition.dy; + _animation = Tween(begin: initSize, end: initSize + _move) + .animate(_controller); + _slideDirection = _move > 0 ? SlideDirection.up : SlideDirection.down; + }); + _controller.forward(); + } + + _end() async { + if (_slideDirection == SlideDirection.up) { + if (_move > 50) { + if (_animation.value > widget.maxHeight + 20) { + setState(() { + _animation = + Tween(begin: _animation.value, end: _expandHeight) + .animate(_slowController); + initSize = _expandHeight; + }); + _slowController.forward(); + } else { + setState(() { + _animation = + Tween(begin: widget.maxHeight, end: widget.maxHeight) + .animate(_controller); + initSize = widget.maxHeight; + }); + _controller.forward(); + } + } else { + setState(() { + _animation = + Tween(begin: _animation.value, end: widget.minHeight) + .animate(_controller); + initSize = widget.minHeight; + }); + _controller.forward(); + } + } else if (_slideDirection == SlideDirection.down) { + if (_move > -50) { + if (_animation.value > widget.maxHeight) { + setState(() { + _animation = + Tween(begin: _animation.value, end: _expandHeight) + .animate(_slowController); + initSize = _expandHeight; + }); + } else { + setState(() { + _animation = + Tween(begin: _animation.value, end: widget.maxHeight) + .animate(_slowController); + initSize = widget.maxHeight; + }); + } + _slowController.forward(); + } else { + if (_animation.value > widget.maxHeight) { + setState(() { + _animation = + Tween(begin: _animation.value, end: widget.maxHeight) + .animate(_slowController); + initSize = widget.maxHeight; + }); + } else { + setState(() { + _animation = + Tween(begin: _animation.value, end: widget.minHeight) + .animate(_controller); + initSize = widget.minHeight; + }); + } + _controller.forward(); + } + } + if (_animation.value >= _expandHeight) { + setState(() { + initSize = _expandHeight; + }); + } else if (_animation.value < widget.minHeight) { + setState(() { + initSize = widget.minHeight; + }); + } + } +} + +class _AudioPanelRoute extends StatefulWidget { + _AudioPanelRoute({this.expandPanel, this.height, Key key}) : super(key: key); + final Widget expandPanel; + final double height; + @override + __AudioPanelRouteState createState() => __AudioPanelRouteState(); +} + +class __AudioPanelRouteState extends State<_AudioPanelRoute> { + @override + Widget build(BuildContext context) { + return MediaQuery.removePadding( + context: context, + removeTop: true, + child: Scaffold( + body: Stack(children: [ + Container( + child: Positioned.fill( + child: GestureDetector( + onTap: () => Navigator.pop(context), + // child: + // Container( + // color: Theme.of(context) + // .scaffoldBackgroundColor + // .withOpacity(0.8), + // + //), + ), + ), + ), + Align( + alignment: Alignment.bottomCenter, + child: Container( + height: widget.height, + decoration: BoxDecoration( + color: context.primaryColor, + boxShadow: [ + BoxShadow( + offset: Offset(0, -1), + blurRadius: 1, + color: context.brightness == Brightness.light + ? Colors.grey[400].withOpacity(0.5) + : Colors.grey[800], + ), + ], + ), + child: SingleChildScrollView( + physics: const NeverScrollableScrollPhysics(), + child: SizedBox( + height: 300, + child: widget.expandPanel, + ), + ), + ), + ), + ]), + ), + ); + } +} diff --git a/lib/util/custom_dropdown.dart b/lib/util/custom_dropdown.dart index 1f8de7d..ffe8568 100644 --- a/lib/util/custom_dropdown.dart +++ b/lib/util/custom_dropdown.dart @@ -1,1606 +1,1606 @@ -// Copyright 2014 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'dart:math' as math; -import 'dart:ui' show window; - -import 'package:flutter/material.dart'; -import 'package:flutter/foundation.dart'; -import 'package:flutter/rendering.dart'; -import 'package:flutter/services.dart'; -import 'package:flutter/widgets.dart'; - -const Duration _kDropdownMenuDuration = Duration(milliseconds: 300); -const double _kMenuItemHeight = kMinInteractiveDimension; -const double _kDenseButtonHeight = 24.0; -const EdgeInsets _kMenuItemPadding = EdgeInsets.symmetric(horizontal: 16.0); -const EdgeInsetsGeometry _kAlignedButtonPadding = - EdgeInsetsDirectional.only(start: 16.0, end: 4.0); -const EdgeInsets _kUnalignedButtonPadding = EdgeInsets.zero; -const EdgeInsets _kAlignedMenuMargin = EdgeInsets.zero; -const EdgeInsetsGeometry _kUnalignedMenuMargin = - EdgeInsetsDirectional.only(start: 16.0, end: 24.0); - -typedef DropdownButtonBuilder = List Function(BuildContext context); - -class _DropdownMenuPainter extends CustomPainter { - _DropdownMenuPainter({ - this.color, - this.elevation, - this.selectedIndex, - this.resize, - this.getSelectedItemOffset, - }) : _painter = BoxDecoration( - // If you add an image here, you must provide a real - // configuration in the paint() function and you must provide some sort - // of onChanged callback here. - color: color, - //Change default 2.0 to 10.0 - borderRadius: BorderRadius.circular(10.0), - boxShadow: kElevationToShadow[elevation], - ).createBoxPainter(), - super(repaint: resize); - - final Color color; - final int elevation; - final int selectedIndex; - final Animation resize; - final ValueGetter getSelectedItemOffset; - final BoxPainter _painter; - - @override - void paint(Canvas canvas, Size size) { - final selectedItemOffset = getSelectedItemOffset(); - final top = Tween( - begin: selectedItemOffset.clamp(0.0, size.height - _kMenuItemHeight) - as double, - end: 0.0, - ); - - final bottom = Tween( - begin: (top.begin + _kMenuItemHeight).clamp(_kMenuItemHeight, size.height) - as double, - end: size.height, - ); - - final rect = Rect.fromLTRB( - 0.0, top.evaluate(resize), size.width, bottom.evaluate(resize)); - - _painter.paint(canvas, rect.topLeft, ImageConfiguration(size: rect.size)); - } - - @override - bool shouldRepaint(_DropdownMenuPainter oldPainter) { - return oldPainter.color != color || - oldPainter.elevation != elevation || - oldPainter.selectedIndex != selectedIndex || - oldPainter.resize != resize; - } -} - -// Do not use the platform-specific default scroll configuration. -// Dropdown menus should never overscroll or display an overscroll indicator. -class _DropdownScrollBehavior extends ScrollBehavior { - const _DropdownScrollBehavior(); - - @override - TargetPlatform getPlatform(BuildContext context) => - Theme.of(context).platform; - - @override - Widget buildViewportChrome( - BuildContext context, Widget child, AxisDirection axisDirection) => - child; - - @override - ScrollPhysics getScrollPhysics(BuildContext context) => - const ClampingScrollPhysics(); -} - -// The widget that is the button wrapping the menu items. -class _DropdownMenuItemButton extends StatefulWidget { - const _DropdownMenuItemButton({ - Key key, - @required this.padding, - @required this.route, - @required this.buttonRect, - @required this.constraints, - @required this.itemIndex, - }) : super(key: key); - - final _DropdownRoute route; - final EdgeInsets padding; - final Rect buttonRect; - final BoxConstraints constraints; - final int itemIndex; - - @override - _DropdownMenuItemButtonState createState() => - _DropdownMenuItemButtonState(); -} - -class _DropdownMenuItemButtonState - extends State<_DropdownMenuItemButton> { - void _handleFocusChange(bool focused) { - bool inTraditionalMode; - switch (FocusManager.instance.highlightMode) { - case FocusHighlightMode.touch: - inTraditionalMode = false; - break; - case FocusHighlightMode.traditional: - inTraditionalMode = true; - break; - } - - if (focused && inTraditionalMode) { - final menuLimits = widget.route.getMenuLimits( - widget.buttonRect, widget.constraints.maxHeight, widget.itemIndex); - widget.route.scrollController.animateTo( - menuLimits.scrollOffset, - curve: Curves.easeInOut, - duration: const Duration(milliseconds: 100), - ); - } - } - - void _handleOnTap() { - final dropdownMenuItem = widget.route.items[widget.itemIndex].item; - - if (dropdownMenuItem.onTap != null) { - dropdownMenuItem.onTap(); - } - - Navigator.pop( - context, - _DropdownRouteResult(dropdownMenuItem.value), - ); - } - - @override - Widget build(BuildContext context) { - CurvedAnimation opacity; - final unit = 0.5 / (widget.route.items.length + 1.5); - if (widget.itemIndex == widget.route.selectedIndex) { - opacity = CurvedAnimation( - parent: widget.route.animation, curve: const Threshold(0.0)); - } else { - final start = - (0.5 + (widget.itemIndex + 1) * unit).clamp(0.0, 1.0) as double; - final end = (start + 1.5 * unit).clamp(0.0, 1.0) as double; - opacity = CurvedAnimation( - parent: widget.route.animation, curve: Interval(start, end)); - } - Widget child = FadeTransition( - opacity: opacity, - child: InkWell( - autofocus: widget.itemIndex == widget.route.selectedIndex, - child: Container( - padding: widget.padding, - child: widget.route.items[widget.itemIndex], - ), - onTap: _handleOnTap, - onFocusChange: _handleFocusChange, - ), - ); - return child; - } -} - -class _DropdownMenu extends StatefulWidget { - const _DropdownMenu({ - Key key, - this.padding, - this.route, - this.buttonRect, - this.constraints, - this.dropdownColor, - this.displayItemCount, - }) : super(key: key); - - final _DropdownRoute route; - final EdgeInsets padding; - final Rect buttonRect; - final BoxConstraints constraints; - final Color dropdownColor; - final int displayItemCount; - - @override - _DropdownMenuState createState() => _DropdownMenuState(); -} - -class _DropdownMenuState extends State<_DropdownMenu> { - CurvedAnimation _fadeOpacity; - CurvedAnimation _resize; - - @override - void initState() { - super.initState(); - // We need to hold these animations as state because of their curve - // direction. When the route's animation reverses, if we were to recreate - // the CurvedAnimation objects in build, we'd lose - // CurvedAnimation._curveDirection. - _fadeOpacity = CurvedAnimation( - parent: widget.route.animation, - curve: const Interval(0.0, 0.25), - reverseCurve: const Interval(0.75, 1.0), - ); - _resize = CurvedAnimation( - parent: widget.route.animation, - curve: const Interval(0.25, 0.5), - reverseCurve: const Threshold(0.0), - ); - } - - @override - Widget build(BuildContext context) { - // The menu is shown in three stages (unit timing in brackets): - // [0s - 0.25s] - Fade in a rect-sized menu container with the selected item. - // [0.25s - 0.5s] - Grow the otherwise empty menu container from the center - // until it's big enough for as many items as we're going to show. - // [0.5s - 1.0s] Fade in the remaining visible items from top to bottom. - // - // When the menu is dismissed we just fade the entire thing out - // in the first 0.25s. - assert(debugCheckHasMaterialLocalizations(context)); - final localizations = MaterialLocalizations.of(context); - final route = widget.route; - final children = [ - for (int itemIndex = 0; itemIndex < route.items.length; ++itemIndex) - _DropdownMenuItemButton( - route: widget.route, - padding: widget.padding, - buttonRect: widget.buttonRect, - constraints: widget.constraints, - itemIndex: itemIndex, - ), - ]; - - return FadeTransition( - opacity: _fadeOpacity, - child: CustomPaint( - painter: _DropdownMenuPainter( - color: widget.dropdownColor ?? Theme.of(context).canvasColor, - elevation: route.elevation, - selectedIndex: route.selectedIndex, - resize: _resize, - // This offset is passed as a callback, not a value, because it must - // be retrieved at paint time (after layout), not at build time. - getSelectedItemOffset: () => route.getItemOffset(route.selectedIndex), - ), - child: Semantics( - scopesRoute: true, - namesRoute: true, - explicitChildNodes: true, - label: localizations.popupMenuLabel, - child: Material( - type: MaterialType.transparency, - textStyle: route.style, - child: ScrollConfiguration( - behavior: const _DropdownScrollBehavior(), - child: Scrollbar( - child: ListView( - controller: widget.route.scrollController, - padding: kMaterialListPadding, - shrinkWrap: true, - children: children, - ), - ), - ), - ), - ), - ), - ); - } -} - -class _DropdownMenuRouteLayout extends SingleChildLayoutDelegate { - _DropdownMenuRouteLayout({ - @required this.buttonRect, - @required this.route, - @required this.textDirection, - this.displayItemCount, - }); - - final Rect buttonRect; - final _DropdownRoute route; - final TextDirection textDirection; - final int displayItemCount; - - @override - BoxConstraints getConstraintsForChild(BoxConstraints constraints) { - // The maximum height of a simple menu should be one or more rows less than - // the view height. This ensures a tappable area outside of the simple menu - // with which to dismiss the menu. - // -- https://material.io/design/components/menus.html#usage - final maxHeight = displayItemCount == null - ? math.max(0.0, constraints.maxHeight - 2 * _kMenuItemHeight) - : math.min(_kMenuItemHeight * displayItemCount, - constraints.maxHeight - 2 * _kMenuItemHeight); - // The width of a menu should be at most the view width. This ensures that - // the menu does not extend past the left and right edges of the screen. - final width = math.min(constraints.maxWidth, buttonRect.width); - return BoxConstraints( - minWidth: width, - maxWidth: width, - minHeight: 0.0, - maxHeight: maxHeight, - ); - } - - @override - Offset getPositionForChild(Size size, Size childSize) { - final menuLimits = - route.getMenuLimits(buttonRect, size.height, route.selectedIndex); - - assert(() { - final container = Offset.zero & size; - if (container.intersect(buttonRect) == buttonRect) { - // If the button was entirely on-screen, then verify - // that the menu is also on-screen. - // If the button was a bit off-screen, then, oh well. - assert(menuLimits.top >= 0.0); - assert(menuLimits.top + menuLimits.height <= size.height); - } - return true; - }()); - assert(textDirection != null); - double left; - switch (textDirection) { - case TextDirection.rtl: - left = (buttonRect.right.clamp(0.0, size.width) as double) - - childSize.width; - break; - case TextDirection.ltr: - left = - buttonRect.left.clamp(0.0, size.width - childSize.width) as double; - break; - } - - return Offset(left, menuLimits.top); - } - - @override - bool shouldRelayout(_DropdownMenuRouteLayout oldDelegate) { - return buttonRect != oldDelegate.buttonRect || - textDirection != oldDelegate.textDirection; - } -} - -// We box the return value so that the return value can be null. Otherwise, -// canceling the route (which returns null) would get confused with actually -// returning a real null value. -class _DropdownRouteResult { - const _DropdownRouteResult(this.result); - - final T result; - - @override - bool operator ==(Object other) { - return other is _DropdownRouteResult && other.result == result; - } - - @override - int get hashCode => result.hashCode; -} - -class _MenuLimits { - const _MenuLimits(this.top, this.bottom, this.height, this.scrollOffset); - final double top; - final double bottom; - final double height; - final double scrollOffset; -} - -class _DropdownRoute extends PopupRoute<_DropdownRouteResult> { - _DropdownRoute({ - this.items, - this.padding, - this.buttonRect, - this.selectedIndex, - this.elevation = 8, - this.theme, - @required this.style, - this.barrierLabel, - this.itemHeight, - this.dropdownColor, - this.displayItemCount, - }) : assert(style != null), - itemHeights = List.filled( - items.length, itemHeight ?? kMinInteractiveDimension); - - final List<_MenuItem> items; - final EdgeInsetsGeometry padding; - final Rect buttonRect; - final int selectedIndex; - final int elevation; - final ThemeData theme; - final TextStyle style; - final double itemHeight; - final Color dropdownColor; - final int displayItemCount; - - final List itemHeights; - ScrollController scrollController; - - @override - Duration get transitionDuration => _kDropdownMenuDuration; - - @override - bool get barrierDismissible => true; - - @override - Color get barrierColor => null; - - @override - final String barrierLabel; - - @override - Widget buildPage(BuildContext context, Animation animation, - Animation secondaryAnimation) { - return LayoutBuilder(builder: (context, constraints) { - return _DropdownRoutePage( - route: this, - constraints: constraints, - items: items, - padding: padding, - buttonRect: buttonRect, - selectedIndex: selectedIndex, - elevation: elevation, - theme: theme, - style: style, - dropdownColor: dropdownColor, - displayItemCount: displayItemCount, - ); - }); - } - - void _dismiss() { - navigator?.removeRoute(this); - } - - double getItemOffset(int index) { - var offset = kMaterialListPadding.top; - if (items.isNotEmpty && index > 0) { - assert(items.length == itemHeights?.length); - if (displayItemCount == null) { - offset += itemHeights - .sublist(0, index) - .reduce((total, height) => total + height); - } else { - offset += itemHeights - .sublist(math.max(0, index + 1 - displayItemCount), index) - .reduce((total, height) => total + height); - } - } - - return offset; - } - - // Returns the vertical extent of the menu and the initial scrollOffset - // for the ListView that contains the menu items. The vertical center of the - // selected item is aligned with the button's vertical center, as far as - // that's possible given availableHeight. - _MenuLimits getMenuLimits( - Rect buttonRect, double availableHeight, int index) { - final maxMenuHeight = displayItemCount == null - ? availableHeight - 2.0 * _kMenuItemHeight - : math.min(_kMenuItemHeight * displayItemCount, - availableHeight - 2 * _kMenuItemHeight); - final buttonTop = buttonRect.top; - final buttonBottom = math.min(buttonRect.bottom, availableHeight); - final selectedItemOffset = getItemOffset(index); - - // If the button is placed on the bottom or top of the screen, its top or - // bottom may be less than [_kMenuItemHeight] from the edge of the screen. - // In this case, we want to change the menu limits to align with the top - // or bottom edge of the button. - final topLimit = math.min(_kMenuItemHeight, buttonTop); - final bottomLimit = - math.max(availableHeight - _kMenuItemHeight, buttonBottom); - - var menuTop = (buttonTop - selectedItemOffset) - - (itemHeights[selectedIndex] - buttonRect.height) / 2.0; - var preferredMenuHeight = kMaterialListPadding.vertical; - if (items.isNotEmpty) { - preferredMenuHeight += - itemHeights.reduce((total, height) => total + height); - } - - // If there are too many elements in the menu, we need to shrink it down - // so it is at most the maxMenuHeight. - final menuHeight = math.min(maxMenuHeight, preferredMenuHeight); - var menuBottom = menuTop + menuHeight; - - // If the computed top or bottom of the menu are outside of the range - // specified, we need to bring them into range. If the item height is larger - // than the button height and the button is at the very bottom or top of the - // screen, the menu will be aligned with the bottom or top of the button - // respectively. - if (menuTop < topLimit) menuTop = math.min(buttonTop, topLimit); - - if (menuBottom > bottomLimit) { - menuBottom = math.max(buttonBottom, bottomLimit); - menuTop = menuBottom - menuHeight; - } - - // If all of the menu items will not fit within availableHeight then - // compute the scroll offset that will line the selected menu item up - // with the select item. This is only done when the menu is first - // shown - subsequently we leave the scroll offset where the user left - // it. This scroll offset is only accurate for fixed height menu items - // (the default). - final scrollOffset = preferredMenuHeight <= maxMenuHeight - ? 0.0 - : displayItemCount == null || displayItemCount > index - ? math.max(0.0, selectedItemOffset - (buttonTop - menuTop)) - : math.max(0.0, (index - displayItemCount + 1) * _kMenuItemHeight); - return _MenuLimits(menuTop, menuBottom, menuHeight, scrollOffset); - } -} - -class _DropdownRoutePage extends StatelessWidget { - const _DropdownRoutePage({ - Key key, - this.route, - this.constraints, - this.items, - this.padding, - this.buttonRect, - this.selectedIndex, - this.elevation = 8, - this.theme, - this.style, - this.dropdownColor, - this.displayItemCount, - }) : super(key: key); - - final _DropdownRoute route; - final BoxConstraints constraints; - final List<_MenuItem> items; - final EdgeInsetsGeometry padding; - final Rect buttonRect; - final int selectedIndex; - final int elevation; - final ThemeData theme; - final TextStyle style; - final Color dropdownColor; - final int displayItemCount; - - @override - Widget build(BuildContext context) { - assert(debugCheckHasDirectionality(context)); - - // Computing the initialScrollOffset now, before the items have been laid - // out. This only works if the item heights are effectively fixed, i.e. either - // DropdownButton.itemHeight is specified or DropdownButton.itemHeight is null - // and all of the items' intrinsic heights are less than kMinInteractiveDimension. - // Otherwise the initialScrollOffset is just a rough approximation based on - // treating the items as if their heights were all equal to kMinInteractveDimension. - if (route.scrollController == null) { - final menuLimits = - route.getMenuLimits(buttonRect, constraints.maxHeight, selectedIndex); - route.scrollController = - ScrollController(initialScrollOffset: menuLimits.scrollOffset); - } - - final textDirection = Directionality.of(context); - Widget menu = _DropdownMenu( - route: route, - padding: padding.resolve(textDirection), - buttonRect: buttonRect, - constraints: constraints, - dropdownColor: dropdownColor, - ); - - if (theme != null) menu = Theme(data: theme, child: menu); - - return MediaQuery.removePadding( - context: context, - removeTop: true, - removeBottom: true, - removeLeft: true, - removeRight: true, - child: Builder( - builder: (context) { - return CustomSingleChildLayout( - delegate: _DropdownMenuRouteLayout( - buttonRect: buttonRect, - route: route, - textDirection: textDirection, - displayItemCount: displayItemCount, - ), - child: menu, - ); - }, - ), - ); - } -} - -// This widget enables _DropdownRoute to look up the sizes of -// each menu item. These sizes are used to compute the offset of the selected -// item so that _DropdownRoutePage can align the vertical center of the -// selected item lines up with the vertical center of the dropdown button, -// as closely as possible. -class _MenuItem extends SingleChildRenderObjectWidget { - const _MenuItem({ - Key key, - @required this.onLayout, - @required this.item, - }) : assert(onLayout != null), - super(key: key, child: item); - - final ValueChanged onLayout; - final DropdownMenuItem item; - - @override - RenderObject createRenderObject(BuildContext context) { - return _RenderMenuItem(onLayout); - } - - @override - void updateRenderObject( - BuildContext context, covariant _RenderMenuItem renderObject) { - renderObject.onLayout = onLayout; - } -} - -class _RenderMenuItem extends RenderProxyBox { - _RenderMenuItem(this.onLayout, [RenderBox child]) - : assert(onLayout != null), - super(child); - - ValueChanged onLayout; - - @override - void performLayout() { - super.performLayout(); - onLayout(size); - } -} - -// The container widget for a menu item created by a [DropdownButton]. It -// provides the default configuration for [DropdownMenuItem]s, as well as a -// [DropdownButton]'s hint and disabledHint widgets. -class _DropdownMenuItemContainer extends StatelessWidget { - /// Creates an item for a dropdown menu. - /// - /// The [child] argument is required. - const _DropdownMenuItemContainer({ - Key key, - @required this.child, - }) : assert(child != null), - super(key: key); - - /// The widget below this widget in the tree. - /// - /// Typically a [Text] widget. - final Widget child; - - @override - Widget build(BuildContext context) { - return Container( - constraints: const BoxConstraints(minHeight: _kMenuItemHeight), - alignment: AlignmentDirectional.centerStart, - child: child, - ); - } -} - -/// An item in a menu created by a [DropdownButton]. -/// -/// The type `T` is the type of the value the entry represents. All the entries -/// in a given menu must represent values with consistent types. -//class DropdownMenuItem extends _DropdownMenuItemContainer { -// /// Creates an item for a dropdown menu. -// /// -// /// The [child] argument is required. -// const DropdownMenuItem({ -// Key key, -// this.onTap, -// this.value, -// @required Widget child, -// }) : assert(child != null), -// super(key: key, child: child); -// -// /// Called when the dropdown menu item is tapped. -// final VoidCallback onTap; -// -// /// The value to return if the user selects this menu item. -// /// -// /// Eventually returned in a call to [DropdownButton.onChanged]. -// final T value; -//} -// -/// An inherited widget that causes any descendant [DropdownButton] -/// widgets to not include their regular underline. -/// -/// This is used by [DataTable] to remove the underline from any -/// [DropdownButton] widgets placed within material data tables, as -/// required by the material design specification. -class DropdownButtonHideUnderline extends InheritedWidget { - /// Creates a [DropdownButtonHideUnderline]. A non-null [child] must - /// be given. - const DropdownButtonHideUnderline({ - Key key, - @required Widget child, - }) : assert(child != null), - super(key: key, child: child); - - /// Returns whether the underline of [DropdownButton] widgets should - /// be hidden. - static bool at(BuildContext context) { - return context.dependOnInheritedWidgetOfExactType< - DropdownButtonHideUnderline>() != - null; - } - - @override - bool updateShouldNotify(DropdownButtonHideUnderline oldWidget) => false; -} - -/// A material design button for selecting from a list of items. -/// -/// A dropdown button lets the user select from a number of items. The button -/// shows the currently selected item as well as an arrow that opens a menu for -/// selecting another item. -/// -/// The type `T` is the type of the [value] that each dropdown item represents. -/// All the entries in a given menu must represent values with consistent types. -/// Typically, an enum is used. Each [DropdownMenuItem] in [items] must be -/// specialized with that same type argument. -/// -/// The [onChanged] callback should update a state variable that defines the -/// dropdown's value. It should also call [State.setState] to rebuild the -/// dropdown with the new value. -/// -/// {@tool dartpad --template=stateful_widget_scaffold_center} -/// -/// This sample shows a `DropdownButton` with a large arrow icon, -/// purple text style, and bold purple underline, whose value is one of "One", -/// "Two", "Free", or "Four". -/// -/// ![](https://flutter.github.io/assets-for-api-docs/assets/material/dropdown_button.png) -/// -/// ```dart -/// String dropdownValue = 'One'; -/// -/// @override -/// Widget build(BuildContext context) { -/// return DropdownButton( -/// value: dropdownValue, -/// icon: Icon(Icons.arrow_downward), -/// iconSize: 24, -/// elevation: 16, -/// style: TextStyle( -/// color: Colors.deepPurple -/// ), -/// underline: Container( -/// height: 2, -/// color: Colors.deepPurpleAccent, -/// ), -/// onChanged: (String newValue) { -/// setState(() { -/// dropdownValue = newValue; -/// }); -/// }, -/// items: ['One', 'Two', 'Free', 'Four'] -/// .map>((String value) { -/// return DropdownMenuItem( -/// value: value, -/// child: Text(value), -/// ); -/// }) -/// .toList(), -/// ); -/// } -/// ``` -/// {@end-tool} -/// -/// If the [onChanged] callback is null or the list of [items] is null -/// then the dropdown button will be disabled, i.e. its arrow will be -/// displayed in grey and it will not respond to input. A disabled button -/// will display the [disabledHint] widget if it is non-null. However, if -/// [disabledHint] is null and [hint] is non-null, the [hint] widget will -/// instead be displayed. -/// -/// Requires one of its ancestors to be a [Material] widget. -/// -/// See also: -/// -/// * [DropdownMenuItem], the class used to represent the [items]. -/// * [DropdownButtonHideUnderline], which prevents its descendant dropdown buttons -/// from displaying their underlines. -/// * [RaisedButton], [FlatButton], ordinary buttons that trigger a single action. -/// * -class MyDropdownButton extends StatefulWidget { - /// Creates a dropdown button. - /// - /// The [items] must have distinct values. If [value] isn't null then it - /// must be equal to one of the [DropDownMenuItem] values. If [items] or - /// [onChanged] is null, the button will be disabled, the down arrow - /// will be greyed out, and the [disabledHint] will be shown (if provided). - /// If [disabledHint] is null and [hint] is non-null, [hint] will instead be - /// shown. - /// - /// The [elevation] and [iconSize] arguments must not be null (they both have - /// defaults, so do not need to be specified). The boolean [isDense] and - /// [isExpanded] arguments must not be null. - /// - /// The [dropdownColor] argument specifies the background color of the - /// dropdown when it is open. If it is null, the current theme's - /// [ThemeData.canvasColor] will be used instead. - MyDropdownButton({ - Key key, - @required this.items, - this.selectedItemBuilder, - this.value, - this.hint, - this.disabledHint, - @required this.onChanged, - this.onTap, - this.elevation = 8, - this.style, - this.underline, - this.icon, - this.iconDisabledColor, - this.iconEnabledColor, - this.iconSize = 24.0, - this.isDense = false, - this.isExpanded = false, - this.itemHeight = kMinInteractiveDimension, - this.focusColor, - this.focusNode, - this.autofocus = false, - this.dropdownColor, - this.displayItemCount, - }) : assert( - items == null || - items.isEmpty || - value == null || - items.where((item) { - return item.value == value; - }).length == - 1, - "There should be exactly one item with [DropdownButton]'s value: " - '$value. \n' - 'Either zero or 2 or more [DropdownMenuItem]s were detected ' - 'with the same value', - ), - assert(elevation != null), - assert(iconSize != null), - assert(isDense != null), - assert(isExpanded != null), - assert(autofocus != null), - assert(itemHeight == null || itemHeight >= kMinInteractiveDimension), - assert(displayItemCount == null || displayItemCount > 0), - super(key: key); - - /// The list of items the user can select. - /// - /// If the [onChanged] callback is null or the list of items is null - /// then the dropdown button will be disabled, i.e. its arrow will be - /// displayed in grey and it will not respond to input. A disabled button - /// will display the [disabledHint] widget if it is non-null. If - /// [disabledHint] is also null but [hint] is non-null, [hint] will instead - /// be displayed. - final List> items; - - /// The value of the currently selected [DropdownMenuItem]. - /// - /// If [value] is null and [hint] is non-null, the [hint] widget is - /// displayed as a placeholder for the dropdown button's value. - final T value; - - /// A placeholder widget that is displayed by the dropdown button. - /// - /// If [value] is null, this widget is displayed as a placeholder for - /// the dropdown button's value. This widget is also displayed if the button - /// is disabled ([items] or [onChanged] is null) and [disabledHint] is null. - final Widget hint; - - /// A message to show when the dropdown is disabled. - /// - /// Displayed if [items] or [onChanged] is null. If [hint] is non-null and - /// [disabledHint] is null, the [hint] widget will be displayed instead. - final Widget disabledHint; - - /// {@template flutter.material.dropdownButton.onChanged} - /// Called when the user selects an item. - /// - /// If the [onChanged] callback is null or the list of [items] is null - /// then the dropdown button will be disabled, i.e. its arrow will be - /// displayed in grey and it will not respond to input. A disabled button - /// will display the [disabledHint] widget if it is non-null. If - /// [disabledHint] is also null but [hint] is non-null, [hint] will instead - /// be displayed. - /// {@endtemplate} - final ValueChanged onChanged; - - /// Called when the dropdown button is tapped. - /// - /// This is distinct from [onChanged], which is called when the user - /// selects an item from the dropdown. - /// - /// The callback will not be invoked if the dropdown button is disabled. - final VoidCallback onTap; - - /// A builder to customize the dropdown buttons corresponding to the - /// [DropdownMenuItem]s in [items]. - /// - /// When a [DropdownMenuItem] is selected, the widget that will be displayed - /// from the list corresponds to the [DropdownMenuItem] of the same index - /// in [items]. - /// - /// {@tool dartpad --template=stateful_widget_scaffold} - /// - /// This sample shows a `DropdownButton` with a button with [Text] that - /// corresponds to but is unique from [DropdownMenuItem]. - /// - /// ```dart - /// final List items = ['1','2','3']; - /// String selectedItem = '1'; - /// - /// @override - /// Widget build(BuildContext context) { - /// return Padding( - /// padding: const EdgeInsets.symmetric(horizontal: 12.0), - /// child: DropdownButton( - /// value: selectedItem, - /// onChanged: (String string) => setState(() => selectedItem = string), - /// selectedItemBuilder: (BuildContext context) { - /// return items.map((String item) { - /// return Text(item); - /// }).toList(); - /// }, - /// items: items.map((String item) { - /// return DropdownMenuItem( - /// child: Text('Log $item'), - /// value: item, - /// ); - /// }).toList(), - /// ), - /// ); - /// } - /// ``` - /// {@end-tool} - /// - /// If this callback is null, the [DropdownMenuItem] from [items] - /// that matches [value] will be displayed. - final DropdownButtonBuilder selectedItemBuilder; - - /// The z-coordinate at which to place the menu when open. - /// - /// The following elevations have defined shadows: 1, 2, 3, 4, 6, 8, 9, 12, - /// 16, and 24. See [kElevationToShadow]. - /// - /// Defaults to 8, the appropriate elevation for dropdown buttons. - final int elevation; - - /// The text style to use for text in the dropdown button and the dropdown - /// menu that appears when you tap the button. - /// - /// To use a separate text style for selected item when it's displayed within - /// the dropdown button,, consider using [selectedItemBuilder]. - /// - /// {@tool dartpad --template=stateful_widget_scaffold} - /// - /// This sample shows a `DropdownButton` with a dropdown button text style - /// that is different than its menu items. - /// - /// ```dart - /// List options = ['One', 'Two', 'Free', 'Four']; - /// String dropdownValue = 'One'; - /// - /// @override - /// Widget build(BuildContext context) { - /// return Container( - /// alignment: Alignment.center, - /// color: Colors.blue, - /// child: DropdownButton( - /// value: dropdownValue, - /// onChanged: (String newValue) { - /// setState(() { - /// dropdownValue = newValue; - /// }); - /// }, - /// style: TextStyle(color: Colors.blue), - /// selectedItemBuilder: (BuildContext context) { - /// return options.map((String value) { - /// return Text( - /// dropdownValue, - /// style: TextStyle(color: Colors.white), - /// ); - /// }).toList(); - /// }, - /// items: options.map>((String value) { - /// return DropdownMenuItem( - /// value: value, - /// child: Text(value), - /// ); - /// }).toList(), - /// ), - /// ); - /// } - /// ``` - /// {@end-tool} - /// - /// Defaults to the [TextTheme.subtitle1] value of the current - /// [ThemeData.textTheme] of the current [Theme]. - final TextStyle style; - - /// The widget to use for drawing the drop-down button's underline. - /// - /// Defaults to a 0.0 width bottom border with color 0xFFBDBDBD. - final Widget underline; - - /// The widget to use for the drop-down button's icon. - /// - /// Defaults to an [Icon] with the [Icons.arrow_drop_down] glyph. - final Widget icon; - - /// The color of any [Icon] descendant of [icon] if this button is disabled, - /// i.e. if [onChanged] is null. - /// - /// Defaults to [Colors.grey.shade400] when the theme's - /// [ThemeData.brightness] is [Brightness.light] and to - /// [Colors.white10] when it is [Brightness.dark] - final Color iconDisabledColor; - - /// The color of any [Icon] descendant of [icon] if this button is enabled, - /// i.e. if [onChanged] is defined. - /// - /// Defaults to [Colors.grey.shade700] when the theme's - /// [ThemeData.brightness] is [Brightness.light] and to - /// [Colors.white70] when it is [Brightness.dark] - final Color iconEnabledColor; - - /// The size to use for the drop-down button's down arrow icon button. - /// - /// Defaults to 24.0. - final double iconSize; - - /// Reduce the button's height. - /// - /// By default this button's height is the same as its menu items' heights. - /// If isDense is true, the button's height is reduced by about half. This - /// can be useful when the button is embedded in a container that adds - /// its own decorations, like [InputDecorator]. - final bool isDense; - - /// Set the dropdown's inner contents to horizontally fill its parent. - /// - /// By default this button's inner width is the minimum size of its contents. - /// If [isExpanded] is true, the inner width is expanded to fill its - /// surrounding container. - final bool isExpanded; - - /// If null, then the menu item heights will vary according to each menu item's - /// intrinsic height. - /// - /// The default value is [kMinInteractiveDimension], which is also the minimum - /// height for menu items. - /// - /// If this value is null and there isn't enough vertical room for the menu, - /// then the menu's initial scroll offset may not align the selected item with - /// the dropdown button. That's because, in this case, the initial scroll - /// offset is computed as if all of the menu item heights were - /// [kMinInteractiveDimension]. - final double itemHeight; - - /// The color for the button's [Material] when it has the input focus. - final Color focusColor; - - /// {@macro flutter.widgets.Focus.focusNode} - final FocusNode focusNode; - - /// {@macro flutter.widgets.Focus.autofocus} - final bool autofocus; - - /// The background color of the dropdown. - /// - /// If it is not provided, the theme's [ThemeData.canvasColor] will be used - /// instead. - final Color dropdownColor; - - final int displayItemCount; - - @override - _MyDropdownButtonState createState() => _MyDropdownButtonState(); -} - -class _MyDropdownButtonState extends State> - // ignore: prefer_mixin - with - // ignore: prefer_mixin - WidgetsBindingObserver { - int _selectedIndex; - _DropdownRoute _dropdownRoute; - Orientation _lastOrientation; - FocusNode _internalNode; - FocusNode get focusNode => widget.focusNode ?? _internalNode; - bool _hasPrimaryFocus = false; - //Map _actionMap; - FocusHighlightMode _focusHighlightMode; - - // Only used if needed to create _internalNode. - FocusNode _createFocusNode() { - return FocusNode(debugLabel: '${widget.runtimeType}'); - } - - @override - void initState() { - super.initState(); - _updateSelectedIndex(); - if (widget.focusNode == null) { - _internalNode ??= _createFocusNode(); - } - // _actionMap = { - // ActivateAction.key: _createAction, - // }; - focusNode.addListener(_handleFocusChanged); - final focusManager = WidgetsBinding.instance.focusManager; - _focusHighlightMode = focusManager.highlightMode; - focusManager.addHighlightModeListener(_handleFocusHighlightModeChange); - } - - @override - void dispose() { - WidgetsBinding.instance.removeObserver(this); - _removeDropdownRoute(); - WidgetsBinding.instance.focusManager - .removeHighlightModeListener(_handleFocusHighlightModeChange); - focusNode.removeListener(_handleFocusChanged); - _internalNode?.dispose(); - super.dispose(); - } - - void _removeDropdownRoute() { - _dropdownRoute?._dismiss(); - _dropdownRoute = null; - _lastOrientation = null; - } - - void _handleFocusChanged() { - if (_hasPrimaryFocus != focusNode.hasPrimaryFocus) { - setState(() { - _hasPrimaryFocus = focusNode.hasPrimaryFocus; - }); - } - } - - void _handleFocusHighlightModeChange(FocusHighlightMode mode) { - if (!mounted) { - return; - } - setState(() { - _focusHighlightMode = mode; - }); - } - - @override - void didUpdateWidget(MyDropdownButton oldWidget) { - super.didUpdateWidget(oldWidget); - if (widget.focusNode != oldWidget.focusNode) { - oldWidget.focusNode?.removeListener(_handleFocusChanged); - if (widget.focusNode == null) { - _internalNode ??= _createFocusNode(); - } - _hasPrimaryFocus = focusNode.hasPrimaryFocus; - focusNode.addListener(_handleFocusChanged); - } - _updateSelectedIndex(); - } - - void _updateSelectedIndex() { - if (!_enabled) { - return; - } - - assert(widget.value == null || - widget.items.where((item) => item.value == widget.value).length == 1); - _selectedIndex = null; - for (var itemIndex = 0; itemIndex < widget.items.length; itemIndex++) { - if (widget.items[itemIndex].value == widget.value) { - _selectedIndex = itemIndex; - return; - } - } - } - - TextStyle get _textStyle => - widget.style ?? Theme.of(context).textTheme.subtitle1; - - void _handleTap() { - final itemBox = context.findRenderObject() as RenderBox; - final itemRect = itemBox.localToGlobal(Offset.zero) & itemBox.size; - final textDirection = Directionality.of(context); - final menuMargin = ButtonTheme.of(context).alignedDropdown - ? _kAlignedMenuMargin - : _kUnalignedMenuMargin; - - final menuItems = List<_MenuItem>(widget.items.length); - for (var index = 0; index < widget.items.length; index += 1) { - menuItems[index] = _MenuItem( - item: widget.items[index], - onLayout: (size) { - // If [_dropdownRoute] is null and onLayout is called, this means - // that performLayout was called on a _DropdownRoute that has not - // left the widget tree but is already on its way out. - // - // Since onLayout is used primarily to collect the desired heights - // of each menu item before laying them out, not having the _DropdownRoute - // collect each item's height to lay out is fine since the route is - // already on its way out. - if (_dropdownRoute == null) return; - - _dropdownRoute.itemHeights[index] = size.height; - }, - ); - } - - assert(_dropdownRoute == null); - _dropdownRoute = _DropdownRoute( - items: menuItems, - buttonRect: menuMargin.resolve(textDirection).inflateRect(itemRect), - padding: _kMenuItemPadding.resolve(textDirection), - selectedIndex: _selectedIndex ?? 0, - elevation: widget.elevation, - theme: Theme.of(context, shadowThemeOnly: true), - style: _textStyle, - barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel, - itemHeight: widget.itemHeight, - dropdownColor: widget.dropdownColor, - displayItemCount: widget.displayItemCount, - ); - - Navigator.push(context, _dropdownRoute).then((newValue) { - _removeDropdownRoute(); - if (!mounted || newValue == null) return; - if (widget.onChanged != null) widget.onChanged(newValue.result); - }); - - if (widget.onTap != null) { - widget.onTap(); - } - } - -// Action _createAction() { -// return CallbackAction( -// ActivateAction.key, -// onInvoke: (FocusNode node, Intent intent) { -// _handleTap(); -// }, -// ); -// } - - // When isDense is true, reduce the height of this button from _kMenuItemHeight to - // _kDenseButtonHeight, but don't make it smaller than the text that it contains. - // Similarly, we don't reduce the height of the button so much that its icon - // would be clipped. - double get _denseButtonHeight { - final fontSize = - _textStyle.fontSize ?? Theme.of(context).textTheme.subtitle1.fontSize; - return math.max(fontSize, math.max(widget.iconSize, _kDenseButtonHeight)); - } - - Color get _iconColor { - // These colors are not defined in the Material Design spec. - if (_enabled) { - if (widget.iconEnabledColor != null) return widget.iconEnabledColor; - - switch (Theme.of(context).brightness) { - case Brightness.light: - return Colors.grey.shade700; - case Brightness.dark: - return Colors.white70; - } - } else { - if (widget.iconDisabledColor != null) return widget.iconDisabledColor; - - switch (Theme.of(context).brightness) { - case Brightness.light: - return Colors.grey.shade400; - case Brightness.dark: - return Colors.white10; - } - } - - assert(false); - return null; - } - - bool get _enabled => - widget.items != null && - widget.items.isNotEmpty && - widget.onChanged != null; - - Orientation _getOrientation(BuildContext context) { - var result = MediaQuery.of(context, nullOk: true)?.orientation; - if (result == null) { - // If there's no MediaQuery, then use the window aspect to determine - // orientation. - final size = window.physicalSize; - result = size.width > size.height - ? Orientation.landscape - : Orientation.portrait; - } - return result; - } - - bool get _showHighlight { - switch (_focusHighlightMode) { - case FocusHighlightMode.touch: - return false; - case FocusHighlightMode.traditional: - return _hasPrimaryFocus; - } - return null; - } - - @override - Widget build(BuildContext context) { - assert(debugCheckHasMaterial(context)); - assert(debugCheckHasMaterialLocalizations(context)); - final newOrientation = _getOrientation(context); - _lastOrientation ??= newOrientation; - if (newOrientation != _lastOrientation) { - _removeDropdownRoute(); - _lastOrientation = newOrientation; - } - - // The width of the button and the menu are defined by the widest - // item and the width of the hint. - List items; - if (_enabled) { - items = widget.selectedItemBuilder == null - ? List.from(widget.items) - : widget.selectedItemBuilder(context); - } else { - items = widget.selectedItemBuilder == null - ? [] - : widget.selectedItemBuilder(context); - } - - int hintIndex; - if (widget.hint != null || (!_enabled && widget.disabledHint != null)) { - var displayedHint = - _enabled ? widget.hint : widget.disabledHint ?? widget.hint; - if (widget.selectedItemBuilder == null) { - displayedHint = _DropdownMenuItemContainer(child: displayedHint); - } - - hintIndex = items.length; - items.add(DefaultTextStyle( - style: _textStyle.copyWith(color: Theme.of(context).hintColor), - child: IgnorePointer( - ignoringSemantics: false, - child: displayedHint, - ), - )); - } - - final padding = ButtonTheme.of(context).alignedDropdown - ? _kAlignedButtonPadding - : _kUnalignedButtonPadding; - - // If value is null (then _selectedIndex is null) or if disabled then we - // display the hint or nothing at all. - final index = _enabled ? (_selectedIndex ?? hintIndex) : hintIndex; - Widget innerItemsWidget; - if (items.isEmpty) { - innerItemsWidget = Container(); - } else { - innerItemsWidget = IndexedStack( - index: index, - alignment: AlignmentDirectional.centerStart, - children: widget.isDense - ? items - : items.map((item) { - return widget.itemHeight != null - ? SizedBox(height: widget.itemHeight, child: item) - : Column( - mainAxisSize: MainAxisSize.min, - children: [item]); - }).toList(), - ); - } - - const defaultIcon = Icon(Icons.arrow_drop_down); - - Widget result = DefaultTextStyle( - style: _textStyle, - child: Container( - decoration: _showHighlight - ? BoxDecoration( - color: widget.focusColor ?? Theme.of(context).focusColor, - borderRadius: const BorderRadius.all(Radius.circular(4.0)), - ) - : null, - padding: padding.resolve(Directionality.of(context)), - height: widget.isDense ? _denseButtonHeight : null, - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - mainAxisSize: MainAxisSize.min, - children: [ - if (widget.isExpanded) - Expanded(child: innerItemsWidget) - else - innerItemsWidget, - IconTheme( - data: IconThemeData( - color: _iconColor, - size: widget.iconSize, - ), - child: widget.icon ?? defaultIcon, - ), - ], - ), - ), - ); - - if (!DropdownButtonHideUnderline.at(context)) { - final bottom = (widget.isDense || widget.itemHeight == null) ? 0.0 : 8.0; - result = Stack( - children: [ - result, - Positioned( - left: 0.0, - right: 0.0, - bottom: bottom, - child: widget.underline ?? - Container( - height: 1.0, - decoration: const BoxDecoration( - border: Border( - bottom: BorderSide( - color: Color(0xFFBDBDBD), - width: 0.0, - ), - ), - ), - ), - ), - ], - ); - } - - return Semantics( - button: true, - child: Focus( - canRequestFocus: _enabled, - focusNode: focusNode, - autofocus: widget.autofocus, - child: GestureDetector( - onTap: _enabled ? _handleTap : null, - behavior: HitTestBehavior.opaque, - child: result, - ), - ), - ); - } -} - -/// A convenience widget that wraps a [DropdownButton] in a [FormField]. -class DropdownButtonFormField extends FormField { - /// Creates a [DropdownButton] widget wrapped in an [InputDecorator] and - /// [FormField]. - /// - /// The [DropdownButton] [items] parameters must not be null. - DropdownButtonFormField({ - Key key, - T value, - @required List> items, - DropdownButtonBuilder selectedItemBuilder, - Widget hint, - @required this.onChanged, - VoidCallback onTap, - this.decoration = const InputDecoration(), - FormFieldSetter onSaved, - FormFieldValidator validator, - bool autovalidate = false, - Widget disabledHint, - int elevation = 8, - TextStyle style, - Widget icon, - Color iconDisabledColor, - Color iconEnabledColor, - double iconSize = 24.0, - bool isDense = true, - bool isExpanded = false, - double itemHeight, - }) : assert( - items == null || - items.isEmpty || - value == null || - items.where((item) { - return item.value == value; - }).length == - 1, - "There should be exactly one item with [DropdownButton]'s value: " - '$value. \n' - 'Either zero or 2 or more [DropdownMenuItem]s were detected ' - 'with the same value', - ), - assert(decoration != null), - assert(elevation != null), - assert(iconSize != null), - assert(isDense != null), - assert(isExpanded != null), - assert(itemHeight == null || itemHeight > 0), - super( - key: key, - onSaved: onSaved, - initialValue: value, - validator: validator, - autovalidateMode: AutovalidateMode.onUserInteraction, - builder: (field) { - final state = field as _DropdownButtonFormFieldState; - final effectiveDecoration = decoration.applyDefaults( - Theme.of(field.context).inputDecorationTheme, - ); - return InputDecorator( - decoration: - effectiveDecoration.copyWith(errorText: field.errorText), - isEmpty: state.value == null, - child: DropdownButtonHideUnderline( - child: DropdownButton( - value: state.value, - items: items, - selectedItemBuilder: selectedItemBuilder, - hint: hint, - onChanged: onChanged == null ? null : state.didChange, - onTap: onTap, - disabledHint: disabledHint, - elevation: elevation, - style: style, - icon: icon, - iconDisabledColor: iconDisabledColor, - iconEnabledColor: iconEnabledColor, - iconSize: iconSize, - isDense: isDense, - isExpanded: isExpanded, - itemHeight: itemHeight, - ), - ), - ); - }, - ); - - /// {@macro flutter.material.dropdownButton.onChanged} - final ValueChanged onChanged; - - /// The decoration to show around the dropdown button form field. - /// - /// By default, draws a horizontal line under the dropdown button field but can be - /// configured to show an icon, label, hint text, and error text. - /// - /// Specify null to remove the decoration entirely (including the - /// extra padding introduced by the decoration to save space for the labels). - final InputDecoration decoration; - - @override - FormFieldState createState() => _DropdownButtonFormFieldState(); -} - -class _DropdownButtonFormFieldState extends FormFieldState { - @override - DropdownButtonFormField get widget => - super.widget as DropdownButtonFormField; - - @override - void didChange(T value) { - super.didChange(value); - assert(widget.onChanged != null); - widget.onChanged(value); - } - - @override - void didUpdateWidget(DropdownButtonFormField oldWidget) { - super.didUpdateWidget(oldWidget); - if (oldWidget.initialValue != widget.initialValue) { - setValue(widget.initialValue); - } - } -} +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:math' as math; +import 'dart:ui' show window; + +import 'package:flutter/material.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; + +const Duration _kDropdownMenuDuration = Duration(milliseconds: 300); +const double _kMenuItemHeight = kMinInteractiveDimension; +const double _kDenseButtonHeight = 24.0; +const EdgeInsets _kMenuItemPadding = EdgeInsets.symmetric(horizontal: 16.0); +const EdgeInsetsGeometry _kAlignedButtonPadding = + EdgeInsetsDirectional.only(start: 16.0, end: 4.0); +const EdgeInsets _kUnalignedButtonPadding = EdgeInsets.zero; +const EdgeInsets _kAlignedMenuMargin = EdgeInsets.zero; +const EdgeInsetsGeometry _kUnalignedMenuMargin = + EdgeInsetsDirectional.only(start: 16.0, end: 24.0); + +typedef DropdownButtonBuilder = List Function(BuildContext context); + +class _DropdownMenuPainter extends CustomPainter { + _DropdownMenuPainter({ + this.color, + this.elevation, + this.selectedIndex, + this.resize, + this.getSelectedItemOffset, + }) : _painter = BoxDecoration( + // If you add an image here, you must provide a real + // configuration in the paint() function and you must provide some sort + // of onChanged callback here. + color: color, + //Change default 2.0 to 10.0 + borderRadius: BorderRadius.circular(10.0), + boxShadow: kElevationToShadow[elevation], + ).createBoxPainter(), + super(repaint: resize); + + final Color color; + final int elevation; + final int selectedIndex; + final Animation resize; + final ValueGetter getSelectedItemOffset; + final BoxPainter _painter; + + @override + void paint(Canvas canvas, Size size) { + final selectedItemOffset = getSelectedItemOffset(); + final top = Tween( + begin: selectedItemOffset.clamp(0.0, size.height - _kMenuItemHeight) + as double, + end: 0.0, + ); + + final bottom = Tween( + begin: (top.begin + _kMenuItemHeight).clamp(_kMenuItemHeight, size.height) + as double, + end: size.height, + ); + + final rect = Rect.fromLTRB( + 0.0, top.evaluate(resize), size.width, bottom.evaluate(resize)); + + _painter.paint(canvas, rect.topLeft, ImageConfiguration(size: rect.size)); + } + + @override + bool shouldRepaint(_DropdownMenuPainter oldPainter) { + return oldPainter.color != color || + oldPainter.elevation != elevation || + oldPainter.selectedIndex != selectedIndex || + oldPainter.resize != resize; + } +} + +// Do not use the platform-specific default scroll configuration. +// Dropdown menus should never overscroll or display an overscroll indicator. +class _DropdownScrollBehavior extends ScrollBehavior { + const _DropdownScrollBehavior(); + + @override + TargetPlatform getPlatform(BuildContext context) => + Theme.of(context).platform; + + @override + Widget buildViewportChrome( + BuildContext context, Widget child, AxisDirection axisDirection) => + child; + + @override + ScrollPhysics getScrollPhysics(BuildContext context) => + const ClampingScrollPhysics(); +} + +// The widget that is the button wrapping the menu items. +class _DropdownMenuItemButton extends StatefulWidget { + const _DropdownMenuItemButton({ + Key key, + @required this.padding, + @required this.route, + @required this.buttonRect, + @required this.constraints, + @required this.itemIndex, + }) : super(key: key); + + final _DropdownRoute route; + final EdgeInsets padding; + final Rect buttonRect; + final BoxConstraints constraints; + final int itemIndex; + + @override + _DropdownMenuItemButtonState createState() => + _DropdownMenuItemButtonState(); +} + +class _DropdownMenuItemButtonState + extends State<_DropdownMenuItemButton> { + void _handleFocusChange(bool focused) { + bool inTraditionalMode; + switch (FocusManager.instance.highlightMode) { + case FocusHighlightMode.touch: + inTraditionalMode = false; + break; + case FocusHighlightMode.traditional: + inTraditionalMode = true; + break; + } + + if (focused && inTraditionalMode) { + final menuLimits = widget.route.getMenuLimits( + widget.buttonRect, widget.constraints.maxHeight, widget.itemIndex); + widget.route.scrollController.animateTo( + menuLimits.scrollOffset, + curve: Curves.easeInOut, + duration: const Duration(milliseconds: 100), + ); + } + } + + void _handleOnTap() { + final dropdownMenuItem = widget.route.items[widget.itemIndex].item; + + if (dropdownMenuItem.onTap != null) { + dropdownMenuItem.onTap(); + } + + Navigator.pop( + context, + _DropdownRouteResult(dropdownMenuItem.value), + ); + } + + @override + Widget build(BuildContext context) { + CurvedAnimation opacity; + final unit = 0.5 / (widget.route.items.length + 1.5); + if (widget.itemIndex == widget.route.selectedIndex) { + opacity = CurvedAnimation( + parent: widget.route.animation, curve: const Threshold(0.0)); + } else { + final start = + (0.5 + (widget.itemIndex + 1) * unit).clamp(0.0, 1.0) as double; + final end = (start + 1.5 * unit).clamp(0.0, 1.0) as double; + opacity = CurvedAnimation( + parent: widget.route.animation, curve: Interval(start, end)); + } + Widget child = FadeTransition( + opacity: opacity, + child: InkWell( + autofocus: widget.itemIndex == widget.route.selectedIndex, + child: Container( + padding: widget.padding, + child: widget.route.items[widget.itemIndex], + ), + onTap: _handleOnTap, + onFocusChange: _handleFocusChange, + ), + ); + return child; + } +} + +class _DropdownMenu extends StatefulWidget { + const _DropdownMenu({ + Key key, + this.padding, + this.route, + this.buttonRect, + this.constraints, + this.dropdownColor, + this.displayItemCount, + }) : super(key: key); + + final _DropdownRoute route; + final EdgeInsets padding; + final Rect buttonRect; + final BoxConstraints constraints; + final Color dropdownColor; + final int displayItemCount; + + @override + _DropdownMenuState createState() => _DropdownMenuState(); +} + +class _DropdownMenuState extends State<_DropdownMenu> { + CurvedAnimation _fadeOpacity; + CurvedAnimation _resize; + + @override + void initState() { + super.initState(); + // We need to hold these animations as state because of their curve + // direction. When the route's animation reverses, if we were to recreate + // the CurvedAnimation objects in build, we'd lose + // CurvedAnimation._curveDirection. + _fadeOpacity = CurvedAnimation( + parent: widget.route.animation, + curve: const Interval(0.0, 0.25), + reverseCurve: const Interval(0.75, 1.0), + ); + _resize = CurvedAnimation( + parent: widget.route.animation, + curve: const Interval(0.25, 0.5), + reverseCurve: const Threshold(0.0), + ); + } + + @override + Widget build(BuildContext context) { + // The menu is shown in three stages (unit timing in brackets): + // [0s - 0.25s] - Fade in a rect-sized menu container with the selected item. + // [0.25s - 0.5s] - Grow the otherwise empty menu container from the center + // until it's big enough for as many items as we're going to show. + // [0.5s - 1.0s] Fade in the remaining visible items from top to bottom. + // + // When the menu is dismissed we just fade the entire thing out + // in the first 0.25s. + assert(debugCheckHasMaterialLocalizations(context)); + final localizations = MaterialLocalizations.of(context); + final route = widget.route; + final children = [ + for (int itemIndex = 0; itemIndex < route.items.length; ++itemIndex) + _DropdownMenuItemButton( + route: widget.route, + padding: widget.padding, + buttonRect: widget.buttonRect, + constraints: widget.constraints, + itemIndex: itemIndex, + ), + ]; + + return FadeTransition( + opacity: _fadeOpacity, + child: CustomPaint( + painter: _DropdownMenuPainter( + color: widget.dropdownColor ?? Theme.of(context).canvasColor, + elevation: route.elevation, + selectedIndex: route.selectedIndex, + resize: _resize, + // This offset is passed as a callback, not a value, because it must + // be retrieved at paint time (after layout), not at build time. + getSelectedItemOffset: () => route.getItemOffset(route.selectedIndex), + ), + child: Semantics( + scopesRoute: true, + namesRoute: true, + explicitChildNodes: true, + label: localizations.popupMenuLabel, + child: Material( + type: MaterialType.transparency, + textStyle: route.style, + child: ScrollConfiguration( + behavior: const _DropdownScrollBehavior(), + child: Scrollbar( + child: ListView( + controller: widget.route.scrollController, + padding: kMaterialListPadding, + shrinkWrap: true, + children: children, + ), + ), + ), + ), + ), + ), + ); + } +} + +class _DropdownMenuRouteLayout extends SingleChildLayoutDelegate { + _DropdownMenuRouteLayout({ + @required this.buttonRect, + @required this.route, + @required this.textDirection, + this.displayItemCount, + }); + + final Rect buttonRect; + final _DropdownRoute route; + final TextDirection textDirection; + final int displayItemCount; + + @override + BoxConstraints getConstraintsForChild(BoxConstraints constraints) { + // The maximum height of a simple menu should be one or more rows less than + // the view height. This ensures a tappable area outside of the simple menu + // with which to dismiss the menu. + // -- https://material.io/design/components/menus.html#usage + final maxHeight = displayItemCount == null + ? math.max(0.0, constraints.maxHeight - 2 * _kMenuItemHeight) + : math.min(_kMenuItemHeight * displayItemCount, + constraints.maxHeight - 2 * _kMenuItemHeight); + // The width of a menu should be at most the view width. This ensures that + // the menu does not extend past the left and right edges of the screen. + final width = math.min(constraints.maxWidth, buttonRect.width); + return BoxConstraints( + minWidth: width, + maxWidth: width, + minHeight: 0.0, + maxHeight: maxHeight, + ); + } + + @override + Offset getPositionForChild(Size size, Size childSize) { + final menuLimits = + route.getMenuLimits(buttonRect, size.height, route.selectedIndex); + + assert(() { + final container = Offset.zero & size; + if (container.intersect(buttonRect) == buttonRect) { + // If the button was entirely on-screen, then verify + // that the menu is also on-screen. + // If the button was a bit off-screen, then, oh well. + assert(menuLimits.top >= 0.0); + assert(menuLimits.top + menuLimits.height <= size.height); + } + return true; + }()); + assert(textDirection != null); + double left; + switch (textDirection) { + case TextDirection.rtl: + left = (buttonRect.right.clamp(0.0, size.width) as double) - + childSize.width; + break; + case TextDirection.ltr: + left = + buttonRect.left.clamp(0.0, size.width - childSize.width) as double; + break; + } + + return Offset(left, menuLimits.top); + } + + @override + bool shouldRelayout(_DropdownMenuRouteLayout oldDelegate) { + return buttonRect != oldDelegate.buttonRect || + textDirection != oldDelegate.textDirection; + } +} + +// We box the return value so that the return value can be null. Otherwise, +// canceling the route (which returns null) would get confused with actually +// returning a real null value. +class _DropdownRouteResult { + const _DropdownRouteResult(this.result); + + final T result; + + @override + bool operator ==(Object other) { + return other is _DropdownRouteResult && other.result == result; + } + + @override + int get hashCode => result.hashCode; +} + +class _MenuLimits { + const _MenuLimits(this.top, this.bottom, this.height, this.scrollOffset); + final double top; + final double bottom; + final double height; + final double scrollOffset; +} + +class _DropdownRoute extends PopupRoute<_DropdownRouteResult> { + _DropdownRoute({ + this.items, + this.padding, + this.buttonRect, + this.selectedIndex, + this.elevation = 8, + this.theme, + @required this.style, + this.barrierLabel, + this.itemHeight, + this.dropdownColor, + this.displayItemCount, + }) : assert(style != null), + itemHeights = List.filled( + items.length, itemHeight ?? kMinInteractiveDimension); + + final List<_MenuItem> items; + final EdgeInsetsGeometry padding; + final Rect buttonRect; + final int selectedIndex; + final int elevation; + final ThemeData theme; + final TextStyle style; + final double itemHeight; + final Color dropdownColor; + final int displayItemCount; + + final List itemHeights; + ScrollController scrollController; + + @override + Duration get transitionDuration => _kDropdownMenuDuration; + + @override + bool get barrierDismissible => true; + + @override + Color get barrierColor => null; + + @override + final String barrierLabel; + + @override + Widget buildPage(BuildContext context, Animation animation, + Animation secondaryAnimation) { + return LayoutBuilder(builder: (context, constraints) { + return _DropdownRoutePage( + route: this, + constraints: constraints, + items: items, + padding: padding, + buttonRect: buttonRect, + selectedIndex: selectedIndex, + elevation: elevation, + theme: theme, + style: style, + dropdownColor: dropdownColor, + displayItemCount: displayItemCount, + ); + }); + } + + void _dismiss() { + navigator?.removeRoute(this); + } + + double getItemOffset(int index) { + var offset = kMaterialListPadding.top; + if (items.isNotEmpty && index > 0) { + assert(items.length == itemHeights?.length); + if (displayItemCount == null) { + offset += itemHeights + .sublist(0, index) + .reduce((total, height) => total + height); + } else { + offset += itemHeights + .sublist(math.max(0, index + 1 - displayItemCount), index) + .reduce((total, height) => total + height); + } + } + + return offset; + } + + // Returns the vertical extent of the menu and the initial scrollOffset + // for the ListView that contains the menu items. The vertical center of the + // selected item is aligned with the button's vertical center, as far as + // that's possible given availableHeight. + _MenuLimits getMenuLimits( + Rect buttonRect, double availableHeight, int index) { + final maxMenuHeight = displayItemCount == null + ? availableHeight - 2.0 * _kMenuItemHeight + : math.min(_kMenuItemHeight * displayItemCount, + availableHeight - 2 * _kMenuItemHeight); + final buttonTop = buttonRect.top; + final buttonBottom = math.min(buttonRect.bottom, availableHeight); + final selectedItemOffset = getItemOffset(index); + + // If the button is placed on the bottom or top of the screen, its top or + // bottom may be less than [_kMenuItemHeight] from the edge of the screen. + // In this case, we want to change the menu limits to align with the top + // or bottom edge of the button. + final topLimit = math.min(_kMenuItemHeight, buttonTop); + final bottomLimit = + math.max(availableHeight - _kMenuItemHeight, buttonBottom); + + var menuTop = (buttonTop - selectedItemOffset) - + (itemHeights[selectedIndex] - buttonRect.height) / 2.0; + var preferredMenuHeight = kMaterialListPadding.vertical; + if (items.isNotEmpty) { + preferredMenuHeight += + itemHeights.reduce((total, height) => total + height); + } + + // If there are too many elements in the menu, we need to shrink it down + // so it is at most the maxMenuHeight. + final menuHeight = math.min(maxMenuHeight, preferredMenuHeight); + var menuBottom = menuTop + menuHeight; + + // If the computed top or bottom of the menu are outside of the range + // specified, we need to bring them into range. If the item height is larger + // than the button height and the button is at the very bottom or top of the + // screen, the menu will be aligned with the bottom or top of the button + // respectively. + if (menuTop < topLimit) menuTop = math.min(buttonTop, topLimit); + + if (menuBottom > bottomLimit) { + menuBottom = math.max(buttonBottom, bottomLimit); + menuTop = menuBottom - menuHeight; + } + + // If all of the menu items will not fit within availableHeight then + // compute the scroll offset that will line the selected menu item up + // with the select item. This is only done when the menu is first + // shown - subsequently we leave the scroll offset where the user left + // it. This scroll offset is only accurate for fixed height menu items + // (the default). + final scrollOffset = preferredMenuHeight <= maxMenuHeight + ? 0.0 + : displayItemCount == null || displayItemCount > index + ? math.max(0.0, selectedItemOffset - (buttonTop - menuTop)) + : math.max(0.0, (index - displayItemCount + 1) * _kMenuItemHeight); + return _MenuLimits(menuTop, menuBottom, menuHeight, scrollOffset); + } +} + +class _DropdownRoutePage extends StatelessWidget { + const _DropdownRoutePage({ + Key key, + this.route, + this.constraints, + this.items, + this.padding, + this.buttonRect, + this.selectedIndex, + this.elevation = 8, + this.theme, + this.style, + this.dropdownColor, + this.displayItemCount, + }) : super(key: key); + + final _DropdownRoute route; + final BoxConstraints constraints; + final List<_MenuItem> items; + final EdgeInsetsGeometry padding; + final Rect buttonRect; + final int selectedIndex; + final int elevation; + final ThemeData theme; + final TextStyle style; + final Color dropdownColor; + final int displayItemCount; + + @override + Widget build(BuildContext context) { + assert(debugCheckHasDirectionality(context)); + + // Computing the initialScrollOffset now, before the items have been laid + // out. This only works if the item heights are effectively fixed, i.e. either + // DropdownButton.itemHeight is specified or DropdownButton.itemHeight is null + // and all of the items' intrinsic heights are less than kMinInteractiveDimension. + // Otherwise the initialScrollOffset is just a rough approximation based on + // treating the items as if their heights were all equal to kMinInteractveDimension. + if (route.scrollController == null) { + final menuLimits = + route.getMenuLimits(buttonRect, constraints.maxHeight, selectedIndex); + route.scrollController = + ScrollController(initialScrollOffset: menuLimits.scrollOffset); + } + + final textDirection = Directionality.of(context); + Widget menu = _DropdownMenu( + route: route, + padding: padding.resolve(textDirection), + buttonRect: buttonRect, + constraints: constraints, + dropdownColor: dropdownColor, + ); + + if (theme != null) menu = Theme(data: theme, child: menu); + + return MediaQuery.removePadding( + context: context, + removeTop: true, + removeBottom: true, + removeLeft: true, + removeRight: true, + child: Builder( + builder: (context) { + return CustomSingleChildLayout( + delegate: _DropdownMenuRouteLayout( + buttonRect: buttonRect, + route: route, + textDirection: textDirection, + displayItemCount: displayItemCount, + ), + child: menu, + ); + }, + ), + ); + } +} + +// This widget enables _DropdownRoute to look up the sizes of +// each menu item. These sizes are used to compute the offset of the selected +// item so that _DropdownRoutePage can align the vertical center of the +// selected item lines up with the vertical center of the dropdown button, +// as closely as possible. +class _MenuItem extends SingleChildRenderObjectWidget { + const _MenuItem({ + Key key, + @required this.onLayout, + @required this.item, + }) : assert(onLayout != null), + super(key: key, child: item); + + final ValueChanged onLayout; + final DropdownMenuItem item; + + @override + RenderObject createRenderObject(BuildContext context) { + return _RenderMenuItem(onLayout); + } + + @override + void updateRenderObject( + BuildContext context, covariant _RenderMenuItem renderObject) { + renderObject.onLayout = onLayout; + } +} + +class _RenderMenuItem extends RenderProxyBox { + _RenderMenuItem(this.onLayout, [RenderBox child]) + : assert(onLayout != null), + super(child); + + ValueChanged onLayout; + + @override + void performLayout() { + super.performLayout(); + onLayout(size); + } +} + +// The container widget for a menu item created by a [DropdownButton]. It +// provides the default configuration for [DropdownMenuItem]s, as well as a +// [DropdownButton]'s hint and disabledHint widgets. +class _DropdownMenuItemContainer extends StatelessWidget { + /// Creates an item for a dropdown menu. + /// + /// The [child] argument is required. + const _DropdownMenuItemContainer({ + Key key, + @required this.child, + }) : assert(child != null), + super(key: key); + + /// The widget below this widget in the tree. + /// + /// Typically a [Text] widget. + final Widget child; + + @override + Widget build(BuildContext context) { + return Container( + constraints: const BoxConstraints(minHeight: _kMenuItemHeight), + alignment: AlignmentDirectional.centerStart, + child: child, + ); + } +} + +/// An item in a menu created by a [DropdownButton]. +/// +/// The type `T` is the type of the value the entry represents. All the entries +/// in a given menu must represent values with consistent types. +//class DropdownMenuItem extends _DropdownMenuItemContainer { +// /// Creates an item for a dropdown menu. +// /// +// /// The [child] argument is required. +// const DropdownMenuItem({ +// Key key, +// this.onTap, +// this.value, +// @required Widget child, +// }) : assert(child != null), +// super(key: key, child: child); +// +// /// Called when the dropdown menu item is tapped. +// final VoidCallback onTap; +// +// /// The value to return if the user selects this menu item. +// /// +// /// Eventually returned in a call to [DropdownButton.onChanged]. +// final T value; +//} +// +/// An inherited widget that causes any descendant [DropdownButton] +/// widgets to not include their regular underline. +/// +/// This is used by [DataTable] to remove the underline from any +/// [DropdownButton] widgets placed within material data tables, as +/// required by the material design specification. +class DropdownButtonHideUnderline extends InheritedWidget { + /// Creates a [DropdownButtonHideUnderline]. A non-null [child] must + /// be given. + const DropdownButtonHideUnderline({ + Key key, + @required Widget child, + }) : assert(child != null), + super(key: key, child: child); + + /// Returns whether the underline of [DropdownButton] widgets should + /// be hidden. + static bool at(BuildContext context) { + return context.dependOnInheritedWidgetOfExactType< + DropdownButtonHideUnderline>() != + null; + } + + @override + bool updateShouldNotify(DropdownButtonHideUnderline oldWidget) => false; +} + +/// A material design button for selecting from a list of items. +/// +/// A dropdown button lets the user select from a number of items. The button +/// shows the currently selected item as well as an arrow that opens a menu for +/// selecting another item. +/// +/// The type `T` is the type of the [value] that each dropdown item represents. +/// All the entries in a given menu must represent values with consistent types. +/// Typically, an enum is used. Each [DropdownMenuItem] in [items] must be +/// specialized with that same type argument. +/// +/// The [onChanged] callback should update a state variable that defines the +/// dropdown's value. It should also call [State.setState] to rebuild the +/// dropdown with the new value. +/// +/// {@tool dartpad --template=stateful_widget_scaffold_center} +/// +/// This sample shows a `DropdownButton` with a large arrow icon, +/// purple text style, and bold purple underline, whose value is one of "One", +/// "Two", "Free", or "Four". +/// +/// ![](https://flutter.github.io/assets-for-api-docs/assets/material/dropdown_button.png) +/// +/// ```dart +/// String dropdownValue = 'One'; +/// +/// @override +/// Widget build(BuildContext context) { +/// return DropdownButton( +/// value: dropdownValue, +/// icon: Icon(Icons.arrow_downward), +/// iconSize: 24, +/// elevation: 16, +/// style: TextStyle( +/// color: Colors.deepPurple +/// ), +/// underline: Container( +/// height: 2, +/// color: Colors.deepPurpleAccent, +/// ), +/// onChanged: (String newValue) { +/// setState(() { +/// dropdownValue = newValue; +/// }); +/// }, +/// items: ['One', 'Two', 'Free', 'Four'] +/// .map>((String value) { +/// return DropdownMenuItem( +/// value: value, +/// child: Text(value), +/// ); +/// }) +/// .toList(), +/// ); +/// } +/// ``` +/// {@end-tool} +/// +/// If the [onChanged] callback is null or the list of [items] is null +/// then the dropdown button will be disabled, i.e. its arrow will be +/// displayed in grey and it will not respond to input. A disabled button +/// will display the [disabledHint] widget if it is non-null. However, if +/// [disabledHint] is null and [hint] is non-null, the [hint] widget will +/// instead be displayed. +/// +/// Requires one of its ancestors to be a [Material] widget. +/// +/// See also: +/// +/// * [DropdownMenuItem], the class used to represent the [items]. +/// * [DropdownButtonHideUnderline], which prevents its descendant dropdown buttons +/// from displaying their underlines. +/// * [RaisedButton], [FlatButton], ordinary buttons that trigger a single action. +/// * +class MyDropdownButton extends StatefulWidget { + /// Creates a dropdown button. + /// + /// The [items] must have distinct values. If [value] isn't null then it + /// must be equal to one of the [DropDownMenuItem] values. If [items] or + /// [onChanged] is null, the button will be disabled, the down arrow + /// will be greyed out, and the [disabledHint] will be shown (if provided). + /// If [disabledHint] is null and [hint] is non-null, [hint] will instead be + /// shown. + /// + /// The [elevation] and [iconSize] arguments must not be null (they both have + /// defaults, so do not need to be specified). The boolean [isDense] and + /// [isExpanded] arguments must not be null. + /// + /// The [dropdownColor] argument specifies the background color of the + /// dropdown when it is open. If it is null, the current theme's + /// [ThemeData.canvasColor] will be used instead. + MyDropdownButton({ + Key key, + @required this.items, + this.selectedItemBuilder, + this.value, + this.hint, + this.disabledHint, + @required this.onChanged, + this.onTap, + this.elevation = 8, + this.style, + this.underline, + this.icon, + this.iconDisabledColor, + this.iconEnabledColor, + this.iconSize = 24.0, + this.isDense = false, + this.isExpanded = false, + this.itemHeight = kMinInteractiveDimension, + this.focusColor, + this.focusNode, + this.autofocus = false, + this.dropdownColor, + this.displayItemCount, + }) : assert( + items == null || + items.isEmpty || + value == null || + items.where((item) { + return item.value == value; + }).length == + 1, + "There should be exactly one item with [DropdownButton]'s value: " + '$value. \n' + 'Either zero or 2 or more [DropdownMenuItem]s were detected ' + 'with the same value', + ), + assert(elevation != null), + assert(iconSize != null), + assert(isDense != null), + assert(isExpanded != null), + assert(autofocus != null), + assert(itemHeight == null || itemHeight >= kMinInteractiveDimension), + assert(displayItemCount == null || displayItemCount > 0), + super(key: key); + + /// The list of items the user can select. + /// + /// If the [onChanged] callback is null or the list of items is null + /// then the dropdown button will be disabled, i.e. its arrow will be + /// displayed in grey and it will not respond to input. A disabled button + /// will display the [disabledHint] widget if it is non-null. If + /// [disabledHint] is also null but [hint] is non-null, [hint] will instead + /// be displayed. + final List> items; + + /// The value of the currently selected [DropdownMenuItem]. + /// + /// If [value] is null and [hint] is non-null, the [hint] widget is + /// displayed as a placeholder for the dropdown button's value. + final T value; + + /// A placeholder widget that is displayed by the dropdown button. + /// + /// If [value] is null, this widget is displayed as a placeholder for + /// the dropdown button's value. This widget is also displayed if the button + /// is disabled ([items] or [onChanged] is null) and [disabledHint] is null. + final Widget hint; + + /// A message to show when the dropdown is disabled. + /// + /// Displayed if [items] or [onChanged] is null. If [hint] is non-null and + /// [disabledHint] is null, the [hint] widget will be displayed instead. + final Widget disabledHint; + + /// {@template flutter.material.dropdownButton.onChanged} + /// Called when the user selects an item. + /// + /// If the [onChanged] callback is null or the list of [items] is null + /// then the dropdown button will be disabled, i.e. its arrow will be + /// displayed in grey and it will not respond to input. A disabled button + /// will display the [disabledHint] widget if it is non-null. If + /// [disabledHint] is also null but [hint] is non-null, [hint] will instead + /// be displayed. + /// {@endtemplate} + final ValueChanged onChanged; + + /// Called when the dropdown button is tapped. + /// + /// This is distinct from [onChanged], which is called when the user + /// selects an item from the dropdown. + /// + /// The callback will not be invoked if the dropdown button is disabled. + final VoidCallback onTap; + + /// A builder to customize the dropdown buttons corresponding to the + /// [DropdownMenuItem]s in [items]. + /// + /// When a [DropdownMenuItem] is selected, the widget that will be displayed + /// from the list corresponds to the [DropdownMenuItem] of the same index + /// in [items]. + /// + /// {@tool dartpad --template=stateful_widget_scaffold} + /// + /// This sample shows a `DropdownButton` with a button with [Text] that + /// corresponds to but is unique from [DropdownMenuItem]. + /// + /// ```dart + /// final List items = ['1','2','3']; + /// String selectedItem = '1'; + /// + /// @override + /// Widget build(BuildContext context) { + /// return Padding( + /// padding: const EdgeInsets.symmetric(horizontal: 12.0), + /// child: DropdownButton( + /// value: selectedItem, + /// onChanged: (String string) => setState(() => selectedItem = string), + /// selectedItemBuilder: (BuildContext context) { + /// return items.map((String item) { + /// return Text(item); + /// }).toList(); + /// }, + /// items: items.map((String item) { + /// return DropdownMenuItem( + /// child: Text('Log $item'), + /// value: item, + /// ); + /// }).toList(), + /// ), + /// ); + /// } + /// ``` + /// {@end-tool} + /// + /// If this callback is null, the [DropdownMenuItem] from [items] + /// that matches [value] will be displayed. + final DropdownButtonBuilder selectedItemBuilder; + + /// The z-coordinate at which to place the menu when open. + /// + /// The following elevations have defined shadows: 1, 2, 3, 4, 6, 8, 9, 12, + /// 16, and 24. See [kElevationToShadow]. + /// + /// Defaults to 8, the appropriate elevation for dropdown buttons. + final int elevation; + + /// The text style to use for text in the dropdown button and the dropdown + /// menu that appears when you tap the button. + /// + /// To use a separate text style for selected item when it's displayed within + /// the dropdown button,, consider using [selectedItemBuilder]. + /// + /// {@tool dartpad --template=stateful_widget_scaffold} + /// + /// This sample shows a `DropdownButton` with a dropdown button text style + /// that is different than its menu items. + /// + /// ```dart + /// List options = ['One', 'Two', 'Free', 'Four']; + /// String dropdownValue = 'One'; + /// + /// @override + /// Widget build(BuildContext context) { + /// return Container( + /// alignment: Alignment.center, + /// color: Colors.blue, + /// child: DropdownButton( + /// value: dropdownValue, + /// onChanged: (String newValue) { + /// setState(() { + /// dropdownValue = newValue; + /// }); + /// }, + /// style: TextStyle(color: Colors.blue), + /// selectedItemBuilder: (BuildContext context) { + /// return options.map((String value) { + /// return Text( + /// dropdownValue, + /// style: TextStyle(color: Colors.white), + /// ); + /// }).toList(); + /// }, + /// items: options.map>((String value) { + /// return DropdownMenuItem( + /// value: value, + /// child: Text(value), + /// ); + /// }).toList(), + /// ), + /// ); + /// } + /// ``` + /// {@end-tool} + /// + /// Defaults to the [TextTheme.subtitle1] value of the current + /// [ThemeData.textTheme] of the current [Theme]. + final TextStyle style; + + /// The widget to use for drawing the drop-down button's underline. + /// + /// Defaults to a 0.0 width bottom border with color 0xFFBDBDBD. + final Widget underline; + + /// The widget to use for the drop-down button's icon. + /// + /// Defaults to an [Icon] with the [Icons.arrow_drop_down] glyph. + final Widget icon; + + /// The color of any [Icon] descendant of [icon] if this button is disabled, + /// i.e. if [onChanged] is null. + /// + /// Defaults to [Colors.grey.shade400] when the theme's + /// [ThemeData.brightness] is [Brightness.light] and to + /// [Colors.white10] when it is [Brightness.dark] + final Color iconDisabledColor; + + /// The color of any [Icon] descendant of [icon] if this button is enabled, + /// i.e. if [onChanged] is defined. + /// + /// Defaults to [Colors.grey.shade700] when the theme's + /// [ThemeData.brightness] is [Brightness.light] and to + /// [Colors.white70] when it is [Brightness.dark] + final Color iconEnabledColor; + + /// The size to use for the drop-down button's down arrow icon button. + /// + /// Defaults to 24.0. + final double iconSize; + + /// Reduce the button's height. + /// + /// By default this button's height is the same as its menu items' heights. + /// If isDense is true, the button's height is reduced by about half. This + /// can be useful when the button is embedded in a container that adds + /// its own decorations, like [InputDecorator]. + final bool isDense; + + /// Set the dropdown's inner contents to horizontally fill its parent. + /// + /// By default this button's inner width is the minimum size of its contents. + /// If [isExpanded] is true, the inner width is expanded to fill its + /// surrounding container. + final bool isExpanded; + + /// If null, then the menu item heights will vary according to each menu item's + /// intrinsic height. + /// + /// The default value is [kMinInteractiveDimension], which is also the minimum + /// height for menu items. + /// + /// If this value is null and there isn't enough vertical room for the menu, + /// then the menu's initial scroll offset may not align the selected item with + /// the dropdown button. That's because, in this case, the initial scroll + /// offset is computed as if all of the menu item heights were + /// [kMinInteractiveDimension]. + final double itemHeight; + + /// The color for the button's [Material] when it has the input focus. + final Color focusColor; + + /// {@macro flutter.widgets.Focus.focusNode} + final FocusNode focusNode; + + /// {@macro flutter.widgets.Focus.autofocus} + final bool autofocus; + + /// The background color of the dropdown. + /// + /// If it is not provided, the theme's [ThemeData.canvasColor] will be used + /// instead. + final Color dropdownColor; + + final int displayItemCount; + + @override + _MyDropdownButtonState createState() => _MyDropdownButtonState(); +} + +class _MyDropdownButtonState extends State> + // ignore: prefer_mixin + with + // ignore: prefer_mixin + WidgetsBindingObserver { + int _selectedIndex; + _DropdownRoute _dropdownRoute; + Orientation _lastOrientation; + FocusNode _internalNode; + FocusNode get focusNode => widget.focusNode ?? _internalNode; + bool _hasPrimaryFocus = false; + //Map _actionMap; + FocusHighlightMode _focusHighlightMode; + + // Only used if needed to create _internalNode. + FocusNode _createFocusNode() { + return FocusNode(debugLabel: '${widget.runtimeType}'); + } + + @override + void initState() { + super.initState(); + _updateSelectedIndex(); + if (widget.focusNode == null) { + _internalNode ??= _createFocusNode(); + } + // _actionMap = { + // ActivateAction.key: _createAction, + // }; + focusNode.addListener(_handleFocusChanged); + final focusManager = WidgetsBinding.instance.focusManager; + _focusHighlightMode = focusManager.highlightMode; + focusManager.addHighlightModeListener(_handleFocusHighlightModeChange); + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + _removeDropdownRoute(); + WidgetsBinding.instance.focusManager + .removeHighlightModeListener(_handleFocusHighlightModeChange); + focusNode.removeListener(_handleFocusChanged); + _internalNode?.dispose(); + super.dispose(); + } + + void _removeDropdownRoute() { + _dropdownRoute?._dismiss(); + _dropdownRoute = null; + _lastOrientation = null; + } + + void _handleFocusChanged() { + if (_hasPrimaryFocus != focusNode.hasPrimaryFocus) { + setState(() { + _hasPrimaryFocus = focusNode.hasPrimaryFocus; + }); + } + } + + void _handleFocusHighlightModeChange(FocusHighlightMode mode) { + if (!mounted) { + return; + } + setState(() { + _focusHighlightMode = mode; + }); + } + + @override + void didUpdateWidget(MyDropdownButton oldWidget) { + super.didUpdateWidget(oldWidget); + if (widget.focusNode != oldWidget.focusNode) { + oldWidget.focusNode?.removeListener(_handleFocusChanged); + if (widget.focusNode == null) { + _internalNode ??= _createFocusNode(); + } + _hasPrimaryFocus = focusNode.hasPrimaryFocus; + focusNode.addListener(_handleFocusChanged); + } + _updateSelectedIndex(); + } + + void _updateSelectedIndex() { + if (!_enabled) { + return; + } + + assert(widget.value == null || + widget.items.where((item) => item.value == widget.value).length == 1); + _selectedIndex = null; + for (var itemIndex = 0; itemIndex < widget.items.length; itemIndex++) { + if (widget.items[itemIndex].value == widget.value) { + _selectedIndex = itemIndex; + return; + } + } + } + + TextStyle get _textStyle => + widget.style ?? Theme.of(context).textTheme.subtitle1; + + void _handleTap() { + final itemBox = context.findRenderObject() as RenderBox; + final itemRect = itemBox.localToGlobal(Offset.zero) & itemBox.size; + final textDirection = Directionality.of(context); + final menuMargin = ButtonTheme.of(context).alignedDropdown + ? _kAlignedMenuMargin + : _kUnalignedMenuMargin; + + final menuItems = List<_MenuItem>(widget.items.length); + for (var index = 0; index < widget.items.length; index += 1) { + menuItems[index] = _MenuItem( + item: widget.items[index], + onLayout: (size) { + // If [_dropdownRoute] is null and onLayout is called, this means + // that performLayout was called on a _DropdownRoute that has not + // left the widget tree but is already on its way out. + // + // Since onLayout is used primarily to collect the desired heights + // of each menu item before laying them out, not having the _DropdownRoute + // collect each item's height to lay out is fine since the route is + // already on its way out. + if (_dropdownRoute == null) return; + + _dropdownRoute.itemHeights[index] = size.height; + }, + ); + } + + assert(_dropdownRoute == null); + _dropdownRoute = _DropdownRoute( + items: menuItems, + buttonRect: menuMargin.resolve(textDirection).inflateRect(itemRect), + padding: _kMenuItemPadding.resolve(textDirection), + selectedIndex: _selectedIndex ?? 0, + elevation: widget.elevation, + theme: Theme.of(context, shadowThemeOnly: true), + style: _textStyle, + barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel, + itemHeight: widget.itemHeight, + dropdownColor: widget.dropdownColor, + displayItemCount: widget.displayItemCount, + ); + + Navigator.push(context, _dropdownRoute).then((newValue) { + _removeDropdownRoute(); + if (!mounted || newValue == null) return; + if (widget.onChanged != null) widget.onChanged(newValue.result); + }); + + if (widget.onTap != null) { + widget.onTap(); + } + } + +// Action _createAction() { +// return CallbackAction( +// ActivateAction.key, +// onInvoke: (FocusNode node, Intent intent) { +// _handleTap(); +// }, +// ); +// } + + // When isDense is true, reduce the height of this button from _kMenuItemHeight to + // _kDenseButtonHeight, but don't make it smaller than the text that it contains. + // Similarly, we don't reduce the height of the button so much that its icon + // would be clipped. + double get _denseButtonHeight { + final fontSize = + _textStyle.fontSize ?? Theme.of(context).textTheme.subtitle1.fontSize; + return math.max(fontSize, math.max(widget.iconSize, _kDenseButtonHeight)); + } + + Color get _iconColor { + // These colors are not defined in the Material Design spec. + if (_enabled) { + if (widget.iconEnabledColor != null) return widget.iconEnabledColor; + + switch (Theme.of(context).brightness) { + case Brightness.light: + return Colors.grey.shade700; + case Brightness.dark: + return Colors.white70; + } + } else { + if (widget.iconDisabledColor != null) return widget.iconDisabledColor; + + switch (Theme.of(context).brightness) { + case Brightness.light: + return Colors.grey.shade400; + case Brightness.dark: + return Colors.white10; + } + } + + assert(false); + return null; + } + + bool get _enabled => + widget.items != null && + widget.items.isNotEmpty && + widget.onChanged != null; + + Orientation _getOrientation(BuildContext context) { + var result = MediaQuery.of(context, nullOk: true)?.orientation; + if (result == null) { + // If there's no MediaQuery, then use the window aspect to determine + // orientation. + final size = window.physicalSize; + result = size.width > size.height + ? Orientation.landscape + : Orientation.portrait; + } + return result; + } + + bool get _showHighlight { + switch (_focusHighlightMode) { + case FocusHighlightMode.touch: + return false; + case FocusHighlightMode.traditional: + return _hasPrimaryFocus; + } + return null; + } + + @override + Widget build(BuildContext context) { + assert(debugCheckHasMaterial(context)); + assert(debugCheckHasMaterialLocalizations(context)); + final newOrientation = _getOrientation(context); + _lastOrientation ??= newOrientation; + if (newOrientation != _lastOrientation) { + _removeDropdownRoute(); + _lastOrientation = newOrientation; + } + + // The width of the button and the menu are defined by the widest + // item and the width of the hint. + List items; + if (_enabled) { + items = widget.selectedItemBuilder == null + ? List.from(widget.items) + : widget.selectedItemBuilder(context); + } else { + items = widget.selectedItemBuilder == null + ? [] + : widget.selectedItemBuilder(context); + } + + int hintIndex; + if (widget.hint != null || (!_enabled && widget.disabledHint != null)) { + var displayedHint = + _enabled ? widget.hint : widget.disabledHint ?? widget.hint; + if (widget.selectedItemBuilder == null) { + displayedHint = _DropdownMenuItemContainer(child: displayedHint); + } + + hintIndex = items.length; + items.add(DefaultTextStyle( + style: _textStyle.copyWith(color: Theme.of(context).hintColor), + child: IgnorePointer( + ignoringSemantics: false, + child: displayedHint, + ), + )); + } + + final padding = ButtonTheme.of(context).alignedDropdown + ? _kAlignedButtonPadding + : _kUnalignedButtonPadding; + + // If value is null (then _selectedIndex is null) or if disabled then we + // display the hint or nothing at all. + final index = _enabled ? (_selectedIndex ?? hintIndex) : hintIndex; + Widget innerItemsWidget; + if (items.isEmpty) { + innerItemsWidget = Container(); + } else { + innerItemsWidget = IndexedStack( + index: index, + alignment: AlignmentDirectional.centerStart, + children: widget.isDense + ? items + : items.map((item) { + return widget.itemHeight != null + ? SizedBox(height: widget.itemHeight, child: item) + : Column( + mainAxisSize: MainAxisSize.min, + children: [item]); + }).toList(), + ); + } + + const defaultIcon = Icon(Icons.arrow_drop_down); + + Widget result = DefaultTextStyle( + style: _textStyle, + child: Container( + decoration: _showHighlight + ? BoxDecoration( + color: widget.focusColor ?? Theme.of(context).focusColor, + borderRadius: const BorderRadius.all(Radius.circular(4.0)), + ) + : null, + padding: padding.resolve(Directionality.of(context)), + height: widget.isDense ? _denseButtonHeight : null, + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + mainAxisSize: MainAxisSize.min, + children: [ + if (widget.isExpanded) + Expanded(child: innerItemsWidget) + else + innerItemsWidget, + IconTheme( + data: IconThemeData( + color: _iconColor, + size: widget.iconSize, + ), + child: widget.icon ?? defaultIcon, + ), + ], + ), + ), + ); + + if (!DropdownButtonHideUnderline.at(context)) { + final bottom = (widget.isDense || widget.itemHeight == null) ? 0.0 : 8.0; + result = Stack( + children: [ + result, + Positioned( + left: 0.0, + right: 0.0, + bottom: bottom, + child: widget.underline ?? + Container( + height: 1.0, + decoration: const BoxDecoration( + border: Border( + bottom: BorderSide( + color: Color(0xFFBDBDBD), + width: 0.0, + ), + ), + ), + ), + ), + ], + ); + } + + return Semantics( + button: true, + child: Focus( + canRequestFocus: _enabled, + focusNode: focusNode, + autofocus: widget.autofocus, + child: GestureDetector( + onTap: _enabled ? _handleTap : null, + behavior: HitTestBehavior.opaque, + child: result, + ), + ), + ); + } +} + +/// A convenience widget that wraps a [DropdownButton] in a [FormField]. +class DropdownButtonFormField extends FormField { + /// Creates a [DropdownButton] widget wrapped in an [InputDecorator] and + /// [FormField]. + /// + /// The [DropdownButton] [items] parameters must not be null. + DropdownButtonFormField({ + Key key, + T value, + @required List> items, + DropdownButtonBuilder selectedItemBuilder, + Widget hint, + @required this.onChanged, + VoidCallback onTap, + this.decoration = const InputDecoration(), + FormFieldSetter onSaved, + FormFieldValidator validator, + bool autovalidate = false, + Widget disabledHint, + int elevation = 8, + TextStyle style, + Widget icon, + Color iconDisabledColor, + Color iconEnabledColor, + double iconSize = 24.0, + bool isDense = true, + bool isExpanded = false, + double itemHeight, + }) : assert( + items == null || + items.isEmpty || + value == null || + items.where((item) { + return item.value == value; + }).length == + 1, + "There should be exactly one item with [DropdownButton]'s value: " + '$value. \n' + 'Either zero or 2 or more [DropdownMenuItem]s were detected ' + 'with the same value', + ), + assert(decoration != null), + assert(elevation != null), + assert(iconSize != null), + assert(isDense != null), + assert(isExpanded != null), + assert(itemHeight == null || itemHeight > 0), + super( + key: key, + onSaved: onSaved, + initialValue: value, + validator: validator, + autovalidateMode: AutovalidateMode.onUserInteraction, + builder: (field) { + final state = field as _DropdownButtonFormFieldState; + final effectiveDecoration = decoration.applyDefaults( + Theme.of(field.context).inputDecorationTheme, + ); + return InputDecorator( + decoration: + effectiveDecoration.copyWith(errorText: field.errorText), + isEmpty: state.value == null, + child: DropdownButtonHideUnderline( + child: DropdownButton( + value: state.value, + items: items, + selectedItemBuilder: selectedItemBuilder, + hint: hint, + onChanged: onChanged == null ? null : state.didChange, + onTap: onTap, + disabledHint: disabledHint, + elevation: elevation, + style: style, + icon: icon, + iconDisabledColor: iconDisabledColor, + iconEnabledColor: iconEnabledColor, + iconSize: iconSize, + isDense: isDense, + isExpanded: isExpanded, + itemHeight: itemHeight, + ), + ), + ); + }, + ); + + /// {@macro flutter.material.dropdownButton.onChanged} + final ValueChanged onChanged; + + /// The decoration to show around the dropdown button form field. + /// + /// By default, draws a horizontal line under the dropdown button field but can be + /// configured to show an icon, label, hint text, and error text. + /// + /// Specify null to remove the decoration entirely (including the + /// extra padding introduced by the decoration to save space for the labels). + final InputDecoration decoration; + + @override + FormFieldState createState() => _DropdownButtonFormFieldState(); +} + +class _DropdownButtonFormFieldState extends FormFieldState { + @override + DropdownButtonFormField get widget => + super.widget as DropdownButtonFormField; + + @override + void didChange(T value) { + super.didChange(value); + assert(widget.onChanged != null); + widget.onChanged(value); + } + + @override + void didUpdateWidget(DropdownButtonFormField oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.initialValue != widget.initialValue) { + setValue(widget.initialValue); + } + } +} diff --git a/lib/util/custom_popupmenu.dart b/lib/util/custom_popupmenu.dart index 98b7254..eb4568f 100644 --- a/lib/util/custom_popupmenu.dart +++ b/lib/util/custom_popupmenu.dart @@ -1,570 +1,570 @@ -import 'package:flutter/foundation.dart'; -import 'package:flutter/rendering.dart'; -import 'package:flutter/widgets.dart'; -import 'package:flutter/material.dart'; - -const Duration _kMenuDuration = Duration(milliseconds: 300); -const double _kMenuCloseIntervalEnd = 2.0 / 3.0; -const double _kMenuMaxWidth = 5.0 * _kMenuWidthStep; -const double _kMenuMinWidth = 2.0 * _kMenuWidthStep; -const double _kMenuVerticalPadding = 8.0; -const double _kMenuWidthStep = 56.0; -const double _kMenuScreenPadding = 8.0; - -class _MenuItem extends SingleChildRenderObjectWidget { - const _MenuItem({ - Key key, - @required this.onLayout, - Widget child, - }) : assert(onLayout != null), - super(key: key, child: child); - - final ValueChanged onLayout; - - @override - RenderObject createRenderObject(BuildContext context) { - return _RenderMenuItem(onLayout); - } - - @override - void updateRenderObject( - BuildContext context, covariant _RenderMenuItem renderObject) { - renderObject.onLayout = onLayout; - } -} - -class _RenderMenuItem extends RenderShiftedBox { - _RenderMenuItem(this.onLayout, [RenderBox child]) - : assert(onLayout != null), - super(child); - - ValueChanged onLayout; - - @override - void performLayout() { - if (child == null) { - size = Size.zero; - } else { - child.layout(constraints, parentUsesSize: true); - size = constraints.constrain(child.size); - } - final childParentData = child.parentData as BoxParentData; - childParentData.offset = Offset.zero; - onLayout(size); - } -} - -class _PopupMenu extends StatelessWidget { - const _PopupMenu({ - Key key, - this.route, - this.semanticLabel, - }) : super(key: key); - - final _PopupMenuRoute route; - final String semanticLabel; - - @override - Widget build(BuildContext context) { - final unit = 1.0 / - (route.items.length + - 1.5); // 1.0 for the width and 0.5 for the last item's fade. - final children = []; - final popupMenuTheme = PopupMenuTheme.of(context); - - for (var i = 0; i < route.items.length; i += 1) { - final start = (i + 1) * unit; - final end = (start + 1.5 * unit).clamp(0.0, 1.0) as double; - final opacity = CurvedAnimation( - parent: route.animation, - curve: Interval(start, end), - ); - Widget item = route.items[i]; - if (route.initialValue != null && - route.items[i].represents(route.initialValue)) { - item = Container( - color: Theme.of(context).highlightColor, - child: item, - ); - } - children.add( - _MenuItem( - onLayout: (size) { - route.itemSizes[i] = size; - }, - child: FadeTransition( - opacity: opacity, - child: item, - ), - ), - ); - } - - final opacity = CurveTween(curve: const Interval(0.0, 1.0 / 3.0)); - final width = CurveTween(curve: Interval(0.0, unit)); - final height = CurveTween(curve: Interval(0.0, unit * route.items.length)); - - final Widget child = ConstrainedBox( - constraints: const BoxConstraints( - minWidth: _kMenuMinWidth, - maxWidth: _kMenuMaxWidth, - ), - child: IntrinsicWidth( - stepWidth: _kMenuWidthStep, - child: Semantics( - scopesRoute: true, - namesRoute: true, - explicitChildNodes: true, - label: semanticLabel, - child: SingleChildScrollView( - padding: const EdgeInsets.only(bottom: _kMenuVerticalPadding), - child: ListBody(children: children), - ), - ), - ), - ); - - return AnimatedBuilder( - animation: route.animation, - builder: (context, child) { - return Opacity( - opacity: opacity.evaluate(route.animation), - child: Material( - shape: route.shape ?? popupMenuTheme.shape, - color: route.color ?? popupMenuTheme.color, - type: MaterialType.card, - elevation: route.elevation ?? popupMenuTheme.elevation ?? 8.0, - child: Align( - alignment: AlignmentDirectional.topEnd, - widthFactor: width.evaluate(route.animation), - heightFactor: height.evaluate(route.animation), - child: child, - ), - ), - ); - }, - child: child, - ); - } -} - -class _PopupMenuRouteLayout extends SingleChildLayoutDelegate { - _PopupMenuRouteLayout(this.position, this.itemSizes, this.selectedItemIndex, - this.textDirection); - - final RelativeRect position; - - List itemSizes; - - final int selectedItemIndex; - - final TextDirection textDirection; - - @override - BoxConstraints getConstraintsForChild(BoxConstraints constraints) { - return BoxConstraints.loose( - constraints.biggest - - const Offset(_kMenuScreenPadding * 2.0, _kMenuScreenPadding * 2.0) - as Size, - ); - } - - @override - Offset getPositionForChild(Size size, Size childSize) { - var y = position.top; - if (selectedItemIndex != null && itemSizes != null) { - var selectedItemOffset = _kMenuVerticalPadding; - for (var index = 0; index < selectedItemIndex; index += 1) { - selectedItemOffset += itemSizes[index].height; - } - selectedItemOffset += itemSizes[selectedItemIndex].height / 2; - y = position.top + - (size.height - position.top - position.bottom) / 2.0 - - selectedItemOffset; - } - - double x; - if (position.left > position.right) { - x = size.width - position.right - childSize.width; - } else if (position.left < position.right) { - // Menu button is closer to the left edge, so grow to the right, aligned to the left edge. - x = position.left; - } else { - // Menu button is equidistant from both edges, so grow in reading direction. - assert(textDirection != null); - switch (textDirection) { - case TextDirection.rtl: - x = size.width - position.right - childSize.width; - break; - case TextDirection.ltr: - x = position.left; - break; - } - } - - if (x < _kMenuScreenPadding) { - x = _kMenuScreenPadding; - } else if (x + childSize.width > size.width - _kMenuScreenPadding) { - x = size.width - childSize.width - _kMenuScreenPadding; - } - if (y < _kMenuScreenPadding) { - y = _kMenuScreenPadding; - } else if (y + childSize.height > size.height - _kMenuScreenPadding) { - y = size.height - childSize.height - _kMenuScreenPadding; - } - return Offset(x, y); - } - - @override - bool shouldRelayout(_PopupMenuRouteLayout oldDelegate) { - assert(itemSizes.length == oldDelegate.itemSizes.length); - - return position != oldDelegate.position || - selectedItemIndex != oldDelegate.selectedItemIndex || - textDirection != oldDelegate.textDirection || - !listEquals(itemSizes, oldDelegate.itemSizes); - } -} - -class _PopupMenuRoute extends PopupRoute { - _PopupMenuRoute({ - this.position, - this.items, - this.initialValue, - this.elevation, - this.theme, - this.popupMenuTheme, - this.barrierLabel, - this.semanticLabel, - this.shape, - this.color, - this.showMenuContext, - this.captureInheritedThemes, - }) : itemSizes = List(items.length); - - final RelativeRect position; - final List> items; - final List itemSizes; - final T initialValue; - final double elevation; - final ThemeData theme; - final String semanticLabel; - final ShapeBorder shape; - final Color color; - final PopupMenuThemeData popupMenuTheme; - final BuildContext showMenuContext; - final bool captureInheritedThemes; - - @override - Animation createAnimation() { - return CurvedAnimation( - parent: super.createAnimation(), - curve: Curves.linear, - reverseCurve: const Interval(0.0, _kMenuCloseIntervalEnd), - ); - } - - @override - Duration get transitionDuration => _kMenuDuration; - - @override - bool get barrierDismissible => true; - - @override - Color get barrierColor => null; - - @override - final String barrierLabel; - - @override - Widget buildPage(BuildContext context, Animation animation, - Animation secondaryAnimation) { - int selectedItemIndex; - if (initialValue != null) { - for (var index = 0; - selectedItemIndex == null && index < items.length; - index += 1) { - if (items[index].represents(initialValue)) selectedItemIndex = index; - } - } - - Widget menu = _PopupMenu(route: this, semanticLabel: semanticLabel); - if (captureInheritedThemes) { - menu = InheritedTheme.captureAll(showMenuContext, menu); - } else { - if (theme != null) menu = Theme(data: theme, child: menu); - } - - return MediaQuery.removePadding( - context: context, - removeTop: true, - removeBottom: true, - removeLeft: true, - removeRight: true, - child: Builder( - builder: (context) { - return CustomSingleChildLayout( - delegate: _PopupMenuRouteLayout( - position, - itemSizes, - selectedItemIndex, - Directionality.of(context), - ), - child: menu, - ); - }, - ), - ); - } -} - -Future _showMenu({ - @required BuildContext context, - @required RelativeRect position, - @required List> items, - T initialValue, - double elevation, - String semanticLabel, - ShapeBorder shape, - Color color, - bool captureInheritedThemes = true, - bool useRootNavigator = false, -}) { - assert(context != null); - assert(position != null); - assert(useRootNavigator != null); - assert(items != null && items.isNotEmpty); - assert(captureInheritedThemes != null); - assert(debugCheckHasMaterialLocalizations(context)); - - var label = semanticLabel; - switch (Theme.of(context).platform) { - case TargetPlatform.iOS: - case TargetPlatform.macOS: - label = semanticLabel; - break; - case TargetPlatform.android: - case TargetPlatform.fuchsia: - case TargetPlatform.linux: - case TargetPlatform.windows: - label = - semanticLabel ?? MaterialLocalizations.of(context)?.popupMenuLabel; - } - - return Navigator.of(context, rootNavigator: useRootNavigator) - .push(_PopupMenuRoute( - position: position, - items: items, - initialValue: initialValue, - elevation: elevation, - semanticLabel: label, - theme: Theme.of(context, shadowThemeOnly: true), - popupMenuTheme: PopupMenuTheme.of(context), - barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel, - shape: shape, - color: color, - showMenuContext: context, - captureInheritedThemes: captureInheritedThemes, - )); -} - -class MyPopupMenuButton extends StatefulWidget { - /// Creates a button that shows a popup menu. - /// - /// The [itemBuilder] argument must not be null. - const MyPopupMenuButton({ - Key key, - @required this.itemBuilder, - this.initialValue, - this.onSelected, - this.onCanceled, - this.tooltip, - this.elevation, - this.padding = const EdgeInsets.all(8.0), - this.child, - this.icon, - this.offset = Offset.zero, - this.enabled = true, - this.shape, - this.color, - this.captureInheritedThemes = true, - }) : assert(itemBuilder != null), - assert(offset != null), - assert(enabled != null), - assert(captureInheritedThemes != null), - assert(!(child != null && icon != null), - 'You can only pass [child] or [icon], not both.'), - super(key: key); - - final PopupMenuItemBuilder itemBuilder; - - final T initialValue; - final PopupMenuItemSelected onSelected; - - final PopupMenuCanceled onCanceled; - - final String tooltip; - - final double elevation; - - final EdgeInsetsGeometry padding; - - final Widget child; - - final Widget icon; - - final Offset offset; - final bool enabled; - final ShapeBorder shape; - - final Color color; - - final bool captureInheritedThemes; - - @override - MyPopupMenuButtonState createState() => MyPopupMenuButtonState(); -} - -class MyPopupMenuButtonState extends State> { - void showButtonMenu() { - final popupMenuTheme = PopupMenuTheme.of(context); - final button = context.findRenderObject() as RenderBox; - final overlay = Overlay.of(context).context.findRenderObject() as RenderBox; - final position = RelativeRect.fromRect( - Rect.fromPoints( - button.localToGlobal(widget.offset, ancestor: overlay), - button.localToGlobal(button.size.bottomRight(Offset.zero), - ancestor: overlay), - ), - Offset.zero & overlay.size, - ); - final items = widget.itemBuilder(context); - // Only show the menu if there is something to show - if (items.isNotEmpty) { - _showMenu( - context: context, - elevation: widget.elevation ?? popupMenuTheme.elevation, - items: items, - initialValue: widget.initialValue, - position: position, - shape: widget.shape ?? popupMenuTheme.shape, - color: widget.color ?? popupMenuTheme.color, - captureInheritedThemes: widget.captureInheritedThemes, - ).then((newValue) { - if (!mounted) return null; - if (newValue == null) { - if (widget.onCanceled != null) widget.onCanceled(); - return null; - } - if (widget.onSelected != null) widget.onSelected(newValue); - }); - } - } - - Icon _getIcon(TargetPlatform platform) { - assert(platform != null); - switch (platform) { - case TargetPlatform.android: - case TargetPlatform.fuchsia: - return const Icon(Icons.more_vert); - case TargetPlatform.iOS: - case TargetPlatform.macOS: - case TargetPlatform.linux: - case TargetPlatform.windows: - return const Icon(Icons.more_horiz); - } - return null; - } - - @override - Widget build(BuildContext context) { - assert(debugCheckHasMaterialLocalizations(context)); - - if (widget.child != null) { - return Tooltip( - message: - widget.tooltip ?? MaterialLocalizations.of(context).showMenuTooltip, - child: InkWell( - onTap: widget.enabled ? showButtonMenu : null, - canRequestFocus: widget.enabled, - child: widget.child, - ), - ); - } - - return IconButton( - icon: widget.icon ?? _getIcon(Theme.of(context).platform), - padding: widget.padding, - tooltip: - widget.tooltip ?? MaterialLocalizations.of(context).showMenuTooltip, - onPressed: widget.enabled ? showButtonMenu : null, - ); - } -} - -class MyPopupMenuItem extends PopupMenuEntry { - const MyPopupMenuItem({ - Key key, - this.value, - this.enabled = true, - this.height = kMinInteractiveDimension, - this.textStyle, - @required this.child, - }) : assert(enabled != null), - assert(height != null), - super(key: key); - - final int value; - - final bool enabled; - - @override - final double height; - final TextStyle textStyle; - - final Widget child; - - @override - bool represents(int value) => value == this.value; - - @override - MyPopupMenuItemState> createState() => - MyPopupMenuItemState>(); -} - -class MyPopupMenuItemState> - extends State { - @protected - Widget buildChild() => widget.child; - - @protected - void handleTap() { - Navigator.pop(context, widget.value); - } - - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - final popupMenuTheme = PopupMenuTheme.of(context); - var style = widget.textStyle ?? - popupMenuTheme.textStyle ?? - theme.textTheme.subtitle1; - - Widget item = AnimatedDefaultTextStyle( - style: style, - duration: kThemeChangeDuration, - child: Container( - // alignment: AlignmentDirectional.centerStart, - // constraints: BoxConstraints(minHeight: widget.height), - padding: const EdgeInsets.all(0), - child: buildChild(), - ), - ); - return item; - // return InkWell( - // onTap: widget.enabled ? handleTap : null, - // canRequestFocus: widget.enabled, - // child: item, - // ); - } -} +import 'package:flutter/foundation.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter/material.dart'; + +const Duration _kMenuDuration = Duration(milliseconds: 300); +const double _kMenuCloseIntervalEnd = 2.0 / 3.0; +const double _kMenuMaxWidth = 5.0 * _kMenuWidthStep; +const double _kMenuMinWidth = 2.0 * _kMenuWidthStep; +const double _kMenuVerticalPadding = 8.0; +const double _kMenuWidthStep = 56.0; +const double _kMenuScreenPadding = 8.0; + +class _MenuItem extends SingleChildRenderObjectWidget { + const _MenuItem({ + Key key, + @required this.onLayout, + Widget child, + }) : assert(onLayout != null), + super(key: key, child: child); + + final ValueChanged onLayout; + + @override + RenderObject createRenderObject(BuildContext context) { + return _RenderMenuItem(onLayout); + } + + @override + void updateRenderObject( + BuildContext context, covariant _RenderMenuItem renderObject) { + renderObject.onLayout = onLayout; + } +} + +class _RenderMenuItem extends RenderShiftedBox { + _RenderMenuItem(this.onLayout, [RenderBox child]) + : assert(onLayout != null), + super(child); + + ValueChanged onLayout; + + @override + void performLayout() { + if (child == null) { + size = Size.zero; + } else { + child.layout(constraints, parentUsesSize: true); + size = constraints.constrain(child.size); + } + final childParentData = child.parentData as BoxParentData; + childParentData.offset = Offset.zero; + onLayout(size); + } +} + +class _PopupMenu extends StatelessWidget { + const _PopupMenu({ + Key key, + this.route, + this.semanticLabel, + }) : super(key: key); + + final _PopupMenuRoute route; + final String semanticLabel; + + @override + Widget build(BuildContext context) { + final unit = 1.0 / + (route.items.length + + 1.5); // 1.0 for the width and 0.5 for the last item's fade. + final children = []; + final popupMenuTheme = PopupMenuTheme.of(context); + + for (var i = 0; i < route.items.length; i += 1) { + final start = (i + 1) * unit; + final end = (start + 1.5 * unit).clamp(0.0, 1.0) as double; + final opacity = CurvedAnimation( + parent: route.animation, + curve: Interval(start, end), + ); + Widget item = route.items[i]; + if (route.initialValue != null && + route.items[i].represents(route.initialValue)) { + item = Container( + color: Theme.of(context).highlightColor, + child: item, + ); + } + children.add( + _MenuItem( + onLayout: (size) { + route.itemSizes[i] = size; + }, + child: FadeTransition( + opacity: opacity, + child: item, + ), + ), + ); + } + + final opacity = CurveTween(curve: const Interval(0.0, 1.0 / 3.0)); + final width = CurveTween(curve: Interval(0.0, unit)); + final height = CurveTween(curve: Interval(0.0, unit * route.items.length)); + + final Widget child = ConstrainedBox( + constraints: const BoxConstraints( + minWidth: _kMenuMinWidth, + maxWidth: _kMenuMaxWidth, + ), + child: IntrinsicWidth( + stepWidth: _kMenuWidthStep, + child: Semantics( + scopesRoute: true, + namesRoute: true, + explicitChildNodes: true, + label: semanticLabel, + child: SingleChildScrollView( + padding: const EdgeInsets.only(bottom: _kMenuVerticalPadding), + child: ListBody(children: children), + ), + ), + ), + ); + + return AnimatedBuilder( + animation: route.animation, + builder: (context, child) { + return Opacity( + opacity: opacity.evaluate(route.animation), + child: Material( + shape: route.shape ?? popupMenuTheme.shape, + color: route.color ?? popupMenuTheme.color, + type: MaterialType.card, + elevation: route.elevation ?? popupMenuTheme.elevation ?? 8.0, + child: Align( + alignment: AlignmentDirectional.topEnd, + widthFactor: width.evaluate(route.animation), + heightFactor: height.evaluate(route.animation), + child: child, + ), + ), + ); + }, + child: child, + ); + } +} + +class _PopupMenuRouteLayout extends SingleChildLayoutDelegate { + _PopupMenuRouteLayout(this.position, this.itemSizes, this.selectedItemIndex, + this.textDirection); + + final RelativeRect position; + + List itemSizes; + + final int selectedItemIndex; + + final TextDirection textDirection; + + @override + BoxConstraints getConstraintsForChild(BoxConstraints constraints) { + return BoxConstraints.loose( + constraints.biggest - + const Offset(_kMenuScreenPadding * 2.0, _kMenuScreenPadding * 2.0) + as Size, + ); + } + + @override + Offset getPositionForChild(Size size, Size childSize) { + var y = position.top; + if (selectedItemIndex != null && itemSizes != null) { + var selectedItemOffset = _kMenuVerticalPadding; + for (var index = 0; index < selectedItemIndex; index += 1) { + selectedItemOffset += itemSizes[index].height; + } + selectedItemOffset += itemSizes[selectedItemIndex].height / 2; + y = position.top + + (size.height - position.top - position.bottom) / 2.0 - + selectedItemOffset; + } + + double x; + if (position.left > position.right) { + x = size.width - position.right - childSize.width; + } else if (position.left < position.right) { + // Menu button is closer to the left edge, so grow to the right, aligned to the left edge. + x = position.left; + } else { + // Menu button is equidistant from both edges, so grow in reading direction. + assert(textDirection != null); + switch (textDirection) { + case TextDirection.rtl: + x = size.width - position.right - childSize.width; + break; + case TextDirection.ltr: + x = position.left; + break; + } + } + + if (x < _kMenuScreenPadding) { + x = _kMenuScreenPadding; + } else if (x + childSize.width > size.width - _kMenuScreenPadding) { + x = size.width - childSize.width - _kMenuScreenPadding; + } + if (y < _kMenuScreenPadding) { + y = _kMenuScreenPadding; + } else if (y + childSize.height > size.height - _kMenuScreenPadding) { + y = size.height - childSize.height - _kMenuScreenPadding; + } + return Offset(x, y); + } + + @override + bool shouldRelayout(_PopupMenuRouteLayout oldDelegate) { + assert(itemSizes.length == oldDelegate.itemSizes.length); + + return position != oldDelegate.position || + selectedItemIndex != oldDelegate.selectedItemIndex || + textDirection != oldDelegate.textDirection || + !listEquals(itemSizes, oldDelegate.itemSizes); + } +} + +class _PopupMenuRoute extends PopupRoute { + _PopupMenuRoute({ + this.position, + this.items, + this.initialValue, + this.elevation, + this.theme, + this.popupMenuTheme, + this.barrierLabel, + this.semanticLabel, + this.shape, + this.color, + this.showMenuContext, + this.captureInheritedThemes, + }) : itemSizes = List(items.length); + + final RelativeRect position; + final List> items; + final List itemSizes; + final T initialValue; + final double elevation; + final ThemeData theme; + final String semanticLabel; + final ShapeBorder shape; + final Color color; + final PopupMenuThemeData popupMenuTheme; + final BuildContext showMenuContext; + final bool captureInheritedThemes; + + @override + Animation createAnimation() { + return CurvedAnimation( + parent: super.createAnimation(), + curve: Curves.linear, + reverseCurve: const Interval(0.0, _kMenuCloseIntervalEnd), + ); + } + + @override + Duration get transitionDuration => _kMenuDuration; + + @override + bool get barrierDismissible => true; + + @override + Color get barrierColor => null; + + @override + final String barrierLabel; + + @override + Widget buildPage(BuildContext context, Animation animation, + Animation secondaryAnimation) { + int selectedItemIndex; + if (initialValue != null) { + for (var index = 0; + selectedItemIndex == null && index < items.length; + index += 1) { + if (items[index].represents(initialValue)) selectedItemIndex = index; + } + } + + Widget menu = _PopupMenu(route: this, semanticLabel: semanticLabel); + if (captureInheritedThemes) { + menu = InheritedTheme.captureAll(showMenuContext, menu); + } else { + if (theme != null) menu = Theme(data: theme, child: menu); + } + + return MediaQuery.removePadding( + context: context, + removeTop: true, + removeBottom: true, + removeLeft: true, + removeRight: true, + child: Builder( + builder: (context) { + return CustomSingleChildLayout( + delegate: _PopupMenuRouteLayout( + position, + itemSizes, + selectedItemIndex, + Directionality.of(context), + ), + child: menu, + ); + }, + ), + ); + } +} + +Future _showMenu({ + @required BuildContext context, + @required RelativeRect position, + @required List> items, + T initialValue, + double elevation, + String semanticLabel, + ShapeBorder shape, + Color color, + bool captureInheritedThemes = true, + bool useRootNavigator = false, +}) { + assert(context != null); + assert(position != null); + assert(useRootNavigator != null); + assert(items != null && items.isNotEmpty); + assert(captureInheritedThemes != null); + assert(debugCheckHasMaterialLocalizations(context)); + + var label = semanticLabel; + switch (Theme.of(context).platform) { + case TargetPlatform.iOS: + case TargetPlatform.macOS: + label = semanticLabel; + break; + case TargetPlatform.android: + case TargetPlatform.fuchsia: + case TargetPlatform.linux: + case TargetPlatform.windows: + label = + semanticLabel ?? MaterialLocalizations.of(context)?.popupMenuLabel; + } + + return Navigator.of(context, rootNavigator: useRootNavigator) + .push(_PopupMenuRoute( + position: position, + items: items, + initialValue: initialValue, + elevation: elevation, + semanticLabel: label, + theme: Theme.of(context, shadowThemeOnly: true), + popupMenuTheme: PopupMenuTheme.of(context), + barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel, + shape: shape, + color: color, + showMenuContext: context, + captureInheritedThemes: captureInheritedThemes, + )); +} + +class MyPopupMenuButton extends StatefulWidget { + /// Creates a button that shows a popup menu. + /// + /// The [itemBuilder] argument must not be null. + const MyPopupMenuButton({ + Key key, + @required this.itemBuilder, + this.initialValue, + this.onSelected, + this.onCanceled, + this.tooltip, + this.elevation, + this.padding = const EdgeInsets.all(8.0), + this.child, + this.icon, + this.offset = Offset.zero, + this.enabled = true, + this.shape, + this.color, + this.captureInheritedThemes = true, + }) : assert(itemBuilder != null), + assert(offset != null), + assert(enabled != null), + assert(captureInheritedThemes != null), + assert(!(child != null && icon != null), + 'You can only pass [child] or [icon], not both.'), + super(key: key); + + final PopupMenuItemBuilder itemBuilder; + + final T initialValue; + final PopupMenuItemSelected onSelected; + + final PopupMenuCanceled onCanceled; + + final String tooltip; + + final double elevation; + + final EdgeInsetsGeometry padding; + + final Widget child; + + final Widget icon; + + final Offset offset; + final bool enabled; + final ShapeBorder shape; + + final Color color; + + final bool captureInheritedThemes; + + @override + MyPopupMenuButtonState createState() => MyPopupMenuButtonState(); +} + +class MyPopupMenuButtonState extends State> { + void showButtonMenu() { + final popupMenuTheme = PopupMenuTheme.of(context); + final button = context.findRenderObject() as RenderBox; + final overlay = Overlay.of(context).context.findRenderObject() as RenderBox; + final position = RelativeRect.fromRect( + Rect.fromPoints( + button.localToGlobal(widget.offset, ancestor: overlay), + button.localToGlobal(button.size.bottomRight(Offset.zero), + ancestor: overlay), + ), + Offset.zero & overlay.size, + ); + final items = widget.itemBuilder(context); + // Only show the menu if there is something to show + if (items.isNotEmpty) { + _showMenu( + context: context, + elevation: widget.elevation ?? popupMenuTheme.elevation, + items: items, + initialValue: widget.initialValue, + position: position, + shape: widget.shape ?? popupMenuTheme.shape, + color: widget.color ?? popupMenuTheme.color, + captureInheritedThemes: widget.captureInheritedThemes, + ).then((newValue) { + if (!mounted) return null; + if (newValue == null) { + if (widget.onCanceled != null) widget.onCanceled(); + return null; + } + if (widget.onSelected != null) widget.onSelected(newValue); + }); + } + } + + Icon _getIcon(TargetPlatform platform) { + assert(platform != null); + switch (platform) { + case TargetPlatform.android: + case TargetPlatform.fuchsia: + return const Icon(Icons.more_vert); + case TargetPlatform.iOS: + case TargetPlatform.macOS: + case TargetPlatform.linux: + case TargetPlatform.windows: + return const Icon(Icons.more_horiz); + } + return null; + } + + @override + Widget build(BuildContext context) { + assert(debugCheckHasMaterialLocalizations(context)); + + if (widget.child != null) { + return Tooltip( + message: + widget.tooltip ?? MaterialLocalizations.of(context).showMenuTooltip, + child: InkWell( + onTap: widget.enabled ? showButtonMenu : null, + canRequestFocus: widget.enabled, + child: widget.child, + ), + ); + } + + return IconButton( + icon: widget.icon ?? _getIcon(Theme.of(context).platform), + padding: widget.padding, + tooltip: + widget.tooltip ?? MaterialLocalizations.of(context).showMenuTooltip, + onPressed: widget.enabled ? showButtonMenu : null, + ); + } +} + +class MyPopupMenuItem extends PopupMenuEntry { + const MyPopupMenuItem({ + Key key, + this.value, + this.enabled = true, + this.height = kMinInteractiveDimension, + this.textStyle, + @required this.child, + }) : assert(enabled != null), + assert(height != null), + super(key: key); + + final int value; + + final bool enabled; + + @override + final double height; + final TextStyle textStyle; + + final Widget child; + + @override + bool represents(int value) => value == this.value; + + @override + MyPopupMenuItemState> createState() => + MyPopupMenuItemState>(); +} + +class MyPopupMenuItemState> + extends State { + @protected + Widget buildChild() => widget.child; + + @protected + void handleTap() { + Navigator.pop(context, widget.value); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final popupMenuTheme = PopupMenuTheme.of(context); + var style = widget.textStyle ?? + popupMenuTheme.textStyle ?? + theme.textTheme.subtitle1; + + Widget item = AnimatedDefaultTextStyle( + style: style, + duration: kThemeChangeDuration, + child: Container( + // alignment: AlignmentDirectional.centerStart, + // constraints: BoxConstraints(minHeight: widget.height), + padding: const EdgeInsets.all(0), + child: buildChild(), + ), + ); + return item; + // return InkWell( + // onTap: widget.enabled ? handleTap : null, + // canRequestFocus: widget.enabled, + // child: item, + // ); + } +} diff --git a/lib/util/custom_slider.dart b/lib/util/custom_slider.dart index 2e372e6..f364ba8 100644 --- a/lib/util/custom_slider.dart +++ b/lib/util/custom_slider.dart @@ -1,88 +1,88 @@ -import 'package:flutter/material.dart'; - -class MyRectangularTrackShape extends RectangularSliderTrackShape { - Rect getPreferredRect({ - @required RenderBox parentBox, - Offset offset = Offset.zero, - @required SliderThemeData sliderTheme, - bool isEnabled = false, - bool isDiscrete = false, - }) { - final trackHeight = sliderTheme.trackHeight; - final trackLeft = offset.dx; - final trackTop = offset.dy + (parentBox.size.height - trackHeight) / 2; - final trackWidth = parentBox.size.width; - return Rect.fromLTWH(trackLeft - 5, trackTop, trackWidth, trackHeight); - } -} - -class MyRoundSliderThumpShape extends SliderComponentShape { - const MyRoundSliderThumpShape({ - this.enabledThumbRadius = 10.0, - this.disabledThumbRadius, - this.thumbCenterColor, - }); - final Color thumbCenterColor; - final double enabledThumbRadius; - final double disabledThumbRadius; - double get _disabledThumbRadius => disabledThumbRadius ?? enabledThumbRadius; - - @override - Size getPreferredSize(bool isEnabled, bool isDiscrete) { - return Size.fromRadius( - isEnabled == true ? enabledThumbRadius : _disabledThumbRadius); - } - - @override - void paint( - PaintingContext context, - Offset center, { - Animation activationAnimation, - @required Animation enableAnimation, - bool isDiscrete, - TextPainter labelPainter, - RenderBox parentBox, - @required SliderThemeData sliderTheme, - TextDirection textDirection, - double value, - double textScaleFactor, - Size sizeWithOverflow, - }) { - final canvas = context.canvas; - final radiusTween = Tween( - begin: _disabledThumbRadius, - end: enabledThumbRadius, - ); - // final ColorTween colorTween = ColorTween( - // begin: sliderTheme.disabledThumbColor, - // end: sliderTheme.thumbColor, - // ); - - canvas.drawCircle( - center, - radiusTween.evaluate(enableAnimation), - Paint() - ..color = thumbCenterColor - ..style = PaintingStyle.fill - ..strokeWidth = 2, - ); - - canvas.drawRect( - Rect.fromLTRB( - center.dx - 10, center.dy + 10, center.dx + 10, center.dy - 10), - Paint() - ..color = Colors.white - ..style = PaintingStyle.fill - ..strokeWidth = 10, - ); - - canvas.drawLine( - Offset(center.dx - 5, center.dy - 2), - Offset(center.dx + 5, center.dy + 2), - Paint() - ..color = Colors.transparent - ..style = PaintingStyle.fill - ..strokeWidth = 2, - ); - } -} +import 'package:flutter/material.dart'; + +class MyRectangularTrackShape extends RectangularSliderTrackShape { + Rect getPreferredRect({ + @required RenderBox parentBox, + Offset offset = Offset.zero, + @required SliderThemeData sliderTheme, + bool isEnabled = false, + bool isDiscrete = false, + }) { + final trackHeight = sliderTheme.trackHeight; + final trackLeft = offset.dx; + final trackTop = offset.dy + (parentBox.size.height - trackHeight) / 2; + final trackWidth = parentBox.size.width; + return Rect.fromLTWH(trackLeft - 5, trackTop, trackWidth, trackHeight); + } +} + +class MyRoundSliderThumpShape extends SliderComponentShape { + const MyRoundSliderThumpShape({ + this.enabledThumbRadius = 10.0, + this.disabledThumbRadius, + this.thumbCenterColor, + }); + final Color thumbCenterColor; + final double enabledThumbRadius; + final double disabledThumbRadius; + double get _disabledThumbRadius => disabledThumbRadius ?? enabledThumbRadius; + + @override + Size getPreferredSize(bool isEnabled, bool isDiscrete) { + return Size.fromRadius( + isEnabled == true ? enabledThumbRadius : _disabledThumbRadius); + } + + @override + void paint( + PaintingContext context, + Offset center, { + Animation activationAnimation, + @required Animation enableAnimation, + bool isDiscrete, + TextPainter labelPainter, + RenderBox parentBox, + @required SliderThemeData sliderTheme, + TextDirection textDirection, + double value, + double textScaleFactor, + Size sizeWithOverflow, + }) { + final canvas = context.canvas; + final radiusTween = Tween( + begin: _disabledThumbRadius, + end: enabledThumbRadius, + ); + // final ColorTween colorTween = ColorTween( + // begin: sliderTheme.disabledThumbColor, + // end: sliderTheme.thumbColor, + // ); + + canvas.drawCircle( + center, + radiusTween.evaluate(enableAnimation), + Paint() + ..color = thumbCenterColor + ..style = PaintingStyle.fill + ..strokeWidth = 2, + ); + + canvas.drawRect( + Rect.fromLTRB( + center.dx - 10, center.dy + 10, center.dx + 10, center.dy - 10), + Paint() + ..color = Colors.white + ..style = PaintingStyle.fill + ..strokeWidth = 10, + ); + + canvas.drawLine( + Offset(center.dx - 5, center.dy - 2), + Offset(center.dx + 5, center.dy + 2), + Paint() + ..color = Colors.transparent + ..style = PaintingStyle.fill + ..strokeWidth = 2, + ); + } +} diff --git a/lib/util/custom_time_picker.dart b/lib/util/custom_time_picker.dart index 831475a..6f58b40 100644 --- a/lib/util/custom_time_picker.dart +++ b/lib/util/custom_time_picker.dart @@ -1,2163 +1,2163 @@ -// Copyright 2014 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// @dart = 2.8 - -import 'dart:async'; -import 'dart:math' as math; -import 'package:flutter/material.dart'; - -import 'package:flutter/rendering.dart'; -import 'package:flutter/services.dart'; -import 'package:flutter/widgets.dart'; - -// Examples can assume: -// BuildContext context; - -const Duration _kDialogSizeAnimationDuration = Duration(milliseconds: 200); -const Duration _kDialAnimateDuration = Duration(milliseconds: 200); -const double _kTwoPi = 2 * math.pi; -const Duration _kVibrateCommitDelay = Duration(milliseconds: 100); - -enum _TimePickerMode { hour, minute } - -const double _kTimePickerHeaderLandscapeWidth = 264.0; -const double _kTimePickerHeaderControlHeight = 80.0; - -const double _kTimePickerWidthPortrait = 328.0; -const double _kTimePickerWidthLandscape = 528.0; - -const double _kTimePickerHeightInput = 226.0; -const double _kTimePickerHeightPortrait = 496.0; -const double _kTimePickerHeightLandscape = 316.0; - -const double _kTimePickerHeightPortraitCollapsed = 484.0; -const double _kTimePickerHeightLandscapeCollapsed = 304.0; - -const BorderRadius _kDefaultBorderRadius = - BorderRadius.all(Radius.circular(10.0)); -const ShapeBorder _kDefaultShape = - RoundedRectangleBorder(borderRadius: _kDefaultBorderRadius); - -/// Interactive input mode of the time picker dialog. -/// -/// In [TimePickerEntryMode.dial] mode, a clock dial is displayed and -/// the user taps or drags the time they wish to select. In -/// TimePickerEntryMode.input] mode, [TextField]s are displayed and the user -/// types in the time they wish to select. -enum TimePickerEntryMode { - /// Tapping/dragging on a clock dial. - dial, - - /// Text input. - input, -} - -/// Provides properties for rendering time picker header fragments. -@immutable -class _TimePickerFragmentContext { - const _TimePickerFragmentContext({ - @required this.selectedTime, - @required this.mode, - @required this.onTimeChange, - @required this.onModeChange, - @required this.use24HourDials, - }) : assert(selectedTime != null), - assert(mode != null), - assert(onTimeChange != null), - assert(onModeChange != null), - assert(use24HourDials != null); - - final TimeOfDay selectedTime; - final _TimePickerMode mode; - final ValueChanged onTimeChange; - final ValueChanged<_TimePickerMode> onModeChange; - final bool use24HourDials; -} - -class _TimePickerHeader extends StatelessWidget { - const _TimePickerHeader({ - @required this.selectedTime, - @required this.mode, - @required this.orientation, - @required this.onModeChanged, - @required this.onChanged, - @required this.use24HourDials, - @required this.helpText, - }) : assert(selectedTime != null), - assert(mode != null), - assert(orientation != null), - assert(use24HourDials != null); - - final TimeOfDay selectedTime; - final _TimePickerMode mode; - final Orientation orientation; - final ValueChanged<_TimePickerMode> onModeChanged; - final ValueChanged onChanged; - final bool use24HourDials; - final String helpText; - - void _handleChangeMode(_TimePickerMode value) { - if (value != mode) onModeChanged(value); - } - - @override - Widget build(BuildContext context) { - assert(debugCheckHasMediaQuery(context)); - final themeData = Theme.of(context); - final timeOfDayFormat = MaterialLocalizations.of(context).timeOfDayFormat( - alwaysUse24HourFormat: MediaQuery.of(context).alwaysUse24HourFormat, - ); - - final fragmentContext = _TimePickerFragmentContext( - selectedTime: selectedTime, - mode: mode, - onTimeChange: onChanged, - onModeChange: _handleChangeMode, - use24HourDials: use24HourDials, - ); - - EdgeInsets padding; - double width; - Widget controls; - - switch (orientation) { - case Orientation.portrait: - // Keep width null because in portrait we don't cap the width. - padding = const EdgeInsets.symmetric(horizontal: 24.0); - controls = Column( - children: [ - const SizedBox(height: 16.0), - Container( - height: kMinInteractiveDimension * 2, - child: Row( - children: [ - if (!use24HourDials && - timeOfDayFormat == - TimeOfDayFormat.a_space_h_colon_mm) ...[ - _DayPeriodControl( - selectedTime: selectedTime, - orientation: orientation, - onChanged: onChanged, - ), - const SizedBox(width: 12.0), - ], - Expanded( - child: _HourControl(fragmentContext: fragmentContext)), - _StringFragment(timeOfDayFormat: timeOfDayFormat), - Expanded( - child: _MinuteControl(fragmentContext: fragmentContext)), - if (!use24HourDials && - timeOfDayFormat != - TimeOfDayFormat.a_space_h_colon_mm) ...[ - const SizedBox(width: 12.0), - _DayPeriodControl( - selectedTime: selectedTime, - orientation: orientation, - onChanged: onChanged, - ), - ] - ], - ), - ), - ], - ); - break; - case Orientation.landscape: - width = _kTimePickerHeaderLandscapeWidth; - padding = const EdgeInsets.symmetric(horizontal: 24.0); - controls = Expanded( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - if (!use24HourDials && - timeOfDayFormat == TimeOfDayFormat.a_space_h_colon_mm) - _DayPeriodControl( - selectedTime: selectedTime, - orientation: orientation, - onChanged: onChanged, - ), - Container( - height: kMinInteractiveDimension * 2, - child: Row( - children: [ - Expanded( - child: _HourControl(fragmentContext: fragmentContext)), - _StringFragment(timeOfDayFormat: timeOfDayFormat), - Expanded( - child: - _MinuteControl(fragmentContext: fragmentContext)), - ], - ), - ), - if (!use24HourDials && - timeOfDayFormat != TimeOfDayFormat.a_space_h_colon_mm) - _DayPeriodControl( - selectedTime: selectedTime, - orientation: orientation, - onChanged: onChanged, - ), - ], - ), - ); - break; - } - - return Container( - width: width, - padding: padding, - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - const SizedBox(height: 16.0), - Text( - helpText ?? - MaterialLocalizations.of(context).timePickerDialHelpText, - style: TimePickerTheme.of(context).helpTextStyle ?? - themeData.textTheme.overline, - ), - controls, - ], - ), - ); - } -} - -class _HourMinuteControl extends StatelessWidget { - const _HourMinuteControl({ - @required this.text, - @required this.onTap, - @required this.isSelected, - }) : assert(text != null), - assert(onTap != null), - assert(isSelected != null); - - final String text; - final GestureTapCallback onTap; - final bool isSelected; - - @override - Widget build(BuildContext context) { - final themeData = Theme.of(context); - final timePickerTheme = TimePickerTheme.of(context); - final isDark = themeData.colorScheme.brightness == Brightness.dark; - final textColor = timePickerTheme.hourMinuteTextColor ?? - MaterialStateColor.resolveWith((states) { - return states.contains(MaterialState.selected) - ? themeData.accentColor - : themeData.colorScheme.onSurface; - }); - final backgroundColor = timePickerTheme.hourMinuteColor ?? - MaterialStateColor.resolveWith((states) { - return states.contains(MaterialState.selected) - ? themeData.accentColor.withOpacity(isDark ? 0.24 : 0.12) - : themeData.colorScheme.onSurface.withOpacity(0.12); - }); - final style = - timePickerTheme.hourMinuteTextStyle ?? themeData.textTheme.headline2; - final shape = timePickerTheme.hourMinuteShape ?? _kDefaultShape; - - final states = isSelected - ? {MaterialState.selected} - : {}; - return Container( - height: _kTimePickerHeaderControlHeight, - child: Material( - color: MaterialStateProperty.resolveAs(backgroundColor, states), - clipBehavior: Clip.antiAlias, - shape: shape, - child: InkWell( - onTap: onTap, - child: Center( - child: Text( - text, - style: style.copyWith( - color: MaterialStateProperty.resolveAs(textColor, states)), - textScaleFactor: 1.0, - ), - ), - ), - ), - ); - } -} - -/// Displays the hour fragment. -/// -/// When tapped changes time picker dial mode to [_TimePickerMode.hour]. -class _HourControl extends StatelessWidget { - const _HourControl({ - @required this.fragmentContext, - }); - - final _TimePickerFragmentContext fragmentContext; - - @override - Widget build(BuildContext context) { - assert(debugCheckHasMediaQuery(context)); - final alwaysUse24HourFormat = MediaQuery.of(context).alwaysUse24HourFormat; - final localizations = MaterialLocalizations.of(context); - final formattedHour = localizations.formatHour( - fragmentContext.selectedTime, - alwaysUse24HourFormat: alwaysUse24HourFormat, - ); - - TimeOfDay hoursFromSelected(int hoursToAdd) { - if (fragmentContext.use24HourDials) { - final selectedHour = fragmentContext.selectedTime.hour; - return fragmentContext.selectedTime.replacing( - hour: (selectedHour + hoursToAdd) % TimeOfDay.hoursPerDay, - ); - } else { - // Cycle 1 through 12 without changing day period. - final periodOffset = fragmentContext.selectedTime.periodOffset; - final hours = fragmentContext.selectedTime.hourOfPeriod; - return fragmentContext.selectedTime.replacing( - hour: periodOffset + (hours + hoursToAdd) % TimeOfDay.hoursPerPeriod, - ); - } - } - - final nextHour = hoursFromSelected(1); - final formattedNextHour = localizations.formatHour( - nextHour, - alwaysUse24HourFormat: alwaysUse24HourFormat, - ); - final previousHour = hoursFromSelected(-1); - final formattedPreviousHour = localizations.formatHour( - previousHour, - alwaysUse24HourFormat: alwaysUse24HourFormat, - ); - - return Semantics( - hint: localizations.timePickerHourModeAnnouncement, - value: formattedHour, - excludeSemantics: true, - increasedValue: formattedNextHour, - onIncrease: () { - fragmentContext.onTimeChange(nextHour); - }, - decreasedValue: formattedPreviousHour, - onDecrease: () { - fragmentContext.onTimeChange(previousHour); - }, - child: _HourMinuteControl( - isSelected: fragmentContext.mode == _TimePickerMode.hour, - text: formattedHour, - onTap: Feedback.wrapForTap( - () => fragmentContext.onModeChange(_TimePickerMode.hour), context), - ), - ); - } -} - -/// A passive fragment showing a string value. -class _StringFragment extends StatelessWidget { - const _StringFragment({ - @required this.timeOfDayFormat, - }); - - final TimeOfDayFormat timeOfDayFormat; - - String _stringFragmentValue(TimeOfDayFormat timeOfDayFormat) { - switch (timeOfDayFormat) { - case TimeOfDayFormat.h_colon_mm_space_a: - case TimeOfDayFormat.a_space_h_colon_mm: - case TimeOfDayFormat.H_colon_mm: - case TimeOfDayFormat.HH_colon_mm: - return ':'; - case TimeOfDayFormat.HH_dot_mm: - return '.'; - case TimeOfDayFormat.frenchCanadian: - return 'h'; - } - return ''; - } - - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - final timePickerTheme = TimePickerTheme.of(context); - final hourMinuteStyle = - timePickerTheme.hourMinuteTextStyle ?? theme.textTheme.headline2; - final textColor = - timePickerTheme.hourMinuteTextColor ?? theme.colorScheme.onSurface; - - return ExcludeSemantics( - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 6.0), - child: Center( - child: Text( - _stringFragmentValue(timeOfDayFormat), - style: hourMinuteStyle.apply( - color: MaterialStateProperty.resolveAs( - textColor, {})), - textScaleFactor: 1.0, - ), - ), - ), - ); - } -} - -/// Displays the minute fragment. -/// -/// When tapped changes time picker dial mode to [_TimePickerMode.minute]. -class _MinuteControl extends StatelessWidget { - const _MinuteControl({ - @required this.fragmentContext, - }); - - final _TimePickerFragmentContext fragmentContext; - - @override - Widget build(BuildContext context) { - final localizations = MaterialLocalizations.of(context); - final formattedMinute = - localizations.formatMinute(fragmentContext.selectedTime); - final nextMinute = fragmentContext.selectedTime.replacing( - minute: - (fragmentContext.selectedTime.minute + 1) % TimeOfDay.minutesPerHour, - ); - final formattedNextMinute = localizations.formatMinute(nextMinute); - final previousMinute = fragmentContext.selectedTime.replacing( - minute: - (fragmentContext.selectedTime.minute - 1) % TimeOfDay.minutesPerHour, - ); - final formattedPreviousMinute = localizations.formatMinute(previousMinute); - - return Semantics( - excludeSemantics: true, - hint: localizations.timePickerMinuteModeAnnouncement, - value: formattedMinute, - increasedValue: formattedNextMinute, - onIncrease: () { - fragmentContext.onTimeChange(nextMinute); - }, - decreasedValue: formattedPreviousMinute, - onDecrease: () { - fragmentContext.onTimeChange(previousMinute); - }, - child: _HourMinuteControl( - isSelected: fragmentContext.mode == _TimePickerMode.minute, - text: formattedMinute, - onTap: Feedback.wrapForTap( - () => fragmentContext.onModeChange(_TimePickerMode.minute), - context), - ), - ); - } -} - -/// Displays the am/pm fragment and provides controls for switching between am -/// and pm. -class _DayPeriodControl extends StatelessWidget { - const _DayPeriodControl({ - @required this.selectedTime, - @required this.onChanged, - @required this.orientation, - }); - - final TimeOfDay selectedTime; - final Orientation orientation; - final ValueChanged onChanged; - - void _togglePeriod() { - final newHour = - (selectedTime.hour + TimeOfDay.hoursPerPeriod) % TimeOfDay.hoursPerDay; - final newTime = selectedTime.replacing(hour: newHour); - onChanged(newTime); - } - - void _setAm(BuildContext context) { - if (selectedTime.period == DayPeriod.am) { - return; - } - switch (Theme.of(context).platform) { - case TargetPlatform.android: - case TargetPlatform.fuchsia: - case TargetPlatform.linux: - case TargetPlatform.windows: - _announceToAccessibility(context, - MaterialLocalizations.of(context).anteMeridiemAbbreviation); - break; - case TargetPlatform.iOS: - case TargetPlatform.macOS: - break; - } - _togglePeriod(); - } - - void _setPm(BuildContext context) { - if (selectedTime.period == DayPeriod.pm) { - return; - } - switch (Theme.of(context).platform) { - case TargetPlatform.android: - case TargetPlatform.fuchsia: - case TargetPlatform.linux: - case TargetPlatform.windows: - _announceToAccessibility(context, - MaterialLocalizations.of(context).postMeridiemAbbreviation); - break; - case TargetPlatform.iOS: - case TargetPlatform.macOS: - break; - } - _togglePeriod(); - } - - @override - Widget build(BuildContext context) { - final materialLocalizations = MaterialLocalizations.of(context); - final colorScheme = Theme.of(context).colorScheme; - final timePickerTheme = TimePickerTheme.of(context); - final isDark = colorScheme.brightness == Brightness.dark; - final textColor = timePickerTheme.dayPeriodTextColor ?? - MaterialStateColor.resolveWith((states) { - return states.contains(MaterialState.selected) - ? colorScheme.primary - : colorScheme.onSurface.withOpacity(0.60); - }); - final backgroundColor = timePickerTheme.dayPeriodColor ?? - MaterialStateColor.resolveWith((states) { - // The unselected day period should match the overall picker dialog - // color. Making it transparent enables that without being redundant - // and allows the optional elevation overlay for dark mode to be - // visible. - return states.contains(MaterialState.selected) - ? colorScheme.primary.withOpacity(isDark ? 0.24 : 0.12) - : Colors.transparent; - }); - final amSelected = selectedTime.period == DayPeriod.am; - final amStates = amSelected - ? {MaterialState.selected} - : {}; - final pmSelected = !amSelected; - final pmStates = pmSelected - ? {MaterialState.selected} - : {}; - final textStyle = timePickerTheme.dayPeriodTextStyle ?? - Theme.of(context).textTheme.subtitle1; - final amStyle = textStyle.copyWith( - color: MaterialStateProperty.resolveAs(textColor, amStates), - ); - final pmStyle = textStyle.copyWith( - color: MaterialStateProperty.resolveAs(textColor, pmStates), - ); - var shape = timePickerTheme.dayPeriodShape ?? - const RoundedRectangleBorder(borderRadius: _kDefaultBorderRadius); - final borderSide = timePickerTheme.dayPeriodBorderSide ?? - BorderSide( - color: Color.alphaBlend( - colorScheme.onBackground.withOpacity(0.38), colorScheme.surface), - ); - // Apply the custom borderSide. - shape = shape.copyWith( - side: borderSide, - ); - - final buttonTextScaleFactor = - math.min(MediaQuery.of(context).textScaleFactor, 2.0); - - final Widget amButton = Material( - color: MaterialStateProperty.resolveAs(backgroundColor, amStates), - child: InkWell( - onTap: Feedback.wrapForTap(() => _setAm(context), context), - child: Semantics( - selected: amSelected, - child: Center( - child: Text( - materialLocalizations.anteMeridiemAbbreviation, - style: amStyle, - textScaleFactor: buttonTextScaleFactor, - ), - ), - ), - ), - ); - - final Widget pmButton = Material( - color: MaterialStateProperty.resolveAs(backgroundColor, pmStates), - child: InkWell( - onTap: Feedback.wrapForTap(() => _setPm(context), context), - child: Semantics( - selected: pmSelected, - child: Center( - child: Text( - materialLocalizations.postMeridiemAbbreviation, - style: pmStyle, - textScaleFactor: buttonTextScaleFactor, - ), - ), - ), - ), - ); - - Widget result; - switch (orientation) { - case Orientation.portrait: - const width = 52.0; - result = _DayPeriodInputPadding( - minSize: const Size(width, kMinInteractiveDimension * 2), - orientation: orientation, - child: Container( - width: width, - height: _kTimePickerHeaderControlHeight, - child: Material( - clipBehavior: Clip.antiAlias, - color: Colors.transparent, - shape: shape, - child: Column( - children: [ - Expanded(child: amButton), - Container( - decoration: BoxDecoration( - border: Border(top: borderSide), - ), - height: 1, - ), - Expanded(child: pmButton), - ], - ), - ), - ), - ); - break; - case Orientation.landscape: - result = _DayPeriodInputPadding( - minSize: const Size(0.0, kMinInteractiveDimension), - orientation: orientation, - child: Container( - height: 40.0, - child: Material( - clipBehavior: Clip.antiAlias, - color: Colors.transparent, - shape: shape, - child: Row( - children: [ - Expanded(child: amButton), - Container( - decoration: BoxDecoration( - border: Border(left: borderSide), - ), - width: 1, - ), - Expanded(child: pmButton), - ], - ), - ), - ), - ); - break; - } - return result; - } -} - -/// A widget to pad the area around the [_DayPeriodControl]'s inner [Material]. -class _DayPeriodInputPadding extends SingleChildRenderObjectWidget { - const _DayPeriodInputPadding({ - Key key, - Widget child, - this.minSize, - this.orientation, - }) : super(key: key, child: child); - - final Size minSize; - final Orientation orientation; - - @override - RenderObject createRenderObject(BuildContext context) { - return _RenderInputPadding(minSize, orientation); - } - - @override - void updateRenderObject( - BuildContext context, covariant _RenderInputPadding renderObject) { - renderObject.minSize = minSize; - } -} - -class _RenderInputPadding extends RenderShiftedBox { - _RenderInputPadding(this._minSize, this.orientation, [RenderBox child]) - : super(child); - - final Orientation orientation; - - Size get minSize => _minSize; - Size _minSize; - set minSize(Size value) { - if (_minSize == value) return; - _minSize = value; - markNeedsLayout(); - } - - @override - double computeMinIntrinsicWidth(double height) { - if (child != null) { - return math.max(child.getMinIntrinsicWidth(height), minSize.width); - } - return 0.0; - } - - @override - double computeMinIntrinsicHeight(double width) { - if (child != null) { - return math.max(child.getMinIntrinsicHeight(width), minSize.height); - } - return 0.0; - } - - @override - double computeMaxIntrinsicWidth(double height) { - if (child != null) { - return math.max(child.getMaxIntrinsicWidth(height), minSize.width); - } - return 0.0; - } - - @override - double computeMaxIntrinsicHeight(double width) { - if (child != null) { - return math.max(child.getMaxIntrinsicHeight(width), minSize.height); - } - return 0.0; - } - - @override - void performLayout() { - if (child != null) { - child.layout(constraints, parentUsesSize: true); - final width = math.max(child.size.width, minSize.width); - final height = math.max(child.size.height, minSize.height); - size = constraints.constrain(Size(width, height)); - final childParentData = child.parentData as BoxParentData; - childParentData.offset = - Alignment.center.alongOffset(size - child.size as Offset); - } else { - size = Size.zero; - } - } - - @override - bool hitTest(BoxHitTestResult result, {Offset position}) { - if (super.hitTest(result, position: position)) { - return true; - } - - if (position.dx < 0.0 || - position.dx > math.max(child.size.width, minSize.width) || - position.dy < 0.0 || - position.dy > math.max(child.size.height, minSize.height)) { - return false; - } - - var newPosition = child.size.center(Offset.zero); - switch (orientation) { - case Orientation.portrait: - if (position.dy > newPosition.dy) { - newPosition += const Offset(0.0, 1.0); - } else { - newPosition += const Offset(0.0, -1.0); - } - break; - case Orientation.landscape: - if (position.dx > newPosition.dx) { - newPosition += const Offset(1.0, 0.0); - } else { - newPosition += const Offset(-1.0, 0.0); - } - break; - } - - return result.addWithRawTransform( - transform: MatrixUtils.forceToPoint(newPosition), - position: newPosition, - hitTest: (result, position) { - assert(position == newPosition); - return child.hitTest(result, position: newPosition); - }, - ); - } -} - -class _TappableLabel { - _TappableLabel({ - @required this.value, - @required this.painter, - @required this.onTap, - }); - - /// The value this label is displaying. - final int value; - - /// Paints the text of the label. - final TextPainter painter; - - /// Called when a tap gesture is detected on the label. - final VoidCallback onTap; -} - -class _DialPainter extends CustomPainter { - _DialPainter({ - @required this.primaryLabels, - @required this.secondaryLabels, - @required this.backgroundColor, - @required this.accentColor, - @required this.dotColor, - @required this.theta, - @required this.textDirection, - @required this.selectedValue, - }) : super(repaint: PaintingBinding.instance.systemFonts); - - final List<_TappableLabel> primaryLabels; - final List<_TappableLabel> secondaryLabels; - final Color backgroundColor; - final Color accentColor; - final Color dotColor; - final double theta; - final TextDirection textDirection; - final int selectedValue; - - static const double _labelPadding = 28.0; - - @override - void paint(Canvas canvas, Size size) { - final radius = size.shortestSide / 2.0; - final center = Offset(size.width / 2.0, size.height / 2.0); - final centerPoint = center; - canvas.drawCircle(centerPoint, radius, Paint()..color = backgroundColor); - - final labelRadius = radius - _labelPadding; - Offset getOffsetForTheta(double theta) { - return center + - Offset(labelRadius * math.cos(theta), -labelRadius * math.sin(theta)); - } - - void paintLabels(List<_TappableLabel> labels) { - if (labels == null) return; - final labelThetaIncrement = -_kTwoPi / labels.length; - var labelTheta = math.pi / 2.0; - - for (final label in labels) { - final labelPainter = label.painter; - final labelOffset = - Offset(-labelPainter.width / 2.0, -labelPainter.height / 2.0); - labelPainter.paint(canvas, getOffsetForTheta(labelTheta) + labelOffset); - labelTheta += labelThetaIncrement; - } - } - - paintLabels(primaryLabels); - - final selectorPaint = Paint()..color = accentColor; - final focusedPoint = getOffsetForTheta(theta); - const focusedRadius = _labelPadding - 4.0; - canvas.drawCircle(centerPoint, 4.0, selectorPaint); - canvas.drawCircle(focusedPoint, focusedRadius, selectorPaint); - selectorPaint.strokeWidth = 2.0; - canvas.drawLine(centerPoint, focusedPoint, selectorPaint); - - // Add a dot inside the selector but only when it isn't over the labels. - // This checks that the selector's theta is between two labels. A remainder - // between 0.1 and 0.45 indicates that the selector is roughly not above any - // labels. The values were derived by manually testing the dial. - final labelThetaIncrement = -_kTwoPi / primaryLabels.length; - if (theta % labelThetaIncrement > 0.1 && - theta % labelThetaIncrement < 0.45) { - canvas.drawCircle(focusedPoint, 2.0, selectorPaint..color = dotColor); - } - - final focusedRect = Rect.fromCircle( - center: focusedPoint, - radius: focusedRadius, - ); - canvas - ..save() - ..clipPath(Path()..addOval(focusedRect)); - paintLabels(secondaryLabels); - canvas.restore(); - } - - @override - bool shouldRepaint(_DialPainter oldPainter) { - return oldPainter.primaryLabels != primaryLabels || - oldPainter.secondaryLabels != secondaryLabels || - oldPainter.backgroundColor != backgroundColor || - oldPainter.accentColor != accentColor || - oldPainter.theta != theta; - } -} - -class _Dial extends StatefulWidget { - const _Dial({ - @required this.selectedTime, - @required this.mode, - @required this.use24HourDials, - @required this.onChanged, - @required this.onHourSelected, - }) : assert(selectedTime != null), - assert(mode != null), - assert(use24HourDials != null); - - final TimeOfDay selectedTime; - final _TimePickerMode mode; - final bool use24HourDials; - final ValueChanged onChanged; - final VoidCallback onHourSelected; - - @override - _DialState createState() => _DialState(); -} - -class _DialState extends State<_Dial> with SingleTickerProviderStateMixin { - @override - void initState() { - super.initState(); - _thetaController = AnimationController( - vsync: this, - duration: _kDialAnimateDuration, - ); - _thetaTween = Tween(begin: _getThetaForTime(widget.selectedTime)); - _theta = _thetaController - .drive(CurveTween(curve: Curves.easeInSine)) - .drive(_thetaTween) - ..addListener(() => setState(() {/* _theta.value has changed */})); - } - - ThemeData themeData; - MaterialLocalizations localizations; - MediaQueryData media; - - @override - void didChangeDependencies() { - super.didChangeDependencies(); - assert(debugCheckHasMediaQuery(context)); - themeData = Theme.of(context); - localizations = MaterialLocalizations.of(context); - media = MediaQuery.of(context); - } - - @override - void didUpdateWidget(_Dial oldWidget) { - super.didUpdateWidget(oldWidget); - if (widget.mode != oldWidget.mode || - widget.selectedTime != oldWidget.selectedTime) { - if (!_dragging) _animateTo(_getThetaForTime(widget.selectedTime)); - } - } - - @override - void dispose() { - _thetaController.dispose(); - super.dispose(); - } - - Tween _thetaTween; - Animation _theta; - AnimationController _thetaController; - bool _dragging = false; - - static double _nearest(double target, double a, double b) { - return ((target - a).abs() < (target - b).abs()) ? a : b; - } - - void _animateTo(double targetTheta) { - final currentTheta = _theta.value; - var beginTheta = - _nearest(targetTheta, currentTheta, currentTheta + _kTwoPi); - beginTheta = _nearest(targetTheta, beginTheta, currentTheta - _kTwoPi); - _thetaTween - ..begin = beginTheta - ..end = targetTheta; - _thetaController - ..value = 0.0 - ..forward(); - } - - double _getThetaForTime(TimeOfDay time) { - final hoursFactor = widget.use24HourDials - ? TimeOfDay.hoursPerDay - : TimeOfDay.hoursPerPeriod; - final fraction = widget.mode == _TimePickerMode.hour - ? (time.hour / hoursFactor) % hoursFactor - : (time.minute / TimeOfDay.minutesPerHour) % TimeOfDay.minutesPerHour; - return (math.pi / 2.0 - fraction * _kTwoPi) % _kTwoPi; - } - - TimeOfDay _getTimeForTheta(double theta, {bool roundMinutes = false}) { - final fraction = (0.25 - (theta % _kTwoPi) / _kTwoPi) % 1.0; - if (widget.mode == _TimePickerMode.hour) { - int newHour; - if (widget.use24HourDials) { - newHour = - (fraction * TimeOfDay.hoursPerDay).round() % TimeOfDay.hoursPerDay; - } else { - newHour = (fraction * TimeOfDay.hoursPerPeriod).round() % - TimeOfDay.hoursPerPeriod; - newHour = newHour + widget.selectedTime.periodOffset; - } - return widget.selectedTime.replacing(hour: newHour); - } else { - var minute = (fraction * TimeOfDay.minutesPerHour).round() % - TimeOfDay.minutesPerHour; - if (roundMinutes) { - // Round the minutes to nearest 5 minute interval. - minute = ((minute + 2) ~/ 5) * 5 % TimeOfDay.minutesPerHour; - } - return widget.selectedTime.replacing(minute: minute); - } - } - - TimeOfDay _notifyOnChangedIfNeeded({bool roundMinutes = false}) { - final current = _getTimeForTheta(_theta.value, roundMinutes: roundMinutes); - if (widget.onChanged == null) return current; - if (current != widget.selectedTime) widget.onChanged(current); - return current; - } - - void _updateThetaForPan({bool roundMinutes = false}) { - setState(() { - final offset = _position - _center; - var angle = (math.atan2(offset.dx, offset.dy) - math.pi / 2.0) % _kTwoPi; - if (roundMinutes) { - angle = _getThetaForTime( - _getTimeForTheta(angle, roundMinutes: roundMinutes)); - } - _thetaTween - ..begin = angle - ..end = angle; // The controller doesn't animate during the pan gesture. - }); - } - - Offset _position; - Offset _center; - - void _handlePanStart(DragStartDetails details) { - assert(!_dragging); - _dragging = true; - final box = context.findRenderObject() as RenderBox; - _position = box.globalToLocal(details.globalPosition); - _center = box.size.center(Offset.zero); - _updateThetaForPan(); - _notifyOnChangedIfNeeded(); - } - - void _handlePanUpdate(DragUpdateDetails details) { - _position += details.delta; - _updateThetaForPan(); - _notifyOnChangedIfNeeded(); - } - - void _handlePanEnd(DragEndDetails details) { - assert(_dragging); - _dragging = false; - _position = null; - _center = null; - _animateTo(_getThetaForTime(widget.selectedTime)); - if (widget.mode == _TimePickerMode.hour) { - if (widget.onHourSelected != null) { - widget.onHourSelected(); - } - } - } - - void _handleTapUp(TapUpDetails details) { - final box = context.findRenderObject() as RenderBox; - _position = box.globalToLocal(details.globalPosition); - _center = box.size.center(Offset.zero); - _updateThetaForPan(roundMinutes: true); - final newTime = _notifyOnChangedIfNeeded(roundMinutes: true); - if (widget.mode == _TimePickerMode.hour) { - if (widget.use24HourDials) { - _announceToAccessibility( - context, localizations.formatDecimal(newTime.hour)); - } else { - _announceToAccessibility( - context, localizations.formatDecimal(newTime.hourOfPeriod)); - } - if (widget.onHourSelected != null) { - widget.onHourSelected(); - } - } else { - _announceToAccessibility( - context, localizations.formatDecimal(newTime.minute)); - } - _animateTo( - _getThetaForTime(_getTimeForTheta(_theta.value, roundMinutes: true))); - _dragging = false; - _position = null; - _center = null; - } - - void _selectHour(int hour) { - _announceToAccessibility(context, localizations.formatDecimal(hour)); - TimeOfDay time; - if (widget.mode == _TimePickerMode.hour && widget.use24HourDials) { - time = TimeOfDay(hour: hour, minute: widget.selectedTime.minute); - } else { - if (widget.selectedTime.period == DayPeriod.am) { - time = TimeOfDay(hour: hour, minute: widget.selectedTime.minute); - } else { - time = TimeOfDay( - hour: hour + TimeOfDay.hoursPerPeriod, - minute: widget.selectedTime.minute); - } - } - final angle = _getThetaForTime(time); - _thetaTween - ..begin = angle - ..end = angle; - _notifyOnChangedIfNeeded(); - } - - void _selectMinute(int minute) { - _announceToAccessibility(context, localizations.formatDecimal(minute)); - final time = TimeOfDay( - hour: widget.selectedTime.hour, - minute: minute, - ); - final angle = _getThetaForTime(time); - _thetaTween - ..begin = angle - ..end = angle; - _notifyOnChangedIfNeeded(); - } - - static const List _amHours = [ - TimeOfDay(hour: 12, minute: 0), - TimeOfDay(hour: 1, minute: 0), - TimeOfDay(hour: 2, minute: 0), - TimeOfDay(hour: 3, minute: 0), - TimeOfDay(hour: 4, minute: 0), - TimeOfDay(hour: 5, minute: 0), - TimeOfDay(hour: 6, minute: 0), - TimeOfDay(hour: 7, minute: 0), - TimeOfDay(hour: 8, minute: 0), - TimeOfDay(hour: 9, minute: 0), - TimeOfDay(hour: 10, minute: 0), - TimeOfDay(hour: 11, minute: 0), - ]; - - static const List _twentyFourHours = [ - TimeOfDay(hour: 0, minute: 0), - TimeOfDay(hour: 2, minute: 0), - TimeOfDay(hour: 4, minute: 0), - TimeOfDay(hour: 6, minute: 0), - TimeOfDay(hour: 8, minute: 0), - TimeOfDay(hour: 10, minute: 0), - TimeOfDay(hour: 12, minute: 0), - TimeOfDay(hour: 14, minute: 0), - TimeOfDay(hour: 16, minute: 0), - TimeOfDay(hour: 18, minute: 0), - TimeOfDay(hour: 20, minute: 0), - TimeOfDay(hour: 22, minute: 0), - ]; - - _TappableLabel _buildTappableLabel(TextTheme textTheme, Color color, - int value, String label, VoidCallback onTap) { - final style = textTheme.subtitle1.copyWith(color: color); - final labelScaleFactor = - math.min(MediaQuery.of(context).textScaleFactor, 2.0); - return _TappableLabel( - value: value, - painter: TextPainter( - text: TextSpan(style: style, text: label), - textDirection: TextDirection.ltr, - textScaleFactor: labelScaleFactor, - )..layout(), - onTap: onTap, - ); - } - - List<_TappableLabel> _build24HourRing(TextTheme textTheme, Color color) => - <_TappableLabel>[ - for (final TimeOfDay timeOfDay in _twentyFourHours) - _buildTappableLabel( - textTheme, - color, - timeOfDay.hour, - localizations.formatHour(timeOfDay, - alwaysUse24HourFormat: media.alwaysUse24HourFormat), - () { - _selectHour(timeOfDay.hour); - }, - ), - ]; - - List<_TappableLabel> _build12HourRing(TextTheme textTheme, Color color) => - <_TappableLabel>[ - for (final TimeOfDay timeOfDay in _amHours) - _buildTappableLabel( - textTheme, - color, - timeOfDay.hour, - localizations.formatHour(timeOfDay, - alwaysUse24HourFormat: media.alwaysUse24HourFormat), - () { - _selectHour(timeOfDay.hour); - }, - ), - ]; - - List<_TappableLabel> _buildMinutes(TextTheme textTheme, Color color) { - const _minuteMarkerValues = [ - TimeOfDay(hour: 0, minute: 0), - TimeOfDay(hour: 0, minute: 5), - TimeOfDay(hour: 0, minute: 10), - TimeOfDay(hour: 0, minute: 15), - TimeOfDay(hour: 0, minute: 20), - TimeOfDay(hour: 0, minute: 25), - TimeOfDay(hour: 0, minute: 30), - TimeOfDay(hour: 0, minute: 35), - TimeOfDay(hour: 0, minute: 40), - TimeOfDay(hour: 0, minute: 45), - TimeOfDay(hour: 0, minute: 50), - TimeOfDay(hour: 0, minute: 55), - ]; - - return <_TappableLabel>[ - for (final TimeOfDay timeOfDay in _minuteMarkerValues) - _buildTappableLabel( - textTheme, - color, - timeOfDay.minute, - localizations.formatMinute(timeOfDay), - () { - _selectMinute(timeOfDay.minute); - }, - ), - ]; - } - - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - final pickerTheme = TimePickerTheme.of(context); - final backgroundColor = pickerTheme.dialBackgroundColor ?? - themeData.colorScheme.onBackground.withOpacity(0.12); - final accentColor = pickerTheme.dialHandColor ?? themeData.accentColor; - final primaryLabelColor = MaterialStateProperty.resolveAs( - pickerTheme.dialTextColor, {}); - final secondaryLabelColor = MaterialStateProperty.resolveAs( - pickerTheme.dialTextColor, {MaterialState.selected}); - List<_TappableLabel> primaryLabels; - List<_TappableLabel> secondaryLabels; - int selectedDialValue; - switch (widget.mode) { - case _TimePickerMode.hour: - if (widget.use24HourDials) { - selectedDialValue = widget.selectedTime.hour; - primaryLabels = _build24HourRing(theme.textTheme, primaryLabelColor); - secondaryLabels = - _build24HourRing(theme.accentTextTheme, secondaryLabelColor); - } else { - selectedDialValue = widget.selectedTime.hourOfPeriod; - primaryLabels = _build12HourRing(theme.textTheme, primaryLabelColor); - secondaryLabels = - _build12HourRing(theme.accentTextTheme, secondaryLabelColor); - } - break; - case _TimePickerMode.minute: - selectedDialValue = widget.selectedTime.minute; - primaryLabels = _buildMinutes(theme.textTheme, primaryLabelColor); - secondaryLabels = - _buildMinutes(theme.accentTextTheme, secondaryLabelColor); - break; - } - - return GestureDetector( - excludeFromSemantics: true, - onPanStart: _handlePanStart, - onPanUpdate: _handlePanUpdate, - onPanEnd: _handlePanEnd, - onTapUp: _handleTapUp, - child: CustomPaint( - key: const ValueKey('time-picker-dial'), - painter: _DialPainter( - selectedValue: selectedDialValue, - primaryLabels: primaryLabels, - secondaryLabels: secondaryLabels, - backgroundColor: backgroundColor, - accentColor: accentColor, - dotColor: theme.colorScheme.surface, - theta: _theta.value, - textDirection: Directionality.of(context), - ), - ), - ); - } -} - -class _TimePickerInput extends StatefulWidget { - const _TimePickerInput({ - Key key, - @required this.initialSelectedTime, - @required this.helpText, - @required this.onChanged, - }) : assert(initialSelectedTime != null), - assert(onChanged != null), - super(key: key); - - /// The time initially selected when the dialog is shown. - final TimeOfDay initialSelectedTime; - - /// Optionally provide your own help text to the time picker. - final String helpText; - - final ValueChanged onChanged; - - @override - _TimePickerInputState createState() => _TimePickerInputState(); -} - -class _TimePickerInputState extends State<_TimePickerInput> { - TimeOfDay _selectedTime; - bool hourHasError = false; - bool minuteHasError = false; - - @override - void initState() { - super.initState(); - _selectedTime = widget.initialSelectedTime; - } - - int _parseHour(String value) { - if (value == null) { - return null; - } - - var newHour = int.tryParse(value); - if (newHour == null) { - return null; - } - - if (MediaQuery.of(context).alwaysUse24HourFormat) { - if (newHour >= 0 && newHour < 24) { - return newHour; - } - } else { - if (newHour > 0 && newHour < 13) { - if ((_selectedTime.period == DayPeriod.pm && newHour != 12) || - (_selectedTime.period == DayPeriod.am && newHour == 12)) { - newHour = - (newHour + TimeOfDay.hoursPerPeriod) % TimeOfDay.hoursPerDay; - } - return newHour; - } - } - return null; - } - - int _parseMinute(String value) { - if (value == null) { - return null; - } - - final newMinute = int.tryParse(value); - if (newMinute == null) { - return null; - } - - if (newMinute >= 0 && newMinute < 60) { - return newMinute; - } - return null; - } - - void _handleHourSavedSubmitted(String value) { - final newHour = _parseHour(value); - if (newHour != null) { - _selectedTime = TimeOfDay(hour: newHour, minute: _selectedTime.minute); - widget.onChanged(_selectedTime); - } - } - - void _handleHourChanged(String value) { - final newHour = _parseHour(value); - if (newHour != null && value.length == 2) { - // If a valid hour is typed, move focus to the minute TextField. - FocusScope.of(context).nextFocus(); - } - } - - void _handleMinuteSavedSubmitted(String value) { - final newMinute = _parseMinute(value); - if (newMinute != null) { - _selectedTime = - TimeOfDay(hour: _selectedTime.hour, minute: int.parse(value)); - widget.onChanged(_selectedTime); - } - } - - void _handleDayPeriodChanged(TimeOfDay value) { - _selectedTime = value; - widget.onChanged(_selectedTime); - } - - String _validateHour(String value) { - final newHour = _parseHour(value); - setState(() { - hourHasError = newHour == null; - }); - // This is used as the validator for the [TextFormField]. - // Returning an empty string allows the field to go into an error state. - // Returning null means no error in the validation of the entered text. - return newHour == null ? '' : null; - } - - String _validateMinute(String value) { - final newMinute = _parseMinute(value); - setState(() { - minuteHasError = newMinute == null; - }); - // This is used as the validator for the [TextFormField]. - // Returning an empty string allows the field to go into an error state. - // Returning null means no error in the validation of the entered text. - return newMinute == null ? '' : null; - } - - @override - Widget build(BuildContext context) { - assert(debugCheckHasMediaQuery(context)); - final media = MediaQuery.of(context); - final timeOfDayFormat = MaterialLocalizations.of(context) - .timeOfDayFormat(alwaysUse24HourFormat: media.alwaysUse24HourFormat); - final use24HourDials = hourFormat(of: timeOfDayFormat) != HourFormat.h; - final theme = Theme.of(context); - final hourMinuteStyle = TimePickerTheme.of(context).hourMinuteTextStyle ?? - theme.textTheme.headline2; - - return Padding( - padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 16.0), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - widget.helpText ?? - MaterialLocalizations.of(context).timePickerInputHelpText, - style: TimePickerTheme.of(context).helpTextStyle ?? - theme.textTheme.overline, - ), - const SizedBox(height: 16.0), - Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - if (!use24HourDials && - timeOfDayFormat == - TimeOfDayFormat.a_space_h_colon_mm) ...[ - _DayPeriodControl( - selectedTime: _selectedTime, - orientation: Orientation.portrait, - onChanged: _handleDayPeriodChanged, - ), - const SizedBox(width: 12.0), - ], - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - const SizedBox(height: 8.0), - _HourMinuteTextField( - selectedTime: _selectedTime, - isHour: true, - style: hourMinuteStyle, - validator: _validateHour, - onSavedSubmitted: _handleHourSavedSubmitted, - onChanged: _handleHourChanged, - ), - const SizedBox(height: 8.0), - if (!hourHasError && !minuteHasError) - ExcludeSemantics( - child: Text( - MaterialLocalizations.of(context).timePickerHourLabel, - style: theme.textTheme.caption, - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - ), - ], - )), - Container( - margin: const EdgeInsets.only(top: 8.0), - height: _kTimePickerHeaderControlHeight, - child: _StringFragment(timeOfDayFormat: timeOfDayFormat), - ), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - const SizedBox(height: 8.0), - _HourMinuteTextField( - selectedTime: _selectedTime, - isHour: false, - style: hourMinuteStyle, - validator: _validateMinute, - onSavedSubmitted: _handleMinuteSavedSubmitted, - ), - const SizedBox(height: 8.0), - if (!hourHasError && !minuteHasError) - ExcludeSemantics( - child: Text( - MaterialLocalizations.of(context).timePickerMinuteLabel, - style: theme.textTheme.caption, - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - ), - ], - )), - if (!use24HourDials && - timeOfDayFormat != - TimeOfDayFormat.a_space_h_colon_mm) ...[ - const SizedBox(width: 12.0), - _DayPeriodControl( - selectedTime: _selectedTime, - orientation: Orientation.portrait, - onChanged: _handleDayPeriodChanged, - ), - ], - ], - ), - if (hourHasError || minuteHasError) - Text( - MaterialLocalizations.of(context).invalidTimeLabel, - style: theme.textTheme.bodyText2 - .copyWith(color: theme.colorScheme.error), - ) - else - const SizedBox(height: 2.0), - ], - ), - ); - } -} - -class _HourMinuteTextField extends StatefulWidget { - const _HourMinuteTextField({ - Key key, - @required this.selectedTime, - @required this.isHour, - @required this.style, - @required this.validator, - @required this.onSavedSubmitted, - this.onChanged, - }) : super(key: key); - - final TimeOfDay selectedTime; - final bool isHour; - final TextStyle style; - final FormFieldValidator validator; - final ValueChanged onSavedSubmitted; - final ValueChanged onChanged; - - @override - _HourMinuteTextFieldState createState() => _HourMinuteTextFieldState(); -} - -class _HourMinuteTextFieldState extends State<_HourMinuteTextField> { - TextEditingController controller; - FocusNode focusNode; - - @override - void initState() { - super.initState(); - focusNode = FocusNode() - ..addListener(() { - setState(() {}); // Rebuild. - }); - } - - @override - void didChangeDependencies() { - super.didChangeDependencies(); - controller ??= TextEditingController(text: _formattedValue); - } - - String get _formattedValue { - final alwaysUse24HourFormat = MediaQuery.of(context).alwaysUse24HourFormat; - final localizations = MaterialLocalizations.of(context); - return !widget.isHour - ? localizations.formatMinute(widget.selectedTime) - : localizations.formatHour( - widget.selectedTime, - alwaysUse24HourFormat: alwaysUse24HourFormat, - ); - } - - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - final timePickerTheme = TimePickerTheme.of(context); - final colorScheme = theme.colorScheme; - - final inputDecorationTheme = timePickerTheme.inputDecorationTheme; - InputDecoration inputDecoration; - if (inputDecorationTheme != null) { - inputDecoration = - const InputDecoration().applyDefaults(inputDecorationTheme); - } else { - final unfocusedFillColor = timePickerTheme.hourMinuteColor ?? - colorScheme.onSurface.withOpacity(0.12); - inputDecoration = InputDecoration( - contentPadding: EdgeInsets.zero, - filled: true, - fillColor: focusNode.hasFocus ? Colors.transparent : unfocusedFillColor, - enabledBorder: const OutlineInputBorder( - borderSide: BorderSide(color: Colors.transparent), - ), - errorBorder: OutlineInputBorder( - borderSide: BorderSide(color: colorScheme.error, width: 2.0), - ), - focusedBorder: OutlineInputBorder( - borderSide: BorderSide(color: colorScheme.primary, width: 2.0), - ), - focusedErrorBorder: OutlineInputBorder( - borderSide: BorderSide(color: colorScheme.error, width: 2.0), - ), - hintStyle: widget.style - .copyWith(color: colorScheme.onSurface.withOpacity(0.36)), - // TODO(rami-a): Remove this logic once https://github.com/flutter/flutter/issues/54104 is fixed. - errorStyle: const TextStyle( - fontSize: 0.0, - height: 0.0), // Prevent the error text from appearing. - ); - } - inputDecoration = inputDecoration.copyWith( - // Remove the hint text when focused because the centered cursor appears - // odd above the hint text. - hintText: focusNode.hasFocus ? null : _formattedValue, - ); - - return SizedBox( - height: _kTimePickerHeaderControlHeight, - child: MediaQuery( - data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0), - child: TextFormField( - expands: true, - maxLines: null, - focusNode: focusNode, - textAlign: TextAlign.center, - keyboardType: TextInputType.number, - style: widget.style.copyWith(color: colorScheme.onSurface), - controller: controller, - decoration: inputDecoration, - validator: widget.validator, - onEditingComplete: () => widget.onSavedSubmitted(controller.text), - onSaved: widget.onSavedSubmitted, - onFieldSubmitted: widget.onSavedSubmitted, - onChanged: widget.onChanged, - ), - ), - ); - } -} - -/// A material design time picker designed to appear inside a popup dialog. -/// -/// Pass this widget to [showDialog]. The value returned by [showDialog] is the -/// selected [TimeOfDay] if the user taps the "OK" button, or null if the user -/// taps the "CANCEL" button. The selected time is reported by calling -/// [Navigator.pop]. -class _TimePickerDialog extends StatefulWidget { - /// Creates a material time picker. - /// - /// [initialTime] must not be null. - const _TimePickerDialog({ - Key key, - @required this.initialTime, - @required this.cancelText, - @required this.confirmText, - @required this.helpText, - this.initialEntryMode = TimePickerEntryMode.dial, - }) : assert(initialTime != null), - super(key: key); - - /// The time initially selected when the dialog is shown. - final TimeOfDay initialTime; - - /// The entry mode for the picker. Whether it's text input or a dial. - final TimePickerEntryMode initialEntryMode; - - /// Optionally provide your own text for the cancel button. - /// - /// If null, the button uses [MaterialLocalizations.cancelButtonLabel]. - final String cancelText; - - /// Optionally provide your own text for the confirm button. - /// - /// If null, the button uses [MaterialLocalizations.okButtonLabel]. - final String confirmText; - - /// Optionally provide your own help text to the header of the time picker. - final String helpText; - - @override - _TimePickerDialogState createState() => _TimePickerDialogState(); -} - -class _TimePickerDialogState extends State<_TimePickerDialog> { - final GlobalKey _formKey = GlobalKey(); - - @override - void initState() { - super.initState(); - _selectedTime = widget.initialTime; - _entryMode = widget.initialEntryMode; - _autoValidate = false; - } - - @override - void didChangeDependencies() { - super.didChangeDependencies(); - localizations = MaterialLocalizations.of(context); - _announceInitialTimeOnce(); - _announceModeOnce(); - } - - TimePickerEntryMode _entryMode; - _TimePickerMode _mode = _TimePickerMode.hour; - _TimePickerMode _lastModeAnnounced; - bool _autoValidate; - - TimeOfDay get selectedTime => _selectedTime; - TimeOfDay _selectedTime; - - Timer _vibrateTimer; - MaterialLocalizations localizations; - - void _vibrate() { - switch (Theme.of(context).platform) { - case TargetPlatform.android: - case TargetPlatform.fuchsia: - case TargetPlatform.linux: - case TargetPlatform.windows: - _vibrateTimer?.cancel(); - _vibrateTimer = Timer(_kVibrateCommitDelay, () { - HapticFeedback.vibrate(); - _vibrateTimer = null; - }); - break; - case TargetPlatform.iOS: - case TargetPlatform.macOS: - break; - } - } - - void _handleModeChanged(_TimePickerMode mode) { - _vibrate(); - setState(() { - _mode = mode; - _announceModeOnce(); - }); - } - - void _handleEntryModeToggle() { - setState(() { - switch (_entryMode) { - case TimePickerEntryMode.dial: - _autoValidate = false; - _entryMode = TimePickerEntryMode.input; - break; - case TimePickerEntryMode.input: - _formKey.currentState.save(); - _entryMode = TimePickerEntryMode.dial; - break; - } - }); - } - - void _announceModeOnce() { - if (_lastModeAnnounced == _mode) { - // Already announced it. - return; - } - - switch (_mode) { - case _TimePickerMode.hour: - _announceToAccessibility( - context, localizations.timePickerHourModeAnnouncement); - break; - case _TimePickerMode.minute: - _announceToAccessibility( - context, localizations.timePickerMinuteModeAnnouncement); - break; - } - _lastModeAnnounced = _mode; - } - - bool _announcedInitialTime = false; - - void _announceInitialTimeOnce() { - if (_announcedInitialTime) return; - - final media = MediaQuery.of(context); - final localizations = MaterialLocalizations.of(context); - _announceToAccessibility( - context, - localizations.formatTimeOfDay(widget.initialTime, - alwaysUse24HourFormat: media.alwaysUse24HourFormat), - ); - _announcedInitialTime = true; - } - - void _handleTimeChanged(TimeOfDay value) { - _vibrate(); - setState(() { - _selectedTime = value; - }); - } - - void _handleHourSelected() { - setState(() { - _mode = _TimePickerMode.minute; - }); - } - - void _handleCancel() { - Navigator.pop(context); - } - - void _handleOk() { - if (_entryMode == TimePickerEntryMode.input) { - final form = _formKey.currentState; - if (!form.validate()) { - setState(() { - _autoValidate = true; - }); - return; - } - form.save(); - } - Navigator.pop(context, _selectedTime); - } - - Size _dialogSize(BuildContext context) { - final orientation = MediaQuery.of(context).orientation; - final theme = Theme.of(context); - // Constrain the textScaleFactor to prevent layout issues. Since only some - // parts of the time picker scale up with textScaleFactor, we cap the factor - // to 1.1 as that provides enough space to reasonably fit all the content. - final textScaleFactor = - math.min(MediaQuery.of(context).textScaleFactor, 1.1); - - double timePickerWidth; - double timePickerHeight; - switch (_entryMode) { - case TimePickerEntryMode.dial: - switch (orientation) { - case Orientation.portrait: - timePickerWidth = _kTimePickerWidthPortrait; - timePickerHeight = - theme.materialTapTargetSize == MaterialTapTargetSize.padded - ? _kTimePickerHeightPortrait - : _kTimePickerHeightPortraitCollapsed; - break; - case Orientation.landscape: - timePickerWidth = _kTimePickerWidthLandscape * textScaleFactor; - timePickerHeight = - theme.materialTapTargetSize == MaterialTapTargetSize.padded - ? _kTimePickerHeightLandscape - : _kTimePickerHeightLandscapeCollapsed; - break; - } - break; - case TimePickerEntryMode.input: - timePickerWidth = _kTimePickerWidthPortrait; - timePickerHeight = _kTimePickerHeightInput; - break; - } - return Size(timePickerWidth, timePickerHeight * textScaleFactor); - } - - @override - Widget build(BuildContext context) { - assert(debugCheckHasMediaQuery(context)); - final media = MediaQuery.of(context); - final timeOfDayFormat = localizations.timeOfDayFormat( - alwaysUse24HourFormat: media.alwaysUse24HourFormat); - final use24HourDials = hourFormat(of: timeOfDayFormat) != HourFormat.h; - final theme = Theme.of(context); - final shape = TimePickerTheme.of(context).shape ?? _kDefaultShape; - final orientation = media.orientation; - - final Widget actions = Row( - children: [ - const SizedBox(width: 10.0), - IconButton( - color: TimePickerTheme.of(context).entryModeIconColor ?? - theme.colorScheme.onSurface.withOpacity( - theme.colorScheme.brightness == Brightness.dark ? 1.0 : 0.6, - ), - onPressed: _handleEntryModeToggle, - icon: Icon(_entryMode == TimePickerEntryMode.dial - ? Icons.keyboard - : Icons.access_time), - tooltip: _entryMode == TimePickerEntryMode.dial - ? MaterialLocalizations.of(context).inputTimeModeButtonLabel - : MaterialLocalizations.of(context).dialModeButtonLabel, - ), - Expanded( - // TODO(rami-a): Move away from ButtonBar to avoid https://github.com/flutter/flutter/issues/53378. - child: ButtonBar( - layoutBehavior: ButtonBarLayoutBehavior.constrained, - children: [ - FlatButton( - onPressed: _handleCancel, - child: Text( - widget.cancelText ?? localizations.cancelButtonLabel, - style: TextStyle(color: Colors.grey[600]), - ), - ), - FlatButton( - onPressed: _handleOk, - child: Text( - widget.confirmText ?? localizations.okButtonLabel, - style: TextStyle(color: Theme.of(context).accentColor), - ), - ), - ], - ), - ), - ], - ); - - Widget picker; - switch (_entryMode) { - case TimePickerEntryMode.dial: - final Widget dial = Padding( - padding: orientation == Orientation.portrait - ? const EdgeInsets.symmetric(horizontal: 36, vertical: 24) - : const EdgeInsets.all(24), - child: ExcludeSemantics( - child: AspectRatio( - aspectRatio: 1.0, - child: _Dial( - mode: _mode, - use24HourDials: use24HourDials, - selectedTime: _selectedTime, - onChanged: _handleTimeChanged, - onHourSelected: _handleHourSelected, - ), - ), - ), - ); - - final Widget header = _TimePickerHeader( - selectedTime: _selectedTime, - mode: _mode, - orientation: orientation, - onModeChanged: _handleModeChanged, - onChanged: _handleTimeChanged, - use24HourDials: use24HourDials, - helpText: widget.helpText, - ); - - switch (orientation) { - case Orientation.portrait: - picker = Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - header, - Expanded( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - // Dial grows and shrinks with the available space. - Expanded(child: dial), - actions, - ], - ), - ), - ], - ); - break; - case Orientation.landscape: - picker = Column( - children: [ - Expanded( - child: Row( - children: [ - header, - Expanded(child: dial), - ], - ), - ), - actions, - ], - ); - break; - } - break; - case TimePickerEntryMode.input: - picker = Form( - key: _formKey, - autovalidate: _autoValidate, - child: SingleChildScrollView( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - _TimePickerInput( - initialSelectedTime: _selectedTime, - helpText: widget.helpText, - onChanged: _handleTimeChanged, - ), - actions, - ], - ), - ), - ); - break; - } - - final dialogSize = _dialogSize(context); - return Dialog( - shape: shape, - elevation: 2, - backgroundColor: TimePickerTheme.of(context).backgroundColor ?? - theme.colorScheme.surface, - insetPadding: EdgeInsets.symmetric( - horizontal: 16.0, - vertical: _entryMode == TimePickerEntryMode.input ? 0.0 : 24.0, - ), - child: AnimatedContainer( - width: dialogSize.width, - height: dialogSize.height, - duration: _kDialogSizeAnimationDuration, - curve: Curves.easeIn, - child: picker, - ), - ); - } - - @override - void dispose() { - _vibrateTimer?.cancel(); - _vibrateTimer = null; - super.dispose(); - } -} - -/// Shows a dialog containing a material design time picker. -/// -/// The returned Future resolves to the time selected by the user when the user -/// closes the dialog. If the user cancels the dialog, null is returned. -/// -/// {@tool snippet} -/// Show a dialog with [initialTime] equal to the current time. -/// -/// ```dart -/// Future selectedTime = showTimePicker( -/// initialTime: TimeOfDay.now(), -/// context: context, -/// ); -/// ``` -/// {@end-tool} -/// -/// The [context], [useRootNavigator] and [routeSettings] arguments are passed to -/// [showDialog], the documentation for which discusses how it is used. -/// -/// The [builder] parameter can be used to wrap the dialog widget -/// to add inherited widgets like [Localizations.override], -/// [Directionality], or [MediaQuery]. -/// -/// The [entryMode] parameter can be used to -/// determine the initial time entry selection of the picker (either a clock -/// dial or text input). -/// -/// Optional strings for the [helpText], [cancelText], and [confirmText] can be -/// provided to override the default values. -/// -/// {@tool snippet} -/// Show a dialog with the text direction overridden to be [TextDirection.rtl]. -/// -/// ```dart -/// Future selectedTimeRTL = showTimePicker( -/// context: context, -/// initialTime: TimeOfDay.now(), -/// builder: (BuildContext context, Widget child) { -/// return Directionality( -/// textDirection: TextDirection.rtl, -/// child: child, -/// ); -/// }, -/// ); -/// ``` -/// {@end-tool} -/// -/// {@tool snippet} -/// Show a dialog with time unconditionally displayed in 24 hour format. -/// -/// ```dart -/// Future selectedTime24Hour = showTimePicker( -/// context: context, -/// initialTime: TimeOfDay(hour: 10, minute: 47), -/// builder: (BuildContext context, Widget child) { -/// return MediaQuery( -/// data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true), -/// child: child, -/// ); -/// }, -/// ); -/// ``` -/// {@end-tool} -/// -/// See also: -/// -/// * [showDatePicker], which shows a dialog that contains a material design -/// date picker. -Future showCustomTimePicker({ - @required BuildContext context, - @required TimeOfDay initialTime, - TransitionBuilder builder, - bool useRootNavigator = true, - TimePickerEntryMode initialEntryMode = TimePickerEntryMode.dial, - String cancelText, - String confirmText, - String helpText, - RouteSettings routeSettings, -}) async { - assert(context != null); - assert(initialTime != null); - assert(useRootNavigator != null); - assert(initialEntryMode != null); - assert(debugCheckHasMaterialLocalizations(context)); - - final Widget dialog = _TimePickerDialog( - initialTime: initialTime, - initialEntryMode: initialEntryMode, - cancelText: cancelText, - confirmText: confirmText, - helpText: helpText, - ); - return await showGeneralDialog( - context: context, - useRootNavigator: useRootNavigator, - routeSettings: routeSettings, - barrierDismissible: true, - barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel, - barrierColor: Colors.black54, - transitionDuration: const Duration(milliseconds: 200), - pageBuilder: (context, animaiton, secondaryAnimation) => - AnnotatedRegion( - value: SystemUiOverlayStyle( - statusBarIconBrightness: Brightness.light, - systemNavigationBarColor: - Theme.of(context).brightness == Brightness.light - ? Color.fromRGBO(113, 113, 113, 1) - : Color.fromRGBO(15, 15, 15, 1), - ), - child: Builder(builder: (context) { - return builder == null ? dialog : builder(context, dialog); - }), - //routeSettings: routeSettings, - ), - ); -} - -void _announceToAccessibility(BuildContext context, String message) { - SemanticsService.announce(message, Directionality.of(context)); -} +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// @dart = 2.8 + +import 'dart:async'; +import 'dart:math' as math; +import 'package:flutter/material.dart'; + +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; + +// Examples can assume: +// BuildContext context; + +const Duration _kDialogSizeAnimationDuration = Duration(milliseconds: 200); +const Duration _kDialAnimateDuration = Duration(milliseconds: 200); +const double _kTwoPi = 2 * math.pi; +const Duration _kVibrateCommitDelay = Duration(milliseconds: 100); + +enum _TimePickerMode { hour, minute } + +const double _kTimePickerHeaderLandscapeWidth = 264.0; +const double _kTimePickerHeaderControlHeight = 80.0; + +const double _kTimePickerWidthPortrait = 328.0; +const double _kTimePickerWidthLandscape = 528.0; + +const double _kTimePickerHeightInput = 226.0; +const double _kTimePickerHeightPortrait = 496.0; +const double _kTimePickerHeightLandscape = 316.0; + +const double _kTimePickerHeightPortraitCollapsed = 484.0; +const double _kTimePickerHeightLandscapeCollapsed = 304.0; + +const BorderRadius _kDefaultBorderRadius = + BorderRadius.all(Radius.circular(10.0)); +const ShapeBorder _kDefaultShape = + RoundedRectangleBorder(borderRadius: _kDefaultBorderRadius); + +/// Interactive input mode of the time picker dialog. +/// +/// In [TimePickerEntryMode.dial] mode, a clock dial is displayed and +/// the user taps or drags the time they wish to select. In +/// TimePickerEntryMode.input] mode, [TextField]s are displayed and the user +/// types in the time they wish to select. +enum TimePickerEntryMode { + /// Tapping/dragging on a clock dial. + dial, + + /// Text input. + input, +} + +/// Provides properties for rendering time picker header fragments. +@immutable +class _TimePickerFragmentContext { + const _TimePickerFragmentContext({ + @required this.selectedTime, + @required this.mode, + @required this.onTimeChange, + @required this.onModeChange, + @required this.use24HourDials, + }) : assert(selectedTime != null), + assert(mode != null), + assert(onTimeChange != null), + assert(onModeChange != null), + assert(use24HourDials != null); + + final TimeOfDay selectedTime; + final _TimePickerMode mode; + final ValueChanged onTimeChange; + final ValueChanged<_TimePickerMode> onModeChange; + final bool use24HourDials; +} + +class _TimePickerHeader extends StatelessWidget { + const _TimePickerHeader({ + @required this.selectedTime, + @required this.mode, + @required this.orientation, + @required this.onModeChanged, + @required this.onChanged, + @required this.use24HourDials, + @required this.helpText, + }) : assert(selectedTime != null), + assert(mode != null), + assert(orientation != null), + assert(use24HourDials != null); + + final TimeOfDay selectedTime; + final _TimePickerMode mode; + final Orientation orientation; + final ValueChanged<_TimePickerMode> onModeChanged; + final ValueChanged onChanged; + final bool use24HourDials; + final String helpText; + + void _handleChangeMode(_TimePickerMode value) { + if (value != mode) onModeChanged(value); + } + + @override + Widget build(BuildContext context) { + assert(debugCheckHasMediaQuery(context)); + final themeData = Theme.of(context); + final timeOfDayFormat = MaterialLocalizations.of(context).timeOfDayFormat( + alwaysUse24HourFormat: MediaQuery.of(context).alwaysUse24HourFormat, + ); + + final fragmentContext = _TimePickerFragmentContext( + selectedTime: selectedTime, + mode: mode, + onTimeChange: onChanged, + onModeChange: _handleChangeMode, + use24HourDials: use24HourDials, + ); + + EdgeInsets padding; + double width; + Widget controls; + + switch (orientation) { + case Orientation.portrait: + // Keep width null because in portrait we don't cap the width. + padding = const EdgeInsets.symmetric(horizontal: 24.0); + controls = Column( + children: [ + const SizedBox(height: 16.0), + Container( + height: kMinInteractiveDimension * 2, + child: Row( + children: [ + if (!use24HourDials && + timeOfDayFormat == + TimeOfDayFormat.a_space_h_colon_mm) ...[ + _DayPeriodControl( + selectedTime: selectedTime, + orientation: orientation, + onChanged: onChanged, + ), + const SizedBox(width: 12.0), + ], + Expanded( + child: _HourControl(fragmentContext: fragmentContext)), + _StringFragment(timeOfDayFormat: timeOfDayFormat), + Expanded( + child: _MinuteControl(fragmentContext: fragmentContext)), + if (!use24HourDials && + timeOfDayFormat != + TimeOfDayFormat.a_space_h_colon_mm) ...[ + const SizedBox(width: 12.0), + _DayPeriodControl( + selectedTime: selectedTime, + orientation: orientation, + onChanged: onChanged, + ), + ] + ], + ), + ), + ], + ); + break; + case Orientation.landscape: + width = _kTimePickerHeaderLandscapeWidth; + padding = const EdgeInsets.symmetric(horizontal: 24.0); + controls = Expanded( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + if (!use24HourDials && + timeOfDayFormat == TimeOfDayFormat.a_space_h_colon_mm) + _DayPeriodControl( + selectedTime: selectedTime, + orientation: orientation, + onChanged: onChanged, + ), + Container( + height: kMinInteractiveDimension * 2, + child: Row( + children: [ + Expanded( + child: _HourControl(fragmentContext: fragmentContext)), + _StringFragment(timeOfDayFormat: timeOfDayFormat), + Expanded( + child: + _MinuteControl(fragmentContext: fragmentContext)), + ], + ), + ), + if (!use24HourDials && + timeOfDayFormat != TimeOfDayFormat.a_space_h_colon_mm) + _DayPeriodControl( + selectedTime: selectedTime, + orientation: orientation, + onChanged: onChanged, + ), + ], + ), + ); + break; + } + + return Container( + width: width, + padding: padding, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const SizedBox(height: 16.0), + Text( + helpText ?? + MaterialLocalizations.of(context).timePickerDialHelpText, + style: TimePickerTheme.of(context).helpTextStyle ?? + themeData.textTheme.overline, + ), + controls, + ], + ), + ); + } +} + +class _HourMinuteControl extends StatelessWidget { + const _HourMinuteControl({ + @required this.text, + @required this.onTap, + @required this.isSelected, + }) : assert(text != null), + assert(onTap != null), + assert(isSelected != null); + + final String text; + final GestureTapCallback onTap; + final bool isSelected; + + @override + Widget build(BuildContext context) { + final themeData = Theme.of(context); + final timePickerTheme = TimePickerTheme.of(context); + final isDark = themeData.colorScheme.brightness == Brightness.dark; + final textColor = timePickerTheme.hourMinuteTextColor ?? + MaterialStateColor.resolveWith((states) { + return states.contains(MaterialState.selected) + ? themeData.accentColor + : themeData.colorScheme.onSurface; + }); + final backgroundColor = timePickerTheme.hourMinuteColor ?? + MaterialStateColor.resolveWith((states) { + return states.contains(MaterialState.selected) + ? themeData.accentColor.withOpacity(isDark ? 0.24 : 0.12) + : themeData.colorScheme.onSurface.withOpacity(0.12); + }); + final style = + timePickerTheme.hourMinuteTextStyle ?? themeData.textTheme.headline2; + final shape = timePickerTheme.hourMinuteShape ?? _kDefaultShape; + + final states = isSelected + ? {MaterialState.selected} + : {}; + return Container( + height: _kTimePickerHeaderControlHeight, + child: Material( + color: MaterialStateProperty.resolveAs(backgroundColor, states), + clipBehavior: Clip.antiAlias, + shape: shape, + child: InkWell( + onTap: onTap, + child: Center( + child: Text( + text, + style: style.copyWith( + color: MaterialStateProperty.resolveAs(textColor, states)), + textScaleFactor: 1.0, + ), + ), + ), + ), + ); + } +} + +/// Displays the hour fragment. +/// +/// When tapped changes time picker dial mode to [_TimePickerMode.hour]. +class _HourControl extends StatelessWidget { + const _HourControl({ + @required this.fragmentContext, + }); + + final _TimePickerFragmentContext fragmentContext; + + @override + Widget build(BuildContext context) { + assert(debugCheckHasMediaQuery(context)); + final alwaysUse24HourFormat = MediaQuery.of(context).alwaysUse24HourFormat; + final localizations = MaterialLocalizations.of(context); + final formattedHour = localizations.formatHour( + fragmentContext.selectedTime, + alwaysUse24HourFormat: alwaysUse24HourFormat, + ); + + TimeOfDay hoursFromSelected(int hoursToAdd) { + if (fragmentContext.use24HourDials) { + final selectedHour = fragmentContext.selectedTime.hour; + return fragmentContext.selectedTime.replacing( + hour: (selectedHour + hoursToAdd) % TimeOfDay.hoursPerDay, + ); + } else { + // Cycle 1 through 12 without changing day period. + final periodOffset = fragmentContext.selectedTime.periodOffset; + final hours = fragmentContext.selectedTime.hourOfPeriod; + return fragmentContext.selectedTime.replacing( + hour: periodOffset + (hours + hoursToAdd) % TimeOfDay.hoursPerPeriod, + ); + } + } + + final nextHour = hoursFromSelected(1); + final formattedNextHour = localizations.formatHour( + nextHour, + alwaysUse24HourFormat: alwaysUse24HourFormat, + ); + final previousHour = hoursFromSelected(-1); + final formattedPreviousHour = localizations.formatHour( + previousHour, + alwaysUse24HourFormat: alwaysUse24HourFormat, + ); + + return Semantics( + hint: localizations.timePickerHourModeAnnouncement, + value: formattedHour, + excludeSemantics: true, + increasedValue: formattedNextHour, + onIncrease: () { + fragmentContext.onTimeChange(nextHour); + }, + decreasedValue: formattedPreviousHour, + onDecrease: () { + fragmentContext.onTimeChange(previousHour); + }, + child: _HourMinuteControl( + isSelected: fragmentContext.mode == _TimePickerMode.hour, + text: formattedHour, + onTap: Feedback.wrapForTap( + () => fragmentContext.onModeChange(_TimePickerMode.hour), context), + ), + ); + } +} + +/// A passive fragment showing a string value. +class _StringFragment extends StatelessWidget { + const _StringFragment({ + @required this.timeOfDayFormat, + }); + + final TimeOfDayFormat timeOfDayFormat; + + String _stringFragmentValue(TimeOfDayFormat timeOfDayFormat) { + switch (timeOfDayFormat) { + case TimeOfDayFormat.h_colon_mm_space_a: + case TimeOfDayFormat.a_space_h_colon_mm: + case TimeOfDayFormat.H_colon_mm: + case TimeOfDayFormat.HH_colon_mm: + return ':'; + case TimeOfDayFormat.HH_dot_mm: + return '.'; + case TimeOfDayFormat.frenchCanadian: + return 'h'; + } + return ''; + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final timePickerTheme = TimePickerTheme.of(context); + final hourMinuteStyle = + timePickerTheme.hourMinuteTextStyle ?? theme.textTheme.headline2; + final textColor = + timePickerTheme.hourMinuteTextColor ?? theme.colorScheme.onSurface; + + return ExcludeSemantics( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 6.0), + child: Center( + child: Text( + _stringFragmentValue(timeOfDayFormat), + style: hourMinuteStyle.apply( + color: MaterialStateProperty.resolveAs( + textColor, {})), + textScaleFactor: 1.0, + ), + ), + ), + ); + } +} + +/// Displays the minute fragment. +/// +/// When tapped changes time picker dial mode to [_TimePickerMode.minute]. +class _MinuteControl extends StatelessWidget { + const _MinuteControl({ + @required this.fragmentContext, + }); + + final _TimePickerFragmentContext fragmentContext; + + @override + Widget build(BuildContext context) { + final localizations = MaterialLocalizations.of(context); + final formattedMinute = + localizations.formatMinute(fragmentContext.selectedTime); + final nextMinute = fragmentContext.selectedTime.replacing( + minute: + (fragmentContext.selectedTime.minute + 1) % TimeOfDay.minutesPerHour, + ); + final formattedNextMinute = localizations.formatMinute(nextMinute); + final previousMinute = fragmentContext.selectedTime.replacing( + minute: + (fragmentContext.selectedTime.minute - 1) % TimeOfDay.minutesPerHour, + ); + final formattedPreviousMinute = localizations.formatMinute(previousMinute); + + return Semantics( + excludeSemantics: true, + hint: localizations.timePickerMinuteModeAnnouncement, + value: formattedMinute, + increasedValue: formattedNextMinute, + onIncrease: () { + fragmentContext.onTimeChange(nextMinute); + }, + decreasedValue: formattedPreviousMinute, + onDecrease: () { + fragmentContext.onTimeChange(previousMinute); + }, + child: _HourMinuteControl( + isSelected: fragmentContext.mode == _TimePickerMode.minute, + text: formattedMinute, + onTap: Feedback.wrapForTap( + () => fragmentContext.onModeChange(_TimePickerMode.minute), + context), + ), + ); + } +} + +/// Displays the am/pm fragment and provides controls for switching between am +/// and pm. +class _DayPeriodControl extends StatelessWidget { + const _DayPeriodControl({ + @required this.selectedTime, + @required this.onChanged, + @required this.orientation, + }); + + final TimeOfDay selectedTime; + final Orientation orientation; + final ValueChanged onChanged; + + void _togglePeriod() { + final newHour = + (selectedTime.hour + TimeOfDay.hoursPerPeriod) % TimeOfDay.hoursPerDay; + final newTime = selectedTime.replacing(hour: newHour); + onChanged(newTime); + } + + void _setAm(BuildContext context) { + if (selectedTime.period == DayPeriod.am) { + return; + } + switch (Theme.of(context).platform) { + case TargetPlatform.android: + case TargetPlatform.fuchsia: + case TargetPlatform.linux: + case TargetPlatform.windows: + _announceToAccessibility(context, + MaterialLocalizations.of(context).anteMeridiemAbbreviation); + break; + case TargetPlatform.iOS: + case TargetPlatform.macOS: + break; + } + _togglePeriod(); + } + + void _setPm(BuildContext context) { + if (selectedTime.period == DayPeriod.pm) { + return; + } + switch (Theme.of(context).platform) { + case TargetPlatform.android: + case TargetPlatform.fuchsia: + case TargetPlatform.linux: + case TargetPlatform.windows: + _announceToAccessibility(context, + MaterialLocalizations.of(context).postMeridiemAbbreviation); + break; + case TargetPlatform.iOS: + case TargetPlatform.macOS: + break; + } + _togglePeriod(); + } + + @override + Widget build(BuildContext context) { + final materialLocalizations = MaterialLocalizations.of(context); + final colorScheme = Theme.of(context).colorScheme; + final timePickerTheme = TimePickerTheme.of(context); + final isDark = colorScheme.brightness == Brightness.dark; + final textColor = timePickerTheme.dayPeriodTextColor ?? + MaterialStateColor.resolveWith((states) { + return states.contains(MaterialState.selected) + ? colorScheme.primary + : colorScheme.onSurface.withOpacity(0.60); + }); + final backgroundColor = timePickerTheme.dayPeriodColor ?? + MaterialStateColor.resolveWith((states) { + // The unselected day period should match the overall picker dialog + // color. Making it transparent enables that without being redundant + // and allows the optional elevation overlay for dark mode to be + // visible. + return states.contains(MaterialState.selected) + ? colorScheme.primary.withOpacity(isDark ? 0.24 : 0.12) + : Colors.transparent; + }); + final amSelected = selectedTime.period == DayPeriod.am; + final amStates = amSelected + ? {MaterialState.selected} + : {}; + final pmSelected = !amSelected; + final pmStates = pmSelected + ? {MaterialState.selected} + : {}; + final textStyle = timePickerTheme.dayPeriodTextStyle ?? + Theme.of(context).textTheme.subtitle1; + final amStyle = textStyle.copyWith( + color: MaterialStateProperty.resolveAs(textColor, amStates), + ); + final pmStyle = textStyle.copyWith( + color: MaterialStateProperty.resolveAs(textColor, pmStates), + ); + var shape = timePickerTheme.dayPeriodShape ?? + const RoundedRectangleBorder(borderRadius: _kDefaultBorderRadius); + final borderSide = timePickerTheme.dayPeriodBorderSide ?? + BorderSide( + color: Color.alphaBlend( + colorScheme.onBackground.withOpacity(0.38), colorScheme.surface), + ); + // Apply the custom borderSide. + shape = shape.copyWith( + side: borderSide, + ); + + final buttonTextScaleFactor = + math.min(MediaQuery.of(context).textScaleFactor, 2.0); + + final Widget amButton = Material( + color: MaterialStateProperty.resolveAs(backgroundColor, amStates), + child: InkWell( + onTap: Feedback.wrapForTap(() => _setAm(context), context), + child: Semantics( + selected: amSelected, + child: Center( + child: Text( + materialLocalizations.anteMeridiemAbbreviation, + style: amStyle, + textScaleFactor: buttonTextScaleFactor, + ), + ), + ), + ), + ); + + final Widget pmButton = Material( + color: MaterialStateProperty.resolveAs(backgroundColor, pmStates), + child: InkWell( + onTap: Feedback.wrapForTap(() => _setPm(context), context), + child: Semantics( + selected: pmSelected, + child: Center( + child: Text( + materialLocalizations.postMeridiemAbbreviation, + style: pmStyle, + textScaleFactor: buttonTextScaleFactor, + ), + ), + ), + ), + ); + + Widget result; + switch (orientation) { + case Orientation.portrait: + const width = 52.0; + result = _DayPeriodInputPadding( + minSize: const Size(width, kMinInteractiveDimension * 2), + orientation: orientation, + child: Container( + width: width, + height: _kTimePickerHeaderControlHeight, + child: Material( + clipBehavior: Clip.antiAlias, + color: Colors.transparent, + shape: shape, + child: Column( + children: [ + Expanded(child: amButton), + Container( + decoration: BoxDecoration( + border: Border(top: borderSide), + ), + height: 1, + ), + Expanded(child: pmButton), + ], + ), + ), + ), + ); + break; + case Orientation.landscape: + result = _DayPeriodInputPadding( + minSize: const Size(0.0, kMinInteractiveDimension), + orientation: orientation, + child: Container( + height: 40.0, + child: Material( + clipBehavior: Clip.antiAlias, + color: Colors.transparent, + shape: shape, + child: Row( + children: [ + Expanded(child: amButton), + Container( + decoration: BoxDecoration( + border: Border(left: borderSide), + ), + width: 1, + ), + Expanded(child: pmButton), + ], + ), + ), + ), + ); + break; + } + return result; + } +} + +/// A widget to pad the area around the [_DayPeriodControl]'s inner [Material]. +class _DayPeriodInputPadding extends SingleChildRenderObjectWidget { + const _DayPeriodInputPadding({ + Key key, + Widget child, + this.minSize, + this.orientation, + }) : super(key: key, child: child); + + final Size minSize; + final Orientation orientation; + + @override + RenderObject createRenderObject(BuildContext context) { + return _RenderInputPadding(minSize, orientation); + } + + @override + void updateRenderObject( + BuildContext context, covariant _RenderInputPadding renderObject) { + renderObject.minSize = minSize; + } +} + +class _RenderInputPadding extends RenderShiftedBox { + _RenderInputPadding(this._minSize, this.orientation, [RenderBox child]) + : super(child); + + final Orientation orientation; + + Size get minSize => _minSize; + Size _minSize; + set minSize(Size value) { + if (_minSize == value) return; + _minSize = value; + markNeedsLayout(); + } + + @override + double computeMinIntrinsicWidth(double height) { + if (child != null) { + return math.max(child.getMinIntrinsicWidth(height), minSize.width); + } + return 0.0; + } + + @override + double computeMinIntrinsicHeight(double width) { + if (child != null) { + return math.max(child.getMinIntrinsicHeight(width), minSize.height); + } + return 0.0; + } + + @override + double computeMaxIntrinsicWidth(double height) { + if (child != null) { + return math.max(child.getMaxIntrinsicWidth(height), minSize.width); + } + return 0.0; + } + + @override + double computeMaxIntrinsicHeight(double width) { + if (child != null) { + return math.max(child.getMaxIntrinsicHeight(width), minSize.height); + } + return 0.0; + } + + @override + void performLayout() { + if (child != null) { + child.layout(constraints, parentUsesSize: true); + final width = math.max(child.size.width, minSize.width); + final height = math.max(child.size.height, minSize.height); + size = constraints.constrain(Size(width, height)); + final childParentData = child.parentData as BoxParentData; + childParentData.offset = + Alignment.center.alongOffset(size - child.size as Offset); + } else { + size = Size.zero; + } + } + + @override + bool hitTest(BoxHitTestResult result, {Offset position}) { + if (super.hitTest(result, position: position)) { + return true; + } + + if (position.dx < 0.0 || + position.dx > math.max(child.size.width, minSize.width) || + position.dy < 0.0 || + position.dy > math.max(child.size.height, minSize.height)) { + return false; + } + + var newPosition = child.size.center(Offset.zero); + switch (orientation) { + case Orientation.portrait: + if (position.dy > newPosition.dy) { + newPosition += const Offset(0.0, 1.0); + } else { + newPosition += const Offset(0.0, -1.0); + } + break; + case Orientation.landscape: + if (position.dx > newPosition.dx) { + newPosition += const Offset(1.0, 0.0); + } else { + newPosition += const Offset(-1.0, 0.0); + } + break; + } + + return result.addWithRawTransform( + transform: MatrixUtils.forceToPoint(newPosition), + position: newPosition, + hitTest: (result, position) { + assert(position == newPosition); + return child.hitTest(result, position: newPosition); + }, + ); + } +} + +class _TappableLabel { + _TappableLabel({ + @required this.value, + @required this.painter, + @required this.onTap, + }); + + /// The value this label is displaying. + final int value; + + /// Paints the text of the label. + final TextPainter painter; + + /// Called when a tap gesture is detected on the label. + final VoidCallback onTap; +} + +class _DialPainter extends CustomPainter { + _DialPainter({ + @required this.primaryLabels, + @required this.secondaryLabels, + @required this.backgroundColor, + @required this.accentColor, + @required this.dotColor, + @required this.theta, + @required this.textDirection, + @required this.selectedValue, + }) : super(repaint: PaintingBinding.instance.systemFonts); + + final List<_TappableLabel> primaryLabels; + final List<_TappableLabel> secondaryLabels; + final Color backgroundColor; + final Color accentColor; + final Color dotColor; + final double theta; + final TextDirection textDirection; + final int selectedValue; + + static const double _labelPadding = 28.0; + + @override + void paint(Canvas canvas, Size size) { + final radius = size.shortestSide / 2.0; + final center = Offset(size.width / 2.0, size.height / 2.0); + final centerPoint = center; + canvas.drawCircle(centerPoint, radius, Paint()..color = backgroundColor); + + final labelRadius = radius - _labelPadding; + Offset getOffsetForTheta(double theta) { + return center + + Offset(labelRadius * math.cos(theta), -labelRadius * math.sin(theta)); + } + + void paintLabels(List<_TappableLabel> labels) { + if (labels == null) return; + final labelThetaIncrement = -_kTwoPi / labels.length; + var labelTheta = math.pi / 2.0; + + for (final label in labels) { + final labelPainter = label.painter; + final labelOffset = + Offset(-labelPainter.width / 2.0, -labelPainter.height / 2.0); + labelPainter.paint(canvas, getOffsetForTheta(labelTheta) + labelOffset); + labelTheta += labelThetaIncrement; + } + } + + paintLabels(primaryLabels); + + final selectorPaint = Paint()..color = accentColor; + final focusedPoint = getOffsetForTheta(theta); + const focusedRadius = _labelPadding - 4.0; + canvas.drawCircle(centerPoint, 4.0, selectorPaint); + canvas.drawCircle(focusedPoint, focusedRadius, selectorPaint); + selectorPaint.strokeWidth = 2.0; + canvas.drawLine(centerPoint, focusedPoint, selectorPaint); + + // Add a dot inside the selector but only when it isn't over the labels. + // This checks that the selector's theta is between two labels. A remainder + // between 0.1 and 0.45 indicates that the selector is roughly not above any + // labels. The values were derived by manually testing the dial. + final labelThetaIncrement = -_kTwoPi / primaryLabels.length; + if (theta % labelThetaIncrement > 0.1 && + theta % labelThetaIncrement < 0.45) { + canvas.drawCircle(focusedPoint, 2.0, selectorPaint..color = dotColor); + } + + final focusedRect = Rect.fromCircle( + center: focusedPoint, + radius: focusedRadius, + ); + canvas + ..save() + ..clipPath(Path()..addOval(focusedRect)); + paintLabels(secondaryLabels); + canvas.restore(); + } + + @override + bool shouldRepaint(_DialPainter oldPainter) { + return oldPainter.primaryLabels != primaryLabels || + oldPainter.secondaryLabels != secondaryLabels || + oldPainter.backgroundColor != backgroundColor || + oldPainter.accentColor != accentColor || + oldPainter.theta != theta; + } +} + +class _Dial extends StatefulWidget { + const _Dial({ + @required this.selectedTime, + @required this.mode, + @required this.use24HourDials, + @required this.onChanged, + @required this.onHourSelected, + }) : assert(selectedTime != null), + assert(mode != null), + assert(use24HourDials != null); + + final TimeOfDay selectedTime; + final _TimePickerMode mode; + final bool use24HourDials; + final ValueChanged onChanged; + final VoidCallback onHourSelected; + + @override + _DialState createState() => _DialState(); +} + +class _DialState extends State<_Dial> with SingleTickerProviderStateMixin { + @override + void initState() { + super.initState(); + _thetaController = AnimationController( + vsync: this, + duration: _kDialAnimateDuration, + ); + _thetaTween = Tween(begin: _getThetaForTime(widget.selectedTime)); + _theta = _thetaController + .drive(CurveTween(curve: Curves.easeInSine)) + .drive(_thetaTween) + ..addListener(() => setState(() {/* _theta.value has changed */})); + } + + ThemeData themeData; + MaterialLocalizations localizations; + MediaQueryData media; + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + assert(debugCheckHasMediaQuery(context)); + themeData = Theme.of(context); + localizations = MaterialLocalizations.of(context); + media = MediaQuery.of(context); + } + + @override + void didUpdateWidget(_Dial oldWidget) { + super.didUpdateWidget(oldWidget); + if (widget.mode != oldWidget.mode || + widget.selectedTime != oldWidget.selectedTime) { + if (!_dragging) _animateTo(_getThetaForTime(widget.selectedTime)); + } + } + + @override + void dispose() { + _thetaController.dispose(); + super.dispose(); + } + + Tween _thetaTween; + Animation _theta; + AnimationController _thetaController; + bool _dragging = false; + + static double _nearest(double target, double a, double b) { + return ((target - a).abs() < (target - b).abs()) ? a : b; + } + + void _animateTo(double targetTheta) { + final currentTheta = _theta.value; + var beginTheta = + _nearest(targetTheta, currentTheta, currentTheta + _kTwoPi); + beginTheta = _nearest(targetTheta, beginTheta, currentTheta - _kTwoPi); + _thetaTween + ..begin = beginTheta + ..end = targetTheta; + _thetaController + ..value = 0.0 + ..forward(); + } + + double _getThetaForTime(TimeOfDay time) { + final hoursFactor = widget.use24HourDials + ? TimeOfDay.hoursPerDay + : TimeOfDay.hoursPerPeriod; + final fraction = widget.mode == _TimePickerMode.hour + ? (time.hour / hoursFactor) % hoursFactor + : (time.minute / TimeOfDay.minutesPerHour) % TimeOfDay.minutesPerHour; + return (math.pi / 2.0 - fraction * _kTwoPi) % _kTwoPi; + } + + TimeOfDay _getTimeForTheta(double theta, {bool roundMinutes = false}) { + final fraction = (0.25 - (theta % _kTwoPi) / _kTwoPi) % 1.0; + if (widget.mode == _TimePickerMode.hour) { + int newHour; + if (widget.use24HourDials) { + newHour = + (fraction * TimeOfDay.hoursPerDay).round() % TimeOfDay.hoursPerDay; + } else { + newHour = (fraction * TimeOfDay.hoursPerPeriod).round() % + TimeOfDay.hoursPerPeriod; + newHour = newHour + widget.selectedTime.periodOffset; + } + return widget.selectedTime.replacing(hour: newHour); + } else { + var minute = (fraction * TimeOfDay.minutesPerHour).round() % + TimeOfDay.minutesPerHour; + if (roundMinutes) { + // Round the minutes to nearest 5 minute interval. + minute = ((minute + 2) ~/ 5) * 5 % TimeOfDay.minutesPerHour; + } + return widget.selectedTime.replacing(minute: minute); + } + } + + TimeOfDay _notifyOnChangedIfNeeded({bool roundMinutes = false}) { + final current = _getTimeForTheta(_theta.value, roundMinutes: roundMinutes); + if (widget.onChanged == null) return current; + if (current != widget.selectedTime) widget.onChanged(current); + return current; + } + + void _updateThetaForPan({bool roundMinutes = false}) { + setState(() { + final offset = _position - _center; + var angle = (math.atan2(offset.dx, offset.dy) - math.pi / 2.0) % _kTwoPi; + if (roundMinutes) { + angle = _getThetaForTime( + _getTimeForTheta(angle, roundMinutes: roundMinutes)); + } + _thetaTween + ..begin = angle + ..end = angle; // The controller doesn't animate during the pan gesture. + }); + } + + Offset _position; + Offset _center; + + void _handlePanStart(DragStartDetails details) { + assert(!_dragging); + _dragging = true; + final box = context.findRenderObject() as RenderBox; + _position = box.globalToLocal(details.globalPosition); + _center = box.size.center(Offset.zero); + _updateThetaForPan(); + _notifyOnChangedIfNeeded(); + } + + void _handlePanUpdate(DragUpdateDetails details) { + _position += details.delta; + _updateThetaForPan(); + _notifyOnChangedIfNeeded(); + } + + void _handlePanEnd(DragEndDetails details) { + assert(_dragging); + _dragging = false; + _position = null; + _center = null; + _animateTo(_getThetaForTime(widget.selectedTime)); + if (widget.mode == _TimePickerMode.hour) { + if (widget.onHourSelected != null) { + widget.onHourSelected(); + } + } + } + + void _handleTapUp(TapUpDetails details) { + final box = context.findRenderObject() as RenderBox; + _position = box.globalToLocal(details.globalPosition); + _center = box.size.center(Offset.zero); + _updateThetaForPan(roundMinutes: true); + final newTime = _notifyOnChangedIfNeeded(roundMinutes: true); + if (widget.mode == _TimePickerMode.hour) { + if (widget.use24HourDials) { + _announceToAccessibility( + context, localizations.formatDecimal(newTime.hour)); + } else { + _announceToAccessibility( + context, localizations.formatDecimal(newTime.hourOfPeriod)); + } + if (widget.onHourSelected != null) { + widget.onHourSelected(); + } + } else { + _announceToAccessibility( + context, localizations.formatDecimal(newTime.minute)); + } + _animateTo( + _getThetaForTime(_getTimeForTheta(_theta.value, roundMinutes: true))); + _dragging = false; + _position = null; + _center = null; + } + + void _selectHour(int hour) { + _announceToAccessibility(context, localizations.formatDecimal(hour)); + TimeOfDay time; + if (widget.mode == _TimePickerMode.hour && widget.use24HourDials) { + time = TimeOfDay(hour: hour, minute: widget.selectedTime.minute); + } else { + if (widget.selectedTime.period == DayPeriod.am) { + time = TimeOfDay(hour: hour, minute: widget.selectedTime.minute); + } else { + time = TimeOfDay( + hour: hour + TimeOfDay.hoursPerPeriod, + minute: widget.selectedTime.minute); + } + } + final angle = _getThetaForTime(time); + _thetaTween + ..begin = angle + ..end = angle; + _notifyOnChangedIfNeeded(); + } + + void _selectMinute(int minute) { + _announceToAccessibility(context, localizations.formatDecimal(minute)); + final time = TimeOfDay( + hour: widget.selectedTime.hour, + minute: minute, + ); + final angle = _getThetaForTime(time); + _thetaTween + ..begin = angle + ..end = angle; + _notifyOnChangedIfNeeded(); + } + + static const List _amHours = [ + TimeOfDay(hour: 12, minute: 0), + TimeOfDay(hour: 1, minute: 0), + TimeOfDay(hour: 2, minute: 0), + TimeOfDay(hour: 3, minute: 0), + TimeOfDay(hour: 4, minute: 0), + TimeOfDay(hour: 5, minute: 0), + TimeOfDay(hour: 6, minute: 0), + TimeOfDay(hour: 7, minute: 0), + TimeOfDay(hour: 8, minute: 0), + TimeOfDay(hour: 9, minute: 0), + TimeOfDay(hour: 10, minute: 0), + TimeOfDay(hour: 11, minute: 0), + ]; + + static const List _twentyFourHours = [ + TimeOfDay(hour: 0, minute: 0), + TimeOfDay(hour: 2, minute: 0), + TimeOfDay(hour: 4, minute: 0), + TimeOfDay(hour: 6, minute: 0), + TimeOfDay(hour: 8, minute: 0), + TimeOfDay(hour: 10, minute: 0), + TimeOfDay(hour: 12, minute: 0), + TimeOfDay(hour: 14, minute: 0), + TimeOfDay(hour: 16, minute: 0), + TimeOfDay(hour: 18, minute: 0), + TimeOfDay(hour: 20, minute: 0), + TimeOfDay(hour: 22, minute: 0), + ]; + + _TappableLabel _buildTappableLabel(TextTheme textTheme, Color color, + int value, String label, VoidCallback onTap) { + final style = textTheme.subtitle1.copyWith(color: color); + final labelScaleFactor = + math.min(MediaQuery.of(context).textScaleFactor, 2.0); + return _TappableLabel( + value: value, + painter: TextPainter( + text: TextSpan(style: style, text: label), + textDirection: TextDirection.ltr, + textScaleFactor: labelScaleFactor, + )..layout(), + onTap: onTap, + ); + } + + List<_TappableLabel> _build24HourRing(TextTheme textTheme, Color color) => + <_TappableLabel>[ + for (final TimeOfDay timeOfDay in _twentyFourHours) + _buildTappableLabel( + textTheme, + color, + timeOfDay.hour, + localizations.formatHour(timeOfDay, + alwaysUse24HourFormat: media.alwaysUse24HourFormat), + () { + _selectHour(timeOfDay.hour); + }, + ), + ]; + + List<_TappableLabel> _build12HourRing(TextTheme textTheme, Color color) => + <_TappableLabel>[ + for (final TimeOfDay timeOfDay in _amHours) + _buildTappableLabel( + textTheme, + color, + timeOfDay.hour, + localizations.formatHour(timeOfDay, + alwaysUse24HourFormat: media.alwaysUse24HourFormat), + () { + _selectHour(timeOfDay.hour); + }, + ), + ]; + + List<_TappableLabel> _buildMinutes(TextTheme textTheme, Color color) { + const _minuteMarkerValues = [ + TimeOfDay(hour: 0, minute: 0), + TimeOfDay(hour: 0, minute: 5), + TimeOfDay(hour: 0, minute: 10), + TimeOfDay(hour: 0, minute: 15), + TimeOfDay(hour: 0, minute: 20), + TimeOfDay(hour: 0, minute: 25), + TimeOfDay(hour: 0, minute: 30), + TimeOfDay(hour: 0, minute: 35), + TimeOfDay(hour: 0, minute: 40), + TimeOfDay(hour: 0, minute: 45), + TimeOfDay(hour: 0, minute: 50), + TimeOfDay(hour: 0, minute: 55), + ]; + + return <_TappableLabel>[ + for (final TimeOfDay timeOfDay in _minuteMarkerValues) + _buildTappableLabel( + textTheme, + color, + timeOfDay.minute, + localizations.formatMinute(timeOfDay), + () { + _selectMinute(timeOfDay.minute); + }, + ), + ]; + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final pickerTheme = TimePickerTheme.of(context); + final backgroundColor = pickerTheme.dialBackgroundColor ?? + themeData.colorScheme.onBackground.withOpacity(0.12); + final accentColor = pickerTheme.dialHandColor ?? themeData.accentColor; + final primaryLabelColor = MaterialStateProperty.resolveAs( + pickerTheme.dialTextColor, {}); + final secondaryLabelColor = MaterialStateProperty.resolveAs( + pickerTheme.dialTextColor, {MaterialState.selected}); + List<_TappableLabel> primaryLabels; + List<_TappableLabel> secondaryLabels; + int selectedDialValue; + switch (widget.mode) { + case _TimePickerMode.hour: + if (widget.use24HourDials) { + selectedDialValue = widget.selectedTime.hour; + primaryLabels = _build24HourRing(theme.textTheme, primaryLabelColor); + secondaryLabels = + _build24HourRing(theme.accentTextTheme, secondaryLabelColor); + } else { + selectedDialValue = widget.selectedTime.hourOfPeriod; + primaryLabels = _build12HourRing(theme.textTheme, primaryLabelColor); + secondaryLabels = + _build12HourRing(theme.accentTextTheme, secondaryLabelColor); + } + break; + case _TimePickerMode.minute: + selectedDialValue = widget.selectedTime.minute; + primaryLabels = _buildMinutes(theme.textTheme, primaryLabelColor); + secondaryLabels = + _buildMinutes(theme.accentTextTheme, secondaryLabelColor); + break; + } + + return GestureDetector( + excludeFromSemantics: true, + onPanStart: _handlePanStart, + onPanUpdate: _handlePanUpdate, + onPanEnd: _handlePanEnd, + onTapUp: _handleTapUp, + child: CustomPaint( + key: const ValueKey('time-picker-dial'), + painter: _DialPainter( + selectedValue: selectedDialValue, + primaryLabels: primaryLabels, + secondaryLabels: secondaryLabels, + backgroundColor: backgroundColor, + accentColor: accentColor, + dotColor: theme.colorScheme.surface, + theta: _theta.value, + textDirection: Directionality.of(context), + ), + ), + ); + } +} + +class _TimePickerInput extends StatefulWidget { + const _TimePickerInput({ + Key key, + @required this.initialSelectedTime, + @required this.helpText, + @required this.onChanged, + }) : assert(initialSelectedTime != null), + assert(onChanged != null), + super(key: key); + + /// The time initially selected when the dialog is shown. + final TimeOfDay initialSelectedTime; + + /// Optionally provide your own help text to the time picker. + final String helpText; + + final ValueChanged onChanged; + + @override + _TimePickerInputState createState() => _TimePickerInputState(); +} + +class _TimePickerInputState extends State<_TimePickerInput> { + TimeOfDay _selectedTime; + bool hourHasError = false; + bool minuteHasError = false; + + @override + void initState() { + super.initState(); + _selectedTime = widget.initialSelectedTime; + } + + int _parseHour(String value) { + if (value == null) { + return null; + } + + var newHour = int.tryParse(value); + if (newHour == null) { + return null; + } + + if (MediaQuery.of(context).alwaysUse24HourFormat) { + if (newHour >= 0 && newHour < 24) { + return newHour; + } + } else { + if (newHour > 0 && newHour < 13) { + if ((_selectedTime.period == DayPeriod.pm && newHour != 12) || + (_selectedTime.period == DayPeriod.am && newHour == 12)) { + newHour = + (newHour + TimeOfDay.hoursPerPeriod) % TimeOfDay.hoursPerDay; + } + return newHour; + } + } + return null; + } + + int _parseMinute(String value) { + if (value == null) { + return null; + } + + final newMinute = int.tryParse(value); + if (newMinute == null) { + return null; + } + + if (newMinute >= 0 && newMinute < 60) { + return newMinute; + } + return null; + } + + void _handleHourSavedSubmitted(String value) { + final newHour = _parseHour(value); + if (newHour != null) { + _selectedTime = TimeOfDay(hour: newHour, minute: _selectedTime.minute); + widget.onChanged(_selectedTime); + } + } + + void _handleHourChanged(String value) { + final newHour = _parseHour(value); + if (newHour != null && value.length == 2) { + // If a valid hour is typed, move focus to the minute TextField. + FocusScope.of(context).nextFocus(); + } + } + + void _handleMinuteSavedSubmitted(String value) { + final newMinute = _parseMinute(value); + if (newMinute != null) { + _selectedTime = + TimeOfDay(hour: _selectedTime.hour, minute: int.parse(value)); + widget.onChanged(_selectedTime); + } + } + + void _handleDayPeriodChanged(TimeOfDay value) { + _selectedTime = value; + widget.onChanged(_selectedTime); + } + + String _validateHour(String value) { + final newHour = _parseHour(value); + setState(() { + hourHasError = newHour == null; + }); + // This is used as the validator for the [TextFormField]. + // Returning an empty string allows the field to go into an error state. + // Returning null means no error in the validation of the entered text. + return newHour == null ? '' : null; + } + + String _validateMinute(String value) { + final newMinute = _parseMinute(value); + setState(() { + minuteHasError = newMinute == null; + }); + // This is used as the validator for the [TextFormField]. + // Returning an empty string allows the field to go into an error state. + // Returning null means no error in the validation of the entered text. + return newMinute == null ? '' : null; + } + + @override + Widget build(BuildContext context) { + assert(debugCheckHasMediaQuery(context)); + final media = MediaQuery.of(context); + final timeOfDayFormat = MaterialLocalizations.of(context) + .timeOfDayFormat(alwaysUse24HourFormat: media.alwaysUse24HourFormat); + final use24HourDials = hourFormat(of: timeOfDayFormat) != HourFormat.h; + final theme = Theme.of(context); + final hourMinuteStyle = TimePickerTheme.of(context).hourMinuteTextStyle ?? + theme.textTheme.headline2; + + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 16.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + widget.helpText ?? + MaterialLocalizations.of(context).timePickerInputHelpText, + style: TimePickerTheme.of(context).helpTextStyle ?? + theme.textTheme.overline, + ), + const SizedBox(height: 16.0), + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (!use24HourDials && + timeOfDayFormat == + TimeOfDayFormat.a_space_h_colon_mm) ...[ + _DayPeriodControl( + selectedTime: _selectedTime, + orientation: Orientation.portrait, + onChanged: _handleDayPeriodChanged, + ), + const SizedBox(width: 12.0), + ], + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const SizedBox(height: 8.0), + _HourMinuteTextField( + selectedTime: _selectedTime, + isHour: true, + style: hourMinuteStyle, + validator: _validateHour, + onSavedSubmitted: _handleHourSavedSubmitted, + onChanged: _handleHourChanged, + ), + const SizedBox(height: 8.0), + if (!hourHasError && !minuteHasError) + ExcludeSemantics( + child: Text( + MaterialLocalizations.of(context).timePickerHourLabel, + style: theme.textTheme.caption, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + ], + )), + Container( + margin: const EdgeInsets.only(top: 8.0), + height: _kTimePickerHeaderControlHeight, + child: _StringFragment(timeOfDayFormat: timeOfDayFormat), + ), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const SizedBox(height: 8.0), + _HourMinuteTextField( + selectedTime: _selectedTime, + isHour: false, + style: hourMinuteStyle, + validator: _validateMinute, + onSavedSubmitted: _handleMinuteSavedSubmitted, + ), + const SizedBox(height: 8.0), + if (!hourHasError && !minuteHasError) + ExcludeSemantics( + child: Text( + MaterialLocalizations.of(context).timePickerMinuteLabel, + style: theme.textTheme.caption, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + ], + )), + if (!use24HourDials && + timeOfDayFormat != + TimeOfDayFormat.a_space_h_colon_mm) ...[ + const SizedBox(width: 12.0), + _DayPeriodControl( + selectedTime: _selectedTime, + orientation: Orientation.portrait, + onChanged: _handleDayPeriodChanged, + ), + ], + ], + ), + if (hourHasError || minuteHasError) + Text( + MaterialLocalizations.of(context).invalidTimeLabel, + style: theme.textTheme.bodyText2 + .copyWith(color: theme.colorScheme.error), + ) + else + const SizedBox(height: 2.0), + ], + ), + ); + } +} + +class _HourMinuteTextField extends StatefulWidget { + const _HourMinuteTextField({ + Key key, + @required this.selectedTime, + @required this.isHour, + @required this.style, + @required this.validator, + @required this.onSavedSubmitted, + this.onChanged, + }) : super(key: key); + + final TimeOfDay selectedTime; + final bool isHour; + final TextStyle style; + final FormFieldValidator validator; + final ValueChanged onSavedSubmitted; + final ValueChanged onChanged; + + @override + _HourMinuteTextFieldState createState() => _HourMinuteTextFieldState(); +} + +class _HourMinuteTextFieldState extends State<_HourMinuteTextField> { + TextEditingController controller; + FocusNode focusNode; + + @override + void initState() { + super.initState(); + focusNode = FocusNode() + ..addListener(() { + setState(() {}); // Rebuild. + }); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + controller ??= TextEditingController(text: _formattedValue); + } + + String get _formattedValue { + final alwaysUse24HourFormat = MediaQuery.of(context).alwaysUse24HourFormat; + final localizations = MaterialLocalizations.of(context); + return !widget.isHour + ? localizations.formatMinute(widget.selectedTime) + : localizations.formatHour( + widget.selectedTime, + alwaysUse24HourFormat: alwaysUse24HourFormat, + ); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final timePickerTheme = TimePickerTheme.of(context); + final colorScheme = theme.colorScheme; + + final inputDecorationTheme = timePickerTheme.inputDecorationTheme; + InputDecoration inputDecoration; + if (inputDecorationTheme != null) { + inputDecoration = + const InputDecoration().applyDefaults(inputDecorationTheme); + } else { + final unfocusedFillColor = timePickerTheme.hourMinuteColor ?? + colorScheme.onSurface.withOpacity(0.12); + inputDecoration = InputDecoration( + contentPadding: EdgeInsets.zero, + filled: true, + fillColor: focusNode.hasFocus ? Colors.transparent : unfocusedFillColor, + enabledBorder: const OutlineInputBorder( + borderSide: BorderSide(color: Colors.transparent), + ), + errorBorder: OutlineInputBorder( + borderSide: BorderSide(color: colorScheme.error, width: 2.0), + ), + focusedBorder: OutlineInputBorder( + borderSide: BorderSide(color: colorScheme.primary, width: 2.0), + ), + focusedErrorBorder: OutlineInputBorder( + borderSide: BorderSide(color: colorScheme.error, width: 2.0), + ), + hintStyle: widget.style + .copyWith(color: colorScheme.onSurface.withOpacity(0.36)), + // TODO(rami-a): Remove this logic once https://github.com/flutter/flutter/issues/54104 is fixed. + errorStyle: const TextStyle( + fontSize: 0.0, + height: 0.0), // Prevent the error text from appearing. + ); + } + inputDecoration = inputDecoration.copyWith( + // Remove the hint text when focused because the centered cursor appears + // odd above the hint text. + hintText: focusNode.hasFocus ? null : _formattedValue, + ); + + return SizedBox( + height: _kTimePickerHeaderControlHeight, + child: MediaQuery( + data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0), + child: TextFormField( + expands: true, + maxLines: null, + focusNode: focusNode, + textAlign: TextAlign.center, + keyboardType: TextInputType.number, + style: widget.style.copyWith(color: colorScheme.onSurface), + controller: controller, + decoration: inputDecoration, + validator: widget.validator, + onEditingComplete: () => widget.onSavedSubmitted(controller.text), + onSaved: widget.onSavedSubmitted, + onFieldSubmitted: widget.onSavedSubmitted, + onChanged: widget.onChanged, + ), + ), + ); + } +} + +/// A material design time picker designed to appear inside a popup dialog. +/// +/// Pass this widget to [showDialog]. The value returned by [showDialog] is the +/// selected [TimeOfDay] if the user taps the "OK" button, or null if the user +/// taps the "CANCEL" button. The selected time is reported by calling +/// [Navigator.pop]. +class _TimePickerDialog extends StatefulWidget { + /// Creates a material time picker. + /// + /// [initialTime] must not be null. + const _TimePickerDialog({ + Key key, + @required this.initialTime, + @required this.cancelText, + @required this.confirmText, + @required this.helpText, + this.initialEntryMode = TimePickerEntryMode.dial, + }) : assert(initialTime != null), + super(key: key); + + /// The time initially selected when the dialog is shown. + final TimeOfDay initialTime; + + /// The entry mode for the picker. Whether it's text input or a dial. + final TimePickerEntryMode initialEntryMode; + + /// Optionally provide your own text for the cancel button. + /// + /// If null, the button uses [MaterialLocalizations.cancelButtonLabel]. + final String cancelText; + + /// Optionally provide your own text for the confirm button. + /// + /// If null, the button uses [MaterialLocalizations.okButtonLabel]. + final String confirmText; + + /// Optionally provide your own help text to the header of the time picker. + final String helpText; + + @override + _TimePickerDialogState createState() => _TimePickerDialogState(); +} + +class _TimePickerDialogState extends State<_TimePickerDialog> { + final GlobalKey _formKey = GlobalKey(); + + @override + void initState() { + super.initState(); + _selectedTime = widget.initialTime; + _entryMode = widget.initialEntryMode; + _autoValidate = false; + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + localizations = MaterialLocalizations.of(context); + _announceInitialTimeOnce(); + _announceModeOnce(); + } + + TimePickerEntryMode _entryMode; + _TimePickerMode _mode = _TimePickerMode.hour; + _TimePickerMode _lastModeAnnounced; + bool _autoValidate; + + TimeOfDay get selectedTime => _selectedTime; + TimeOfDay _selectedTime; + + Timer _vibrateTimer; + MaterialLocalizations localizations; + + void _vibrate() { + switch (Theme.of(context).platform) { + case TargetPlatform.android: + case TargetPlatform.fuchsia: + case TargetPlatform.linux: + case TargetPlatform.windows: + _vibrateTimer?.cancel(); + _vibrateTimer = Timer(_kVibrateCommitDelay, () { + HapticFeedback.vibrate(); + _vibrateTimer = null; + }); + break; + case TargetPlatform.iOS: + case TargetPlatform.macOS: + break; + } + } + + void _handleModeChanged(_TimePickerMode mode) { + _vibrate(); + setState(() { + _mode = mode; + _announceModeOnce(); + }); + } + + void _handleEntryModeToggle() { + setState(() { + switch (_entryMode) { + case TimePickerEntryMode.dial: + _autoValidate = false; + _entryMode = TimePickerEntryMode.input; + break; + case TimePickerEntryMode.input: + _formKey.currentState.save(); + _entryMode = TimePickerEntryMode.dial; + break; + } + }); + } + + void _announceModeOnce() { + if (_lastModeAnnounced == _mode) { + // Already announced it. + return; + } + + switch (_mode) { + case _TimePickerMode.hour: + _announceToAccessibility( + context, localizations.timePickerHourModeAnnouncement); + break; + case _TimePickerMode.minute: + _announceToAccessibility( + context, localizations.timePickerMinuteModeAnnouncement); + break; + } + _lastModeAnnounced = _mode; + } + + bool _announcedInitialTime = false; + + void _announceInitialTimeOnce() { + if (_announcedInitialTime) return; + + final media = MediaQuery.of(context); + final localizations = MaterialLocalizations.of(context); + _announceToAccessibility( + context, + localizations.formatTimeOfDay(widget.initialTime, + alwaysUse24HourFormat: media.alwaysUse24HourFormat), + ); + _announcedInitialTime = true; + } + + void _handleTimeChanged(TimeOfDay value) { + _vibrate(); + setState(() { + _selectedTime = value; + }); + } + + void _handleHourSelected() { + setState(() { + _mode = _TimePickerMode.minute; + }); + } + + void _handleCancel() { + Navigator.pop(context); + } + + void _handleOk() { + if (_entryMode == TimePickerEntryMode.input) { + final form = _formKey.currentState; + if (!form.validate()) { + setState(() { + _autoValidate = true; + }); + return; + } + form.save(); + } + Navigator.pop(context, _selectedTime); + } + + Size _dialogSize(BuildContext context) { + final orientation = MediaQuery.of(context).orientation; + final theme = Theme.of(context); + // Constrain the textScaleFactor to prevent layout issues. Since only some + // parts of the time picker scale up with textScaleFactor, we cap the factor + // to 1.1 as that provides enough space to reasonably fit all the content. + final textScaleFactor = + math.min(MediaQuery.of(context).textScaleFactor, 1.1); + + double timePickerWidth; + double timePickerHeight; + switch (_entryMode) { + case TimePickerEntryMode.dial: + switch (orientation) { + case Orientation.portrait: + timePickerWidth = _kTimePickerWidthPortrait; + timePickerHeight = + theme.materialTapTargetSize == MaterialTapTargetSize.padded + ? _kTimePickerHeightPortrait + : _kTimePickerHeightPortraitCollapsed; + break; + case Orientation.landscape: + timePickerWidth = _kTimePickerWidthLandscape * textScaleFactor; + timePickerHeight = + theme.materialTapTargetSize == MaterialTapTargetSize.padded + ? _kTimePickerHeightLandscape + : _kTimePickerHeightLandscapeCollapsed; + break; + } + break; + case TimePickerEntryMode.input: + timePickerWidth = _kTimePickerWidthPortrait; + timePickerHeight = _kTimePickerHeightInput; + break; + } + return Size(timePickerWidth, timePickerHeight * textScaleFactor); + } + + @override + Widget build(BuildContext context) { + assert(debugCheckHasMediaQuery(context)); + final media = MediaQuery.of(context); + final timeOfDayFormat = localizations.timeOfDayFormat( + alwaysUse24HourFormat: media.alwaysUse24HourFormat); + final use24HourDials = hourFormat(of: timeOfDayFormat) != HourFormat.h; + final theme = Theme.of(context); + final shape = TimePickerTheme.of(context).shape ?? _kDefaultShape; + final orientation = media.orientation; + + final Widget actions = Row( + children: [ + const SizedBox(width: 10.0), + IconButton( + color: TimePickerTheme.of(context).entryModeIconColor ?? + theme.colorScheme.onSurface.withOpacity( + theme.colorScheme.brightness == Brightness.dark ? 1.0 : 0.6, + ), + onPressed: _handleEntryModeToggle, + icon: Icon(_entryMode == TimePickerEntryMode.dial + ? Icons.keyboard + : Icons.access_time), + tooltip: _entryMode == TimePickerEntryMode.dial + ? MaterialLocalizations.of(context).inputTimeModeButtonLabel + : MaterialLocalizations.of(context).dialModeButtonLabel, + ), + Expanded( + // TODO(rami-a): Move away from ButtonBar to avoid https://github.com/flutter/flutter/issues/53378. + child: ButtonBar( + layoutBehavior: ButtonBarLayoutBehavior.constrained, + children: [ + FlatButton( + onPressed: _handleCancel, + child: Text( + widget.cancelText ?? localizations.cancelButtonLabel, + style: TextStyle(color: Colors.grey[600]), + ), + ), + FlatButton( + onPressed: _handleOk, + child: Text( + widget.confirmText ?? localizations.okButtonLabel, + style: TextStyle(color: Theme.of(context).accentColor), + ), + ), + ], + ), + ), + ], + ); + + Widget picker; + switch (_entryMode) { + case TimePickerEntryMode.dial: + final Widget dial = Padding( + padding: orientation == Orientation.portrait + ? const EdgeInsets.symmetric(horizontal: 36, vertical: 24) + : const EdgeInsets.all(24), + child: ExcludeSemantics( + child: AspectRatio( + aspectRatio: 1.0, + child: _Dial( + mode: _mode, + use24HourDials: use24HourDials, + selectedTime: _selectedTime, + onChanged: _handleTimeChanged, + onHourSelected: _handleHourSelected, + ), + ), + ), + ); + + final Widget header = _TimePickerHeader( + selectedTime: _selectedTime, + mode: _mode, + orientation: orientation, + onModeChanged: _handleModeChanged, + onChanged: _handleTimeChanged, + use24HourDials: use24HourDials, + helpText: widget.helpText, + ); + + switch (orientation) { + case Orientation.portrait: + picker = Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + header, + Expanded( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + // Dial grows and shrinks with the available space. + Expanded(child: dial), + actions, + ], + ), + ), + ], + ); + break; + case Orientation.landscape: + picker = Column( + children: [ + Expanded( + child: Row( + children: [ + header, + Expanded(child: dial), + ], + ), + ), + actions, + ], + ); + break; + } + break; + case TimePickerEntryMode.input: + picker = Form( + key: _formKey, + autovalidate: _autoValidate, + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + _TimePickerInput( + initialSelectedTime: _selectedTime, + helpText: widget.helpText, + onChanged: _handleTimeChanged, + ), + actions, + ], + ), + ), + ); + break; + } + + final dialogSize = _dialogSize(context); + return Dialog( + shape: shape, + elevation: 2, + backgroundColor: TimePickerTheme.of(context).backgroundColor ?? + theme.colorScheme.surface, + insetPadding: EdgeInsets.symmetric( + horizontal: 16.0, + vertical: _entryMode == TimePickerEntryMode.input ? 0.0 : 24.0, + ), + child: AnimatedContainer( + width: dialogSize.width, + height: dialogSize.height, + duration: _kDialogSizeAnimationDuration, + curve: Curves.easeIn, + child: picker, + ), + ); + } + + @override + void dispose() { + _vibrateTimer?.cancel(); + _vibrateTimer = null; + super.dispose(); + } +} + +/// Shows a dialog containing a material design time picker. +/// +/// The returned Future resolves to the time selected by the user when the user +/// closes the dialog. If the user cancels the dialog, null is returned. +/// +/// {@tool snippet} +/// Show a dialog with [initialTime] equal to the current time. +/// +/// ```dart +/// Future selectedTime = showTimePicker( +/// initialTime: TimeOfDay.now(), +/// context: context, +/// ); +/// ``` +/// {@end-tool} +/// +/// The [context], [useRootNavigator] and [routeSettings] arguments are passed to +/// [showDialog], the documentation for which discusses how it is used. +/// +/// The [builder] parameter can be used to wrap the dialog widget +/// to add inherited widgets like [Localizations.override], +/// [Directionality], or [MediaQuery]. +/// +/// The [entryMode] parameter can be used to +/// determine the initial time entry selection of the picker (either a clock +/// dial or text input). +/// +/// Optional strings for the [helpText], [cancelText], and [confirmText] can be +/// provided to override the default values. +/// +/// {@tool snippet} +/// Show a dialog with the text direction overridden to be [TextDirection.rtl]. +/// +/// ```dart +/// Future selectedTimeRTL = showTimePicker( +/// context: context, +/// initialTime: TimeOfDay.now(), +/// builder: (BuildContext context, Widget child) { +/// return Directionality( +/// textDirection: TextDirection.rtl, +/// child: child, +/// ); +/// }, +/// ); +/// ``` +/// {@end-tool} +/// +/// {@tool snippet} +/// Show a dialog with time unconditionally displayed in 24 hour format. +/// +/// ```dart +/// Future selectedTime24Hour = showTimePicker( +/// context: context, +/// initialTime: TimeOfDay(hour: 10, minute: 47), +/// builder: (BuildContext context, Widget child) { +/// return MediaQuery( +/// data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true), +/// child: child, +/// ); +/// }, +/// ); +/// ``` +/// {@end-tool} +/// +/// See also: +/// +/// * [showDatePicker], which shows a dialog that contains a material design +/// date picker. +Future showCustomTimePicker({ + @required BuildContext context, + @required TimeOfDay initialTime, + TransitionBuilder builder, + bool useRootNavigator = true, + TimePickerEntryMode initialEntryMode = TimePickerEntryMode.dial, + String cancelText, + String confirmText, + String helpText, + RouteSettings routeSettings, +}) async { + assert(context != null); + assert(initialTime != null); + assert(useRootNavigator != null); + assert(initialEntryMode != null); + assert(debugCheckHasMaterialLocalizations(context)); + + final Widget dialog = _TimePickerDialog( + initialTime: initialTime, + initialEntryMode: initialEntryMode, + cancelText: cancelText, + confirmText: confirmText, + helpText: helpText, + ); + return await showGeneralDialog( + context: context, + useRootNavigator: useRootNavigator, + routeSettings: routeSettings, + barrierDismissible: true, + barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel, + barrierColor: Colors.black54, + transitionDuration: const Duration(milliseconds: 200), + pageBuilder: (context, animaiton, secondaryAnimation) => + AnnotatedRegion( + value: SystemUiOverlayStyle( + statusBarIconBrightness: Brightness.light, + systemNavigationBarColor: + Theme.of(context).brightness == Brightness.light + ? Color.fromRGBO(113, 113, 113, 1) + : Color.fromRGBO(15, 15, 15, 1), + ), + child: Builder(builder: (context) { + return builder == null ? dialog : builder(context, dialog); + }), + //routeSettings: routeSettings, + ), + ); +} + +void _announceToAccessibility(BuildContext context, String message) { + SemanticsService.announce(message, Directionality.of(context)); +} diff --git a/lib/util/custom_widget.dart b/lib/util/custom_widget.dart index 11d1cb2..fcaf4ed 100644 --- a/lib/util/custom_widget.dart +++ b/lib/util/custom_widget.dart @@ -1,1222 +1,1222 @@ -import 'dart:math' as math; - -import 'package:flutter/material.dart'; - -import '../type/episodebrief.dart'; -import 'episodegrid.dart'; -import 'extension_helper.dart'; - -const kTwoPi = math.pi * 2; -const kPi = math.pi; -const kHalfPi = math.pi / 2; - -//Layout change indicator -class LayoutPainter extends CustomPainter { - double scale; - Color color; - LayoutPainter(this.scale, this.color); - @override - void paint(Canvas canvas, Size size) { - var _paint = Paint() - ..color = color - ..strokeWidth = 1.0 - ..style = PaintingStyle.stroke - ..strokeCap = StrokeCap.round; - - canvas.drawRect(Rect.fromLTRB(0, 0, 10 + 5 * scale, 10), _paint); - if (scale < 4) { - canvas.drawRect( - Rect.fromLTRB(10 + 5 * scale, 0, 20 + 10 * scale, 10), _paint); - canvas.drawRect( - Rect.fromLTRB(20 + 5 * scale, 0, 30, 10 - 10 * scale), _paint); - } - } - - @override - bool shouldRepaint(LayoutPainter oldDelegate) { - return oldDelegate.scale != scale || oldDelegate.color != color; - } -} - -/// Multi select button. -class MultiSelectPainter extends CustomPainter { - Color color; - MultiSelectPainter({@required this.color}); - @override - void paint(Canvas canvas, Size size) { - var paint = Paint() - ..color = color - ..strokeWidth = 1.0 - ..style = PaintingStyle.fill - ..strokeCap = StrokeCap.round; - final x = size.width / 2; - final y = size.height / 2; - var path = Path(); - path.moveTo(0, 0); - path.lineTo(x, 0); - path.lineTo(x, y * 2); - path.lineTo(x * 2, y * 2); - path.lineTo(x * 2, y); - path.lineTo(0, y); - path.lineTo(0, 0); - path.close(); - canvas.drawPath(path, paint); - } - - @override - bool shouldRepaint(MultiSelectPainter oldDelegate) { - return false; - } -} - -//Dark sky used in sleep timer -class StarSky extends CustomPainter { - @override - void paint(Canvas canvas, Size size) { - final points = [ - Offset(50, 100), - Offset(150, 75), - Offset(250, 250), - Offset(130, 200), - Offset(270, 150), - ]; - final pisces = [ - Offset(9, 4), - Offset(11, 5), - Offset(7, 6), - Offset(10, 7), - Offset(8, 8), - Offset(9, 13), - Offset(12, 17), - Offset(5, 19), - Offset(7, 19) - ].map((e) => e * 10).toList(); - final orion = [ - Offset(3, 1), - Offset(6, 1), - Offset(1, 4), - Offset(2, 4), - Offset(2, 7), - Offset(10, 8), - Offset(3, 10), - Offset(8, 10), - Offset(19, 11), - Offset(11, 13), - Offset(18, 14), - Offset(5, 19), - Offset(7, 19), - Offset(9, 18), - Offset(15, 19), - Offset(16, 18), - Offset(2, 25), - Offset(10, 26) - ].map((e) => Offset(e.dx * 10 + 250, e.dy * 10)).toList(); - - var paint = Paint() - ..color = Colors.white - ..strokeWidth = 2.0 - ..strokeCap = StrokeCap.round; - var _fullPaint = Paint() - ..color = Colors.white - ..strokeWidth = 1.0 - ..strokeCap = StrokeCap.butt - ..style = PaintingStyle.fill; - _darwStar(Offset center, double radius) { - canvas.drawCircle(center, radius, paint); - var path = Path() - ..addOval(Rect.fromCircle(center: center, radius: radius * 2)); - canvas.drawShadow(path.shift(Offset(0, -6)), Colors.white, 6, true); - } - - _darwBigStar(Offset center, double radius) { - var path = Path(); - path.moveTo(center.dx - radius * 1.5, center.dy); - path.quadraticBezierTo(center.dx - radius * 0.2, center.dy - radius * 0.2, - center.dx, center.dy - radius * 2); - path.quadraticBezierTo(center.dx + radius * 0.2, center.dy - radius * 0.2, - center.dx + radius * 1.5, center.dy); - path.quadraticBezierTo(center.dx + radius * 0.2, center.dy + radius * 0.2, - center.dx, center.dy + radius * 2); - path.quadraticBezierTo(center.dx - radius * 0.2, center.dy + radius * 0.2, - center.dx - radius * 1.5, center.dy); - path.close(); - - canvas.drawPath(path, _fullPaint); - canvas.drawShadow(path.shift(Offset(0, -6)), Colors.white, 10, true); - } - - for (var center in pisces) { - _darwStar(center, 2); - } - for (var center in orion) { - _darwStar(center, 2); - } - for (var center in points) { - _darwBigStar(center, 4); - _darwStar(center, 2); - } - } - - @override - bool shouldRepaint(StarSky oldDelegate) { - return false; - } -} - -//Listened indicator -class ListenedPainter extends CustomPainter { - final Color _color; - double stroke; - ListenedPainter(this._color, {this.stroke = 1.0}); - @override - void paint(Canvas canvas, Size size) { - var _paint = Paint() - ..color = _color - ..strokeWidth = stroke - ..strokeCap = StrokeCap.round - ..style = PaintingStyle.stroke; - var _path = Path(); - _path.moveTo(size.width / 6, size.height * 3 / 8); - _path.lineTo(size.width / 6, size.height * 5 / 8); - _path.moveTo(size.width / 3, size.height / 4); - _path.lineTo(size.width / 3, size.height * 3 / 4); - _path.moveTo(size.width / 2, size.height / 8); - _path.lineTo(size.width / 2, size.height * 7 / 8); - _path.moveTo(size.width * 5 / 6, size.height * 3 / 8); - _path.lineTo(size.width * 5 / 6, size.height * 5 / 8); - _path.moveTo(size.width * 2 / 3, size.height / 4); - _path.lineTo(size.width * 2 / 3, size.height * 3 / 4); - - canvas.drawPath(_path, _paint); - } - - @override - bool shouldRepaint(ListenedPainter oldDelegate) { - return false; - } -} - -//Listened Completely indicator -class ListenedAllPainter extends CustomPainter { - final Color color; - final double stroke; - ListenedAllPainter(this.color, {this.stroke = 1.0}); - @override - void paint(Canvas canvas, Size size) { - var _paint = Paint() - ..color = color - ..strokeWidth = stroke - ..strokeCap = StrokeCap.round - ..style = PaintingStyle.stroke; - var _path = Path(); - _path.moveTo(size.width / 6, size.height * 3 / 8); - _path.lineTo(size.width / 6, size.height * 5 / 8); - _path.moveTo(size.width / 3, size.height / 4); - _path.lineTo(size.width / 3, size.height * 3 / 4); - _path.moveTo(size.width / 2, size.height * 3 / 8); - _path.lineTo(size.width / 2, size.height * 5 / 8); - _path.moveTo(size.width * 2 / 3, size.height * 4 / 9); - _path.lineTo(size.width * 2 / 3, size.height * 5 / 9); - _path.moveTo(size.width / 2, size.height * 3 / 4); - _path.lineTo(size.width * 2 / 3, size.height * 7 / 8); - _path.lineTo(size.width * 7 / 8, size.height * 5 / 8); - - canvas.drawPath(_path, _paint); - } - - @override - bool shouldRepaint(ListenedAllPainter oldDelegate) { - return false; - } -} - -//Mark Listened indicator -class MarkListenedPainter extends CustomPainter { - final Color color; - double stroke; - MarkListenedPainter(this.color, {this.stroke = 1.0}); - @override - void paint(Canvas canvas, Size size) { - var _paint = Paint() - ..color = color - ..strokeWidth = stroke - ..strokeCap = StrokeCap.round - ..style = PaintingStyle.stroke; - var _path = Path(); - _path.moveTo(size.width / 6, size.height * 3 / 8); - _path.lineTo(size.width / 6, size.height * 5 / 8); - _path.moveTo(size.width / 3, size.height / 4); - _path.lineTo(size.width / 3, size.height * 3 / 4); - _path.moveTo(size.width / 2, size.height * 3 / 8); - _path.lineTo(size.width / 2, size.height * 5 / 8); - // _path.moveTo(size.width * 2 / 3, size.height * 4 / 9); - // _path.lineTo(size.width * 2 / 3, size.height * 5 / 9); - _path.moveTo(size.width / 2, size.height * 13 / 18); - _path.lineTo(size.width * 5 / 6, size.height * 13 / 18); - _path.moveTo(size.width * 2 / 3, size.height * 5 / 9); - _path.lineTo(size.width * 2 / 3, size.height * 8 / 9); - - canvas.drawPath(_path, _paint); - } - - @override - bool shouldRepaint(MarkListenedPainter oldDelegate) { - return false; - } -} - -/// Hide listened painter. -class HideListenedPainter extends CustomPainter { - Color color; - Color backgroundColor; - double fraction; - double stroke; - HideListenedPainter( - {this.color, this.stroke = 1.0, this.backgroundColor, this.fraction}); - @override - void paint(Canvas canvas, Size size) { - var _paint = Paint() - ..color = color - ..strokeWidth = stroke - ..strokeCap = StrokeCap.round - ..style = PaintingStyle.stroke; - var _linePaint = Paint() - ..color = backgroundColor - ..strokeWidth = stroke * 2 - ..strokeCap = StrokeCap.round - ..style = PaintingStyle.stroke; - var _path = Path(); - - _path.moveTo(size.width / 6, size.height * 3 / 8); - _path.lineTo(size.width / 6, size.height * 5 / 8); - _path.moveTo(size.width / 3, size.height / 4); - _path.lineTo(size.width / 3, size.height * 3 / 4); - _path.moveTo(size.width / 2, size.height / 8); - _path.lineTo(size.width / 2, size.height * 7 / 8); - _path.moveTo(size.width * 5 / 6, size.height * 3 / 8); - _path.lineTo(size.width * 5 / 6, size.height * 5 / 8); - _path.moveTo(size.width * 2 / 3, size.height / 4); - _path.lineTo(size.width * 2 / 3, size.height * 3 / 4); - - canvas.drawPath(_path, _paint); - if (fraction > 0) { - canvas.drawLine( - Offset(size.width, size.height) / 5, - Offset(size.width, size.height) / 5 + - Offset(size.width, size.height) * 3 / 5 * fraction, - _linePaint); - } - } - - @override - bool shouldRepaint(HideListenedPainter oldDelegate) { - return oldDelegate.fraction != fraction; - } -} - -class HideListened extends StatefulWidget { - final bool hideListened; - HideListened({this.hideListened, Key key}) : super(key: key); - @override - _HideListenedState createState() => _HideListenedState(); -} - -class _HideListenedState extends State - with SingleTickerProviderStateMixin { - double _fraction = 0.0; - Animation animation; - AnimationController _controller; - @override - void initState() { - super.initState(); - _controller = - AnimationController(vsync: this, duration: Duration(milliseconds: 400)); - animation = Tween(begin: 0.0, end: 1.0).animate(_controller) - ..addListener(() { - if (mounted) { - setState(() { - _fraction = animation.value; - }); - } - }); - if (widget.hideListened) _controller.forward(); - } - - @override - void didUpdateWidget(HideListened oldWidget) { - if (oldWidget.hideListened != widget.hideListened) { - if (widget.hideListened) { - _controller.forward(); - } else { - _controller.reverse(); - } - } - super.didUpdateWidget(oldWidget); - } - - @override - void dispose() { - _controller.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - return CustomPaint( - painter: HideListenedPainter( - fraction: _fraction, - color: context.textColor, - backgroundColor: context.accentColor)); - } -} - -//Add new episode to palylist -class AddToPlaylistPainter extends CustomPainter { - final Color color; - final Color textColor; - AddToPlaylistPainter(this.color, this.textColor); - @override - void paint(Canvas canvas, Size size) { - var _paint = Paint() - ..color = color - ..strokeWidth = 1 - ..strokeCap = StrokeCap.round - ..style = PaintingStyle.stroke; - var _path = Path(); - _path.moveTo(0, size.height / 5); - _path.lineTo(size.width * 4 / 7, size.height / 5); - _path.moveTo(0, size.height / 2); - _path.lineTo(size.width * 4 / 7, size.height / 2); - _path.moveTo(0, size.height * 4 / 5); - _path.lineTo(size.width * 3 / 7, size.height * 4 / 5); - - var textPainter = TextPainter( - textAlign: TextAlign.center, - textDirection: TextDirection.ltr, - text: TextSpan( - text: 'N', - style: TextStyle( - fontStyle: FontStyle.italic, color: textColor, fontSize: 10), - )) - ..layout(); - textPainter.paint(canvas, Offset(size.width * 4 / 7, size.height * 3 / 5)); - canvas.drawPath(_path, _paint); - } - - @override - bool shouldRepaint(CustomPainter oldDelegate) { - return true; - } -} - -//Wave play indicator -class WavePainter extends CustomPainter { - final double _fraction; - double _value; - final Color _color; - WavePainter(this._fraction, this._color); - @override - void paint(Canvas canvas, Size size) { - if (_fraction < 0.5) { - _value = _fraction; - } else { - _value = 1 - _fraction; - } - var _path = Path(); - var _paint = Paint() - ..color = _color - ..strokeWidth = 2.0 - ..strokeCap = StrokeCap.round - ..style = PaintingStyle.stroke; - _path.moveTo(0, size.height / 2); - _path.lineTo(0, size.height / 2 + size.height * _value * 0.2); - _path.moveTo(0, size.height / 2); - _path.lineTo(0, size.height / 2 - size.height * _value * 0.2); - _path.moveTo(size.width / 4, size.height / 2); - _path.lineTo(size.width / 4, size.height / 2 + size.height * _value * 0.8); - _path.moveTo(size.width / 4, size.height / 2); - _path.lineTo(size.width / 4, size.height / 2 - size.height * _value * 0.8); - _path.moveTo(size.width / 2, size.height / 2); - _path.lineTo(size.width / 2, size.height / 2 + size.height * _value * 0.5); - _path.moveTo(size.width / 2, size.height / 2); - _path.lineTo(size.width / 2, size.height / 2 - size.height * _value * 0.5); - _path.moveTo(size.width * 3 / 4, size.height / 2); - _path.lineTo( - size.width * 3 / 4, size.height / 2 + size.height * _value * 0.6); - _path.moveTo(size.width * 3 / 4, size.height / 2); - _path.lineTo( - size.width * 3 / 4, size.height / 2 - size.height * _value * 0.6); - _path.moveTo(size.width, size.height / 2); - _path.lineTo(size.width, size.height / 2 + size.height * _value * 0.2); - _path.moveTo(size.width, size.height / 2); - _path.lineTo(size.width, size.height / 2 - size.height * _value * 0.2); - canvas.drawPath(_path, _paint); - } - - @override - bool shouldRepaint(WavePainter oldDelegate) { - return oldDelegate._fraction != _fraction; - } -} - -class WaveLoader extends StatefulWidget { - final Color color; - WaveLoader({this.color, Key key}) : super(key: key); - @override - _WaveLoaderState createState() => _WaveLoaderState(); -} - -class _WaveLoaderState extends State - with SingleTickerProviderStateMixin { - double _fraction = 0.0; - Animation animation; - AnimationController _controller; - @override - void initState() { - super.initState(); - _controller = AnimationController( - vsync: this, duration: Duration(milliseconds: 1000)); - animation = Tween(begin: 0.0, end: 1.0).animate(_controller) - ..addListener(() { - if (mounted) { - setState(() { - _fraction = animation.value; - }); - } - }); - _controller.forward(); - _controller.addStatusListener((status) { - if (status == AnimationStatus.completed) { - _controller.reset(); - } else if (status == AnimationStatus.dismissed) { - _controller.forward(); - } - }); - } - - @override - void dispose() { - _controller.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - return CustomPaint( - painter: WavePainter(_fraction, widget.color ?? Colors.white)); - } -} - -//Love shape -class LovePainter extends CustomPainter { - @override - void paint(Canvas canvas, Size size) { - var _path = Path(); - var _paint = Paint() - ..color = Colors.red - ..strokeWidth = 2.0 - ..strokeCap = StrokeCap.round; - - _path.moveTo(size.width / 2, size.height / 6); - _path.quadraticBezierTo(size.width / 4, 0, size.width / 8, size.height / 6); - _path.quadraticBezierTo( - 0, size.height / 3, size.width / 8, size.height * 0.55); - _path.quadraticBezierTo( - size.width / 4, size.height * 0.8, size.width / 2, size.height); - _path.quadraticBezierTo(size.width * 0.75, size.height * 0.8, - size.width * 7 / 8, size.height * 0.55); - _path.quadraticBezierTo( - size.width, size.height / 3, size.width * 7 / 8, size.height / 6); - _path.quadraticBezierTo( - size.width * 3 / 4, 0, size.width / 2, size.height / 6); - - canvas.drawPath(_path, _paint); - } - - @override - bool shouldRepaint(CustomPainter oldDelegate) { - return true; - } -} - -//Line buffer indicator -//Not used -class LinePainter extends CustomPainter { - final double _fraction; - Paint _paint; - final Color _maincolor; - LinePainter(this._fraction, this._maincolor) { - _paint = Paint() - ..color = _maincolor - ..strokeWidth = 2.0 - ..strokeCap = StrokeCap.round; - } - - @override - void paint(Canvas canvas, Size size) { - canvas.drawLine(Offset(0, size.height / 2.0), - Offset(size.width * _fraction, size.height / 2.0), _paint); - } - - @override - bool shouldRepaint(LinePainter oldDelegate) { - return oldDelegate._fraction != _fraction; - } -} - -class LineLoader extends StatefulWidget { - @override - _LineLoaderState createState() => _LineLoaderState(); -} - -class _LineLoaderState extends State - with SingleTickerProviderStateMixin { - double _fraction = 0.0; - Animation animation; - AnimationController controller; - @override - void initState() { - super.initState(); - controller = - AnimationController(vsync: this, duration: Duration(milliseconds: 500)); - animation = Tween(begin: 0.0, end: 1.0).animate(controller) - ..addListener(() { - if (mounted) { - setState(() { - _fraction = animation.value; - }); - } - }); - controller.forward(); - controller.addStatusListener((status) { - if (status == AnimationStatus.completed) { - controller.reset(); - } else if (status == AnimationStatus.dismissed) { - controller.forward(); - } - }); - } - - @override - void dispose() { - controller.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - return CustomPaint( - painter: LinePainter(_fraction, Theme.of(context).accentColor)); - } -} - -class ImageRotate extends StatefulWidget { - final EpisodeBrief episodeItem; - ImageRotate({this.episodeItem, Key key}) : super(key: key); - @override - _ImageRotateState createState() => _ImageRotateState(); -} - -class _ImageRotateState extends State - with SingleTickerProviderStateMixin { - Animation _animation; - AnimationController _controller; - double _value; - - @override - void initState() { - super.initState(); - _value = 0; - _controller = AnimationController( - vsync: this, - duration: Duration(milliseconds: 2000), - ); - _animation = Tween(begin: 0.0, end: 1.0).animate(_controller) - ..addListener(() { - if (mounted) { - setState(() { - _value = _animation.value; - }); - } - }); - _controller.forward(); - _controller.addStatusListener((status) { - if (status == AnimationStatus.completed) { - _controller.reset(); - } else if (status == AnimationStatus.dismissed) { - _controller.forward(); - } - }); - } - - @override - void dispose() { - _controller.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - return Transform.rotate( - angle: 2 * math.pi * _value, - child: Padding( - padding: EdgeInsets.symmetric(vertical: 10.0), - child: SizedBox( - width: 30, - height: 30, - child: CircleAvatar( - backgroundColor: widget.episodeItem.backgroudColor(context), - backgroundImage: widget.episodeItem.avatarImage), - ), - ), - ); - } -} - -class LoveOpen extends StatefulWidget { - @override - _LoveOpenState createState() => _LoveOpenState(); -} - -class _LoveOpenState extends State - with SingleTickerProviderStateMixin { - Animation _animationA; - AnimationController _controller; - - @override - void initState() { - super.initState(); - _controller = AnimationController( - vsync: this, - duration: Duration(milliseconds: 1000), - ); - - _animationA = Tween(begin: 0.0, end: 1.0).animate(_controller) - ..addListener(() { - if (mounted) setState(() {}); - }); - - _controller.forward(); - _controller.addStatusListener((status) { - if (status == AnimationStatus.completed) { - _controller.reset(); - } - }); - } - - @override - void dispose() { - _controller.dispose(); - super.dispose(); - } - - Widget _littleHeart(double scale, double value, double angle) => Container( - alignment: Alignment.centerLeft, - padding: EdgeInsets.only(left: value), - child: ScaleTransition( - scale: _animationA, - alignment: Alignment.center, - child: Transform.rotate( - angle: angle, - child: SizedBox( - height: 5 * scale, - width: 6 * scale, - child: CustomPaint( - painter: LovePainter(), - ), - ), - ), - ), - ); - - @override - Widget build(BuildContext context) { - return Container( - width: 50, - height: 50, - alignment: Alignment.center, - child: Column( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - children: [ - Row( - children: [ - _littleHeart(0.5, 10, -math.pi / 6), - _littleHeart(1.2, 3, 0), - ], - ), - Row( - children: [ - _littleHeart(0.8, 6, math.pi * 1.5), - _littleHeart(0.9, 24, math.pi / 2), - ], - ), - Row( - mainAxisAlignment: MainAxisAlignment.start, - children: [ - _littleHeart(1, 8, -math.pi * 0.7), - _littleHeart(0.8, 8, math.pi), - _littleHeart(0.6, 3, -math.pi * 1.2) - ], - ), - ], - ), - ); - } -} - -//Heart rise -class HeartSet extends StatefulWidget { - final double height; - final double width; - HeartSet({Key key, this.height, this.width}) : super(key: key); - - @override - _HeartSetState createState() => _HeartSetState(); -} - -class _HeartSetState extends State - with SingleTickerProviderStateMixin { - Animation _animation; - AnimationController _controller; - double _value; - @override - void initState() { - super.initState(); - _value = 0; - _controller = AnimationController( - vsync: this, - duration: Duration(seconds: 2), - ); - - _animation = Tween(begin: 0.0, end: 1.0).animate(_controller) - ..addListener(() { - if (mounted) { - setState(() { - _value = _animation.value; - }); - } - }); - - _controller.forward(); - _controller.addStatusListener((status) { - if (status == AnimationStatus.completed) { - _controller.reset(); - } - }); - } - - @override - void dispose() { - _controller.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - return Container( - height: widget.height, - width: widget.width, - alignment: Alignment(0.5, 1 - _value), - child: Icon(Icons.favorite, - color: Colors.blue.withOpacity(0.7), size: 20 * _value), - ); - } -} - -class HeartOpen extends StatefulWidget { - final double height; - final double width; - HeartOpen({Key key, this.height, this.width}) : super(key: key); - - @override - _HeartOpenState createState() => _HeartOpenState(); -} - -class _HeartOpenState extends State - with SingleTickerProviderStateMixin { - Animation _animation; - AnimationController _controller; - double _value; - @override - void initState() { - super.initState(); - _value = 0; - _controller = AnimationController( - vsync: this, - duration: Duration(seconds: 2), - ); - - _animation = Tween(begin: 0.0, end: 1.0).animate(_controller) - ..addListener(() { - if (mounted) { - setState(() { - _value = _animation.value; - }); - } - }); - - _controller.forward(); - _controller.addStatusListener((status) { - if (status == AnimationStatus.completed) { - _controller.reset(); - } - }); - } - - @override - void dispose() { - _controller.dispose(); - super.dispose(); - } - - Widget _position(int i) { - var scale = _list[i]; - var position = _list[i + 1]; - return Positioned( - left: widget.width * position, - bottom: widget.height * _value * scale, - child: Icon(Icons.favorite, - color: _value > 0.5 - ? Colors.red.withOpacity(2 - _value * 2) - : Colors.red, - size: 20 * _value * scale), - ); - } - - final List _list = - List.generate(20, (index) => math.Random().nextDouble()); - final List _index = List.generate(19, (index) => index); - @override - Widget build(BuildContext context) { - return Stack( - children: [ - Container( - height: widget.height, - width: widget.width, - alignment: Alignment(0.5, 1 - _value), - child: Icon(Icons.favorite, - color: Colors.blue.withOpacity(0.7), size: 20 * _value), - ), - ..._index.map(_position).toList(), - ], - ); - } -} - -/// Icon using a painter. -class IconPainter extends StatelessWidget { - const IconPainter(this.painter, {this.height = 10, this.width = 30, Key key}) - : super(key: key); - final double height; - final double width; - final CustomPainter painter; - @override - Widget build(BuildContext context) { - return SizedBox( - height: height, - width: width, - child: CustomPaint( - painter: painter, - ), - ); - } -} - -/// A dot just a dot. -class DotIndicator extends StatelessWidget { - DotIndicator({this.radius = 8, this.color, Key key}) - : assert(radius > 0), - super(key: key); - final Color color; - final double radius; - - @override - Widget build(BuildContext context) { - return Container( - width: radius, - height: radius, - decoration: BoxDecoration( - shape: BoxShape.circle, color: color ?? context.accentColor)); - } -} - -///Download button. -class DownloadPainter extends CustomPainter { - double fraction; - Color color; - Color progressColor; - double progress; - double pauseProgress; - double stroke; - DownloadPainter( - {this.fraction, - this.color, - this.progressColor, - this.progress = 0, - this.stroke = 2, - this.pauseProgress = 0}); - - @override - void paint(Canvas canvas, Size size) { - var _paint = Paint() - ..color = color - ..strokeWidth = stroke - ..strokeCap = StrokeCap.round; - var _circlePaint = Paint() - ..color = color.withAlpha(70) - ..style = PaintingStyle.stroke - ..strokeWidth = stroke; - var _progressPaint = Paint() - ..color = progressColor - ..strokeCap = StrokeCap.round - ..style = PaintingStyle.stroke - ..strokeWidth = stroke; - var width = size.width; - var height = size.height; - var center = Offset(size.width / 2, size.height / 2); - if (pauseProgress == 0 && progress < 1) { - canvas.drawLine( - Offset(width / 2, 4), Offset(width / 2, height * 4 / 5), _paint); - canvas.drawLine(Offset(width / 4, height / 2), - Offset(width / 2, height * 4 / 5), _paint); - canvas.drawLine(Offset(width * 3 / 4, height / 2), - Offset(width / 2, height * 4 / 5), _paint); - } - - if (fraction == 0) { - canvas.drawLine( - Offset(width / 5, height), Offset(width * 4 / 5, height), _paint); - } else if (progress < 1) { - canvas.drawArc(Rect.fromCircle(center: center, radius: width / 2), - math.pi / 2, math.pi * fraction, false, _circlePaint); - canvas.drawArc(Rect.fromCircle(center: center, radius: width / 2), - math.pi / 2, -math.pi * fraction, false, _circlePaint); - } - - if (progress == 1) { - canvas.drawLine(Offset(width / 5, height * 9 / 10), - Offset(width * 4 / 5, height * 9 / 10), _progressPaint); - canvas.drawLine(Offset(width / 5, height * 5 / 10), - Offset(width * 2 / 5, height * 7 / 10), _progressPaint); - canvas.drawLine(Offset(width * 4 / 5, height * 3 / 10), - Offset(width * 2 / 5, height * 7 / 10), _progressPaint); - } - - if (fraction == 1 && progress < 1) { - canvas.drawArc(Rect.fromCircle(center: center, radius: width / 2), - -math.pi / 2, math.pi * 2 * progress, false, _progressPaint); - } - - if (pauseProgress > 0) { - canvas.drawLine( - Offset(width / 5 + height * 3 * pauseProgress / 20, - height / 2 - height * pauseProgress / 5), - Offset(width / 2 - height * 3 * pauseProgress / 20, - height * 4 / 5 - height * pauseProgress / 10), - _paint); - canvas.drawLine( - Offset(width * 4 / 5 - height * 3 * pauseProgress / 20, - height / 2 - height * pauseProgress / 5), - Offset(width / 2 + height * 3 * pauseProgress / 20, - height * 4 / 5 - height * pauseProgress / 10), - _paint); - } - } - - @override - bool shouldRepaint(DownloadPainter oldDelegate) { - return oldDelegate.fraction != fraction || - oldDelegate.progress != progress || - oldDelegate.pauseProgress != pauseProgress; - } -} - -/// Layout icon button. -class LayoutButton extends StatelessWidget { - const LayoutButton({this.layout, this.onPressed, Key key}) : super(key: key); - final Layout layout; - final ValueChanged onPressed; - @override - Widget build(BuildContext context) { - return IconButton( - padding: EdgeInsets.zero, - onPressed: () { - if (layout == Layout.three) { - onPressed(Layout.one); - } else if (layout == Layout.two) { - onPressed(Layout.three); - } else { - onPressed(Layout.two); - } - }, - icon: layout == Layout.three - ? SizedBox( - height: 10, - width: 30, - child: CustomPaint( - painter: LayoutPainter(0, context.textColor), - ), - ) - : layout == Layout.two - ? SizedBox( - height: 10, - width: 30, - child: CustomPaint( - painter: LayoutPainter(1, context.textColor), - ), - ) - : SizedBox( - height: 10, - width: 30, - child: CustomPaint( - painter: - LayoutPainter(4, context.textTheme.bodyText1.color), - ), - ), - ); - } -} - -/// Remove scroll view overlay effect. -class NoGrowBehavior extends ScrollBehavior { - @override - Widget buildViewportChrome( - BuildContext context, Widget child, AxisDirection axisDirection) { - return child; - } -} - -class Meteor extends CustomPainter { - Paint _paint; - Meteor() { - _paint = Paint() - ..color = Colors.white - ..strokeWidth = 2.0 - ..strokeCap = StrokeCap.round; - } - - @override - void paint(Canvas canvas, Size size) { - canvas.drawLine(Offset(0, 0), Offset(size.width, size.height), _paint); - } - - @override - bool shouldRepaint(Meteor oldDelegate) { - return false; - } -} - -/// Used in sleep mode widget. -class MeteorLoader extends StatefulWidget { - @override - _MeteorLoaderState createState() => _MeteorLoaderState(); -} - -class _MeteorLoaderState extends State - with SingleTickerProviderStateMixin { - double _fraction = 0.0; - double _move = 0.0; - Animation animation; - AnimationController controller; - @override - void initState() { - super.initState(); - controller = - AnimationController(vsync: this, duration: Duration(milliseconds: 500)); - animation = Tween(begin: 0.0, end: 1.0).animate(controller) - ..addListener(() { - if (mounted) { - setState(() { - _move = animation.value; - if (animation.value <= 0.5) { - _fraction = animation.value * 2; - } else { - _fraction = 2 - (animation.value) * 2; - } - }); - } - }); - controller.forward(); - } - - @override - void dispose() { - controller.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - return Positioned( - top: 300 * _move + 10, - left: 150 * _move + 50, - child: SizedBox( - width: 50 * _fraction, - height: 100 * _fraction, - child: CustomPaint(painter: Meteor())), - ); - } -} - -/// Custom paint in player widget. Tab indicator. -class TabIndicator extends CustomPainter { - double fraction; - double indicatorSize; - Color color; - Color accentColor; - int index; - TabIndicator( - {this.fraction, - this.color, - this.accentColor, - this.indicatorSize, - this.index}); - - @override - void paint(Canvas canvas, Size size) { - var _paint = Paint() - ..color = color - ..strokeWidth = 3.0 - ..strokeCap = StrokeCap.round; - var _accentPaint = Paint() - ..color = accentColor - ..strokeWidth = 3.0 - ..strokeCap = StrokeCap.round; - var leftStartE = Offset(indicatorSize, size.height); - var rightStartE = Offset(size.width - indicatorSize, size.height); - var startPoint = Offset(size.width / 2, 0); - var leftStart = startPoint + (leftStartE - startPoint) * fraction; - var rightStart = startPoint + (rightStartE - startPoint) * fraction; - var leftEnd = startPoint + - Offset(-size.height, size.height) + - Offset(-(size.width / 2 - size.height) * fraction, 0); - var rightEnd = startPoint + - Offset(size.height, size.height) + - Offset((size.width / 2 - size.height) * fraction, 0); - canvas.drawLine(leftStart, leftEnd, - index == 0 || fraction == 0 ? _accentPaint : _paint); - canvas.drawLine(rightStart, rightEnd, - index == 1 || fraction == 0 ? _accentPaint : _paint); - } - - @override - bool shouldRepaint(TabIndicator oldDelegate) { - return oldDelegate.fraction != fraction || oldDelegate.index != index; - } -} - -/// Custom back button -class CustomBackButton extends StatelessWidget { - const CustomBackButton({Key key}) : super(key: key); - @override - Widget build(BuildContext context) { - return IconButton( - splashRadius: 25, - icon: const BackButtonIcon(), - tooltip: context.s.back, - onPressed: () { - Navigator.maybePop(context); - }, - ); - } -} +import 'dart:math' as math; + +import 'package:flutter/material.dart'; + +import '../type/episodebrief.dart'; +import 'episodegrid.dart'; +import 'extension_helper.dart'; + +const kTwoPi = math.pi * 2; +const kPi = math.pi; +const kHalfPi = math.pi / 2; + +//Layout change indicator +class LayoutPainter extends CustomPainter { + double scale; + Color color; + LayoutPainter(this.scale, this.color); + @override + void paint(Canvas canvas, Size size) { + var _paint = Paint() + ..color = color + ..strokeWidth = 1.0 + ..style = PaintingStyle.stroke + ..strokeCap = StrokeCap.round; + + canvas.drawRect(Rect.fromLTRB(0, 0, 10 + 5 * scale, 10), _paint); + if (scale < 4) { + canvas.drawRect( + Rect.fromLTRB(10 + 5 * scale, 0, 20 + 10 * scale, 10), _paint); + canvas.drawRect( + Rect.fromLTRB(20 + 5 * scale, 0, 30, 10 - 10 * scale), _paint); + } + } + + @override + bool shouldRepaint(LayoutPainter oldDelegate) { + return oldDelegate.scale != scale || oldDelegate.color != color; + } +} + +/// Multi select button. +class MultiSelectPainter extends CustomPainter { + Color color; + MultiSelectPainter({@required this.color}); + @override + void paint(Canvas canvas, Size size) { + var paint = Paint() + ..color = color + ..strokeWidth = 1.0 + ..style = PaintingStyle.fill + ..strokeCap = StrokeCap.round; + final x = size.width / 2; + final y = size.height / 2; + var path = Path(); + path.moveTo(0, 0); + path.lineTo(x, 0); + path.lineTo(x, y * 2); + path.lineTo(x * 2, y * 2); + path.lineTo(x * 2, y); + path.lineTo(0, y); + path.lineTo(0, 0); + path.close(); + canvas.drawPath(path, paint); + } + + @override + bool shouldRepaint(MultiSelectPainter oldDelegate) { + return false; + } +} + +//Dark sky used in sleep timer +class StarSky extends CustomPainter { + @override + void paint(Canvas canvas, Size size) { + final points = [ + Offset(50, 100), + Offset(150, 75), + Offset(250, 250), + Offset(130, 200), + Offset(270, 150), + ]; + final pisces = [ + Offset(9, 4), + Offset(11, 5), + Offset(7, 6), + Offset(10, 7), + Offset(8, 8), + Offset(9, 13), + Offset(12, 17), + Offset(5, 19), + Offset(7, 19) + ].map((e) => e * 10).toList(); + final orion = [ + Offset(3, 1), + Offset(6, 1), + Offset(1, 4), + Offset(2, 4), + Offset(2, 7), + Offset(10, 8), + Offset(3, 10), + Offset(8, 10), + Offset(19, 11), + Offset(11, 13), + Offset(18, 14), + Offset(5, 19), + Offset(7, 19), + Offset(9, 18), + Offset(15, 19), + Offset(16, 18), + Offset(2, 25), + Offset(10, 26) + ].map((e) => Offset(e.dx * 10 + 250, e.dy * 10)).toList(); + + var paint = Paint() + ..color = Colors.white + ..strokeWidth = 2.0 + ..strokeCap = StrokeCap.round; + var _fullPaint = Paint() + ..color = Colors.white + ..strokeWidth = 1.0 + ..strokeCap = StrokeCap.butt + ..style = PaintingStyle.fill; + _darwStar(Offset center, double radius) { + canvas.drawCircle(center, radius, paint); + var path = Path() + ..addOval(Rect.fromCircle(center: center, radius: radius * 2)); + canvas.drawShadow(path.shift(Offset(0, -6)), Colors.white, 6, true); + } + + _darwBigStar(Offset center, double radius) { + var path = Path(); + path.moveTo(center.dx - radius * 1.5, center.dy); + path.quadraticBezierTo(center.dx - radius * 0.2, center.dy - radius * 0.2, + center.dx, center.dy - radius * 2); + path.quadraticBezierTo(center.dx + radius * 0.2, center.dy - radius * 0.2, + center.dx + radius * 1.5, center.dy); + path.quadraticBezierTo(center.dx + radius * 0.2, center.dy + radius * 0.2, + center.dx, center.dy + radius * 2); + path.quadraticBezierTo(center.dx - radius * 0.2, center.dy + radius * 0.2, + center.dx - radius * 1.5, center.dy); + path.close(); + + canvas.drawPath(path, _fullPaint); + canvas.drawShadow(path.shift(Offset(0, -6)), Colors.white, 10, true); + } + + for (var center in pisces) { + _darwStar(center, 2); + } + for (var center in orion) { + _darwStar(center, 2); + } + for (var center in points) { + _darwBigStar(center, 4); + _darwStar(center, 2); + } + } + + @override + bool shouldRepaint(StarSky oldDelegate) { + return false; + } +} + +//Listened indicator +class ListenedPainter extends CustomPainter { + final Color _color; + double stroke; + ListenedPainter(this._color, {this.stroke = 1.0}); + @override + void paint(Canvas canvas, Size size) { + var _paint = Paint() + ..color = _color + ..strokeWidth = stroke + ..strokeCap = StrokeCap.round + ..style = PaintingStyle.stroke; + var _path = Path(); + _path.moveTo(size.width / 6, size.height * 3 / 8); + _path.lineTo(size.width / 6, size.height * 5 / 8); + _path.moveTo(size.width / 3, size.height / 4); + _path.lineTo(size.width / 3, size.height * 3 / 4); + _path.moveTo(size.width / 2, size.height / 8); + _path.lineTo(size.width / 2, size.height * 7 / 8); + _path.moveTo(size.width * 5 / 6, size.height * 3 / 8); + _path.lineTo(size.width * 5 / 6, size.height * 5 / 8); + _path.moveTo(size.width * 2 / 3, size.height / 4); + _path.lineTo(size.width * 2 / 3, size.height * 3 / 4); + + canvas.drawPath(_path, _paint); + } + + @override + bool shouldRepaint(ListenedPainter oldDelegate) { + return false; + } +} + +//Listened Completely indicator +class ListenedAllPainter extends CustomPainter { + final Color color; + final double stroke; + ListenedAllPainter(this.color, {this.stroke = 1.0}); + @override + void paint(Canvas canvas, Size size) { + var _paint = Paint() + ..color = color + ..strokeWidth = stroke + ..strokeCap = StrokeCap.round + ..style = PaintingStyle.stroke; + var _path = Path(); + _path.moveTo(size.width / 6, size.height * 3 / 8); + _path.lineTo(size.width / 6, size.height * 5 / 8); + _path.moveTo(size.width / 3, size.height / 4); + _path.lineTo(size.width / 3, size.height * 3 / 4); + _path.moveTo(size.width / 2, size.height * 3 / 8); + _path.lineTo(size.width / 2, size.height * 5 / 8); + _path.moveTo(size.width * 2 / 3, size.height * 4 / 9); + _path.lineTo(size.width * 2 / 3, size.height * 5 / 9); + _path.moveTo(size.width / 2, size.height * 3 / 4); + _path.lineTo(size.width * 2 / 3, size.height * 7 / 8); + _path.lineTo(size.width * 7 / 8, size.height * 5 / 8); + + canvas.drawPath(_path, _paint); + } + + @override + bool shouldRepaint(ListenedAllPainter oldDelegate) { + return false; + } +} + +//Mark Listened indicator +class MarkListenedPainter extends CustomPainter { + final Color color; + double stroke; + MarkListenedPainter(this.color, {this.stroke = 1.0}); + @override + void paint(Canvas canvas, Size size) { + var _paint = Paint() + ..color = color + ..strokeWidth = stroke + ..strokeCap = StrokeCap.round + ..style = PaintingStyle.stroke; + var _path = Path(); + _path.moveTo(size.width / 6, size.height * 3 / 8); + _path.lineTo(size.width / 6, size.height * 5 / 8); + _path.moveTo(size.width / 3, size.height / 4); + _path.lineTo(size.width / 3, size.height * 3 / 4); + _path.moveTo(size.width / 2, size.height * 3 / 8); + _path.lineTo(size.width / 2, size.height * 5 / 8); + // _path.moveTo(size.width * 2 / 3, size.height * 4 / 9); + // _path.lineTo(size.width * 2 / 3, size.height * 5 / 9); + _path.moveTo(size.width / 2, size.height * 13 / 18); + _path.lineTo(size.width * 5 / 6, size.height * 13 / 18); + _path.moveTo(size.width * 2 / 3, size.height * 5 / 9); + _path.lineTo(size.width * 2 / 3, size.height * 8 / 9); + + canvas.drawPath(_path, _paint); + } + + @override + bool shouldRepaint(MarkListenedPainter oldDelegate) { + return false; + } +} + +/// Hide listened painter. +class HideListenedPainter extends CustomPainter { + Color color; + Color backgroundColor; + double fraction; + double stroke; + HideListenedPainter( + {this.color, this.stroke = 1.0, this.backgroundColor, this.fraction}); + @override + void paint(Canvas canvas, Size size) { + var _paint = Paint() + ..color = color + ..strokeWidth = stroke + ..strokeCap = StrokeCap.round + ..style = PaintingStyle.stroke; + var _linePaint = Paint() + ..color = backgroundColor + ..strokeWidth = stroke * 2 + ..strokeCap = StrokeCap.round + ..style = PaintingStyle.stroke; + var _path = Path(); + + _path.moveTo(size.width / 6, size.height * 3 / 8); + _path.lineTo(size.width / 6, size.height * 5 / 8); + _path.moveTo(size.width / 3, size.height / 4); + _path.lineTo(size.width / 3, size.height * 3 / 4); + _path.moveTo(size.width / 2, size.height / 8); + _path.lineTo(size.width / 2, size.height * 7 / 8); + _path.moveTo(size.width * 5 / 6, size.height * 3 / 8); + _path.lineTo(size.width * 5 / 6, size.height * 5 / 8); + _path.moveTo(size.width * 2 / 3, size.height / 4); + _path.lineTo(size.width * 2 / 3, size.height * 3 / 4); + + canvas.drawPath(_path, _paint); + if (fraction > 0) { + canvas.drawLine( + Offset(size.width, size.height) / 5, + Offset(size.width, size.height) / 5 + + Offset(size.width, size.height) * 3 / 5 * fraction, + _linePaint); + } + } + + @override + bool shouldRepaint(HideListenedPainter oldDelegate) { + return oldDelegate.fraction != fraction; + } +} + +class HideListened extends StatefulWidget { + final bool hideListened; + HideListened({this.hideListened, Key key}) : super(key: key); + @override + _HideListenedState createState() => _HideListenedState(); +} + +class _HideListenedState extends State + with SingleTickerProviderStateMixin { + double _fraction = 0.0; + Animation animation; + AnimationController _controller; + @override + void initState() { + super.initState(); + _controller = + AnimationController(vsync: this, duration: Duration(milliseconds: 400)); + animation = Tween(begin: 0.0, end: 1.0).animate(_controller) + ..addListener(() { + if (mounted) { + setState(() { + _fraction = animation.value; + }); + } + }); + if (widget.hideListened) _controller.forward(); + } + + @override + void didUpdateWidget(HideListened oldWidget) { + if (oldWidget.hideListened != widget.hideListened) { + if (widget.hideListened) { + _controller.forward(); + } else { + _controller.reverse(); + } + } + super.didUpdateWidget(oldWidget); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return CustomPaint( + painter: HideListenedPainter( + fraction: _fraction, + color: context.textColor, + backgroundColor: context.accentColor)); + } +} + +//Add new episode to palylist +class AddToPlaylistPainter extends CustomPainter { + final Color color; + final Color textColor; + AddToPlaylistPainter(this.color, this.textColor); + @override + void paint(Canvas canvas, Size size) { + var _paint = Paint() + ..color = color + ..strokeWidth = 1 + ..strokeCap = StrokeCap.round + ..style = PaintingStyle.stroke; + var _path = Path(); + _path.moveTo(0, size.height / 5); + _path.lineTo(size.width * 4 / 7, size.height / 5); + _path.moveTo(0, size.height / 2); + _path.lineTo(size.width * 4 / 7, size.height / 2); + _path.moveTo(0, size.height * 4 / 5); + _path.lineTo(size.width * 3 / 7, size.height * 4 / 5); + + var textPainter = TextPainter( + textAlign: TextAlign.center, + textDirection: TextDirection.ltr, + text: TextSpan( + text: 'N', + style: TextStyle( + fontStyle: FontStyle.italic, color: textColor, fontSize: 10), + )) + ..layout(); + textPainter.paint(canvas, Offset(size.width * 4 / 7, size.height * 3 / 5)); + canvas.drawPath(_path, _paint); + } + + @override + bool shouldRepaint(CustomPainter oldDelegate) { + return true; + } +} + +//Wave play indicator +class WavePainter extends CustomPainter { + final double _fraction; + double _value; + final Color _color; + WavePainter(this._fraction, this._color); + @override + void paint(Canvas canvas, Size size) { + if (_fraction < 0.5) { + _value = _fraction; + } else { + _value = 1 - _fraction; + } + var _path = Path(); + var _paint = Paint() + ..color = _color + ..strokeWidth = 2.0 + ..strokeCap = StrokeCap.round + ..style = PaintingStyle.stroke; + _path.moveTo(0, size.height / 2); + _path.lineTo(0, size.height / 2 + size.height * _value * 0.2); + _path.moveTo(0, size.height / 2); + _path.lineTo(0, size.height / 2 - size.height * _value * 0.2); + _path.moveTo(size.width / 4, size.height / 2); + _path.lineTo(size.width / 4, size.height / 2 + size.height * _value * 0.8); + _path.moveTo(size.width / 4, size.height / 2); + _path.lineTo(size.width / 4, size.height / 2 - size.height * _value * 0.8); + _path.moveTo(size.width / 2, size.height / 2); + _path.lineTo(size.width / 2, size.height / 2 + size.height * _value * 0.5); + _path.moveTo(size.width / 2, size.height / 2); + _path.lineTo(size.width / 2, size.height / 2 - size.height * _value * 0.5); + _path.moveTo(size.width * 3 / 4, size.height / 2); + _path.lineTo( + size.width * 3 / 4, size.height / 2 + size.height * _value * 0.6); + _path.moveTo(size.width * 3 / 4, size.height / 2); + _path.lineTo( + size.width * 3 / 4, size.height / 2 - size.height * _value * 0.6); + _path.moveTo(size.width, size.height / 2); + _path.lineTo(size.width, size.height / 2 + size.height * _value * 0.2); + _path.moveTo(size.width, size.height / 2); + _path.lineTo(size.width, size.height / 2 - size.height * _value * 0.2); + canvas.drawPath(_path, _paint); + } + + @override + bool shouldRepaint(WavePainter oldDelegate) { + return oldDelegate._fraction != _fraction; + } +} + +class WaveLoader extends StatefulWidget { + final Color color; + WaveLoader({this.color, Key key}) : super(key: key); + @override + _WaveLoaderState createState() => _WaveLoaderState(); +} + +class _WaveLoaderState extends State + with SingleTickerProviderStateMixin { + double _fraction = 0.0; + Animation animation; + AnimationController _controller; + @override + void initState() { + super.initState(); + _controller = AnimationController( + vsync: this, duration: Duration(milliseconds: 1000)); + animation = Tween(begin: 0.0, end: 1.0).animate(_controller) + ..addListener(() { + if (mounted) { + setState(() { + _fraction = animation.value; + }); + } + }); + _controller.forward(); + _controller.addStatusListener((status) { + if (status == AnimationStatus.completed) { + _controller.reset(); + } else if (status == AnimationStatus.dismissed) { + _controller.forward(); + } + }); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return CustomPaint( + painter: WavePainter(_fraction, widget.color ?? Colors.white)); + } +} + +//Love shape +class LovePainter extends CustomPainter { + @override + void paint(Canvas canvas, Size size) { + var _path = Path(); + var _paint = Paint() + ..color = Colors.red + ..strokeWidth = 2.0 + ..strokeCap = StrokeCap.round; + + _path.moveTo(size.width / 2, size.height / 6); + _path.quadraticBezierTo(size.width / 4, 0, size.width / 8, size.height / 6); + _path.quadraticBezierTo( + 0, size.height / 3, size.width / 8, size.height * 0.55); + _path.quadraticBezierTo( + size.width / 4, size.height * 0.8, size.width / 2, size.height); + _path.quadraticBezierTo(size.width * 0.75, size.height * 0.8, + size.width * 7 / 8, size.height * 0.55); + _path.quadraticBezierTo( + size.width, size.height / 3, size.width * 7 / 8, size.height / 6); + _path.quadraticBezierTo( + size.width * 3 / 4, 0, size.width / 2, size.height / 6); + + canvas.drawPath(_path, _paint); + } + + @override + bool shouldRepaint(CustomPainter oldDelegate) { + return true; + } +} + +//Line buffer indicator +//Not used +class LinePainter extends CustomPainter { + final double _fraction; + Paint _paint; + final Color _maincolor; + LinePainter(this._fraction, this._maincolor) { + _paint = Paint() + ..color = _maincolor + ..strokeWidth = 2.0 + ..strokeCap = StrokeCap.round; + } + + @override + void paint(Canvas canvas, Size size) { + canvas.drawLine(Offset(0, size.height / 2.0), + Offset(size.width * _fraction, size.height / 2.0), _paint); + } + + @override + bool shouldRepaint(LinePainter oldDelegate) { + return oldDelegate._fraction != _fraction; + } +} + +class LineLoader extends StatefulWidget { + @override + _LineLoaderState createState() => _LineLoaderState(); +} + +class _LineLoaderState extends State + with SingleTickerProviderStateMixin { + double _fraction = 0.0; + Animation animation; + AnimationController controller; + @override + void initState() { + super.initState(); + controller = + AnimationController(vsync: this, duration: Duration(milliseconds: 500)); + animation = Tween(begin: 0.0, end: 1.0).animate(controller) + ..addListener(() { + if (mounted) { + setState(() { + _fraction = animation.value; + }); + } + }); + controller.forward(); + controller.addStatusListener((status) { + if (status == AnimationStatus.completed) { + controller.reset(); + } else if (status == AnimationStatus.dismissed) { + controller.forward(); + } + }); + } + + @override + void dispose() { + controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return CustomPaint( + painter: LinePainter(_fraction, Theme.of(context).accentColor)); + } +} + +class ImageRotate extends StatefulWidget { + final EpisodeBrief episodeItem; + ImageRotate({this.episodeItem, Key key}) : super(key: key); + @override + _ImageRotateState createState() => _ImageRotateState(); +} + +class _ImageRotateState extends State + with SingleTickerProviderStateMixin { + Animation _animation; + AnimationController _controller; + double _value; + + @override + void initState() { + super.initState(); + _value = 0; + _controller = AnimationController( + vsync: this, + duration: Duration(milliseconds: 2000), + ); + _animation = Tween(begin: 0.0, end: 1.0).animate(_controller) + ..addListener(() { + if (mounted) { + setState(() { + _value = _animation.value; + }); + } + }); + _controller.forward(); + _controller.addStatusListener((status) { + if (status == AnimationStatus.completed) { + _controller.reset(); + } else if (status == AnimationStatus.dismissed) { + _controller.forward(); + } + }); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Transform.rotate( + angle: 2 * math.pi * _value, + child: Padding( + padding: EdgeInsets.symmetric(vertical: 10.0), + child: SizedBox( + width: 30, + height: 30, + child: CircleAvatar( + backgroundColor: widget.episodeItem.backgroudColor(context), + backgroundImage: widget.episodeItem.avatarImage), + ), + ), + ); + } +} + +class LoveOpen extends StatefulWidget { + @override + _LoveOpenState createState() => _LoveOpenState(); +} + +class _LoveOpenState extends State + with SingleTickerProviderStateMixin { + Animation _animationA; + AnimationController _controller; + + @override + void initState() { + super.initState(); + _controller = AnimationController( + vsync: this, + duration: Duration(milliseconds: 1000), + ); + + _animationA = Tween(begin: 0.0, end: 1.0).animate(_controller) + ..addListener(() { + if (mounted) setState(() {}); + }); + + _controller.forward(); + _controller.addStatusListener((status) { + if (status == AnimationStatus.completed) { + _controller.reset(); + } + }); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + Widget _littleHeart(double scale, double value, double angle) => Container( + alignment: Alignment.centerLeft, + padding: EdgeInsets.only(left: value), + child: ScaleTransition( + scale: _animationA, + alignment: Alignment.center, + child: Transform.rotate( + angle: angle, + child: SizedBox( + height: 5 * scale, + width: 6 * scale, + child: CustomPaint( + painter: LovePainter(), + ), + ), + ), + ), + ); + + @override + Widget build(BuildContext context) { + return Container( + width: 50, + height: 50, + alignment: Alignment.center, + child: Column( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Row( + children: [ + _littleHeart(0.5, 10, -math.pi / 6), + _littleHeart(1.2, 3, 0), + ], + ), + Row( + children: [ + _littleHeart(0.8, 6, math.pi * 1.5), + _littleHeart(0.9, 24, math.pi / 2), + ], + ), + Row( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + _littleHeart(1, 8, -math.pi * 0.7), + _littleHeart(0.8, 8, math.pi), + _littleHeart(0.6, 3, -math.pi * 1.2) + ], + ), + ], + ), + ); + } +} + +//Heart rise +class HeartSet extends StatefulWidget { + final double height; + final double width; + HeartSet({Key key, this.height, this.width}) : super(key: key); + + @override + _HeartSetState createState() => _HeartSetState(); +} + +class _HeartSetState extends State + with SingleTickerProviderStateMixin { + Animation _animation; + AnimationController _controller; + double _value; + @override + void initState() { + super.initState(); + _value = 0; + _controller = AnimationController( + vsync: this, + duration: Duration(seconds: 2), + ); + + _animation = Tween(begin: 0.0, end: 1.0).animate(_controller) + ..addListener(() { + if (mounted) { + setState(() { + _value = _animation.value; + }); + } + }); + + _controller.forward(); + _controller.addStatusListener((status) { + if (status == AnimationStatus.completed) { + _controller.reset(); + } + }); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Container( + height: widget.height, + width: widget.width, + alignment: Alignment(0.5, 1 - _value), + child: Icon(Icons.favorite, + color: Colors.blue.withOpacity(0.7), size: 20 * _value), + ); + } +} + +class HeartOpen extends StatefulWidget { + final double height; + final double width; + HeartOpen({Key key, this.height, this.width}) : super(key: key); + + @override + _HeartOpenState createState() => _HeartOpenState(); +} + +class _HeartOpenState extends State + with SingleTickerProviderStateMixin { + Animation _animation; + AnimationController _controller; + double _value; + @override + void initState() { + super.initState(); + _value = 0; + _controller = AnimationController( + vsync: this, + duration: Duration(seconds: 2), + ); + + _animation = Tween(begin: 0.0, end: 1.0).animate(_controller) + ..addListener(() { + if (mounted) { + setState(() { + _value = _animation.value; + }); + } + }); + + _controller.forward(); + _controller.addStatusListener((status) { + if (status == AnimationStatus.completed) { + _controller.reset(); + } + }); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + Widget _position(int i) { + var scale = _list[i]; + var position = _list[i + 1]; + return Positioned( + left: widget.width * position, + bottom: widget.height * _value * scale, + child: Icon(Icons.favorite, + color: _value > 0.5 + ? Colors.red.withOpacity(2 - _value * 2) + : Colors.red, + size: 20 * _value * scale), + ); + } + + final List _list = + List.generate(20, (index) => math.Random().nextDouble()); + final List _index = List.generate(19, (index) => index); + @override + Widget build(BuildContext context) { + return Stack( + children: [ + Container( + height: widget.height, + width: widget.width, + alignment: Alignment(0.5, 1 - _value), + child: Icon(Icons.favorite, + color: Colors.blue.withOpacity(0.7), size: 20 * _value), + ), + ..._index.map(_position).toList(), + ], + ); + } +} + +/// Icon using a painter. +class IconPainter extends StatelessWidget { + const IconPainter(this.painter, {this.height = 10, this.width = 30, Key key}) + : super(key: key); + final double height; + final double width; + final CustomPainter painter; + @override + Widget build(BuildContext context) { + return SizedBox( + height: height, + width: width, + child: CustomPaint( + painter: painter, + ), + ); + } +} + +/// A dot just a dot. +class DotIndicator extends StatelessWidget { + DotIndicator({this.radius = 8, this.color, Key key}) + : assert(radius > 0), + super(key: key); + final Color color; + final double radius; + + @override + Widget build(BuildContext context) { + return Container( + width: radius, + height: radius, + decoration: BoxDecoration( + shape: BoxShape.circle, color: color ?? context.accentColor)); + } +} + +///Download button. +class DownloadPainter extends CustomPainter { + double fraction; + Color color; + Color progressColor; + double progress; + double pauseProgress; + double stroke; + DownloadPainter( + {this.fraction, + this.color, + this.progressColor, + this.progress = 0, + this.stroke = 2, + this.pauseProgress = 0}); + + @override + void paint(Canvas canvas, Size size) { + var _paint = Paint() + ..color = color + ..strokeWidth = stroke + ..strokeCap = StrokeCap.round; + var _circlePaint = Paint() + ..color = color.withAlpha(70) + ..style = PaintingStyle.stroke + ..strokeWidth = stroke; + var _progressPaint = Paint() + ..color = progressColor + ..strokeCap = StrokeCap.round + ..style = PaintingStyle.stroke + ..strokeWidth = stroke; + var width = size.width; + var height = size.height; + var center = Offset(size.width / 2, size.height / 2); + if (pauseProgress == 0 && progress < 1) { + canvas.drawLine( + Offset(width / 2, 4), Offset(width / 2, height * 4 / 5), _paint); + canvas.drawLine(Offset(width / 4, height / 2), + Offset(width / 2, height * 4 / 5), _paint); + canvas.drawLine(Offset(width * 3 / 4, height / 2), + Offset(width / 2, height * 4 / 5), _paint); + } + + if (fraction == 0) { + canvas.drawLine( + Offset(width / 5, height), Offset(width * 4 / 5, height), _paint); + } else if (progress < 1) { + canvas.drawArc(Rect.fromCircle(center: center, radius: width / 2), + math.pi / 2, math.pi * fraction, false, _circlePaint); + canvas.drawArc(Rect.fromCircle(center: center, radius: width / 2), + math.pi / 2, -math.pi * fraction, false, _circlePaint); + } + + if (progress == 1) { + canvas.drawLine(Offset(width / 5, height * 9 / 10), + Offset(width * 4 / 5, height * 9 / 10), _progressPaint); + canvas.drawLine(Offset(width / 5, height * 5 / 10), + Offset(width * 2 / 5, height * 7 / 10), _progressPaint); + canvas.drawLine(Offset(width * 4 / 5, height * 3 / 10), + Offset(width * 2 / 5, height * 7 / 10), _progressPaint); + } + + if (fraction == 1 && progress < 1) { + canvas.drawArc(Rect.fromCircle(center: center, radius: width / 2), + -math.pi / 2, math.pi * 2 * progress, false, _progressPaint); + } + + if (pauseProgress > 0) { + canvas.drawLine( + Offset(width / 5 + height * 3 * pauseProgress / 20, + height / 2 - height * pauseProgress / 5), + Offset(width / 2 - height * 3 * pauseProgress / 20, + height * 4 / 5 - height * pauseProgress / 10), + _paint); + canvas.drawLine( + Offset(width * 4 / 5 - height * 3 * pauseProgress / 20, + height / 2 - height * pauseProgress / 5), + Offset(width / 2 + height * 3 * pauseProgress / 20, + height * 4 / 5 - height * pauseProgress / 10), + _paint); + } + } + + @override + bool shouldRepaint(DownloadPainter oldDelegate) { + return oldDelegate.fraction != fraction || + oldDelegate.progress != progress || + oldDelegate.pauseProgress != pauseProgress; + } +} + +/// Layout icon button. +class LayoutButton extends StatelessWidget { + const LayoutButton({this.layout, this.onPressed, Key key}) : super(key: key); + final Layout layout; + final ValueChanged onPressed; + @override + Widget build(BuildContext context) { + return IconButton( + padding: EdgeInsets.zero, + onPressed: () { + if (layout == Layout.three) { + onPressed(Layout.one); + } else if (layout == Layout.two) { + onPressed(Layout.three); + } else { + onPressed(Layout.two); + } + }, + icon: layout == Layout.three + ? SizedBox( + height: 10, + width: 30, + child: CustomPaint( + painter: LayoutPainter(0, context.textColor), + ), + ) + : layout == Layout.two + ? SizedBox( + height: 10, + width: 30, + child: CustomPaint( + painter: LayoutPainter(1, context.textColor), + ), + ) + : SizedBox( + height: 10, + width: 30, + child: CustomPaint( + painter: + LayoutPainter(4, context.textTheme.bodyText1.color), + ), + ), + ); + } +} + +/// Remove scroll view overlay effect. +class NoGrowBehavior extends ScrollBehavior { + @override + Widget buildViewportChrome( + BuildContext context, Widget child, AxisDirection axisDirection) { + return child; + } +} + +class Meteor extends CustomPainter { + Paint _paint; + Meteor() { + _paint = Paint() + ..color = Colors.white + ..strokeWidth = 2.0 + ..strokeCap = StrokeCap.round; + } + + @override + void paint(Canvas canvas, Size size) { + canvas.drawLine(Offset(0, 0), Offset(size.width, size.height), _paint); + } + + @override + bool shouldRepaint(Meteor oldDelegate) { + return false; + } +} + +/// Used in sleep mode widget. +class MeteorLoader extends StatefulWidget { + @override + _MeteorLoaderState createState() => _MeteorLoaderState(); +} + +class _MeteorLoaderState extends State + with SingleTickerProviderStateMixin { + double _fraction = 0.0; + double _move = 0.0; + Animation animation; + AnimationController controller; + @override + void initState() { + super.initState(); + controller = + AnimationController(vsync: this, duration: Duration(milliseconds: 500)); + animation = Tween(begin: 0.0, end: 1.0).animate(controller) + ..addListener(() { + if (mounted) { + setState(() { + _move = animation.value; + if (animation.value <= 0.5) { + _fraction = animation.value * 2; + } else { + _fraction = 2 - (animation.value) * 2; + } + }); + } + }); + controller.forward(); + } + + @override + void dispose() { + controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Positioned( + top: 300 * _move + 10, + left: 150 * _move + 50, + child: SizedBox( + width: 50 * _fraction, + height: 100 * _fraction, + child: CustomPaint(painter: Meteor())), + ); + } +} + +/// Custom paint in player widget. Tab indicator. +class TabIndicator extends CustomPainter { + double fraction; + double indicatorSize; + Color color; + Color accentColor; + int index; + TabIndicator( + {this.fraction, + this.color, + this.accentColor, + this.indicatorSize, + this.index}); + + @override + void paint(Canvas canvas, Size size) { + var _paint = Paint() + ..color = color + ..strokeWidth = 3.0 + ..strokeCap = StrokeCap.round; + var _accentPaint = Paint() + ..color = accentColor + ..strokeWidth = 3.0 + ..strokeCap = StrokeCap.round; + var leftStartE = Offset(indicatorSize, size.height); + var rightStartE = Offset(size.width - indicatorSize, size.height); + var startPoint = Offset(size.width / 2, 0); + var leftStart = startPoint + (leftStartE - startPoint) * fraction; + var rightStart = startPoint + (rightStartE - startPoint) * fraction; + var leftEnd = startPoint + + Offset(-size.height, size.height) + + Offset(-(size.width / 2 - size.height) * fraction, 0); + var rightEnd = startPoint + + Offset(size.height, size.height) + + Offset((size.width / 2 - size.height) * fraction, 0); + canvas.drawLine(leftStart, leftEnd, + index == 0 || fraction == 0 ? _accentPaint : _paint); + canvas.drawLine(rightStart, rightEnd, + index == 1 || fraction == 0 ? _accentPaint : _paint); + } + + @override + bool shouldRepaint(TabIndicator oldDelegate) { + return oldDelegate.fraction != fraction || oldDelegate.index != index; + } +} + +/// Custom back button +class CustomBackButton extends StatelessWidget { + const CustomBackButton({Key key}) : super(key: key); + @override + Widget build(BuildContext context) { + return IconButton( + splashRadius: 25, + icon: const BackButtonIcon(), + tooltip: context.s.back, + onPressed: () { + Navigator.maybePop(context); + }, + ); + } +} diff --git a/lib/util/duraiton_picker.dart b/lib/util/duraiton_picker.dart index 56b3bac..657b9ed 100644 --- a/lib/util/duraiton_picker.dart +++ b/lib/util/duraiton_picker.dart @@ -1,654 +1,654 @@ -//Forked from https://github.com/cdharris/flutter_duration_picker -//Copyright https://github.com/cdharris -//License MIT https://github.com/cdharris/flutter_duration_picker/blob/master/LICENSE - -import 'dart:async'; -import 'dart:math' as math; - -import 'package:flutter/material.dart'; -import 'package:flutter/rendering.dart'; -import 'package:flutter/services.dart'; -import 'package:flutter/widgets.dart'; - -const Duration _kDialAnimateDuration = Duration(milliseconds: 200); - -const double _kDurationPickerWidthPortrait = 328.0; -const double _kDurationPickerWidthLandscape = 512.0; - -const double _kDurationPickerHeightPortrait = 380.0; -const double _kDurationPickerHeightLandscape = 304.0; - -const double _kTwoPi = 2 * math.pi; -const double _kPiByTwo = math.pi / 2; - -const double _kCircleTop = _kPiByTwo; - -class _DialPainter extends CustomPainter { - const _DialPainter({ - @required this.context, - @required this.labels, - @required this.backgroundColor, - @required this.accentColor, - @required this.theta, - @required this.textDirection, - @required this.selectedValue, - @required this.pct, - @required this.multiplier, - @required this.secondHand, - }); - - final List labels; - final Color backgroundColor; - final Color accentColor; - final double theta; - final TextDirection textDirection; - final int selectedValue; - final BuildContext context; - - final double pct; - final int multiplier; - final int secondHand; - - @override - void paint(Canvas canvas, Size size) { - const _epsilon = .001; - const _sweep = _kTwoPi - _epsilon; - const _startAngle = -math.pi / 2.0; - - final radius = size.shortestSide / 2.0; - final center = Offset(size.width / 2.0, size.height / 2.0); - final centerPoint = center; - - var pctTheta = (0.25 - (theta % _kTwoPi) / _kTwoPi) % 1.0; - - // Draw the background outer ring - canvas.drawCircle(centerPoint, radius, Paint()..color = backgroundColor); - - // Draw a translucent circle for every hour - for (var i = 0; i < multiplier; i = i + 1) { - canvas.drawCircle(centerPoint, radius, - Paint()..color = accentColor.withOpacity((i == 0) ? 0.3 : 0.1)); - } - - // Draw the inner background circle - canvas.drawCircle(centerPoint, radius * 0.88, - Paint()..color = Theme.of(context).canvasColor); - - // Get the offset point for an angle value of theta, and a distance of _radius - Offset getOffsetForTheta(double theta, double _radius) { - return center + - Offset(_radius * math.cos(theta), -_radius * math.sin(theta)); - } - - // Draw the handle that is used to drag and to indicate the position around the circle - final handlePaint = Paint()..color = accentColor; - final handlePoint = getOffsetForTheta(theta, radius - 10.0); - canvas.drawCircle(handlePoint, 20.0, handlePaint); - - // Draw the Text in the center of the circle which displays hours and mins - var minutes = (multiplier == 0) ? '' : "${multiplier}min "; -// int minutes = (pctTheta * 60).round(); -// minutes = minutes == 60 ? 0 : minutes; - var seconds = "$secondHand"; - - var textDurationValuePainter = TextPainter( - textAlign: TextAlign.center, - text: TextSpan( - text: '$minutes$seconds', - style: Theme.of(context) - .textTheme - .headline4 - .copyWith(fontSize: size.shortestSide * 0.15)), - textDirection: TextDirection.ltr) - ..layout(); - var middleForValueText = Offset( - centerPoint.dx - (textDurationValuePainter.width / 2), - centerPoint.dy - textDurationValuePainter.height / 2); - textDurationValuePainter.paint(canvas, middleForValueText); - - var textMinPainter = TextPainter( - textAlign: TextAlign.center, - text: TextSpan( - text: 'sec', //th: ${theta}', - style: Theme.of(context).textTheme.bodyText1), - textDirection: TextDirection.ltr) - ..layout(); - textMinPainter.paint( - canvas, - Offset( - centerPoint.dx - (textMinPainter.width / 2), - centerPoint.dy + - (textDurationValuePainter.height / 2) - - textMinPainter.height / 2)); - - // Draw an arc around the circle for the amount of the circle that has elapsed. - var elapsedPainter = Paint() - ..style = PaintingStyle.stroke - ..strokeCap = StrokeCap.round - ..color = accentColor.withOpacity(0.3) - ..isAntiAlias = true - ..strokeWidth = radius * 0.12; - - canvas.drawArc( - Rect.fromCircle( - center: centerPoint, - radius: radius - radius * 0.12 / 2, - ), - _startAngle, - _sweep * pctTheta, - false, - elapsedPainter, - ); - - // Paint the labels (the minute strings) - void paintLabels(List labels) { - if (labels == null) return; - final labelThetaIncrement = -_kTwoPi / labels.length; - var labelTheta = _kPiByTwo; - - for (var label in labels) { - final labelOffset = Offset(-label.width / 2.0, -label.height / 2.0); - - label.paint( - canvas, getOffsetForTheta(labelTheta, radius - 40.0) + labelOffset); - - labelTheta += labelThetaIncrement; - } - } - - paintLabels(labels); - } - - @override - bool shouldRepaint(_DialPainter oldPainter) { - return oldPainter.labels != labels || - oldPainter.backgroundColor != backgroundColor || - oldPainter.accentColor != accentColor || - oldPainter.theta != theta; - } -} - -class _Dial extends StatefulWidget { - const _Dial( - {@required this.duration, - @required this.onChanged, - this.snapToMins = 1.0}) - : assert(duration != null); - - final Duration duration; - final ValueChanged onChanged; - - /// The resolution of mins of the dial, i.e. if snapToMins = 5.0, only durations of 5min intervals will be selectable. - final double snapToMins; - @override - _DialState createState() => _DialState(); -} - -class _DialState extends State<_Dial> with SingleTickerProviderStateMixin { - @override - void initState() { - super.initState(); - _thetaController = AnimationController( - vsync: this, - duration: _kDialAnimateDuration, - ); - _thetaTween = Tween(begin: _getThetaForDuration(widget.duration)); - _theta = _thetaTween.animate( - CurvedAnimation(parent: _thetaController, curve: Curves.fastOutSlowIn)) - ..addListener(() => setState(() {})); - _thetaController.addStatusListener((status) { -// if (status == AnimationStatus.completed && _hours != _snappedHours) { -// _hours = _snappedHours; - if (status == AnimationStatus.completed) { - _minutes = _minuteHand(_turningAngle); - _seconds = _secondHand(_turningAngle); - setState(() {}); - } - }); -// _hours = widget.duration.inHours; - - _turningAngle = _kPiByTwo - widget.duration.inSeconds / 60.0 * _kTwoPi; - _minutes = _minuteHand(_turningAngle); - _seconds = _secondHand(_turningAngle); - } - - ThemeData themeData; - MaterialLocalizations localizations; - MediaQueryData media; - - @override - void didChangeDependencies() { - super.didChangeDependencies(); - assert(debugCheckHasMediaQuery(context)); - themeData = Theme.of(context); - localizations = MaterialLocalizations.of(context); - media = MediaQuery.of(context); - } - - @override - void dispose() { - _thetaController.dispose(); - super.dispose(); - } - - Tween _thetaTween; - Animation _theta; - AnimationController _thetaController; - - final double _pct = 0.0; - int _seconds = 0; - bool _dragging = false; - int _minutes = 0; - double _turningAngle = 0.0; - - static double _nearest(double target, double a, double b) { - return ((target - a).abs() < (target - b).abs()) ? a : b; - } - - void _animateTo(double targetTheta) { - final currentTheta = _theta.value; - var beginTheta = - _nearest(targetTheta, currentTheta, currentTheta + _kTwoPi); - beginTheta = _nearest(targetTheta, beginTheta, currentTheta - _kTwoPi); - _thetaTween - ..begin = beginTheta - ..end = targetTheta; - _thetaController - ..value = 0.0 - ..forward(); - } - - double _getThetaForDuration(Duration duration) { - return (_kPiByTwo - (duration.inSeconds % 60) / 60.0 * _kTwoPi) % _kTwoPi; - } - - Duration _getTimeForTheta(double theta) { - return _angleToDuration(_turningAngle); - } - - Duration _notifyOnChangedIfNeeded() { -// final Duration current = _getTimeForTheta(_theta.value); -// var d = Duration(hours: _hours, minutes: current.inMinutes % 60); - _minutes = _minuteHand(_turningAngle); - _seconds = _secondHand(_turningAngle); - - var d = _angleToDuration(_turningAngle); - - widget.onChanged(d); - - return d; - } - - void _updateThetaForPan() { - setState(() { - final offset = _position - _center; - final angle = (math.atan2(offset.dx, offset.dy) - _kPiByTwo) % _kTwoPi; - - // Stop accidental abrupt pans from making the dial seem like it starts from 1h. - // (happens when wanting to pan from 0 clockwise, but when doing so quickly, one actually pans from before 0 (e.g. setting the duration to 59mins, and then crossing 0, which would then mean 1h 1min). - if (angle >= _kCircleTop && - _theta.value <= _kCircleTop && - _theta.value >= 0.1 && // to allow the radians sign change at 15mins. - _minutes == 0) return; - - _thetaTween - ..begin = angle - ..end = angle; - }); - } - - Offset _position; - Offset _center; - - void _handlePanStart(DragStartDetails details) { - assert(!_dragging); - _dragging = true; - final RenderBox box = context.findRenderObject(); - _position = box.globalToLocal(details.globalPosition); - _center = box.size.center(Offset.zero); - //_updateThetaForPan(); - _notifyOnChangedIfNeeded(); - } - - void _handlePanUpdate(DragUpdateDetails details) { - var oldTheta = _theta.value; - _position += details.delta; - _updateThetaForPan(); - var newTheta = _theta.value; -// _updateRotations(oldTheta, newTheta); - _updateTurningAngle(oldTheta, newTheta); - _notifyOnChangedIfNeeded(); - } - - int _minuteHand(double angle) { - return _angleToDuration(angle).inMinutes.toInt(); - } - - int _secondHand(double angle) { - // Result is in [0; 59], even if overall time is >= 1 hour - return (_angleToSeconds(angle) % 60.0).toInt(); - } - - Duration _angleToDuration(double angle) { - return _secondToDuration(_angleToSeconds(angle)); - } - - Duration _secondToDuration(seconds) { - return Duration( - minutes: (seconds ~/ 60).toInt(), seconds: (seconds % 60.0).toInt()); - } - - double _angleToSeconds(double angle) { - // Coordinate transformation from mathematical COS to dial COS - var dialAngle = _kPiByTwo - angle; - - // Turn dial angle into minutes, may go beyond 60 minutes (multiple turns) - return dialAngle / _kTwoPi * 60.0; - } - - void _updateTurningAngle(double oldTheta, double newTheta) { - // Register any angle by which the user has turned the dial. - // - // The resulting turning angle fully captures the state of the dial, - // including multiple turns (= full hours). The [_turningAngle] is in - // mathematical coordinate system, i.e. 3-o-clock position being zero, and - // increasing counter clock wise. - - // From positive to negative (in mathematical COS) - if (newTheta > 1.5 * math.pi && oldTheta < 0.5 * math.pi) { - _turningAngle = _turningAngle - ((_kTwoPi - newTheta) + oldTheta); - } - // From negative to positive (in mathematical COS) - else if (newTheta < 0.5 * math.pi && oldTheta > 1.5 * math.pi) { - _turningAngle = _turningAngle + ((_kTwoPi - oldTheta) + newTheta); - } else { - _turningAngle = _turningAngle + (newTheta - oldTheta); - } - } - - void _handlePanEnd(DragEndDetails details) { - assert(_dragging); - _dragging = false; - _position = null; - _center = null; - //_notifyOnChangedIfNeeded(); - //_animateTo(_getThetaForDuration(widget.duration)); - } - - void _handleTapUp(TapUpDetails details) { - final RenderBox box = context.findRenderObject(); - _position = box.globalToLocal(details.globalPosition); - _center = box.size.center(Offset.zero); - _updateThetaForPan(); - _notifyOnChangedIfNeeded(); - - _animateTo(_getThetaForDuration(_getTimeForTheta(_theta.value))); - _dragging = false; - _position = null; - _center = null; - } - - List _buildSeconds(TextTheme textTheme) { - final style = textTheme.subtitle1; - - const _secondsMarkerValues = [ - Duration(seconds: 0), - Duration(seconds: 5), - Duration(seconds: 10), - Duration(seconds: 15), - Duration(seconds: 20), - Duration(seconds: 25), - Duration(seconds: 30), - Duration(seconds: 35), - Duration(seconds: 40), - Duration(seconds: 45), - Duration(seconds: 50), - Duration(seconds: 55), - ]; - - final labels = []; - for (var duration in _secondsMarkerValues) { - var painter = TextPainter( - text: TextSpan(style: style, text: duration.inSeconds.toString()), - textDirection: TextDirection.ltr, - )..layout(); - labels.add(painter); - } - return labels; - } - - @override - Widget build(BuildContext context) { - Color backgroundColor; - switch (themeData.brightness) { - case Brightness.light: - backgroundColor = Colors.grey[200]; - break; - case Brightness.dark: - backgroundColor = themeData.backgroundColor; - break; - } - - final theme = Theme.of(context); - - int selectedDialValue; - _minutes = _minuteHand(_turningAngle); - _seconds = _secondHand(_turningAngle); - - return GestureDetector( - excludeFromSemantics: true, - onPanStart: _handlePanStart, - onPanUpdate: _handlePanUpdate, - onPanEnd: _handlePanEnd, - onTapUp: _handleTapUp, - child: CustomPaint( - painter: _DialPainter( - pct: _pct, - multiplier: _minutes, - secondHand: _seconds, - context: context, - selectedValue: selectedDialValue, - labels: _buildSeconds(theme.textTheme), - backgroundColor: backgroundColor, - accentColor: themeData.accentColor, - theta: _theta.value, - textDirection: Directionality.of(context), - ), - )); - } -} - -/// A duration picker designed to appear inside a popup dialog. -/// -/// Pass this widget to [showDialog]. The value returned by [showDialog] is the -/// selected [Duration] if the user taps the "OK" button, or null if the user -/// taps the "CANCEL" button. The selected time is reported by calling -/// [Navigator.pop]. -class _DurationPickerDialog extends StatefulWidget { - /// Creates a duration picker. - /// - /// [initialTime] must not be null. - const _DurationPickerDialog( - {Key key, @required this.initialTime, this.snapToMins}) - : assert(initialTime != null), - super(key: key); - - /// The duration initially selected when the dialog is shown. - final Duration initialTime; - final double snapToMins; - - @override - _DurationPickerDialogState createState() => _DurationPickerDialogState(); -} - -class _DurationPickerDialogState extends State<_DurationPickerDialog> { - @override - void initState() { - super.initState(); - _selectedDuration = widget.initialTime; - } - - @override - void didChangeDependencies() { - super.didChangeDependencies(); - localizations = MaterialLocalizations.of(context); - } - - Duration get selectedDuration => _selectedDuration; - Duration _selectedDuration; - - MaterialLocalizations localizations; - - void _handleTimeChanged(Duration value) { - setState(() { - _selectedDuration = value; - }); - } - - void _handleCancel() { - Navigator.pop(context); - } - - void _handleOk() { - Navigator.pop(context, _selectedDuration); - } - - @override - Widget build(BuildContext context) { - assert(debugCheckHasMediaQuery(context)); - final theme = Theme.of(context); - - final Widget picker = Padding( - padding: const EdgeInsets.all(16.0), - child: AspectRatio( - aspectRatio: 1.0, - child: _Dial( - duration: _selectedDuration, - onChanged: _handleTimeChanged, - snapToMins: widget.snapToMins, - ))); - - final Widget actions = ButtonBar(children: [ - FlatButton( - child: Text(localizations.cancelButtonLabel), - onPressed: _handleCancel), - FlatButton( - child: Text(localizations.okButtonLabel), onPressed: _handleOk), - ]); - - final dialog = - Dialog(child: OrientationBuilder(builder: (context, orientation) { - final Widget pickerAndActions = Container( - color: theme.dialogBackgroundColor, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Expanded( - child: - picker), // picker grows and shrinks with the available space - actions, - ], - ), - ); - - assert(orientation != null); - switch (orientation) { - case Orientation.portrait: - return SizedBox( - width: _kDurationPickerWidthPortrait, - height: _kDurationPickerHeightPortrait, - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Expanded( - child: pickerAndActions, - ), - ])); - case Orientation.landscape: - return SizedBox( - width: _kDurationPickerWidthLandscape, - height: _kDurationPickerHeightLandscape, - child: Row( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Flexible( - child: pickerAndActions, - ), - ])); - } - return null; - })); - - return Theme( - data: theme.copyWith( - dialogBackgroundColor: Colors.transparent, - ), - child: dialog, - ); - } - - @override - void dispose() { - super.dispose(); - } -} - -/// Shows a dialog containing the duration picker. -/// -/// The returned Future resolves to the duration selected by the user when the user -/// closes the dialog. If the user cancels the dialog, null is returned. -/// -/// To show a dialog with [initialTime] equal to the current time: -/// -/// ```dart -/// showDurationPicker( -/// initialTime: new Duration.now(), -/// context: context, -/// ); -/// ``` -Future showDurationPicker( - {@required BuildContext context, - @required Duration initialTime, - double snapToMins}) async { - assert(context != null); - assert(initialTime != null); - - return await showDialog( - context: context, - builder: (context) => - _DurationPickerDialog(initialTime: initialTime, snapToMins: snapToMins), - ); -} - -class DurationPicker extends StatelessWidget { - final Duration duration; - final ValueChanged onChange; - final double snapToMins; - - final double width; - final double height; - - DurationPicker( - {this.duration = const Duration(minutes: 0), - @required this.onChange, - this.snapToMins, - this.width, - this.height, - Key key}) - : super(key: key); - - @override - Widget build(BuildContext context) { - return SizedBox( - width: width ?? _kDurationPickerWidthPortrait / 1.5, - height: height ?? _kDurationPickerHeightPortrait / 1.5, - child: _Dial( - duration: duration, - onChanged: onChange, - snapToMins: snapToMins, - ), - ); - } -} +//Forked from https://github.com/cdharris/flutter_duration_picker +//Copyright https://github.com/cdharris +//License MIT https://github.com/cdharris/flutter_duration_picker/blob/master/LICENSE + +import 'dart:async'; +import 'dart:math' as math; + +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; + +const Duration _kDialAnimateDuration = Duration(milliseconds: 200); + +const double _kDurationPickerWidthPortrait = 328.0; +const double _kDurationPickerWidthLandscape = 512.0; + +const double _kDurationPickerHeightPortrait = 380.0; +const double _kDurationPickerHeightLandscape = 304.0; + +const double _kTwoPi = 2 * math.pi; +const double _kPiByTwo = math.pi / 2; + +const double _kCircleTop = _kPiByTwo; + +class _DialPainter extends CustomPainter { + const _DialPainter({ + @required this.context, + @required this.labels, + @required this.backgroundColor, + @required this.accentColor, + @required this.theta, + @required this.textDirection, + @required this.selectedValue, + @required this.pct, + @required this.multiplier, + @required this.secondHand, + }); + + final List labels; + final Color backgroundColor; + final Color accentColor; + final double theta; + final TextDirection textDirection; + final int selectedValue; + final BuildContext context; + + final double pct; + final int multiplier; + final int secondHand; + + @override + void paint(Canvas canvas, Size size) { + const _epsilon = .001; + const _sweep = _kTwoPi - _epsilon; + const _startAngle = -math.pi / 2.0; + + final radius = size.shortestSide / 2.0; + final center = Offset(size.width / 2.0, size.height / 2.0); + final centerPoint = center; + + var pctTheta = (0.25 - (theta % _kTwoPi) / _kTwoPi) % 1.0; + + // Draw the background outer ring + canvas.drawCircle(centerPoint, radius, Paint()..color = backgroundColor); + + // Draw a translucent circle for every hour + for (var i = 0; i < multiplier; i = i + 1) { + canvas.drawCircle(centerPoint, radius, + Paint()..color = accentColor.withOpacity((i == 0) ? 0.3 : 0.1)); + } + + // Draw the inner background circle + canvas.drawCircle(centerPoint, radius * 0.88, + Paint()..color = Theme.of(context).canvasColor); + + // Get the offset point for an angle value of theta, and a distance of _radius + Offset getOffsetForTheta(double theta, double _radius) { + return center + + Offset(_radius * math.cos(theta), -_radius * math.sin(theta)); + } + + // Draw the handle that is used to drag and to indicate the position around the circle + final handlePaint = Paint()..color = accentColor; + final handlePoint = getOffsetForTheta(theta, radius - 10.0); + canvas.drawCircle(handlePoint, 20.0, handlePaint); + + // Draw the Text in the center of the circle which displays hours and mins + var minutes = (multiplier == 0) ? '' : "${multiplier}min "; +// int minutes = (pctTheta * 60).round(); +// minutes = minutes == 60 ? 0 : minutes; + var seconds = "$secondHand"; + + var textDurationValuePainter = TextPainter( + textAlign: TextAlign.center, + text: TextSpan( + text: '$minutes$seconds', + style: Theme.of(context) + .textTheme + .headline4 + .copyWith(fontSize: size.shortestSide * 0.15)), + textDirection: TextDirection.ltr) + ..layout(); + var middleForValueText = Offset( + centerPoint.dx - (textDurationValuePainter.width / 2), + centerPoint.dy - textDurationValuePainter.height / 2); + textDurationValuePainter.paint(canvas, middleForValueText); + + var textMinPainter = TextPainter( + textAlign: TextAlign.center, + text: TextSpan( + text: 'sec', //th: ${theta}', + style: Theme.of(context).textTheme.bodyText1), + textDirection: TextDirection.ltr) + ..layout(); + textMinPainter.paint( + canvas, + Offset( + centerPoint.dx - (textMinPainter.width / 2), + centerPoint.dy + + (textDurationValuePainter.height / 2) - + textMinPainter.height / 2)); + + // Draw an arc around the circle for the amount of the circle that has elapsed. + var elapsedPainter = Paint() + ..style = PaintingStyle.stroke + ..strokeCap = StrokeCap.round + ..color = accentColor.withOpacity(0.3) + ..isAntiAlias = true + ..strokeWidth = radius * 0.12; + + canvas.drawArc( + Rect.fromCircle( + center: centerPoint, + radius: radius - radius * 0.12 / 2, + ), + _startAngle, + _sweep * pctTheta, + false, + elapsedPainter, + ); + + // Paint the labels (the minute strings) + void paintLabels(List labels) { + if (labels == null) return; + final labelThetaIncrement = -_kTwoPi / labels.length; + var labelTheta = _kPiByTwo; + + for (var label in labels) { + final labelOffset = Offset(-label.width / 2.0, -label.height / 2.0); + + label.paint( + canvas, getOffsetForTheta(labelTheta, radius - 40.0) + labelOffset); + + labelTheta += labelThetaIncrement; + } + } + + paintLabels(labels); + } + + @override + bool shouldRepaint(_DialPainter oldPainter) { + return oldPainter.labels != labels || + oldPainter.backgroundColor != backgroundColor || + oldPainter.accentColor != accentColor || + oldPainter.theta != theta; + } +} + +class _Dial extends StatefulWidget { + const _Dial( + {@required this.duration, + @required this.onChanged, + this.snapToMins = 1.0}) + : assert(duration != null); + + final Duration duration; + final ValueChanged onChanged; + + /// The resolution of mins of the dial, i.e. if snapToMins = 5.0, only durations of 5min intervals will be selectable. + final double snapToMins; + @override + _DialState createState() => _DialState(); +} + +class _DialState extends State<_Dial> with SingleTickerProviderStateMixin { + @override + void initState() { + super.initState(); + _thetaController = AnimationController( + vsync: this, + duration: _kDialAnimateDuration, + ); + _thetaTween = Tween(begin: _getThetaForDuration(widget.duration)); + _theta = _thetaTween.animate( + CurvedAnimation(parent: _thetaController, curve: Curves.fastOutSlowIn)) + ..addListener(() => setState(() {})); + _thetaController.addStatusListener((status) { +// if (status == AnimationStatus.completed && _hours != _snappedHours) { +// _hours = _snappedHours; + if (status == AnimationStatus.completed) { + _minutes = _minuteHand(_turningAngle); + _seconds = _secondHand(_turningAngle); + setState(() {}); + } + }); +// _hours = widget.duration.inHours; + + _turningAngle = _kPiByTwo - widget.duration.inSeconds / 60.0 * _kTwoPi; + _minutes = _minuteHand(_turningAngle); + _seconds = _secondHand(_turningAngle); + } + + ThemeData themeData; + MaterialLocalizations localizations; + MediaQueryData media; + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + assert(debugCheckHasMediaQuery(context)); + themeData = Theme.of(context); + localizations = MaterialLocalizations.of(context); + media = MediaQuery.of(context); + } + + @override + void dispose() { + _thetaController.dispose(); + super.dispose(); + } + + Tween _thetaTween; + Animation _theta; + AnimationController _thetaController; + + final double _pct = 0.0; + int _seconds = 0; + bool _dragging = false; + int _minutes = 0; + double _turningAngle = 0.0; + + static double _nearest(double target, double a, double b) { + return ((target - a).abs() < (target - b).abs()) ? a : b; + } + + void _animateTo(double targetTheta) { + final currentTheta = _theta.value; + var beginTheta = + _nearest(targetTheta, currentTheta, currentTheta + _kTwoPi); + beginTheta = _nearest(targetTheta, beginTheta, currentTheta - _kTwoPi); + _thetaTween + ..begin = beginTheta + ..end = targetTheta; + _thetaController + ..value = 0.0 + ..forward(); + } + + double _getThetaForDuration(Duration duration) { + return (_kPiByTwo - (duration.inSeconds % 60) / 60.0 * _kTwoPi) % _kTwoPi; + } + + Duration _getTimeForTheta(double theta) { + return _angleToDuration(_turningAngle); + } + + Duration _notifyOnChangedIfNeeded() { +// final Duration current = _getTimeForTheta(_theta.value); +// var d = Duration(hours: _hours, minutes: current.inMinutes % 60); + _minutes = _minuteHand(_turningAngle); + _seconds = _secondHand(_turningAngle); + + var d = _angleToDuration(_turningAngle); + + widget.onChanged(d); + + return d; + } + + void _updateThetaForPan() { + setState(() { + final offset = _position - _center; + final angle = (math.atan2(offset.dx, offset.dy) - _kPiByTwo) % _kTwoPi; + + // Stop accidental abrupt pans from making the dial seem like it starts from 1h. + // (happens when wanting to pan from 0 clockwise, but when doing so quickly, one actually pans from before 0 (e.g. setting the duration to 59mins, and then crossing 0, which would then mean 1h 1min). + if (angle >= _kCircleTop && + _theta.value <= _kCircleTop && + _theta.value >= 0.1 && // to allow the radians sign change at 15mins. + _minutes == 0) return; + + _thetaTween + ..begin = angle + ..end = angle; + }); + } + + Offset _position; + Offset _center; + + void _handlePanStart(DragStartDetails details) { + assert(!_dragging); + _dragging = true; + final RenderBox box = context.findRenderObject(); + _position = box.globalToLocal(details.globalPosition); + _center = box.size.center(Offset.zero); + //_updateThetaForPan(); + _notifyOnChangedIfNeeded(); + } + + void _handlePanUpdate(DragUpdateDetails details) { + var oldTheta = _theta.value; + _position += details.delta; + _updateThetaForPan(); + var newTheta = _theta.value; +// _updateRotations(oldTheta, newTheta); + _updateTurningAngle(oldTheta, newTheta); + _notifyOnChangedIfNeeded(); + } + + int _minuteHand(double angle) { + return _angleToDuration(angle).inMinutes.toInt(); + } + + int _secondHand(double angle) { + // Result is in [0; 59], even if overall time is >= 1 hour + return (_angleToSeconds(angle) % 60.0).toInt(); + } + + Duration _angleToDuration(double angle) { + return _secondToDuration(_angleToSeconds(angle)); + } + + Duration _secondToDuration(seconds) { + return Duration( + minutes: (seconds ~/ 60).toInt(), seconds: (seconds % 60.0).toInt()); + } + + double _angleToSeconds(double angle) { + // Coordinate transformation from mathematical COS to dial COS + var dialAngle = _kPiByTwo - angle; + + // Turn dial angle into minutes, may go beyond 60 minutes (multiple turns) + return dialAngle / _kTwoPi * 60.0; + } + + void _updateTurningAngle(double oldTheta, double newTheta) { + // Register any angle by which the user has turned the dial. + // + // The resulting turning angle fully captures the state of the dial, + // including multiple turns (= full hours). The [_turningAngle] is in + // mathematical coordinate system, i.e. 3-o-clock position being zero, and + // increasing counter clock wise. + + // From positive to negative (in mathematical COS) + if (newTheta > 1.5 * math.pi && oldTheta < 0.5 * math.pi) { + _turningAngle = _turningAngle - ((_kTwoPi - newTheta) + oldTheta); + } + // From negative to positive (in mathematical COS) + else if (newTheta < 0.5 * math.pi && oldTheta > 1.5 * math.pi) { + _turningAngle = _turningAngle + ((_kTwoPi - oldTheta) + newTheta); + } else { + _turningAngle = _turningAngle + (newTheta - oldTheta); + } + } + + void _handlePanEnd(DragEndDetails details) { + assert(_dragging); + _dragging = false; + _position = null; + _center = null; + //_notifyOnChangedIfNeeded(); + //_animateTo(_getThetaForDuration(widget.duration)); + } + + void _handleTapUp(TapUpDetails details) { + final RenderBox box = context.findRenderObject(); + _position = box.globalToLocal(details.globalPosition); + _center = box.size.center(Offset.zero); + _updateThetaForPan(); + _notifyOnChangedIfNeeded(); + + _animateTo(_getThetaForDuration(_getTimeForTheta(_theta.value))); + _dragging = false; + _position = null; + _center = null; + } + + List _buildSeconds(TextTheme textTheme) { + final style = textTheme.subtitle1; + + const _secondsMarkerValues = [ + Duration(seconds: 0), + Duration(seconds: 5), + Duration(seconds: 10), + Duration(seconds: 15), + Duration(seconds: 20), + Duration(seconds: 25), + Duration(seconds: 30), + Duration(seconds: 35), + Duration(seconds: 40), + Duration(seconds: 45), + Duration(seconds: 50), + Duration(seconds: 55), + ]; + + final labels = []; + for (var duration in _secondsMarkerValues) { + var painter = TextPainter( + text: TextSpan(style: style, text: duration.inSeconds.toString()), + textDirection: TextDirection.ltr, + )..layout(); + labels.add(painter); + } + return labels; + } + + @override + Widget build(BuildContext context) { + Color backgroundColor; + switch (themeData.brightness) { + case Brightness.light: + backgroundColor = Colors.grey[200]; + break; + case Brightness.dark: + backgroundColor = themeData.backgroundColor; + break; + } + + final theme = Theme.of(context); + + int selectedDialValue; + _minutes = _minuteHand(_turningAngle); + _seconds = _secondHand(_turningAngle); + + return GestureDetector( + excludeFromSemantics: true, + onPanStart: _handlePanStart, + onPanUpdate: _handlePanUpdate, + onPanEnd: _handlePanEnd, + onTapUp: _handleTapUp, + child: CustomPaint( + painter: _DialPainter( + pct: _pct, + multiplier: _minutes, + secondHand: _seconds, + context: context, + selectedValue: selectedDialValue, + labels: _buildSeconds(theme.textTheme), + backgroundColor: backgroundColor, + accentColor: themeData.accentColor, + theta: _theta.value, + textDirection: Directionality.of(context), + ), + )); + } +} + +/// A duration picker designed to appear inside a popup dialog. +/// +/// Pass this widget to [showDialog]. The value returned by [showDialog] is the +/// selected [Duration] if the user taps the "OK" button, or null if the user +/// taps the "CANCEL" button. The selected time is reported by calling +/// [Navigator.pop]. +class _DurationPickerDialog extends StatefulWidget { + /// Creates a duration picker. + /// + /// [initialTime] must not be null. + const _DurationPickerDialog( + {Key key, @required this.initialTime, this.snapToMins}) + : assert(initialTime != null), + super(key: key); + + /// The duration initially selected when the dialog is shown. + final Duration initialTime; + final double snapToMins; + + @override + _DurationPickerDialogState createState() => _DurationPickerDialogState(); +} + +class _DurationPickerDialogState extends State<_DurationPickerDialog> { + @override + void initState() { + super.initState(); + _selectedDuration = widget.initialTime; + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + localizations = MaterialLocalizations.of(context); + } + + Duration get selectedDuration => _selectedDuration; + Duration _selectedDuration; + + MaterialLocalizations localizations; + + void _handleTimeChanged(Duration value) { + setState(() { + _selectedDuration = value; + }); + } + + void _handleCancel() { + Navigator.pop(context); + } + + void _handleOk() { + Navigator.pop(context, _selectedDuration); + } + + @override + Widget build(BuildContext context) { + assert(debugCheckHasMediaQuery(context)); + final theme = Theme.of(context); + + final Widget picker = Padding( + padding: const EdgeInsets.all(16.0), + child: AspectRatio( + aspectRatio: 1.0, + child: _Dial( + duration: _selectedDuration, + onChanged: _handleTimeChanged, + snapToMins: widget.snapToMins, + ))); + + final Widget actions = ButtonBar(children: [ + FlatButton( + child: Text(localizations.cancelButtonLabel), + onPressed: _handleCancel), + FlatButton( + child: Text(localizations.okButtonLabel), onPressed: _handleOk), + ]); + + final dialog = + Dialog(child: OrientationBuilder(builder: (context, orientation) { + final Widget pickerAndActions = Container( + color: theme.dialogBackgroundColor, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Expanded( + child: + picker), // picker grows and shrinks with the available space + actions, + ], + ), + ); + + assert(orientation != null); + switch (orientation) { + case Orientation.portrait: + return SizedBox( + width: _kDurationPickerWidthPortrait, + height: _kDurationPickerHeightPortrait, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Expanded( + child: pickerAndActions, + ), + ])); + case Orientation.landscape: + return SizedBox( + width: _kDurationPickerWidthLandscape, + height: _kDurationPickerHeightLandscape, + child: Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Flexible( + child: pickerAndActions, + ), + ])); + } + return null; + })); + + return Theme( + data: theme.copyWith( + dialogBackgroundColor: Colors.transparent, + ), + child: dialog, + ); + } + + @override + void dispose() { + super.dispose(); + } +} + +/// Shows a dialog containing the duration picker. +/// +/// The returned Future resolves to the duration selected by the user when the user +/// closes the dialog. If the user cancels the dialog, null is returned. +/// +/// To show a dialog with [initialTime] equal to the current time: +/// +/// ```dart +/// showDurationPicker( +/// initialTime: new Duration.now(), +/// context: context, +/// ); +/// ``` +Future showDurationPicker( + {@required BuildContext context, + @required Duration initialTime, + double snapToMins}) async { + assert(context != null); + assert(initialTime != null); + + return await showDialog( + context: context, + builder: (context) => + _DurationPickerDialog(initialTime: initialTime, snapToMins: snapToMins), + ); +} + +class DurationPicker extends StatelessWidget { + final Duration duration; + final ValueChanged onChange; + final double snapToMins; + + final double width; + final double height; + + DurationPicker( + {this.duration = const Duration(minutes: 0), + @required this.onChange, + this.snapToMins, + this.width, + this.height, + Key key}) + : super(key: key); + + @override + Widget build(BuildContext context) { + return SizedBox( + width: width ?? _kDurationPickerWidthPortrait / 1.5, + height: height ?? _kDurationPickerHeightPortrait / 1.5, + child: _Dial( + duration: duration, + onChanged: onChange, + snapToMins: snapToMins, + ), + ); + } +} diff --git a/lib/util/episodegrid.dart b/lib/util/episodegrid.dart index 3ab8de2..2982fbc 100644 --- a/lib/util/episodegrid.dart +++ b/lib/util/episodegrid.dart @@ -1,849 +1,849 @@ -import 'dart:ui'; - -import 'package:auto_animated/auto_animated.dart'; -import 'package:connectivity/connectivity.dart'; -import 'package:flutter/material.dart'; -import 'package:fluttertoast/fluttertoast.dart'; -import 'package:focused_menu/focused_menu.dart'; -import 'package:focused_menu/modals.dart'; -import 'package:google_fonts/google_fonts.dart'; -import 'package:line_icons/line_icons.dart'; -import 'package:permission_handler/permission_handler.dart'; -import 'package:provider/provider.dart'; -import 'package:tuple/tuple.dart'; - -import '../episodes/episode_detail.dart'; -import '../home/audioplayer.dart'; -import '../local_storage/key_value_storage.dart'; -import '../local_storage/sqflite_localpodcast.dart'; -import '../state/audio_state.dart'; -import '../state/download_state.dart'; -import '../type/episodebrief.dart'; -import '../type/play_histroy.dart'; -import 'custom_widget.dart'; -import 'extension_helper.dart'; -import 'general_dialog.dart'; -import 'open_container.dart'; - -enum Layout { three, two, one } - -// ignore: must_be_immutable -class EpisodeGrid extends StatelessWidget { - final List episodes; - final bool showFavorite; - final bool showDownload; - final bool showNumber; - final int episodeCount; - final Layout layout; - final bool reverse; - final bool multiSelect; - final ValueChanged> onSelect; - final List selectedList; - - /// Count of animation items. - final int initNum; - - EpisodeGrid( - {Key key, - @required this.episodes, - this.initNum = 12, - this.showDownload = false, - this.showFavorite = false, - this.showNumber = false, - this.episodeCount = 0, - this.layout = Layout.three, - this.reverse, - this.multiSelect = false, - this.onSelect, - this.selectedList}) - : super(key: key); - - List _selectedList = []; - - Future _isListened(EpisodeBrief episode) async { - var dbHelper = DBHelper(); - return await dbHelper.isListened(episode.enclosureUrl); - } - - Future>> _initData( - EpisodeBrief episode) async { - var menuList = await _getEpisodeMenu(); - var tapToOpen = await _getTapToOpenPopupMenu(); - var listened = await _isListened(episode); - var liked = await _isLiked(episode); - var downloaded = await _isDownloaded(episode); - return Tuple5(listened, liked, downloaded, tapToOpen, menuList); - } - - Future _isLiked(EpisodeBrief episode) async { - var dbHelper = DBHelper(); - return await dbHelper.isLiked(episode.enclosureUrl); - } - - Future> _getEpisodeMenu() async { - var popupMenuStorage = KeyValueStorage(episodePopupMenuKey); - var list = await popupMenuStorage.getMenu(); - return list; - } - - Future _isDownloaded(EpisodeBrief episode) async { - var dbHelper = DBHelper(); - return await dbHelper.isDownloaded(episode.enclosureUrl); - } - - Future _getTapToOpenPopupMenu() async { - var tapToOpenPopupMenuStorage = KeyValueStorage(tapToOpenPopupMenuKey); - var boo = await tapToOpenPopupMenuStorage.getBool(defaultValue: false); - return boo; - } - - Future _markListened(EpisodeBrief episode) async { - var dbHelper = DBHelper(); - final history = PlayHistory(episode.title, episode.enclosureUrl, 0, 1); - await dbHelper.saveHistory(history); - } - - Future _markNotListened(String url) async { - var dbHelper = DBHelper(); - await dbHelper.markNotListened(url); - } - - Future _saveLiked(String url) async { - var dbHelper = DBHelper(); - await dbHelper.setLiked(url); - } - - Future _setUnliked(String url) async { - var dbHelper = DBHelper(); - await dbHelper.setUniked(url); - } - - Future _requestDownload(BuildContext context, - {EpisodeBrief episode}) async { - final permissionReady = await _checkPermmison(); - final downloadUsingData = await KeyValueStorage(downloadUsingDataKey) - .getBool(defaultValue: true, reverse: true); - final result = await Connectivity().checkConnectivity(); - final usingData = result == ConnectivityResult.mobile; - var dataConfirm = true; - if (permissionReady) { - if (downloadUsingData && usingData) { - dataConfirm = await _useDataConfirm(context); - } - if (dataConfirm) { - context.read().startTask(episode); - Fluttertoast.showToast( - msg: context.s.downloadStart, - gravity: ToastGravity.BOTTOM, - ); - } - } - } - - Future _checkPermmison() async { - var permission = await Permission.storage.status; - if (permission != PermissionStatus.granted) { - var permissions = await [Permission.storage].request(); - if (permissions[Permission.storage] == PermissionStatus.granted) { - return true; - } else { - return false; - } - } else { - return true; - } - } - - Future _useDataConfirm(BuildContext context) async { - var ifUseData = false; - final s = context.s; - await generalDialog( - context, - title: Text(s.cellularConfirm), - content: Text(s.cellularConfirmDes), - actions: [ - FlatButton( - onPressed: () { - Navigator.of(context).pop(); - }, - child: Text( - s.cancel, - style: TextStyle(color: Colors.grey[600]), - ), - ), - FlatButton( - onPressed: () { - ifUseData = true; - Navigator.of(context).pop(); - }, - child: Text( - s.confirm, - style: TextStyle(color: Colors.red), - ), - ) - ], - ); - return ifUseData; - } - - /// Episode title widget. - Widget _title(EpisodeBrief episode) => Container( - alignment: - layout == Layout.one ? Alignment.centerLeft : Alignment.topLeft, - padding: EdgeInsets.only(top: 2.0), - child: Text( - episode.title, - maxLines: layout == Layout.one ? 1 : 4, - overflow: - layout == Layout.one ? TextOverflow.ellipsis : TextOverflow.fade, - ), - ); - - /// Circel avatar widget. - Widget _circleImage(BuildContext context, - {EpisodeBrief episode, Color color, bool boo, double radius}) => - Container( - height: radius ?? context.width / 16, - width: radius ?? context.width / 16, - child: boo - ? Center() - : CircleAvatar( - backgroundColor: color.withOpacity(0.5), - backgroundImage: episode.avatarImage), - ); - - Widget _downloadIndicater(BuildContext context, - {EpisodeBrief episode, bool isDownloaded}) => - showDownload || layout != Layout.three - ? isDownloaded - ? Container( - height: 20, - width: 20, - alignment: Alignment.center, - margin: EdgeInsets.symmetric(horizontal: 5), - padding: EdgeInsets.fromLTRB(2, 2, 2, 3), - decoration: BoxDecoration( - color: context.accentColor, - shape: BoxShape.circle, - ), - child: CustomPaint( - size: Size(12, 12), - painter: DownloadPainter( - stroke: 1.0, - color: context.accentColor, - fraction: 1, - progressColor: Colors.white, - progress: 1, - ), - ), - ) - : Center() - : Center(); - - /// New indicator widget. - Widget _isNewIndicator(EpisodeBrief episode) => episode.isNew == 1 - ? Container( - padding: EdgeInsets.symmetric(horizontal: 2), - child: Text('New', - style: TextStyle(color: Colors.red, fontStyle: FontStyle.italic)), - ) - : Center(); - - /// Count indicator widget. - Widget _numberIndicater(BuildContext context, {int index, Color color}) => - showNumber - ? Container( - alignment: Alignment.topRight, - child: Text( - reverse - ? (index + 1).toString() - : (episodeCount - index).toString(), - style: GoogleFonts.teko( - textStyle: TextStyle( - fontSize: context.width / 24, - color: color, - ), - ), - ), - ) - : Center(); - - /// Pubdate widget - Widget _pubDate(BuildContext context, {EpisodeBrief episode, Color color}) => - Text( - episode.pubDate.toDate(context), - overflow: TextOverflow.visible, - textAlign: TextAlign.center, - style: TextStyle( - height: 1, - fontSize: context.width / 35, - color: color, - fontStyle: FontStyle.italic), - ); - Widget _episodeCard(BuildContext context, - {int index, Color color, bool isLiked, bool isDownloaded, bool boo}) { - var width = context.width; - if (layout == Layout.one) { - return _layoutOneCard(context, - index: index, - color: color, - isLiked: isLiked, - isDownloaded: isDownloaded, - boo: boo); - } - return Padding( - padding: const EdgeInsets.all(8.0), - child: Column( - mainAxisAlignment: MainAxisAlignment.start, - children: [ - Expanded( - flex: layout == Layout.one ? 1 : 2, - child: Row( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - layout != Layout.one - ? _circleImage(context, - episode: episodes[index], color: color, boo: boo) - : _pubDate(context, episode: episodes[index], color: color), - Spacer(), - _isNewIndicator(episodes[index]), - _downloadIndicater(context, - episode: episodes[index], isDownloaded: isDownloaded), - _numberIndicater(context, index: index, color: color) - ], - ), - ), - Expanded( - flex: layout == Layout.one ? 3 : 5, - child: layout != Layout.one - ? _title(episodes[index]) - : Row( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - _circleImage(context, - episode: episodes[index], color: color, boo: boo), - SizedBox( - width: 5, - ), - Expanded(child: _title(episodes[index])) - ], - ), - ), - Expanded( - flex: 1, - child: Row( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisAlignment: MainAxisAlignment.start, - children: [ - if (layout != Layout.one) - _pubDate(context, episode: episodes[index], color: color), - Spacer(), - if (layout != Layout.three && episodes[index].duration != 0) - Align( - alignment: Alignment.center, - child: Text( - episodes[index].duration.toTime, - style: TextStyle(fontSize: width / 35), - ), - ), - if (episodes[index].duration != 0 && - episodes[index].enclosureLength != null && - episodes[index].enclosureLength != 0 && - layout != Layout.three) - Text( - '|', - style: TextStyle( - fontSize: width / 35, - ), - ), - if (layout != Layout.three && - episodes[index].enclosureLength != null && - episodes[index].enclosureLength != 0) - Align( - alignment: Alignment.center, - child: Text( - '${(episodes[index].enclosureLength) ~/ 1000000}MB', - style: TextStyle(fontSize: width / 35), - ), - ), - Padding( - padding: EdgeInsets.all(1), - ), - if ((showFavorite || layout != Layout.three) && isLiked) - Icon( - Icons.favorite, - color: Colors.red, - size: width / 35, - ) - ], - ), - ), - ], - ), - ); - } - - Widget _layoutOneCard(BuildContext context, - {int index, Color color, bool isLiked, bool isDownloaded, bool boo}) { - var width = context.width; - return Padding( - padding: EdgeInsets.symmetric(vertical: 8), - child: Row( - mainAxisAlignment: MainAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Expanded( - flex: 1, - child: Center( - child: _circleImage(context, - episode: episodes[index], - color: color, - boo: boo, - radius: context.width / 8), - ), - ), - Expanded( - flex: 4, - child: Column( - mainAxisSize: MainAxisSize.min, - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Expanded( - flex: 1, - child: Row( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Expanded( - child: Text(episodes[index].feedTitle, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle( - fontWeight: FontWeight.bold, color: color)), - ), - _isNewIndicator(episodes[index]), - _downloadIndicater(context, - episode: episodes[index], isDownloaded: isDownloaded), - _numberIndicater(context, index: index, color: color) - ], - ), - ), - Expanded( - flex: 2, - child: Align( - alignment: Alignment.topLeft, - child: _title(episodes[index]))), - Expanded( - flex: 1, - child: Row( - crossAxisAlignment: CrossAxisAlignment.center, - mainAxisAlignment: MainAxisAlignment.start, - children: [ - if (episodes[index].duration != 0) - Align( - alignment: Alignment.center, - child: Text( - episodes[index].duration.toTime, - style: TextStyle(fontSize: width / 35), - ), - ), - if (episodes[index].duration != 0 && - episodes[index].enclosureLength != null && - episodes[index].enclosureLength != 0 && - layout != Layout.three) - Text( - '|', - style: TextStyle( - fontSize: width / 35, - ), - ), - if (episodes[index].enclosureLength != null && - episodes[index].enclosureLength != 0) - Align( - alignment: Alignment.center, - child: Text( - '${(episodes[index].enclosureLength) ~/ 1000000}MB', - style: TextStyle(fontSize: width / 35), - ), - ), - SizedBox(width: 4), - if (isLiked) - Icon( - Icons.favorite, - color: Colors.red, - size: width / 35, - ), - Spacer(), - _pubDate(context, - episode: episodes[index], color: color), - ]), - ) - ], - ), - ), - SizedBox(width: 8) - ], - ), - ); - } - - @override - Widget build(BuildContext context) { - var audio = Provider.of(context, listen: false); - final options = LiveOptions( - delay: Duration.zero, - showItemInterval: Duration(milliseconds: 50), - showItemDuration: Duration(milliseconds: 50), - ); - final scrollController = ScrollController(); - final s = context.s; - return SliverPadding( - padding: const EdgeInsets.only( - top: 10.0, bottom: 5.0, left: 15.0, right: 15.0), - sliver: LiveSliverGrid.options( - controller: scrollController, - options: options, - itemCount: episodes.length, - gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( - childAspectRatio: layout == Layout.three - ? 1 - : layout == Layout.two - ? 1.5 - : 4, - crossAxisCount: layout == Layout.three - ? 3 - : layout == Layout.two - ? 2 - : 1, - mainAxisSpacing: 6.0, - crossAxisSpacing: 6.0, - ), - itemBuilder: (context, index, animation) { - final c = episodes[index].backgroudColor(context); - scrollController.addListener(() {}); - - return FadeTransition( - opacity: Tween(begin: index < initNum ? 0 : 1, end: 1) - .animate(animation), - child: Selector, bool>>( - selector: (_, audio) => Tuple3( - audio?.episode, - audio.queue.playlist.map((e) => e.enclosureUrl).toList(), - audio.episodeState), - builder: (_, data, __) => OpenContainerWrapper( - avatarSize: layout == Layout.one - ? context.width / 8 - : context.width / 16, - episode: episodes[index], - closedBuilder: (context, action, boo) => - FutureBuilder>>( - future: _initData(episodes[index]), - initialData: Tuple5(0, false, false, false, []), - builder: (context, snapshot) { - var isListened = snapshot.data.item1; - var isLiked = snapshot.data.item2; - var isDownloaded = snapshot.data.item3; - var tapToOpen = snapshot.data.item4; - var menuList = snapshot.data.item5; - return Container( - decoration: BoxDecoration( - borderRadius: BorderRadius.all(Radius.circular(5.0)), - color: isListened > 0 - ? context.brightness == Brightness.light - ? Colors.grey[200] - : Color.fromRGBO(50, 50, 50, 1) - : context.scaffoldBackgroundColor, - boxShadow: [ - BoxShadow( - color: context.brightness == Brightness.light - ? context.primaryColor - : Color.fromRGBO(40, 40, 40, 1), - blurRadius: 0.5, - spreadRadius: 0.5, - ), - ]), - alignment: Alignment.center, - child: multiSelect - ? Material( - color: Colors.transparent, - child: InkWell( - onTap: () { - if (!selectedList.contains(episodes[index])) { - _selectedList = selectedList; - _selectedList.add(episodes[index]); - } else { - _selectedList = selectedList; - _selectedList.remove(episodes[index]); - } - onSelect(_selectedList); - }, - child: Container( - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(5.0), - border: Border.all( - color: selectedList - .contains(episodes[index]) - ? context.accentColor - : context.brightness == - Brightness.light - ? context.primaryColor - : context.scaffoldBackgroundColor, - width: 1.0, - ), - ), - child: _episodeCard(context, - index: index, - isLiked: isLiked, - isDownloaded: isDownloaded, - color: c, - boo: boo), - ), - ), - ) - : Container( - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(5.0), - border: Border.all( - color: context.brightness == Brightness.light - ? context.primaryColor - : context.scaffoldBackgroundColor, - width: 1.0, - ), - ), - child: FocusedMenuHolder( - blurSize: 0.0, - menuItemExtent: 45, - menuBoxDecoration: BoxDecoration( - color: Colors.transparent, - borderRadius: BorderRadius.circular(15.0)), - duration: Duration(milliseconds: 100), - tapMode: tapToOpen - ? TapMode.onTap - : TapMode.onLongPress, - animateMenuItems: false, - blurBackgroundColor: - context.brightness == Brightness.light - ? Colors.white38 - : Colors.black38, - bottomOffsetHeight: 10, - menuOffset: 6, - menuItems: [ - FocusedMenuItem( - backgroundColor: - context.brightness == Brightness.light - ? context.primaryColor - : context.dialogBackgroundColor, - title: Text(data.item1 != episodes[index] - ? s.play - : s.playing), - trailingIcon: Icon( - LineIcons.play_circle_solid, - color: Theme.of(context).accentColor, - ), - onPressed: () { - if (data.item1 != episodes[index]) { - audio.episodeLoad(episodes[index]); - } - }), - menuList.contains(1) - ? FocusedMenuItem( - backgroundColor: context.brightness == - Brightness.light - ? context.primaryColor - : context.dialogBackgroundColor, - title: data.item2.contains( - episodes[index].enclosureUrl) - ? Text(s.remove) - : Text(s.later), - trailingIcon: Icon( - LineIcons.clock_solid, - color: Colors.cyan, - ), - onPressed: () { - if (!data.item2.contains( - episodes[index].enclosureUrl)) { - audio.addToPlaylist( - episodes[index]); - Fluttertoast.showToast( - msg: s.toastAddPlaylist, - gravity: ToastGravity.BOTTOM, - ); - } else { - audio.delFromPlaylist( - episodes[index]); - Fluttertoast.showToast( - msg: s.toastRemovePlaylist, - gravity: ToastGravity.BOTTOM, - ); - } - }) - : null, - menuList.contains(2) - ? FocusedMenuItem( - backgroundColor: context.brightness == - Brightness.light - ? context.primaryColor - : context.dialogBackgroundColor, - title: isLiked - ? Text(s.unlike) - : Text(s.like), - trailingIcon: Icon(LineIcons.heart, - color: Colors.red, size: 21), - onPressed: () async { - if (isLiked) { - await _setUnliked( - episodes[index].enclosureUrl); - audio.setEpisodeState = true; - Fluttertoast.showToast( - msg: s.unliked, - gravity: ToastGravity.BOTTOM, - ); - } else { - await _saveLiked( - episodes[index].enclosureUrl); - audio.setEpisodeState = true; - Fluttertoast.showToast( - msg: s.liked, - gravity: ToastGravity.BOTTOM, - ); - } - }) - : null, - menuList.contains(3) - ? FocusedMenuItem( - backgroundColor: context.brightness == - Brightness.light - ? context.primaryColor - : context.dialogBackgroundColor, - title: isListened > 0 - ? Text(s.markNotListened, - style: TextStyle( - color: context.textColor - .withOpacity(0.5))) - : Text( - s.markListened, - maxLines: 1, - overflow: - TextOverflow.ellipsis, - ), - trailingIcon: SizedBox( - width: 23, - height: 23, - child: CustomPaint( - painter: ListenedAllPainter( - Colors.blue, - stroke: 1.5)), - ), - onPressed: () async { - if (isListened < 1) { - await _markListened( - episodes[index]); - audio.setEpisodeState = true; - Fluttertoast.showToast( - msg: s.markListened, - gravity: ToastGravity.BOTTOM, - ); - } else { - await _markNotListened( - episodes[index].enclosureUrl); - audio.setEpisodeState = true; - Fluttertoast.showToast( - msg: s.markNotListened, - gravity: ToastGravity.BOTTOM, - ); - } - }) - : null, - menuList.contains(4) - ? FocusedMenuItem( - backgroundColor: context.brightness == - Brightness.light - ? context.primaryColor - : context.dialogBackgroundColor, - title: isDownloaded - ? Text(s.downloaded, - style: TextStyle( - color: context.textColor - .withOpacity(0.5))) - : Text(s.download), - trailingIcon: Icon( - LineIcons.download_solid, - color: Colors.green), - onPressed: () async { - if (!isDownloaded) { - await _requestDownload(context, - episode: episodes[index]); - // downloader - // .startTask(episodes[index]); - } - }) - : null - ], - action: action, - child: _episodeCard(context, - index: index, - isLiked: isLiked, - isDownloaded: isDownloaded, - color: c, - boo: boo), - ), - ), - ); - }, - ), - ), - ), - ); - }, - ), - ); - } -} - -class OpenContainerWrapper extends StatelessWidget { - const OpenContainerWrapper( - {this.closedBuilder, this.episode, this.playerRunning, this.avatarSize}); - - final OpenContainerBuilder closedBuilder; - final EpisodeBrief episode; - final bool playerRunning; - final double avatarSize; - - @override - Widget build(BuildContext context) { - return Selector>( - selector: (_, audio) => Tuple2(audio.playerRunning, audio.playerHeight), - builder: (_, data, __) => OpenContainer( - playerRunning: data.item1, - playerHeight: kMinPlayerHeight[data.item2.index], - flightWidget: CircleAvatar(backgroundImage: episode.avatarImage), - flightWidgetSize: avatarSize, - transitionDuration: Duration(milliseconds: 400), - beginColor: Theme.of(context).primaryColor, - endColor: Theme.of(context).primaryColor, - closedColor: Theme.of(context).brightness == Brightness.light - ? Theme.of(context).primaryColor - : Theme.of(context).scaffoldBackgroundColor, - openColor: Theme.of(context).scaffoldBackgroundColor, - openElevation: 0, - closedElevation: 0, - openShape: - RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)), - closedShape: - RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0)), - transitionType: ContainerTransitionType.fadeThrough, - openBuilder: (context, _, boo) { - return EpisodeDetail( - episodeItem: episode, - hide: boo, - ); - }, - tappable: true, - closedBuilder: closedBuilder, - ), - ); - } -} +import 'dart:ui'; + +import 'package:auto_animated/auto_animated.dart'; +import 'package:connectivity/connectivity.dart'; +import 'package:flutter/material.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:focused_menu/focused_menu.dart'; +import 'package:focused_menu/modals.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:line_icons/line_icons.dart'; +import 'package:permission_handler/permission_handler.dart'; +import 'package:provider/provider.dart'; +import 'package:tuple/tuple.dart'; + +import '../episodes/episode_detail.dart'; +import '../home/audioplayer.dart'; +import '../local_storage/key_value_storage.dart'; +import '../local_storage/sqflite_localpodcast.dart'; +import '../state/audio_state.dart'; +import '../state/download_state.dart'; +import '../type/episodebrief.dart'; +import '../type/play_histroy.dart'; +import 'custom_widget.dart'; +import 'extension_helper.dart'; +import 'general_dialog.dart'; +import 'open_container.dart'; + +enum Layout { three, two, one } + +// ignore: must_be_immutable +class EpisodeGrid extends StatelessWidget { + final List episodes; + final bool showFavorite; + final bool showDownload; + final bool showNumber; + final int episodeCount; + final Layout layout; + final bool reverse; + final bool multiSelect; + final ValueChanged> onSelect; + final List selectedList; + + /// Count of animation items. + final int initNum; + + EpisodeGrid( + {Key key, + @required this.episodes, + this.initNum = 12, + this.showDownload = false, + this.showFavorite = false, + this.showNumber = false, + this.episodeCount = 0, + this.layout = Layout.three, + this.reverse, + this.multiSelect = false, + this.onSelect, + this.selectedList}) + : super(key: key); + + List _selectedList = []; + + Future _isListened(EpisodeBrief episode) async { + var dbHelper = DBHelper(); + return await dbHelper.isListened(episode.enclosureUrl); + } + + Future>> _initData( + EpisodeBrief episode) async { + var menuList = await _getEpisodeMenu(); + var tapToOpen = await _getTapToOpenPopupMenu(); + var listened = await _isListened(episode); + var liked = await _isLiked(episode); + var downloaded = await _isDownloaded(episode); + return Tuple5(listened, liked, downloaded, tapToOpen, menuList); + } + + Future _isLiked(EpisodeBrief episode) async { + var dbHelper = DBHelper(); + return await dbHelper.isLiked(episode.enclosureUrl); + } + + Future> _getEpisodeMenu() async { + var popupMenuStorage = KeyValueStorage(episodePopupMenuKey); + var list = await popupMenuStorage.getMenu(); + return list; + } + + Future _isDownloaded(EpisodeBrief episode) async { + var dbHelper = DBHelper(); + return await dbHelper.isDownloaded(episode.enclosureUrl); + } + + Future _getTapToOpenPopupMenu() async { + var tapToOpenPopupMenuStorage = KeyValueStorage(tapToOpenPopupMenuKey); + var boo = await tapToOpenPopupMenuStorage.getBool(defaultValue: false); + return boo; + } + + Future _markListened(EpisodeBrief episode) async { + var dbHelper = DBHelper(); + final history = PlayHistory(episode.title, episode.enclosureUrl, 0, 1); + await dbHelper.saveHistory(history); + } + + Future _markNotListened(String url) async { + var dbHelper = DBHelper(); + await dbHelper.markNotListened(url); + } + + Future _saveLiked(String url) async { + var dbHelper = DBHelper(); + await dbHelper.setLiked(url); + } + + Future _setUnliked(String url) async { + var dbHelper = DBHelper(); + await dbHelper.setUniked(url); + } + + Future _requestDownload(BuildContext context, + {EpisodeBrief episode}) async { + final permissionReady = await _checkPermmison(); + final downloadUsingData = await KeyValueStorage(downloadUsingDataKey) + .getBool(defaultValue: true, reverse: true); + final result = await Connectivity().checkConnectivity(); + final usingData = result == ConnectivityResult.mobile; + var dataConfirm = true; + if (permissionReady) { + if (downloadUsingData && usingData) { + dataConfirm = await _useDataConfirm(context); + } + if (dataConfirm) { + context.read().startTask(episode); + Fluttertoast.showToast( + msg: context.s.downloadStart, + gravity: ToastGravity.BOTTOM, + ); + } + } + } + + Future _checkPermmison() async { + var permission = await Permission.storage.status; + if (permission != PermissionStatus.granted) { + var permissions = await [Permission.storage].request(); + if (permissions[Permission.storage] == PermissionStatus.granted) { + return true; + } else { + return false; + } + } else { + return true; + } + } + + Future _useDataConfirm(BuildContext context) async { + var ifUseData = false; + final s = context.s; + await generalDialog( + context, + title: Text(s.cellularConfirm), + content: Text(s.cellularConfirmDes), + actions: [ + FlatButton( + onPressed: () { + Navigator.of(context).pop(); + }, + child: Text( + s.cancel, + style: TextStyle(color: Colors.grey[600]), + ), + ), + FlatButton( + onPressed: () { + ifUseData = true; + Navigator.of(context).pop(); + }, + child: Text( + s.confirm, + style: TextStyle(color: Colors.red), + ), + ) + ], + ); + return ifUseData; + } + + /// Episode title widget. + Widget _title(EpisodeBrief episode) => Container( + alignment: + layout == Layout.one ? Alignment.centerLeft : Alignment.topLeft, + padding: EdgeInsets.only(top: 2.0), + child: Text( + episode.title, + maxLines: layout == Layout.one ? 1 : 4, + overflow: + layout == Layout.one ? TextOverflow.ellipsis : TextOverflow.fade, + ), + ); + + /// Circel avatar widget. + Widget _circleImage(BuildContext context, + {EpisodeBrief episode, Color color, bool boo, double radius}) => + Container( + height: radius ?? context.width / 16, + width: radius ?? context.width / 16, + child: boo + ? Center() + : CircleAvatar( + backgroundColor: color.withOpacity(0.5), + backgroundImage: episode.avatarImage), + ); + + Widget _downloadIndicater(BuildContext context, + {EpisodeBrief episode, bool isDownloaded}) => + showDownload || layout != Layout.three + ? isDownloaded + ? Container( + height: 20, + width: 20, + alignment: Alignment.center, + margin: EdgeInsets.symmetric(horizontal: 5), + padding: EdgeInsets.fromLTRB(2, 2, 2, 3), + decoration: BoxDecoration( + color: context.accentColor, + shape: BoxShape.circle, + ), + child: CustomPaint( + size: Size(12, 12), + painter: DownloadPainter( + stroke: 1.0, + color: context.accentColor, + fraction: 1, + progressColor: Colors.white, + progress: 1, + ), + ), + ) + : Center() + : Center(); + + /// New indicator widget. + Widget _isNewIndicator(EpisodeBrief episode) => episode.isNew == 1 + ? Container( + padding: EdgeInsets.symmetric(horizontal: 2), + child: Text('New', + style: TextStyle(color: Colors.red, fontStyle: FontStyle.italic)), + ) + : Center(); + + /// Count indicator widget. + Widget _numberIndicater(BuildContext context, {int index, Color color}) => + showNumber + ? Container( + alignment: Alignment.topRight, + child: Text( + reverse + ? (index + 1).toString() + : (episodeCount - index).toString(), + style: GoogleFonts.teko( + textStyle: TextStyle( + fontSize: context.width / 24, + color: color, + ), + ), + ), + ) + : Center(); + + /// Pubdate widget + Widget _pubDate(BuildContext context, {EpisodeBrief episode, Color color}) => + Text( + episode.pubDate.toDate(context), + overflow: TextOverflow.visible, + textAlign: TextAlign.center, + style: TextStyle( + height: 1, + fontSize: context.width / 35, + color: color, + fontStyle: FontStyle.italic), + ); + Widget _episodeCard(BuildContext context, + {int index, Color color, bool isLiked, bool isDownloaded, bool boo}) { + var width = context.width; + if (layout == Layout.one) { + return _layoutOneCard(context, + index: index, + color: color, + isLiked: isLiked, + isDownloaded: isDownloaded, + boo: boo); + } + return Padding( + padding: const EdgeInsets.all(8.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + Expanded( + flex: layout == Layout.one ? 1 : 2, + child: Row( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + layout != Layout.one + ? _circleImage(context, + episode: episodes[index], color: color, boo: boo) + : _pubDate(context, episode: episodes[index], color: color), + Spacer(), + _isNewIndicator(episodes[index]), + _downloadIndicater(context, + episode: episodes[index], isDownloaded: isDownloaded), + _numberIndicater(context, index: index, color: color) + ], + ), + ), + Expanded( + flex: layout == Layout.one ? 3 : 5, + child: layout != Layout.one + ? _title(episodes[index]) + : Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + _circleImage(context, + episode: episodes[index], color: color, boo: boo), + SizedBox( + width: 5, + ), + Expanded(child: _title(episodes[index])) + ], + ), + ), + Expanded( + flex: 1, + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.start, + children: [ + if (layout != Layout.one) + _pubDate(context, episode: episodes[index], color: color), + Spacer(), + if (layout != Layout.three && episodes[index].duration != 0) + Align( + alignment: Alignment.center, + child: Text( + episodes[index].duration.toTime, + style: TextStyle(fontSize: width / 35), + ), + ), + if (episodes[index].duration != 0 && + episodes[index].enclosureLength != null && + episodes[index].enclosureLength != 0 && + layout != Layout.three) + Text( + '|', + style: TextStyle( + fontSize: width / 35, + ), + ), + if (layout != Layout.three && + episodes[index].enclosureLength != null && + episodes[index].enclosureLength != 0) + Align( + alignment: Alignment.center, + child: Text( + '${(episodes[index].enclosureLength) ~/ 1000000}MB', + style: TextStyle(fontSize: width / 35), + ), + ), + Padding( + padding: EdgeInsets.all(1), + ), + if ((showFavorite || layout != Layout.three) && isLiked) + Icon( + Icons.favorite, + color: Colors.red, + size: width / 35, + ) + ], + ), + ), + ], + ), + ); + } + + Widget _layoutOneCard(BuildContext context, + {int index, Color color, bool isLiked, bool isDownloaded, bool boo}) { + var width = context.width; + return Padding( + padding: EdgeInsets.symmetric(vertical: 8), + child: Row( + mainAxisAlignment: MainAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Expanded( + flex: 1, + child: Center( + child: _circleImage(context, + episode: episodes[index], + color: color, + boo: boo, + radius: context.width / 8), + ), + ), + Expanded( + flex: 4, + child: Column( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Expanded( + flex: 1, + child: Row( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Expanded( + child: Text(episodes[index].feedTitle, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontWeight: FontWeight.bold, color: color)), + ), + _isNewIndicator(episodes[index]), + _downloadIndicater(context, + episode: episodes[index], isDownloaded: isDownloaded), + _numberIndicater(context, index: index, color: color) + ], + ), + ), + Expanded( + flex: 2, + child: Align( + alignment: Alignment.topLeft, + child: _title(episodes[index]))), + Expanded( + flex: 1, + child: Row( + crossAxisAlignment: CrossAxisAlignment.center, + mainAxisAlignment: MainAxisAlignment.start, + children: [ + if (episodes[index].duration != 0) + Align( + alignment: Alignment.center, + child: Text( + episodes[index].duration.toTime, + style: TextStyle(fontSize: width / 35), + ), + ), + if (episodes[index].duration != 0 && + episodes[index].enclosureLength != null && + episodes[index].enclosureLength != 0 && + layout != Layout.three) + Text( + '|', + style: TextStyle( + fontSize: width / 35, + ), + ), + if (episodes[index].enclosureLength != null && + episodes[index].enclosureLength != 0) + Align( + alignment: Alignment.center, + child: Text( + '${(episodes[index].enclosureLength) ~/ 1000000}MB', + style: TextStyle(fontSize: width / 35), + ), + ), + SizedBox(width: 4), + if (isLiked) + Icon( + Icons.favorite, + color: Colors.red, + size: width / 35, + ), + Spacer(), + _pubDate(context, + episode: episodes[index], color: color), + ]), + ) + ], + ), + ), + SizedBox(width: 8) + ], + ), + ); + } + + @override + Widget build(BuildContext context) { + var audio = Provider.of(context, listen: false); + final options = LiveOptions( + delay: Duration.zero, + showItemInterval: Duration(milliseconds: 50), + showItemDuration: Duration(milliseconds: 50), + ); + final scrollController = ScrollController(); + final s = context.s; + return SliverPadding( + padding: const EdgeInsets.only( + top: 10.0, bottom: 5.0, left: 15.0, right: 15.0), + sliver: LiveSliverGrid.options( + controller: scrollController, + options: options, + itemCount: episodes.length, + gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( + childAspectRatio: layout == Layout.three + ? 1 + : layout == Layout.two + ? 1.5 + : 4, + crossAxisCount: layout == Layout.three + ? 3 + : layout == Layout.two + ? 2 + : 1, + mainAxisSpacing: 6.0, + crossAxisSpacing: 6.0, + ), + itemBuilder: (context, index, animation) { + final c = episodes[index].backgroudColor(context); + scrollController.addListener(() {}); + + return FadeTransition( + opacity: Tween(begin: index < initNum ? 0 : 1, end: 1) + .animate(animation), + child: Selector, bool>>( + selector: (_, audio) => Tuple3( + audio?.episode, + audio.queue.playlist.map((e) => e.enclosureUrl).toList(), + audio.episodeState), + builder: (_, data, __) => OpenContainerWrapper( + avatarSize: layout == Layout.one + ? context.width / 8 + : context.width / 16, + episode: episodes[index], + closedBuilder: (context, action, boo) => + FutureBuilder>>( + future: _initData(episodes[index]), + initialData: Tuple5(0, false, false, false, []), + builder: (context, snapshot) { + var isListened = snapshot.data.item1; + var isLiked = snapshot.data.item2; + var isDownloaded = snapshot.data.item3; + var tapToOpen = snapshot.data.item4; + var menuList = snapshot.data.item5; + return Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.all(Radius.circular(5.0)), + color: isListened > 0 + ? context.brightness == Brightness.light + ? Colors.grey[200] + : Color.fromRGBO(50, 50, 50, 1) + : context.scaffoldBackgroundColor, + boxShadow: [ + BoxShadow( + color: context.brightness == Brightness.light + ? context.primaryColor + : Color.fromRGBO(40, 40, 40, 1), + blurRadius: 0.5, + spreadRadius: 0.5, + ), + ]), + alignment: Alignment.center, + child: multiSelect + ? Material( + color: Colors.transparent, + child: InkWell( + onTap: () { + if (!selectedList.contains(episodes[index])) { + _selectedList = selectedList; + _selectedList.add(episodes[index]); + } else { + _selectedList = selectedList; + _selectedList.remove(episodes[index]); + } + onSelect(_selectedList); + }, + child: Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(5.0), + border: Border.all( + color: selectedList + .contains(episodes[index]) + ? context.accentColor + : context.brightness == + Brightness.light + ? context.primaryColor + : context.scaffoldBackgroundColor, + width: 1.0, + ), + ), + child: _episodeCard(context, + index: index, + isLiked: isLiked, + isDownloaded: isDownloaded, + color: c, + boo: boo), + ), + ), + ) + : Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(5.0), + border: Border.all( + color: context.brightness == Brightness.light + ? context.primaryColor + : context.scaffoldBackgroundColor, + width: 1.0, + ), + ), + child: FocusedMenuHolder( + blurSize: 0.0, + menuItemExtent: 45, + menuBoxDecoration: BoxDecoration( + color: Colors.transparent, + borderRadius: BorderRadius.circular(15.0)), + duration: Duration(milliseconds: 100), + tapMode: tapToOpen + ? TapMode.onTap + : TapMode.onLongPress, + animateMenuItems: false, + blurBackgroundColor: + context.brightness == Brightness.light + ? Colors.white38 + : Colors.black38, + bottomOffsetHeight: 10, + menuOffset: 6, + menuItems: [ + FocusedMenuItem( + backgroundColor: + context.brightness == Brightness.light + ? context.primaryColor + : context.dialogBackgroundColor, + title: Text(data.item1 != episodes[index] + ? s.play + : s.playing), + trailingIcon: Icon( + LineIcons.play_circle_solid, + color: Theme.of(context).accentColor, + ), + onPressed: () { + if (data.item1 != episodes[index]) { + audio.episodeLoad(episodes[index]); + } + }), + menuList.contains(1) + ? FocusedMenuItem( + backgroundColor: context.brightness == + Brightness.light + ? context.primaryColor + : context.dialogBackgroundColor, + title: data.item2.contains( + episodes[index].enclosureUrl) + ? Text(s.remove) + : Text(s.later), + trailingIcon: Icon( + LineIcons.clock_solid, + color: Colors.cyan, + ), + onPressed: () { + if (!data.item2.contains( + episodes[index].enclosureUrl)) { + audio.addToPlaylist( + episodes[index]); + Fluttertoast.showToast( + msg: s.toastAddPlaylist, + gravity: ToastGravity.BOTTOM, + ); + } else { + audio.delFromPlaylist( + episodes[index]); + Fluttertoast.showToast( + msg: s.toastRemovePlaylist, + gravity: ToastGravity.BOTTOM, + ); + } + }) + : null, + menuList.contains(2) + ? FocusedMenuItem( + backgroundColor: context.brightness == + Brightness.light + ? context.primaryColor + : context.dialogBackgroundColor, + title: isLiked + ? Text(s.unlike) + : Text(s.like), + trailingIcon: Icon(LineIcons.heart, + color: Colors.red, size: 21), + onPressed: () async { + if (isLiked) { + await _setUnliked( + episodes[index].enclosureUrl); + audio.setEpisodeState = true; + Fluttertoast.showToast( + msg: s.unliked, + gravity: ToastGravity.BOTTOM, + ); + } else { + await _saveLiked( + episodes[index].enclosureUrl); + audio.setEpisodeState = true; + Fluttertoast.showToast( + msg: s.liked, + gravity: ToastGravity.BOTTOM, + ); + } + }) + : null, + menuList.contains(3) + ? FocusedMenuItem( + backgroundColor: context.brightness == + Brightness.light + ? context.primaryColor + : context.dialogBackgroundColor, + title: isListened > 0 + ? Text(s.markNotListened, + style: TextStyle( + color: context.textColor + .withOpacity(0.5))) + : Text( + s.markListened, + maxLines: 1, + overflow: + TextOverflow.ellipsis, + ), + trailingIcon: SizedBox( + width: 23, + height: 23, + child: CustomPaint( + painter: ListenedAllPainter( + Colors.blue, + stroke: 1.5)), + ), + onPressed: () async { + if (isListened < 1) { + await _markListened( + episodes[index]); + audio.setEpisodeState = true; + Fluttertoast.showToast( + msg: s.markListened, + gravity: ToastGravity.BOTTOM, + ); + } else { + await _markNotListened( + episodes[index].enclosureUrl); + audio.setEpisodeState = true; + Fluttertoast.showToast( + msg: s.markNotListened, + gravity: ToastGravity.BOTTOM, + ); + } + }) + : null, + menuList.contains(4) + ? FocusedMenuItem( + backgroundColor: context.brightness == + Brightness.light + ? context.primaryColor + : context.dialogBackgroundColor, + title: isDownloaded + ? Text(s.downloaded, + style: TextStyle( + color: context.textColor + .withOpacity(0.5))) + : Text(s.download), + trailingIcon: Icon( + LineIcons.download_solid, + color: Colors.green), + onPressed: () async { + if (!isDownloaded) { + await _requestDownload(context, + episode: episodes[index]); + // downloader + // .startTask(episodes[index]); + } + }) + : null + ], + action: action, + child: _episodeCard(context, + index: index, + isLiked: isLiked, + isDownloaded: isDownloaded, + color: c, + boo: boo), + ), + ), + ); + }, + ), + ), + ), + ); + }, + ), + ); + } +} + +class OpenContainerWrapper extends StatelessWidget { + const OpenContainerWrapper( + {this.closedBuilder, this.episode, this.playerRunning, this.avatarSize}); + + final OpenContainerBuilder closedBuilder; + final EpisodeBrief episode; + final bool playerRunning; + final double avatarSize; + + @override + Widget build(BuildContext context) { + return Selector>( + selector: (_, audio) => Tuple2(audio.playerRunning, audio.playerHeight), + builder: (_, data, __) => OpenContainer( + playerRunning: data.item1, + playerHeight: kMinPlayerHeight[data.item2.index], + flightWidget: CircleAvatar(backgroundImage: episode.avatarImage), + flightWidgetSize: avatarSize, + transitionDuration: Duration(milliseconds: 400), + beginColor: Theme.of(context).primaryColor, + endColor: Theme.of(context).primaryColor, + closedColor: Theme.of(context).brightness == Brightness.light + ? Theme.of(context).primaryColor + : Theme.of(context).scaffoldBackgroundColor, + openColor: Theme.of(context).scaffoldBackgroundColor, + openElevation: 0, + closedElevation: 0, + openShape: + RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)), + closedShape: + RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0)), + transitionType: ContainerTransitionType.fadeThrough, + openBuilder: (context, _, boo) { + return EpisodeDetail( + episodeItem: episode, + hide: boo, + ); + }, + tappable: true, + closedBuilder: closedBuilder, + ), + ); + } +} diff --git a/lib/util/extension_helper.dart b/lib/util/extension_helper.dart index 9b44553..1695b3f 100644 --- a/lib/util/extension_helper.dart +++ b/lib/util/extension_helper.dart @@ -1,100 +1,100 @@ -import 'dart:convert'; -import 'dart:developer' as developer; - -import 'package:flutter/material.dart'; -import 'package:fluttertoast/fluttertoast.dart'; -import 'package:intl/intl.dart'; -import 'package:url_launcher/url_launcher.dart'; -import '../generated/l10n.dart'; - -extension ContextExtension on BuildContext { - Color get primaryColor => Theme.of(this).primaryColor; - Color get accentColor => Theme.of(this).accentColor; - Color get scaffoldBackgroundColor => Theme.of(this).scaffoldBackgroundColor; - Color get primaryColorDark => Theme.of(this).primaryColorDark; - Color get textColor => Theme.of(this).textTheme.bodyText1.color; - Color get dialogBackgroundColor => Theme.of(this).dialogBackgroundColor; - Brightness get brightness => Theme.of(this).brightness; - double get width => MediaQuery.of(this).size.width; - double get height => MediaQuery.of(this).size.height; - double get paddingTop => MediaQuery.of(this).padding.top; - TextTheme get textTheme => Theme.of(this).textTheme; - S get s => S.of(this); -} - -extension IntExtension on int { - String toDate(BuildContext context) { - if (this == null) return ''; - final s = context.s; - var date = DateTime.fromMillisecondsSinceEpoch(this, isUtc: true); - var difference = DateTime.now().toUtc().difference(date); - if (difference.inMinutes < 30) { - return s.minsAgo(difference.inMinutes); - } else if (difference.inMinutes < 60) { - return s.hoursAgo(0); - } else if (difference.inHours < 24) { - return s.hoursAgo(difference.inHours); - } else if (difference.inDays < 7) { - return s.daysAgo(difference.inDays); - } else { - return DateFormat.yMMMd().format( - DateTime.fromMillisecondsSinceEpoch(this, isUtc: true).toLocal()); - } - } - - String get toTime => - '${(this ~/ 60).toString().padLeft(2, '0')}:${(truncate() % 60).toString().padLeft(2, '0')}'; - - String toInterval(BuildContext context) { - if (this == null || isNegative) return ''; - final s = context.s; - var interval = Duration(milliseconds: this); - if (interval.inHours <= 48) { - return s.publishedDaily; - } else if (interval.inDays > 2 && interval.inDays <= 14) { - return s.publishedWeekly; - } else if (interval.inDays > 14 && interval.inDays < 60) { - return s.publishedMonthly; - } else { - return s.publishedYearly; - } - } -} - -extension StringExtension on String { - Future get launchUrl async { - if (await canLaunch(this)) { - await launch(this); - } else { - developer.log('Could not launch $this'); - Fluttertoast.showToast( - msg: '$this Invalid Link', - gravity: ToastGravity.TOP, - ); - } - } - - Color colorizedark() { - Color c; - var color = json.decode(this); - if (color[0] > 200 && color[1] > 200 && color[2] > 200) { - c = Color.fromRGBO((255 - color[0]), 255 - color[1], 255 - color[2], 1.0); - } else { - c = Color.fromRGBO(color[0], color[1] > 200 ? 190 : color[1], - color[2] > 200 ? 190 : color[2], 1); - } - return c; - } - - Color colorizeLight() { - Color c; - var color = json.decode(this); - if (color[0] < 50 && color[1] < 50 && color[2] < 50) { - c = Color.fromRGBO((255 - color[0]), 255 - color[1], 255 - color[2], 1.0); - } else { - c = Color.fromRGBO(color[0] < 50 ? 100 : color[0], - color[1] < 50 ? 100 : color[1], color[2] < 50 ? 100 : color[2], 1.0); - } - return c; - } -} +import 'dart:convert'; +import 'dart:developer' as developer; + +import 'package:flutter/material.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:intl/intl.dart'; +import 'package:url_launcher/url_launcher.dart'; +import '../generated/l10n.dart'; + +extension ContextExtension on BuildContext { + Color get primaryColor => Theme.of(this).primaryColor; + Color get accentColor => Theme.of(this).accentColor; + Color get scaffoldBackgroundColor => Theme.of(this).scaffoldBackgroundColor; + Color get primaryColorDark => Theme.of(this).primaryColorDark; + Color get textColor => Theme.of(this).textTheme.bodyText1.color; + Color get dialogBackgroundColor => Theme.of(this).dialogBackgroundColor; + Brightness get brightness => Theme.of(this).brightness; + double get width => MediaQuery.of(this).size.width; + double get height => MediaQuery.of(this).size.height; + double get paddingTop => MediaQuery.of(this).padding.top; + TextTheme get textTheme => Theme.of(this).textTheme; + S get s => S.of(this); +} + +extension IntExtension on int { + String toDate(BuildContext context) { + if (this == null) return ''; + final s = context.s; + var date = DateTime.fromMillisecondsSinceEpoch(this, isUtc: true); + var difference = DateTime.now().toUtc().difference(date); + if (difference.inMinutes < 30) { + return s.minsAgo(difference.inMinutes); + } else if (difference.inMinutes < 60) { + return s.hoursAgo(0); + } else if (difference.inHours < 24) { + return s.hoursAgo(difference.inHours); + } else if (difference.inDays < 7) { + return s.daysAgo(difference.inDays); + } else { + return DateFormat.yMMMd().format( + DateTime.fromMillisecondsSinceEpoch(this, isUtc: true).toLocal()); + } + } + + String get toTime => + '${(this ~/ 60).toString().padLeft(2, '0')}:${(truncate() % 60).toString().padLeft(2, '0')}'; + + String toInterval(BuildContext context) { + if (this == null || isNegative) return ''; + final s = context.s; + var interval = Duration(milliseconds: this); + if (interval.inHours <= 48) { + return s.publishedDaily; + } else if (interval.inDays > 2 && interval.inDays <= 14) { + return s.publishedWeekly; + } else if (interval.inDays > 14 && interval.inDays < 60) { + return s.publishedMonthly; + } else { + return s.publishedYearly; + } + } +} + +extension StringExtension on String { + Future get launchUrl async { + if (await canLaunch(this)) { + await launch(this); + } else { + developer.log('Could not launch $this'); + Fluttertoast.showToast( + msg: '$this Invalid Link', + gravity: ToastGravity.TOP, + ); + } + } + + Color colorizedark() { + Color c; + var color = json.decode(this); + if (color[0] > 200 && color[1] > 200 && color[2] > 200) { + c = Color.fromRGBO((255 - color[0]), 255 - color[1], 255 - color[2], 1.0); + } else { + c = Color.fromRGBO(color[0], color[1] > 200 ? 190 : color[1], + color[2] > 200 ? 190 : color[2], 1); + } + return c; + } + + Color colorizeLight() { + Color c; + var color = json.decode(this); + if (color[0] < 50 && color[1] < 50 && color[2] < 50) { + c = Color.fromRGBO((255 - color[0]), 255 - color[1], 255 - color[2], 1.0); + } else { + c = Color.fromRGBO(color[0] < 50 ? 100 : color[0], + color[1] < 50 ? 100 : color[1], color[2] < 50 ? 100 : color[2], 1.0); + } + return c; + } +} diff --git a/lib/util/general_dialog.dart b/lib/util/general_dialog.dart index 64a97da..f720f83 100644 --- a/lib/util/general_dialog.dart +++ b/lib/util/general_dialog.dart @@ -1,79 +1,79 @@ -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; - -import 'extension_helper.dart'; - -Future generalDialog(BuildContext context, - {Widget title, Widget content, List actions}) async => - await showGeneralDialog( - context: context, - barrierDismissible: true, - barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel, - barrierColor: Colors.black54, - transitionDuration: const Duration(milliseconds: 200), - pageBuilder: (context, animaiton, secondaryAnimation) => - AnnotatedRegion( - value: SystemUiOverlayStyle( - statusBarIconBrightness: Brightness.light, - systemNavigationBarColor: context.brightness == Brightness.light - ? Color.fromRGBO(113, 113, 113, 1) - : Color.fromRGBO(15, 15, 15, 1), - ), - child: AlertDialog( - elevation: 2, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(10.0)), - titlePadding: EdgeInsets.all(20), - title: SizedBox(width: context.width - 120, child: title), - content: content, - contentPadding: EdgeInsets.fromLTRB(20, 0, 20, 0), - actions: actions), - ), - ); - -Future generalSheet(BuildContext context, {Widget child, String title}) async => - await showModalBottomSheet( - useRootNavigator: true, - isScrollControlled: true, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.only( - topLeft: Radius.circular(16.0), topRight: Radius.circular(16.0)), - ), - elevation: 2, - context: context, - builder: (context) { - final statusHeight = MediaQuery.of(context).padding.top; - return SafeArea( - child: ConstrainedBox( - constraints: - BoxConstraints(maxHeight: context.height - statusHeight - 80), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Container( - height: 4, - width: 25, - margin: EdgeInsets.only(top: 10.0, bottom: 2.0), - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(2.0), - color: context.primaryColorDark), - ), - Padding( - padding: EdgeInsets.only( - left: 50, right: 50, top: 6.0, bottom: 15), - child: Text( - title, - style: context.textTheme.headline6, - textAlign: TextAlign.center, - maxLines: 1, - overflow: TextOverflow.clip, - ), - ), - Divider(height: 1), - Flexible(child: SingleChildScrollView(child: child)), - ], - ), - ), - ); - }, - ); +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import 'extension_helper.dart'; + +Future generalDialog(BuildContext context, + {Widget title, Widget content, List actions}) async => + await showGeneralDialog( + context: context, + barrierDismissible: true, + barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel, + barrierColor: Colors.black54, + transitionDuration: const Duration(milliseconds: 200), + pageBuilder: (context, animaiton, secondaryAnimation) => + AnnotatedRegion( + value: SystemUiOverlayStyle( + statusBarIconBrightness: Brightness.light, + systemNavigationBarColor: context.brightness == Brightness.light + ? Color.fromRGBO(113, 113, 113, 1) + : Color.fromRGBO(15, 15, 15, 1), + ), + child: AlertDialog( + elevation: 2, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10.0)), + titlePadding: EdgeInsets.all(20), + title: SizedBox(width: context.width - 120, child: title), + content: content, + contentPadding: EdgeInsets.fromLTRB(20, 0, 20, 0), + actions: actions), + ), + ); + +Future generalSheet(BuildContext context, {Widget child, String title}) async => + await showModalBottomSheet( + useRootNavigator: true, + isScrollControlled: true, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.only( + topLeft: Radius.circular(16.0), topRight: Radius.circular(16.0)), + ), + elevation: 2, + context: context, + builder: (context) { + final statusHeight = MediaQuery.of(context).padding.top; + return SafeArea( + child: ConstrainedBox( + constraints: + BoxConstraints(maxHeight: context.height - statusHeight - 80), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + height: 4, + width: 25, + margin: EdgeInsets.only(top: 10.0, bottom: 2.0), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(2.0), + color: context.primaryColorDark), + ), + Padding( + padding: EdgeInsets.only( + left: 50, right: 50, top: 6.0, bottom: 15), + child: Text( + title, + style: context.textTheme.headline6, + textAlign: TextAlign.center, + maxLines: 1, + overflow: TextOverflow.clip, + ), + ), + Divider(height: 1), + Flexible(child: SingleChildScrollView(child: child)), + ], + ), + ), + ); + }, + ); diff --git a/lib/util/muiliselect_bar.dart b/lib/util/muiliselect_bar.dart index e5ec842..fe4c710 100644 --- a/lib/util/muiliselect_bar.dart +++ b/lib/util/muiliselect_bar.dart @@ -1,448 +1,448 @@ -import 'package:connectivity/connectivity.dart'; -import 'package:flutter/material.dart'; -import 'package:fluttertoast/fluttertoast.dart'; -import 'package:permission_handler/permission_handler.dart'; -import 'package:provider/provider.dart'; - -import '../local_storage/key_value_storage.dart'; -import '../local_storage/sqflite_localpodcast.dart'; -import '../state/audio_state.dart'; -import '../state/download_state.dart'; -import '../type/episodebrief.dart'; -import '../type/play_histroy.dart'; -import 'custom_widget.dart'; -import 'extension_helper.dart'; -import 'general_dialog.dart'; - -class MultiSelectMenuBar extends StatefulWidget { - MultiSelectMenuBar( - {this.selectedList, - this.selectAll, - this.onSelectAll, - this.onClose, - this.onSelectAfter, - this.onSelectBefore, - this.hideFavorite = false, - Key key}) - : assert(onClose != null), - super(key: key); - final List selectedList; - final bool selectAll; - final ValueChanged onSelectAll; - final ValueChanged onClose; - final ValueChanged onSelectBefore; - final ValueChanged onSelectAfter; - final bool hideFavorite; - - @override - _MultiSelectMenuBarState createState() => _MultiSelectMenuBarState(); -} - -///Multi select menu bar. -class _MultiSelectMenuBarState extends State { - bool _liked; - bool _marked; - bool _inPlaylist; - bool _downloaded; - final _dbHelper = DBHelper(); - - @override - void initState() { - super.initState(); - _liked = false; - _marked = false; - _downloaded = false; - _inPlaylist = false; - } - - @override - void didUpdateWidget(MultiSelectMenuBar oldWidget) { - if (oldWidget.selectedList != widget.selectedList) { - setState(() { - _liked = false; - _marked = false; - _downloaded = false; - _inPlaylist = false; - }); - super.didUpdateWidget(oldWidget); - } - } - - Future _saveLiked() async { - for (var episode in widget.selectedList) { - await _dbHelper.setLiked(episode.enclosureUrl); - } - if (mounted) { - setState(() => _liked = true); - widget.onClose(false); - } - } - - Future _setUnliked() async { - for (var episode in widget.selectedList) { - await _dbHelper.setUniked(episode.enclosureUrl); - } - if (mounted) { - setState(() => _liked = false); - widget.onClose(false); - } - } - - Future _markListened() async { - for (var episode in widget.selectedList) { - final history = PlayHistory(episode.title, episode.enclosureUrl, 0, 1); - await _dbHelper.saveHistory(history); - } - if (mounted) { - setState(() => _marked = true); - widget.onClose(false); - } - } - - Future _markNotListened() async { - for (var episode in widget.selectedList) { - await _dbHelper.markNotListened(episode.enclosureUrl); - } - if (mounted) { - setState(() => _marked = false); - widget.onClose(false); - } - } - - Future _requestDownload() async { - final permissionReady = await _checkPermmison(); - final downloadUsingData = await KeyValueStorage(downloadUsingDataKey) - .getBool(defaultValue: true, reverse: true); - var dataConfirm = true; - final result = await Connectivity().checkConnectivity(); - final usingData = result == ConnectivityResult.mobile; - if (permissionReady) { - if (downloadUsingData && usingData) { - dataConfirm = await _useDataConfirm(); - } - if (dataConfirm) { - for (var episode in widget.selectedList) { - Provider.of(context, listen: false).startTask(episode); - } - if (mounted) { - setState(() { - _downloaded = true; - }); - } - } - } - } - - Future _useDataConfirm() async { - var ifUseData = false; - final s = context.s; - await generalDialog( - context, - title: Text(s.cellularConfirm), - content: Text(s.cellularConfirmDes), - actions: [ - FlatButton( - onPressed: () { - Navigator.of(context).pop(); - }, - child: Text( - s.cancel, - style: TextStyle(color: Colors.grey[600]), - ), - ), - FlatButton( - onPressed: () { - ifUseData = true; - Navigator.of(context).pop(); - }, - child: Text( - s.confirm, - style: TextStyle(color: Colors.red), - ), - ) - ], - ); - return ifUseData; - } - - Future _checkPermmison() async { - var permission = await Permission.storage.status; - if (permission != PermissionStatus.granted) { - var permissions = await [Permission.storage].request(); - if (permissions[Permission.storage] == PermissionStatus.granted) { - return true; - } else { - return false; - } - } else { - return true; - } - } - - Widget _buttonOnMenu({Widget child, VoidCallback onTap}) => Material( - color: Colors.transparent, - child: InkWell( - onTap: onTap, - child: SizedBox( - height: 40, - child: Padding( - padding: EdgeInsets.symmetric(horizontal: 12.0), child: child), - ), - ), - ); - OverlayEntry _createOverlayEntry() { - RenderBox renderBox = context.findRenderObject(); - var offset = renderBox.localToGlobal(Offset.zero); - return OverlayEntry( - builder: (constext) => Positioned( - left: offset.dx + 50, - top: offset.dy - 60, - child: Container( - width: 70, - height: 100, - //color: Colors.grey[200], - child: HeartOpen(width: 50, height: 80)), - ), - ); - } - - @override - Widget build(BuildContext context) { - final s = context.s; - var audio = context.watch(); - return TweenAnimationBuilder( - tween: Tween(begin: 0, end: 1), - duration: Duration(milliseconds: 500), - builder: (context, value, child) => Container( - height: widget.selectAll == null ? 40 : 90.0 * value, - decoration: BoxDecoration(color: context.primaryColor), - child: SingleChildScrollView( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - if (widget.selectAll != null) - Row( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - SizedBox( - height: 40, - child: Center( - child: Padding( - padding: EdgeInsets.symmetric(horizontal: 20.0), - child: Text( - '${widget.selectedList.length} selected', - style: context.textTheme.headline6 - .copyWith(color: context.accentColor))), - ), - ), - Spacer(), - if (widget.selectedList.length == 1) - SizedBox( - height: 25, - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 5), - child: OutlinedButton( - style: OutlinedButton.styleFrom( - side: BorderSide(color: context.accentColor), - primary: context.textColor, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.all( - Radius.circular(100)))), - onPressed: () { - widget.onSelectBefore(true); - }, - child: Text('Before')), - ), - ), - if (widget.selectedList.length == 1) - SizedBox( - height: 25, - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 5), - child: OutlinedButton( - style: OutlinedButton.styleFrom( - side: BorderSide(color: context.accentColor), - primary: context.textColor, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.all( - Radius.circular(100)))), - onPressed: () { - widget.onSelectAfter(true); - }, - child: Text('After')), - ), - ), - SizedBox( - height: 25, - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 5), - child: OutlinedButton( - style: OutlinedButton.styleFrom( - side: BorderSide(color: context.accentColor), - backgroundColor: widget.selectAll - ? context.accentColor - : null, - primary: widget.selectAll - ? Colors.white - : context.textColor, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.all( - Radius.circular(100)))), - onPressed: () { - widget.onSelectAll(!widget.selectAll); - }, - child: Text('All')), - ), - ) - ], - ), - Row( - children: [ - if (!widget.hideFavorite) - _buttonOnMenu( - child: _liked - ? Icon(Icons.favorite, color: Colors.red) - : Icon( - Icons.favorite_border, - color: Colors.grey[700], - ), - onTap: () async { - if (widget.selectedList.isNotEmpty) { - if (!_liked) { - await _saveLiked(); - Fluttertoast.showToast( - msg: s.liked, - gravity: ToastGravity.BOTTOM, - ); - } else { - await _setUnliked(); - Fluttertoast.showToast( - msg: s.unliked, - gravity: ToastGravity.BOTTOM, - ); - } - audio.setEpisodeState = true; - } - // OverlayEntry _overlayEntry; - // _overlayEntry = _createOverlayEntry(); - // Overlay.of(context).insert(_overlayEntry); - // await Future.delayed(Duration(seconds: 2)); - // _overlayEntry?.remove(); - }), - _buttonOnMenu( - child: _downloaded - ? Center( - child: SizedBox( - height: 20, - width: 20, - child: CustomPaint( - painter: DownloadPainter( - color: context.accentColor, - fraction: 1, - progressColor: context.accentColor, - progress: 1), - ), - ), - ) - : Center( - child: SizedBox( - height: 20, - width: 20, - child: CustomPaint( - painter: DownloadPainter( - color: Colors.grey[700], - fraction: 0, - progressColor: context.accentColor, - ), - ), - ), - ), - onTap: () { - if (widget.selectedList.isNotEmpty) { - if (!_downloaded) _requestDownload(); - } - }, - ), - _buttonOnMenu( - child: _inPlaylist - ? Icon(Icons.playlist_add_check, - color: context.accentColor) - : Icon( - Icons.playlist_add, - color: Colors.grey[700], - ), - onTap: () async { - if (widget.selectedList.isNotEmpty) { - if (!_inPlaylist) { - for (var episode in widget.selectedList) { - audio.addToPlaylist(episode); - Fluttertoast.showToast( - msg: s.toastAddPlaylist, - gravity: ToastGravity.BOTTOM, - ); - } - setState(() => _inPlaylist = true); - } else { - for (var episode in widget.selectedList) { - audio.delFromPlaylist(episode); - Fluttertoast.showToast( - msg: s.toastRemovePlaylist, - gravity: ToastGravity.BOTTOM, - ); - } - setState(() => _inPlaylist = false); - } - } - }), - _buttonOnMenu( - child: Padding( - padding: EdgeInsets.symmetric(vertical: 8), - child: CustomPaint( - size: Size(25, 25), - painter: ListenedAllPainter( - _marked ? context.accentColor : Colors.grey[700], - stroke: 2.0), - ), - ), - onTap: () async { - if (widget.selectedList.isNotEmpty) { - if (!_marked) { - await _markListened(); - Fluttertoast.showToast( - msg: s.markListened, - gravity: ToastGravity.BOTTOM, - ); - } else { - await _markNotListened(); - Fluttertoast.showToast( - msg: s.markNotListened, - gravity: ToastGravity.BOTTOM, - ); - } - } - }), - Spacer(), - if (widget.selectAll == null) - SizedBox( - height: 40, - child: Center( - child: Padding( - padding: EdgeInsets.symmetric(horizontal: 10.0), - child: Text( - '${widget.selectedList.length} selected', - style: context.textTheme.headline6 - .copyWith(color: context.accentColor))), - ), - ), - _buttonOnMenu( - child: Icon(Icons.close), - onTap: () => widget.onClose(true)) - ], - ), - ], - ), - ), - ), - ); - } -} +import 'package:connectivity/connectivity.dart'; +import 'package:flutter/material.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:permission_handler/permission_handler.dart'; +import 'package:provider/provider.dart'; + +import '../local_storage/key_value_storage.dart'; +import '../local_storage/sqflite_localpodcast.dart'; +import '../state/audio_state.dart'; +import '../state/download_state.dart'; +import '../type/episodebrief.dart'; +import '../type/play_histroy.dart'; +import 'custom_widget.dart'; +import 'extension_helper.dart'; +import 'general_dialog.dart'; + +class MultiSelectMenuBar extends StatefulWidget { + MultiSelectMenuBar( + {this.selectedList, + this.selectAll, + this.onSelectAll, + this.onClose, + this.onSelectAfter, + this.onSelectBefore, + this.hideFavorite = false, + Key key}) + : assert(onClose != null), + super(key: key); + final List selectedList; + final bool selectAll; + final ValueChanged onSelectAll; + final ValueChanged onClose; + final ValueChanged onSelectBefore; + final ValueChanged onSelectAfter; + final bool hideFavorite; + + @override + _MultiSelectMenuBarState createState() => _MultiSelectMenuBarState(); +} + +///Multi select menu bar. +class _MultiSelectMenuBarState extends State { + bool _liked; + bool _marked; + bool _inPlaylist; + bool _downloaded; + final _dbHelper = DBHelper(); + + @override + void initState() { + super.initState(); + _liked = false; + _marked = false; + _downloaded = false; + _inPlaylist = false; + } + + @override + void didUpdateWidget(MultiSelectMenuBar oldWidget) { + if (oldWidget.selectedList != widget.selectedList) { + setState(() { + _liked = false; + _marked = false; + _downloaded = false; + _inPlaylist = false; + }); + super.didUpdateWidget(oldWidget); + } + } + + Future _saveLiked() async { + for (var episode in widget.selectedList) { + await _dbHelper.setLiked(episode.enclosureUrl); + } + if (mounted) { + setState(() => _liked = true); + widget.onClose(false); + } + } + + Future _setUnliked() async { + for (var episode in widget.selectedList) { + await _dbHelper.setUniked(episode.enclosureUrl); + } + if (mounted) { + setState(() => _liked = false); + widget.onClose(false); + } + } + + Future _markListened() async { + for (var episode in widget.selectedList) { + final history = PlayHistory(episode.title, episode.enclosureUrl, 0, 1); + await _dbHelper.saveHistory(history); + } + if (mounted) { + setState(() => _marked = true); + widget.onClose(false); + } + } + + Future _markNotListened() async { + for (var episode in widget.selectedList) { + await _dbHelper.markNotListened(episode.enclosureUrl); + } + if (mounted) { + setState(() => _marked = false); + widget.onClose(false); + } + } + + Future _requestDownload() async { + final permissionReady = await _checkPermmison(); + final downloadUsingData = await KeyValueStorage(downloadUsingDataKey) + .getBool(defaultValue: true, reverse: true); + var dataConfirm = true; + final result = await Connectivity().checkConnectivity(); + final usingData = result == ConnectivityResult.mobile; + if (permissionReady) { + if (downloadUsingData && usingData) { + dataConfirm = await _useDataConfirm(); + } + if (dataConfirm) { + for (var episode in widget.selectedList) { + Provider.of(context, listen: false).startTask(episode); + } + if (mounted) { + setState(() { + _downloaded = true; + }); + } + } + } + } + + Future _useDataConfirm() async { + var ifUseData = false; + final s = context.s; + await generalDialog( + context, + title: Text(s.cellularConfirm), + content: Text(s.cellularConfirmDes), + actions: [ + FlatButton( + onPressed: () { + Navigator.of(context).pop(); + }, + child: Text( + s.cancel, + style: TextStyle(color: Colors.grey[600]), + ), + ), + FlatButton( + onPressed: () { + ifUseData = true; + Navigator.of(context).pop(); + }, + child: Text( + s.confirm, + style: TextStyle(color: Colors.red), + ), + ) + ], + ); + return ifUseData; + } + + Future _checkPermmison() async { + var permission = await Permission.storage.status; + if (permission != PermissionStatus.granted) { + var permissions = await [Permission.storage].request(); + if (permissions[Permission.storage] == PermissionStatus.granted) { + return true; + } else { + return false; + } + } else { + return true; + } + } + + Widget _buttonOnMenu({Widget child, VoidCallback onTap}) => Material( + color: Colors.transparent, + child: InkWell( + onTap: onTap, + child: SizedBox( + height: 40, + child: Padding( + padding: EdgeInsets.symmetric(horizontal: 12.0), child: child), + ), + ), + ); + OverlayEntry _createOverlayEntry() { + RenderBox renderBox = context.findRenderObject(); + var offset = renderBox.localToGlobal(Offset.zero); + return OverlayEntry( + builder: (constext) => Positioned( + left: offset.dx + 50, + top: offset.dy - 60, + child: Container( + width: 70, + height: 100, + //color: Colors.grey[200], + child: HeartOpen(width: 50, height: 80)), + ), + ); + } + + @override + Widget build(BuildContext context) { + final s = context.s; + var audio = context.watch(); + return TweenAnimationBuilder( + tween: Tween(begin: 0, end: 1), + duration: Duration(milliseconds: 500), + builder: (context, value, child) => Container( + height: widget.selectAll == null ? 40 : 90.0 * value, + decoration: BoxDecoration(color: context.primaryColor), + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (widget.selectAll != null) + Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + SizedBox( + height: 40, + child: Center( + child: Padding( + padding: EdgeInsets.symmetric(horizontal: 20.0), + child: Text( + '${widget.selectedList.length} selected', + style: context.textTheme.headline6 + .copyWith(color: context.accentColor))), + ), + ), + Spacer(), + if (widget.selectedList.length == 1) + SizedBox( + height: 25, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 5), + child: OutlinedButton( + style: OutlinedButton.styleFrom( + side: BorderSide(color: context.accentColor), + primary: context.textColor, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.all( + Radius.circular(100)))), + onPressed: () { + widget.onSelectBefore(true); + }, + child: Text('Before')), + ), + ), + if (widget.selectedList.length == 1) + SizedBox( + height: 25, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 5), + child: OutlinedButton( + style: OutlinedButton.styleFrom( + side: BorderSide(color: context.accentColor), + primary: context.textColor, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.all( + Radius.circular(100)))), + onPressed: () { + widget.onSelectAfter(true); + }, + child: Text('After')), + ), + ), + SizedBox( + height: 25, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 5), + child: OutlinedButton( + style: OutlinedButton.styleFrom( + side: BorderSide(color: context.accentColor), + backgroundColor: widget.selectAll + ? context.accentColor + : null, + primary: widget.selectAll + ? Colors.white + : context.textColor, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.all( + Radius.circular(100)))), + onPressed: () { + widget.onSelectAll(!widget.selectAll); + }, + child: Text('All')), + ), + ) + ], + ), + Row( + children: [ + if (!widget.hideFavorite) + _buttonOnMenu( + child: _liked + ? Icon(Icons.favorite, color: Colors.red) + : Icon( + Icons.favorite_border, + color: Colors.grey[700], + ), + onTap: () async { + if (widget.selectedList.isNotEmpty) { + if (!_liked) { + await _saveLiked(); + Fluttertoast.showToast( + msg: s.liked, + gravity: ToastGravity.BOTTOM, + ); + } else { + await _setUnliked(); + Fluttertoast.showToast( + msg: s.unliked, + gravity: ToastGravity.BOTTOM, + ); + } + audio.setEpisodeState = true; + } + // OverlayEntry _overlayEntry; + // _overlayEntry = _createOverlayEntry(); + // Overlay.of(context).insert(_overlayEntry); + // await Future.delayed(Duration(seconds: 2)); + // _overlayEntry?.remove(); + }), + _buttonOnMenu( + child: _downloaded + ? Center( + child: SizedBox( + height: 20, + width: 20, + child: CustomPaint( + painter: DownloadPainter( + color: context.accentColor, + fraction: 1, + progressColor: context.accentColor, + progress: 1), + ), + ), + ) + : Center( + child: SizedBox( + height: 20, + width: 20, + child: CustomPaint( + painter: DownloadPainter( + color: Colors.grey[700], + fraction: 0, + progressColor: context.accentColor, + ), + ), + ), + ), + onTap: () { + if (widget.selectedList.isNotEmpty) { + if (!_downloaded) _requestDownload(); + } + }, + ), + _buttonOnMenu( + child: _inPlaylist + ? Icon(Icons.playlist_add_check, + color: context.accentColor) + : Icon( + Icons.playlist_add, + color: Colors.grey[700], + ), + onTap: () async { + if (widget.selectedList.isNotEmpty) { + if (!_inPlaylist) { + for (var episode in widget.selectedList) { + audio.addToPlaylist(episode); + Fluttertoast.showToast( + msg: s.toastAddPlaylist, + gravity: ToastGravity.BOTTOM, + ); + } + setState(() => _inPlaylist = true); + } else { + for (var episode in widget.selectedList) { + audio.delFromPlaylist(episode); + Fluttertoast.showToast( + msg: s.toastRemovePlaylist, + gravity: ToastGravity.BOTTOM, + ); + } + setState(() => _inPlaylist = false); + } + } + }), + _buttonOnMenu( + child: Padding( + padding: EdgeInsets.symmetric(vertical: 8), + child: CustomPaint( + size: Size(25, 25), + painter: ListenedAllPainter( + _marked ? context.accentColor : Colors.grey[700], + stroke: 2.0), + ), + ), + onTap: () async { + if (widget.selectedList.isNotEmpty) { + if (!_marked) { + await _markListened(); + Fluttertoast.showToast( + msg: s.markListened, + gravity: ToastGravity.BOTTOM, + ); + } else { + await _markNotListened(); + Fluttertoast.showToast( + msg: s.markNotListened, + gravity: ToastGravity.BOTTOM, + ); + } + } + }), + Spacer(), + if (widget.selectAll == null) + SizedBox( + height: 40, + child: Center( + child: Padding( + padding: EdgeInsets.symmetric(horizontal: 10.0), + child: Text( + '${widget.selectedList.length} selected', + style: context.textTheme.headline6 + .copyWith(color: context.accentColor))), + ), + ), + _buttonOnMenu( + child: Icon(Icons.close), + onTap: () => widget.onClose(true)) + ], + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/util/open_container.dart b/lib/util/open_container.dart index ee64edc..cb862ec 100644 --- a/lib/util/open_container.dart +++ b/lib/util/open_container.dart @@ -1,870 +1,870 @@ -// Copyright 2019 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter/material.dart'; -import 'package:flutter/scheduler.dart'; -import 'extension_helper.dart'; - -/// Signature for a function that creates a [Widget] to be used within an -/// [OpenContainer]. -/// -/// The `action` callback provided to [OpenContainer.openBuilder] can be used -/// to open the container. The `action` callback provided to -/// [OpenContainer.closedBuilder] can be used to close the container again. -typedef OpenContainerBuilder = Widget Function( - BuildContext context, - VoidCallback action, - bool hide, -); - -/// The [OpenContainer] widget's fade transition type. -/// -/// This determines the type of fade transition that the incoming and outgoing -/// contents will use. -enum ContainerTransitionType { - /// Fades the incoming element in over the outgoing element. - fade, - - /// First fades the outgoing element out, and starts fading the incoming - /// element in once the outgoing element has completely faded out. - fadeThrough, -} - -/// A container that grows to fill the screen to reveal new content when tapped. -/// -/// While the container is closed, it shows the [Widget] returned by -/// [closedBuilder]. When the container is tapped it grows to fill the entire -/// size of the surrounding [Navigator] while fading out the widget returned by -/// [closedBuilder] and fading in the widget returned by [openBuilder]. When the -/// container is closed again via the callback provided to [openBuilder] or via -/// Android's back button, the animation is reversed: The container shrinks back -/// to its original size while the widget returned by [openBuilder] is faded out -/// and the widget returned by [openBuilder] is faded back in. -/// -/// By default, the container is in the closed state. During the transition from -/// closed to open and vice versa the widgets returned by the [openBuilder] and -/// [closedBuilder] exist in the tree at the same time. Therefore, the widgets -/// returned by these builders cannot include the same global key. -/// -/// -/// See also: -/// -/// * [Transitions with animated containers](https://material.io/design/motion/choreography.html#transformation) -/// in the Material spec. -class OpenContainer extends StatefulWidget { - /// Creates an [OpenContainer]. - /// - /// All arguments except for [key] must not be null. The arguments - /// [closedBuilder] and [closedBuilder] are required. - const OpenContainer({ - Key key, - this.closedColor = Colors.white, - this.openColor = Colors.white, - this.beginColor = Colors.white, - this.endColor = Colors.white, - this.closedElevation = 1.0, - this.openElevation = 4.0, - this.closedShape = const RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(4.0)), - ), - this.openShape = const RoundedRectangleBorder(), - @required this.closedBuilder, - @required this.openBuilder, - this.flightWidget, - this.flightWidgetSize, - this.playerRunning, - this.playerHeight, - this.tappable = true, - this.transitionDuration = const Duration(milliseconds: 300), - this.transitionType = ContainerTransitionType.fade, - }) : assert(closedColor != null), - assert(openColor != null), - assert(closedElevation != null), - assert(openElevation != null), - assert(closedShape != null), - assert(openShape != null), - assert(closedBuilder != null), - assert(openBuilder != null), - assert(tappable != null), - assert(transitionType != null), - super(key: key); - - /// Background color of the container while it is closed. - /// - /// When the container is opened, it will first transition from this color - /// to [Colors.white] and then transition from there to [openColor] in one - /// smooth animation. When the container is closed, it will transition back to - /// this color from [openColor] via [Colors.white]. - /// - /// Defaults to [Colors.white]. - /// - /// See also: - /// - /// * [Material.color], which is used to implement this property. - /// - final Color beginColor; - final Color endColor; - final Color closedColor; - final Widget flightWidget; - final double flightWidgetSize; - final bool playerRunning; - final double playerHeight; - - /// Background color of the container while it is open. - /// - /// When the container is closed, it will first transition from [closedColor] - /// to [Colors.white] and then transition from there to this color in one - /// smooth animation. When the container is closed, it will transition back to - /// [closedColor] from this color via [Colors.white]. - /// - /// Defaults to [Colors.white]. - /// - /// See also: - /// - /// * [Material.color], which is used to implement this property. - final Color openColor; - - /// Elevation of the container while it is closed. - /// - /// When the container is opened, it will transition from this elevation to - /// [openElevation]. When the container is closed, it will transition back - /// from [openElevation] to this elevation. - /// - /// Defaults to 1.0. - /// - /// See also: - /// - /// * [Material.elevation], which is used to implement this property. - final double closedElevation; - - /// Elevation of the container while it is open. - /// - /// When the container is opened, it will transition to this elevation from - /// [closedElevation]. When the container is closed, it will transition back - /// from this elevation to [closedElevation]. - /// - /// Defaults to 4.0. - /// - /// See also: - /// - /// * [Material.elevation], which is used to implement this property. - final double openElevation; - - /// Shape of the container while it is closed. - /// - /// When the container is opened it will transition from this shape to - /// [openShape]. When the container is closed, it will transition back to this - /// shape. - /// - /// Defaults to a [RoundedRectangleBorder] with a [Radius.circular] of 4.0. - /// - /// See also: - /// - /// * [Material.shape], which is used to implement this property. - final ShapeBorder closedShape; - - /// Shape of the container while it is open. - /// - /// When the container is opened it will transition from [closedShape] to - /// this shape. When the container is closed, it will transition from this - /// shape back to [closedShape]. - /// - /// Defaults to a rectangular. - /// - /// See also: - /// - /// * [Material.shape], which is used to implement this property. - final ShapeBorder openShape; - - /// Called to obtain the child for the container in the closed state. - /// - /// The [Widget] returned by this builder is faded out when the container - /// opens and at the same time the widget returned by [openBuilder] is faded - /// in while the container grows to fill the surrounding [Navigator]. - /// - /// The `action` callback provided to the builder can be called to open the - /// container. - final OpenContainerBuilder closedBuilder; - - /// Called to obtain the child for the container in the open state. - /// - /// The [Widget] returned by this builder is faded in when the container - /// opens and at the same time the widget returned by [closedBuilder] is - /// faded out while the container grows to fill the surrounding [Navigator]. - /// - /// The `action` callback provided to the builder can be called to close the - /// container. - final OpenContainerBuilder openBuilder; - - /// Whether the entire closed container can be tapped to open it. - /// - /// Defaults to true. - /// - /// When this is set to false the container can only be opened by calling the - /// `action` callback that is provided to the [closedBuilder]. - final bool tappable; - - /// The time it will take to animate the container from its closed to its - /// open state and vice versa. - /// - /// Defaults to 300ms. - final Duration transitionDuration; - - /// The type of fade transition that the container will use for its - /// incoming and outgoing widgets. - /// - /// Defaults to [ContainerTransitionType.fade]. - final ContainerTransitionType transitionType; - - @override - _OpenContainerState createState() => _OpenContainerState(); -} - -class _OpenContainerState extends State { - // Key used in [_OpenContainerRoute] to hide the widget returned by - // [OpenContainer.openBuilder] in the source route while the container is - // opening/open. A copy of that widget is included in the - // [_OpenContainerRoute] where it fades out. To avoid issues with double - // shadows and transparency, we hide it in the source route. - final GlobalKey<_HideableState> _hideableKey = GlobalKey<_HideableState>(); - - // Key used to steal the state of the widget returned by - // [OpenContainer.openBuilder] from the source route and attach it to the - // same widget included in the [_OpenContainerRoute] where it fades out. - final GlobalKey _closedBuilderKey = GlobalKey(); - - void openContainer() { - Navigator.of(context).push(_OpenContainerRoute( - beginColor: widget.beginColor, - endColor: widget.endColor, - closedColor: widget.closedColor, - openColor: widget.openColor, - closedElevation: widget.closedElevation, - openElevation: widget.openElevation, - closedShape: widget.closedShape, - openShape: widget.openShape, - closedBuilder: widget.closedBuilder, - openBuilder: widget.openBuilder, - hideableKey: _hideableKey, - closedBuilderKey: _closedBuilderKey, - transitionDuration: widget.transitionDuration, - transitionType: widget.transitionType, - flightWidget: widget.flightWidget, - flightWidgetSize: widget.flightWidgetSize, - playerRunning: widget.playerRunning, - playerHeight: widget.playerHeight, - )); - } - - @override - Widget build(BuildContext context) { - return _Hideable( - key: _hideableKey, - child: GestureDetector( - onTap: widget.tappable ? openContainer : null, - child: Material( - color: Colors.transparent, - // clipBehavior: Clip.antiAlias, - // color: widget.closedColor, - // elevation: widget.closedElevation, - // shape: widget.closedShape, - child: Builder( - key: _closedBuilderKey, - builder: (context) { - return widget.closedBuilder(context, openContainer, false); - }, - ), - ), - ), - ); - } -} - -/// Controls the visibility of its child. -/// -/// The child can be in one of three states: -/// -/// * It is included in the tree and fully visible. (The `placeholderSize` is -/// null and `isVisible` is true.) -/// * It is included in the tree, but not visible; its size is maintained. -/// (The `placeholderSize` is null and `isVisible` is false.) -/// * It is not included in the tree. Instead a [SizedBox] of dimensions -/// specified by `placeholderSize` is included in the tree. (The value of -/// `isVisible` is ignored). -class _Hideable extends StatefulWidget { - const _Hideable({ - Key key, - this.child, - }) : super(key: key); - - final Widget child; - - @override - State<_Hideable> createState() => _HideableState(); -} - -class _HideableState extends State<_Hideable> { - /// When non-null the child is replaced by a [SizedBox] of the set size. - Size get placeholderSize => _placeholderSize; - Size _placeholderSize; - set placeholderSize(Size value) { - if (_placeholderSize == value) { - return; - } - setState(() { - _placeholderSize = value; - }); - } - - /// When true the child is not visible, but will maintain its size. - /// - /// The value of this property is ignored when [placeholderSize] is non-null - /// (i.e. [isInTree] returns false). - bool get isVisible => _visible; - bool _visible = true; - set isVisible(bool value) { - assert(value != null); - if (_visible == value) { - return; - } - setState(() { - _visible = value; - }); - } - - /// Whether the child is currently included in the tree. - /// - /// When it is included, it may be visible or not according to [isVisible]. - bool get isInTree => _placeholderSize == null; - - @override - Widget build(BuildContext context) { - if (_placeholderSize != null) { - return SizedBox.fromSize(size: _placeholderSize); - } - return Opacity( - opacity: _visible ? 1.0 : 0.0, - child: widget.child, - ); - } -} - -class _OpenContainerRoute extends ModalRoute { - _OpenContainerRoute({ - @required this.closedColor, - @required this.openColor, - @required this.beginColor, - @required this.endColor, - @required double closedElevation, - @required this.openElevation, - @required ShapeBorder closedShape, - @required this.openShape, - @required this.closedBuilder, - @required this.openBuilder, - @required this.hideableKey, - @required this.closedBuilderKey, - @required this.transitionDuration, - @required this.transitionType, - this.flightWidget, - this.flightWidgetSize, - this.playerRunning, - this.playerHeight, - }) : assert(closedColor != null), - assert(openColor != null), - assert(closedElevation != null), - assert(openElevation != null), - assert(closedShape != null), - assert(openBuilder != null), - assert(closedBuilder != null), - assert(hideableKey != null), - assert(closedBuilderKey != null), - assert(transitionType != null), - _elevationTween = Tween( - begin: closedElevation, - end: openElevation, - ), - _shapeTween = ShapeBorderTween( - begin: closedShape, - end: openShape, - ), - _colorTween = _getColorTween( - transitionType: transitionType, - closedColor: closedColor, - openColor: openColor, - beginColor: beginColor, - endColor: endColor), - _closedOpacityTween = _getClosedOpacityTween(transitionType), - _openOpacityTween = _getOpenOpacityTween(transitionType); - - final Widget flightWidget; - final double flightWidgetSize; - final bool playerRunning; - final double playerHeight; - static _FlippableTweenSequence _getColorTween({ - @required ContainerTransitionType transitionType, - @required Color closedColor, - @required Color openColor, - @required Color beginColor, - @required Color endColor, - }) { - switch (transitionType) { - case ContainerTransitionType.fade: - return _FlippableTweenSequence( - >[ - TweenSequenceItem( - tween: ConstantTween(closedColor), - weight: 1 / 5, - ), - TweenSequenceItem( - tween: ColorTween(begin: closedColor, end: openColor), - weight: 1 / 5, - ), - TweenSequenceItem( - tween: ConstantTween(openColor), - weight: 3 / 5, - ), - ], - ); - case ContainerTransitionType.fadeThrough: - return _FlippableTweenSequence( - >[ - TweenSequenceItem( - tween: ColorTween(begin: closedColor, end: endColor), - weight: 1 / 5, - ), - TweenSequenceItem( - tween: ColorTween(begin: beginColor, end: openColor), - weight: 4 / 5, - ), - ], - ); - } - return null; // unreachable - } - - static _FlippableTweenSequence _getClosedOpacityTween( - ContainerTransitionType transitionType) { - switch (transitionType) { - case ContainerTransitionType.fade: - return _FlippableTweenSequence( - >[ - TweenSequenceItem( - tween: ConstantTween(1.0), - weight: 1, - ), - ], - ); - break; - case ContainerTransitionType.fadeThrough: - return _FlippableTweenSequence( - >[ - TweenSequenceItem( - tween: Tween(begin: 1.0, end: 0.0), - weight: 1 / 5, - ), - TweenSequenceItem( - tween: ConstantTween(0.0), - weight: 4 / 5, - ), - ], - ); - break; - } - return null; // unreachable - } - - static _FlippableTweenSequence _getOpenOpacityTween( - ContainerTransitionType transitionType) { - switch (transitionType) { - case ContainerTransitionType.fade: - return _FlippableTweenSequence( - >[ - TweenSequenceItem( - tween: ConstantTween(0.0), - weight: 1 / 5, - ), - TweenSequenceItem( - tween: Tween(begin: 0.0, end: 1.0), - weight: 1 / 5, - ), - TweenSequenceItem( - tween: ConstantTween(1.0), - weight: 3 / 5, - ), - ], - ); - break; - case ContainerTransitionType.fadeThrough: - return _FlippableTweenSequence( - >[ - TweenSequenceItem( - tween: ConstantTween(0.0), - weight: 1 / 5, - ), - TweenSequenceItem( - tween: Tween(begin: 0.0, end: 1.0), - weight: 4 / 5, - ), - ], - ); - break; - } - return null; // unreachable - } - - final Color closedColor; - final Color openColor; - final Color beginColor; - final Color endColor; - final double openElevation; - final ShapeBorder openShape; - final OpenContainerBuilder closedBuilder; - final OpenContainerBuilder openBuilder; - - // See [_OpenContainerState._hideableKey]. - final GlobalKey<_HideableState> hideableKey; - - // See [_OpenContainerState._closedBuilderKey]. - final GlobalKey closedBuilderKey; - - @override - final Duration transitionDuration; - final ContainerTransitionType transitionType; - - final Tween _elevationTween; - final ShapeBorderTween _shapeTween; - final _FlippableTweenSequence _closedOpacityTween; - final _FlippableTweenSequence _openOpacityTween; - final _FlippableTweenSequence _colorTween; - - // Key used for the widget returned by [OpenContainer.openBuilder] to keep - // its state when the shape of the widget tree is changed at the end of the - // animation to remove all the craft that was necessary to make the animation - // work. - final GlobalKey _openBuilderKey = GlobalKey(); - - // Defines the position and the size of the (opening) [OpenContainer] within - // the bounds of the enclosing [Navigator]. - final RectTween _rectTween = RectTween(); - final Tween _positionTween = Tween(); - final Tween _avatarScaleTween = Tween(); - AnimationStatus _lastAnimationStatus; - AnimationStatus _currentAnimationStatus; - - @override - TickerFuture didPush() { - _takeMeasurements(navigatorContext: hideableKey.currentContext); - - animation.addStatusListener((status) { - _lastAnimationStatus = _currentAnimationStatus; - _currentAnimationStatus = status; - switch (status) { - case AnimationStatus.dismissed: - hideableKey.currentState - ..placeholderSize = null - ..isVisible = true; - break; - case AnimationStatus.completed: - hideableKey.currentState - ..placeholderSize = null - ..isVisible = false; - break; - case AnimationStatus.forward: - case AnimationStatus.reverse: - break; - } - }); - - return super.didPush(); - } - - @override - bool didPop(void result) { - _takeMeasurements( - navigatorContext: subtreeContext, - delayForSourceRoute: true, - ); - return super.didPop(result); - } - - void _takeMeasurements({ - BuildContext navigatorContext, - bool delayForSourceRoute = false, - }) { - final RenderBox navigator = - Navigator.of(navigatorContext).context.findRenderObject(); - final navSize = _getSize(navigator); - _rectTween.end = Offset.zero & navSize; - void takeMeasurementsInSourceRoute([Duration _]) { - if (!navigator.attached || hideableKey.currentContext == null) { - return; - } - _rectTween.begin = _getRect(hideableKey, navigator); - - hideableKey.currentState.placeholderSize = _rectTween.begin.size; - } - - if (delayForSourceRoute) { - SchedulerBinding.instance - .addPostFrameCallback(takeMeasurementsInSourceRoute); - } else { - takeMeasurementsInSourceRoute(); - } - } - - Size _getSize(RenderBox render) { - assert(render != null && render.hasSize); - return render.size; - } - - // Returns the bounds of the [RenderObject] identified by `key` in the - // coordinate system of `ancestor`. - Rect _getRect(GlobalKey key, RenderBox ancestor) { - assert(key.currentContext != null); - assert(ancestor != null && ancestor.hasSize); - final RenderBox render = key.currentContext.findRenderObject(); - assert(render != null && render.hasSize); - return MatrixUtils.transformRect( - render.getTransformTo(ancestor), - Offset.zero & render.size, - ); - } - - bool get _transitionWasInterrupted { - var wasInProgress = false; - var isInProgress = false; - - switch (_currentAnimationStatus) { - case AnimationStatus.completed: - case AnimationStatus.dismissed: - isInProgress = false; - break; - case AnimationStatus.forward: - case AnimationStatus.reverse: - isInProgress = true; - break; - } - switch (_lastAnimationStatus) { - case AnimationStatus.completed: - case AnimationStatus.dismissed: - wasInProgress = false; - break; - case AnimationStatus.forward: - case AnimationStatus.reverse: - wasInProgress = true; - break; - } - return wasInProgress && isInProgress; - } - - void closeContainer() { - Navigator.of(subtreeContext).pop(); - } - - @override - Widget buildPage( - BuildContext context, - Animation animation, - Animation secondaryAnimation, - ) { - return Align( - alignment: Alignment.topLeft, - child: AnimatedBuilder( - animation: animation, - builder: (context, child) { - if (animation.isCompleted) { - return SizedBox.expand( - child: Material( - color: openColor, - elevation: openElevation, - shape: openShape, - child: Builder( - key: _openBuilderKey, - builder: (context) { - return openBuilder(context, closeContainer, false); - }, - ), - ), - ); - } - - final Animation curvedAnimation = CurvedAnimation( - parent: animation, - curve: Curves.fastOutSlowIn, - reverseCurve: - _transitionWasInterrupted ? null : Curves.fastOutSlowIn.flipped, - ); - final Animation secondCurvedAnimation = CurvedAnimation( - parent: animation, - curve: Curves.easeOutCirc, - reverseCurve: - _transitionWasInterrupted ? null : Curves.easeOutCirc.flipped, - ); - TweenSequence colorTween; - TweenSequence closedOpacityTween, openOpacityTween; - switch (animation.status) { - case AnimationStatus.dismissed: - case AnimationStatus.forward: - closedOpacityTween = _closedOpacityTween; - openOpacityTween = _openOpacityTween; - colorTween = _colorTween; - break; - case AnimationStatus.reverse: - if (_transitionWasInterrupted) { - closedOpacityTween = _closedOpacityTween; - openOpacityTween = _openOpacityTween; - colorTween = _colorTween; - break; - } - closedOpacityTween = _closedOpacityTween.flipped; - openOpacityTween = _openOpacityTween.flipped; - colorTween = _colorTween.flipped; - break; - case AnimationStatus.completed: - assert(false); // Unreachable. - break; - } - assert(colorTween != null); - assert(closedOpacityTween != null); - assert(openOpacityTween != null); - - final rect = _rectTween.evaluate(curvedAnimation); - _positionTween.begin = - Offset(_rectTween.begin.left + 10, _rectTween.begin.top + 10); - _positionTween.end = Offset( - 10, - playerRunning - ? MediaQuery.of(context).size.height - 40 - playerHeight - : MediaQuery.of(context).size.height - 40); - - _avatarScaleTween.begin = flightWidgetSize; - _avatarScaleTween.end = 30; - return SizedBox.expand( - child: Stack( - children: [ - Container( - child: Align( - alignment: Alignment.topLeft, - child: Transform.translate( - offset: Offset(rect.left, rect.top), - child: SizedBox( - width: rect.width, - height: rect.height * - (playerRunning - ? (1 - playerHeight / context.height) - : 1), - child: Material( - clipBehavior: Clip.antiAlias, - animationDuration: Duration.zero, - color: colorTween.evaluate(animation), - shape: _shapeTween.evaluate(curvedAnimation), - elevation: _elevationTween.evaluate(curvedAnimation), - child: Stack( - fit: StackFit.passthrough, - children: [ - // Closed child fading out. - FittedBox( - fit: BoxFit.fitWidth, - alignment: Alignment.topLeft, - child: SizedBox( - width: _rectTween.begin.width, - height: _rectTween.begin.height, - child: hideableKey.currentState.isInTree - ? null - : Opacity( - opacity: closedOpacityTween - .evaluate(animation), - child: Builder( - key: closedBuilderKey, - builder: (context) { - // Use dummy "open container" callback - // since we are in the process of opening. - return closedBuilder( - context, () {}, true); - }, - ), - ), - ), - ), - - // Open child fading in. - FittedBox( - fit: BoxFit.fitWidth, - alignment: Alignment.topLeft, - child: SizedBox( - width: _rectTween.end.width, - height: _rectTween.end.height, - child: Opacity( - opacity: - openOpacityTween.evaluate(animation), - child: Builder( - key: _openBuilderKey, - builder: (context) { - return openBuilder( - context, closeContainer, true); - }, - ), - ), - ), - ), - ], - ), - ), - ), - ), - ), - ), - Positioned( - top: _positionTween.evaluate(secondCurvedAnimation).dy, - left: _positionTween.evaluate(secondCurvedAnimation).dx, - child: SizedBox( - height: _avatarScaleTween.evaluate(secondCurvedAnimation), - width: _avatarScaleTween.evaluate(secondCurvedAnimation), - child: flightWidget, - ), - ), - ], - ), - ); - }, - ), - ); - } - - @override - bool get maintainState => true; - - @override - Color get barrierColor => null; - - @override - bool get opaque => true; - - @override - bool get barrierDismissible => false; - - @override - String get barrierLabel => null; -} - -class _FlippableTweenSequence extends TweenSequence { - _FlippableTweenSequence(this._items) : super(_items); - - final List> _items; - _FlippableTweenSequence _flipped; - - _FlippableTweenSequence get flipped { - if (_flipped == null) { - final newItems = >[]; - for (var i = 0; i < _items.length; i++) { - newItems.add(TweenSequenceItem( - tween: _items[i].tween, - weight: _items[_items.length - 1 - i].weight, - )); - } - _flipped = _FlippableTweenSequence(newItems); - } - return _flipped; - } -} +// Copyright 2019 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'extension_helper.dart'; + +/// Signature for a function that creates a [Widget] to be used within an +/// [OpenContainer]. +/// +/// The `action` callback provided to [OpenContainer.openBuilder] can be used +/// to open the container. The `action` callback provided to +/// [OpenContainer.closedBuilder] can be used to close the container again. +typedef OpenContainerBuilder = Widget Function( + BuildContext context, + VoidCallback action, + bool hide, +); + +/// The [OpenContainer] widget's fade transition type. +/// +/// This determines the type of fade transition that the incoming and outgoing +/// contents will use. +enum ContainerTransitionType { + /// Fades the incoming element in over the outgoing element. + fade, + + /// First fades the outgoing element out, and starts fading the incoming + /// element in once the outgoing element has completely faded out. + fadeThrough, +} + +/// A container that grows to fill the screen to reveal new content when tapped. +/// +/// While the container is closed, it shows the [Widget] returned by +/// [closedBuilder]. When the container is tapped it grows to fill the entire +/// size of the surrounding [Navigator] while fading out the widget returned by +/// [closedBuilder] and fading in the widget returned by [openBuilder]. When the +/// container is closed again via the callback provided to [openBuilder] or via +/// Android's back button, the animation is reversed: The container shrinks back +/// to its original size while the widget returned by [openBuilder] is faded out +/// and the widget returned by [openBuilder] is faded back in. +/// +/// By default, the container is in the closed state. During the transition from +/// closed to open and vice versa the widgets returned by the [openBuilder] and +/// [closedBuilder] exist in the tree at the same time. Therefore, the widgets +/// returned by these builders cannot include the same global key. +/// +/// +/// See also: +/// +/// * [Transitions with animated containers](https://material.io/design/motion/choreography.html#transformation) +/// in the Material spec. +class OpenContainer extends StatefulWidget { + /// Creates an [OpenContainer]. + /// + /// All arguments except for [key] must not be null. The arguments + /// [closedBuilder] and [closedBuilder] are required. + const OpenContainer({ + Key key, + this.closedColor = Colors.white, + this.openColor = Colors.white, + this.beginColor = Colors.white, + this.endColor = Colors.white, + this.closedElevation = 1.0, + this.openElevation = 4.0, + this.closedShape = const RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(4.0)), + ), + this.openShape = const RoundedRectangleBorder(), + @required this.closedBuilder, + @required this.openBuilder, + this.flightWidget, + this.flightWidgetSize, + this.playerRunning, + this.playerHeight, + this.tappable = true, + this.transitionDuration = const Duration(milliseconds: 300), + this.transitionType = ContainerTransitionType.fade, + }) : assert(closedColor != null), + assert(openColor != null), + assert(closedElevation != null), + assert(openElevation != null), + assert(closedShape != null), + assert(openShape != null), + assert(closedBuilder != null), + assert(openBuilder != null), + assert(tappable != null), + assert(transitionType != null), + super(key: key); + + /// Background color of the container while it is closed. + /// + /// When the container is opened, it will first transition from this color + /// to [Colors.white] and then transition from there to [openColor] in one + /// smooth animation. When the container is closed, it will transition back to + /// this color from [openColor] via [Colors.white]. + /// + /// Defaults to [Colors.white]. + /// + /// See also: + /// + /// * [Material.color], which is used to implement this property. + /// + final Color beginColor; + final Color endColor; + final Color closedColor; + final Widget flightWidget; + final double flightWidgetSize; + final bool playerRunning; + final double playerHeight; + + /// Background color of the container while it is open. + /// + /// When the container is closed, it will first transition from [closedColor] + /// to [Colors.white] and then transition from there to this color in one + /// smooth animation. When the container is closed, it will transition back to + /// [closedColor] from this color via [Colors.white]. + /// + /// Defaults to [Colors.white]. + /// + /// See also: + /// + /// * [Material.color], which is used to implement this property. + final Color openColor; + + /// Elevation of the container while it is closed. + /// + /// When the container is opened, it will transition from this elevation to + /// [openElevation]. When the container is closed, it will transition back + /// from [openElevation] to this elevation. + /// + /// Defaults to 1.0. + /// + /// See also: + /// + /// * [Material.elevation], which is used to implement this property. + final double closedElevation; + + /// Elevation of the container while it is open. + /// + /// When the container is opened, it will transition to this elevation from + /// [closedElevation]. When the container is closed, it will transition back + /// from this elevation to [closedElevation]. + /// + /// Defaults to 4.0. + /// + /// See also: + /// + /// * [Material.elevation], which is used to implement this property. + final double openElevation; + + /// Shape of the container while it is closed. + /// + /// When the container is opened it will transition from this shape to + /// [openShape]. When the container is closed, it will transition back to this + /// shape. + /// + /// Defaults to a [RoundedRectangleBorder] with a [Radius.circular] of 4.0. + /// + /// See also: + /// + /// * [Material.shape], which is used to implement this property. + final ShapeBorder closedShape; + + /// Shape of the container while it is open. + /// + /// When the container is opened it will transition from [closedShape] to + /// this shape. When the container is closed, it will transition from this + /// shape back to [closedShape]. + /// + /// Defaults to a rectangular. + /// + /// See also: + /// + /// * [Material.shape], which is used to implement this property. + final ShapeBorder openShape; + + /// Called to obtain the child for the container in the closed state. + /// + /// The [Widget] returned by this builder is faded out when the container + /// opens and at the same time the widget returned by [openBuilder] is faded + /// in while the container grows to fill the surrounding [Navigator]. + /// + /// The `action` callback provided to the builder can be called to open the + /// container. + final OpenContainerBuilder closedBuilder; + + /// Called to obtain the child for the container in the open state. + /// + /// The [Widget] returned by this builder is faded in when the container + /// opens and at the same time the widget returned by [closedBuilder] is + /// faded out while the container grows to fill the surrounding [Navigator]. + /// + /// The `action` callback provided to the builder can be called to close the + /// container. + final OpenContainerBuilder openBuilder; + + /// Whether the entire closed container can be tapped to open it. + /// + /// Defaults to true. + /// + /// When this is set to false the container can only be opened by calling the + /// `action` callback that is provided to the [closedBuilder]. + final bool tappable; + + /// The time it will take to animate the container from its closed to its + /// open state and vice versa. + /// + /// Defaults to 300ms. + final Duration transitionDuration; + + /// The type of fade transition that the container will use for its + /// incoming and outgoing widgets. + /// + /// Defaults to [ContainerTransitionType.fade]. + final ContainerTransitionType transitionType; + + @override + _OpenContainerState createState() => _OpenContainerState(); +} + +class _OpenContainerState extends State { + // Key used in [_OpenContainerRoute] to hide the widget returned by + // [OpenContainer.openBuilder] in the source route while the container is + // opening/open. A copy of that widget is included in the + // [_OpenContainerRoute] where it fades out. To avoid issues with double + // shadows and transparency, we hide it in the source route. + final GlobalKey<_HideableState> _hideableKey = GlobalKey<_HideableState>(); + + // Key used to steal the state of the widget returned by + // [OpenContainer.openBuilder] from the source route and attach it to the + // same widget included in the [_OpenContainerRoute] where it fades out. + final GlobalKey _closedBuilderKey = GlobalKey(); + + void openContainer() { + Navigator.of(context).push(_OpenContainerRoute( + beginColor: widget.beginColor, + endColor: widget.endColor, + closedColor: widget.closedColor, + openColor: widget.openColor, + closedElevation: widget.closedElevation, + openElevation: widget.openElevation, + closedShape: widget.closedShape, + openShape: widget.openShape, + closedBuilder: widget.closedBuilder, + openBuilder: widget.openBuilder, + hideableKey: _hideableKey, + closedBuilderKey: _closedBuilderKey, + transitionDuration: widget.transitionDuration, + transitionType: widget.transitionType, + flightWidget: widget.flightWidget, + flightWidgetSize: widget.flightWidgetSize, + playerRunning: widget.playerRunning, + playerHeight: widget.playerHeight, + )); + } + + @override + Widget build(BuildContext context) { + return _Hideable( + key: _hideableKey, + child: GestureDetector( + onTap: widget.tappable ? openContainer : null, + child: Material( + color: Colors.transparent, + // clipBehavior: Clip.antiAlias, + // color: widget.closedColor, + // elevation: widget.closedElevation, + // shape: widget.closedShape, + child: Builder( + key: _closedBuilderKey, + builder: (context) { + return widget.closedBuilder(context, openContainer, false); + }, + ), + ), + ), + ); + } +} + +/// Controls the visibility of its child. +/// +/// The child can be in one of three states: +/// +/// * It is included in the tree and fully visible. (The `placeholderSize` is +/// null and `isVisible` is true.) +/// * It is included in the tree, but not visible; its size is maintained. +/// (The `placeholderSize` is null and `isVisible` is false.) +/// * It is not included in the tree. Instead a [SizedBox] of dimensions +/// specified by `placeholderSize` is included in the tree. (The value of +/// `isVisible` is ignored). +class _Hideable extends StatefulWidget { + const _Hideable({ + Key key, + this.child, + }) : super(key: key); + + final Widget child; + + @override + State<_Hideable> createState() => _HideableState(); +} + +class _HideableState extends State<_Hideable> { + /// When non-null the child is replaced by a [SizedBox] of the set size. + Size get placeholderSize => _placeholderSize; + Size _placeholderSize; + set placeholderSize(Size value) { + if (_placeholderSize == value) { + return; + } + setState(() { + _placeholderSize = value; + }); + } + + /// When true the child is not visible, but will maintain its size. + /// + /// The value of this property is ignored when [placeholderSize] is non-null + /// (i.e. [isInTree] returns false). + bool get isVisible => _visible; + bool _visible = true; + set isVisible(bool value) { + assert(value != null); + if (_visible == value) { + return; + } + setState(() { + _visible = value; + }); + } + + /// Whether the child is currently included in the tree. + /// + /// When it is included, it may be visible or not according to [isVisible]. + bool get isInTree => _placeholderSize == null; + + @override + Widget build(BuildContext context) { + if (_placeholderSize != null) { + return SizedBox.fromSize(size: _placeholderSize); + } + return Opacity( + opacity: _visible ? 1.0 : 0.0, + child: widget.child, + ); + } +} + +class _OpenContainerRoute extends ModalRoute { + _OpenContainerRoute({ + @required this.closedColor, + @required this.openColor, + @required this.beginColor, + @required this.endColor, + @required double closedElevation, + @required this.openElevation, + @required ShapeBorder closedShape, + @required this.openShape, + @required this.closedBuilder, + @required this.openBuilder, + @required this.hideableKey, + @required this.closedBuilderKey, + @required this.transitionDuration, + @required this.transitionType, + this.flightWidget, + this.flightWidgetSize, + this.playerRunning, + this.playerHeight, + }) : assert(closedColor != null), + assert(openColor != null), + assert(closedElevation != null), + assert(openElevation != null), + assert(closedShape != null), + assert(openBuilder != null), + assert(closedBuilder != null), + assert(hideableKey != null), + assert(closedBuilderKey != null), + assert(transitionType != null), + _elevationTween = Tween( + begin: closedElevation, + end: openElevation, + ), + _shapeTween = ShapeBorderTween( + begin: closedShape, + end: openShape, + ), + _colorTween = _getColorTween( + transitionType: transitionType, + closedColor: closedColor, + openColor: openColor, + beginColor: beginColor, + endColor: endColor), + _closedOpacityTween = _getClosedOpacityTween(transitionType), + _openOpacityTween = _getOpenOpacityTween(transitionType); + + final Widget flightWidget; + final double flightWidgetSize; + final bool playerRunning; + final double playerHeight; + static _FlippableTweenSequence _getColorTween({ + @required ContainerTransitionType transitionType, + @required Color closedColor, + @required Color openColor, + @required Color beginColor, + @required Color endColor, + }) { + switch (transitionType) { + case ContainerTransitionType.fade: + return _FlippableTweenSequence( + >[ + TweenSequenceItem( + tween: ConstantTween(closedColor), + weight: 1 / 5, + ), + TweenSequenceItem( + tween: ColorTween(begin: closedColor, end: openColor), + weight: 1 / 5, + ), + TweenSequenceItem( + tween: ConstantTween(openColor), + weight: 3 / 5, + ), + ], + ); + case ContainerTransitionType.fadeThrough: + return _FlippableTweenSequence( + >[ + TweenSequenceItem( + tween: ColorTween(begin: closedColor, end: endColor), + weight: 1 / 5, + ), + TweenSequenceItem( + tween: ColorTween(begin: beginColor, end: openColor), + weight: 4 / 5, + ), + ], + ); + } + return null; // unreachable + } + + static _FlippableTweenSequence _getClosedOpacityTween( + ContainerTransitionType transitionType) { + switch (transitionType) { + case ContainerTransitionType.fade: + return _FlippableTweenSequence( + >[ + TweenSequenceItem( + tween: ConstantTween(1.0), + weight: 1, + ), + ], + ); + break; + case ContainerTransitionType.fadeThrough: + return _FlippableTweenSequence( + >[ + TweenSequenceItem( + tween: Tween(begin: 1.0, end: 0.0), + weight: 1 / 5, + ), + TweenSequenceItem( + tween: ConstantTween(0.0), + weight: 4 / 5, + ), + ], + ); + break; + } + return null; // unreachable + } + + static _FlippableTweenSequence _getOpenOpacityTween( + ContainerTransitionType transitionType) { + switch (transitionType) { + case ContainerTransitionType.fade: + return _FlippableTweenSequence( + >[ + TweenSequenceItem( + tween: ConstantTween(0.0), + weight: 1 / 5, + ), + TweenSequenceItem( + tween: Tween(begin: 0.0, end: 1.0), + weight: 1 / 5, + ), + TweenSequenceItem( + tween: ConstantTween(1.0), + weight: 3 / 5, + ), + ], + ); + break; + case ContainerTransitionType.fadeThrough: + return _FlippableTweenSequence( + >[ + TweenSequenceItem( + tween: ConstantTween(0.0), + weight: 1 / 5, + ), + TweenSequenceItem( + tween: Tween(begin: 0.0, end: 1.0), + weight: 4 / 5, + ), + ], + ); + break; + } + return null; // unreachable + } + + final Color closedColor; + final Color openColor; + final Color beginColor; + final Color endColor; + final double openElevation; + final ShapeBorder openShape; + final OpenContainerBuilder closedBuilder; + final OpenContainerBuilder openBuilder; + + // See [_OpenContainerState._hideableKey]. + final GlobalKey<_HideableState> hideableKey; + + // See [_OpenContainerState._closedBuilderKey]. + final GlobalKey closedBuilderKey; + + @override + final Duration transitionDuration; + final ContainerTransitionType transitionType; + + final Tween _elevationTween; + final ShapeBorderTween _shapeTween; + final _FlippableTweenSequence _closedOpacityTween; + final _FlippableTweenSequence _openOpacityTween; + final _FlippableTweenSequence _colorTween; + + // Key used for the widget returned by [OpenContainer.openBuilder] to keep + // its state when the shape of the widget tree is changed at the end of the + // animation to remove all the craft that was necessary to make the animation + // work. + final GlobalKey _openBuilderKey = GlobalKey(); + + // Defines the position and the size of the (opening) [OpenContainer] within + // the bounds of the enclosing [Navigator]. + final RectTween _rectTween = RectTween(); + final Tween _positionTween = Tween(); + final Tween _avatarScaleTween = Tween(); + AnimationStatus _lastAnimationStatus; + AnimationStatus _currentAnimationStatus; + + @override + TickerFuture didPush() { + _takeMeasurements(navigatorContext: hideableKey.currentContext); + + animation.addStatusListener((status) { + _lastAnimationStatus = _currentAnimationStatus; + _currentAnimationStatus = status; + switch (status) { + case AnimationStatus.dismissed: + hideableKey.currentState + ..placeholderSize = null + ..isVisible = true; + break; + case AnimationStatus.completed: + hideableKey.currentState + ..placeholderSize = null + ..isVisible = false; + break; + case AnimationStatus.forward: + case AnimationStatus.reverse: + break; + } + }); + + return super.didPush(); + } + + @override + bool didPop(void result) { + _takeMeasurements( + navigatorContext: subtreeContext, + delayForSourceRoute: true, + ); + return super.didPop(result); + } + + void _takeMeasurements({ + BuildContext navigatorContext, + bool delayForSourceRoute = false, + }) { + final RenderBox navigator = + Navigator.of(navigatorContext).context.findRenderObject(); + final navSize = _getSize(navigator); + _rectTween.end = Offset.zero & navSize; + void takeMeasurementsInSourceRoute([Duration _]) { + if (!navigator.attached || hideableKey.currentContext == null) { + return; + } + _rectTween.begin = _getRect(hideableKey, navigator); + + hideableKey.currentState.placeholderSize = _rectTween.begin.size; + } + + if (delayForSourceRoute) { + SchedulerBinding.instance + .addPostFrameCallback(takeMeasurementsInSourceRoute); + } else { + takeMeasurementsInSourceRoute(); + } + } + + Size _getSize(RenderBox render) { + assert(render != null && render.hasSize); + return render.size; + } + + // Returns the bounds of the [RenderObject] identified by `key` in the + // coordinate system of `ancestor`. + Rect _getRect(GlobalKey key, RenderBox ancestor) { + assert(key.currentContext != null); + assert(ancestor != null && ancestor.hasSize); + final RenderBox render = key.currentContext.findRenderObject(); + assert(render != null && render.hasSize); + return MatrixUtils.transformRect( + render.getTransformTo(ancestor), + Offset.zero & render.size, + ); + } + + bool get _transitionWasInterrupted { + var wasInProgress = false; + var isInProgress = false; + + switch (_currentAnimationStatus) { + case AnimationStatus.completed: + case AnimationStatus.dismissed: + isInProgress = false; + break; + case AnimationStatus.forward: + case AnimationStatus.reverse: + isInProgress = true; + break; + } + switch (_lastAnimationStatus) { + case AnimationStatus.completed: + case AnimationStatus.dismissed: + wasInProgress = false; + break; + case AnimationStatus.forward: + case AnimationStatus.reverse: + wasInProgress = true; + break; + } + return wasInProgress && isInProgress; + } + + void closeContainer() { + Navigator.of(subtreeContext).pop(); + } + + @override + Widget buildPage( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + ) { + return Align( + alignment: Alignment.topLeft, + child: AnimatedBuilder( + animation: animation, + builder: (context, child) { + if (animation.isCompleted) { + return SizedBox.expand( + child: Material( + color: openColor, + elevation: openElevation, + shape: openShape, + child: Builder( + key: _openBuilderKey, + builder: (context) { + return openBuilder(context, closeContainer, false); + }, + ), + ), + ); + } + + final Animation curvedAnimation = CurvedAnimation( + parent: animation, + curve: Curves.fastOutSlowIn, + reverseCurve: + _transitionWasInterrupted ? null : Curves.fastOutSlowIn.flipped, + ); + final Animation secondCurvedAnimation = CurvedAnimation( + parent: animation, + curve: Curves.easeOutCirc, + reverseCurve: + _transitionWasInterrupted ? null : Curves.easeOutCirc.flipped, + ); + TweenSequence colorTween; + TweenSequence closedOpacityTween, openOpacityTween; + switch (animation.status) { + case AnimationStatus.dismissed: + case AnimationStatus.forward: + closedOpacityTween = _closedOpacityTween; + openOpacityTween = _openOpacityTween; + colorTween = _colorTween; + break; + case AnimationStatus.reverse: + if (_transitionWasInterrupted) { + closedOpacityTween = _closedOpacityTween; + openOpacityTween = _openOpacityTween; + colorTween = _colorTween; + break; + } + closedOpacityTween = _closedOpacityTween.flipped; + openOpacityTween = _openOpacityTween.flipped; + colorTween = _colorTween.flipped; + break; + case AnimationStatus.completed: + assert(false); // Unreachable. + break; + } + assert(colorTween != null); + assert(closedOpacityTween != null); + assert(openOpacityTween != null); + + final rect = _rectTween.evaluate(curvedAnimation); + _positionTween.begin = + Offset(_rectTween.begin.left + 10, _rectTween.begin.top + 10); + _positionTween.end = Offset( + 10, + playerRunning + ? MediaQuery.of(context).size.height - 40 - playerHeight + : MediaQuery.of(context).size.height - 40); + + _avatarScaleTween.begin = flightWidgetSize; + _avatarScaleTween.end = 30; + return SizedBox.expand( + child: Stack( + children: [ + Container( + child: Align( + alignment: Alignment.topLeft, + child: Transform.translate( + offset: Offset(rect.left, rect.top), + child: SizedBox( + width: rect.width, + height: rect.height * + (playerRunning + ? (1 - playerHeight / context.height) + : 1), + child: Material( + clipBehavior: Clip.antiAlias, + animationDuration: Duration.zero, + color: colorTween.evaluate(animation), + shape: _shapeTween.evaluate(curvedAnimation), + elevation: _elevationTween.evaluate(curvedAnimation), + child: Stack( + fit: StackFit.passthrough, + children: [ + // Closed child fading out. + FittedBox( + fit: BoxFit.fitWidth, + alignment: Alignment.topLeft, + child: SizedBox( + width: _rectTween.begin.width, + height: _rectTween.begin.height, + child: hideableKey.currentState.isInTree + ? null + : Opacity( + opacity: closedOpacityTween + .evaluate(animation), + child: Builder( + key: closedBuilderKey, + builder: (context) { + // Use dummy "open container" callback + // since we are in the process of opening. + return closedBuilder( + context, () {}, true); + }, + ), + ), + ), + ), + + // Open child fading in. + FittedBox( + fit: BoxFit.fitWidth, + alignment: Alignment.topLeft, + child: SizedBox( + width: _rectTween.end.width, + height: _rectTween.end.height, + child: Opacity( + opacity: + openOpacityTween.evaluate(animation), + child: Builder( + key: _openBuilderKey, + builder: (context) { + return openBuilder( + context, closeContainer, true); + }, + ), + ), + ), + ), + ], + ), + ), + ), + ), + ), + ), + Positioned( + top: _positionTween.evaluate(secondCurvedAnimation).dy, + left: _positionTween.evaluate(secondCurvedAnimation).dx, + child: SizedBox( + height: _avatarScaleTween.evaluate(secondCurvedAnimation), + width: _avatarScaleTween.evaluate(secondCurvedAnimation), + child: flightWidget, + ), + ), + ], + ), + ); + }, + ), + ); + } + + @override + bool get maintainState => true; + + @override + Color get barrierColor => null; + + @override + bool get opaque => true; + + @override + bool get barrierDismissible => false; + + @override + String get barrierLabel => null; +} + +class _FlippableTweenSequence extends TweenSequence { + _FlippableTweenSequence(this._items) : super(_items); + + final List> _items; + _FlippableTweenSequence _flipped; + + _FlippableTweenSequence get flipped { + if (_flipped == null) { + final newItems = >[]; + for (var i = 0; i < _items.length; i++) { + newItems.add(TweenSequenceItem( + tween: _items[i].tween, + weight: _items[_items.length - 1 - i].weight, + )); + } + _flipped = _FlippableTweenSequence(newItems); + } + return _flipped; + } +} diff --git a/lib/util/pageroute.dart b/lib/util/pageroute.dart index 77289a9..7b1f026 100644 --- a/lib/util/pageroute.dart +++ b/lib/util/pageroute.dart @@ -1,157 +1,157 @@ -import 'package:flutter/material.dart'; - -//Slide Transition -class SlideLeftRoute extends PageRouteBuilder { - final Widget page; - SlideLeftRoute({this.page}) - : super( - pageBuilder: ( - context, - animation, - secondaryAnimation, - ) => - page, - transitionsBuilder: ( - context, - animation, - secondaryAnimation, - child, - ) { - var begin = Offset(1.0, 0.0); - var end = Offset.zero; - var curve = Curves.easeOutQuart; - var tween = - Tween(begin: begin, end: end).chain(CurveTween(curve: curve)); - var tweenSequence = TweenSequence(>[ - TweenSequenceItem( - tween: tween, - weight: 90.0, - ), - TweenSequenceItem( - tween: ConstantTween(Offset.zero), - weight: 10.0, - ), - ]); - return SlideTransition( - position: animation.drive(tweenSequence), - child: child, - ); - }); -} - -class SlideLeftHideRoute extends PageRouteBuilder { - final Widget page; - // final Widget transitionPage; - SlideLeftHideRoute({this.page}) - : super( - pageBuilder: ( - context, - animation, - secondaryAnimation, - ) => - page, - // transitionDuration: Duration(milliseconds: 300), - transitionsBuilder: ( - context, - animation, - secondaryAnimation, - child, - ) { - return SlideTransition( - position: Tween( - begin: const Offset(1, 0), - end: Offset.zero, - ).animate(animation), - child: child); - }, - ); -} - -class SlideUptRoute extends PageRouteBuilder { - final Widget page; - SlideUptRoute({this.page}) - : super( - pageBuilder: ( - context, - animation, - secondaryAnimation, - ) => - page, - transitionsBuilder: ( - context, - animation, - secondaryAnimation, - child, - ) => - SlideTransition( - position: Tween( - begin: const Offset(0, 1), - end: Offset.zero, - ).animate(animation), - child: child, - ), - ); -} - -//Scale Pageroute -class ScaleRoute extends PageRouteBuilder { - final Widget page; - ScaleRoute({this.page}) - : super( - pageBuilder: ( - context, - animation, - secondaryAnimation, - ) => - page, - transitionsBuilder: ( - context, - animation, - secondaryAnimation, - child, - ) => - ScaleTransition( - scale: Tween( - begin: 0.0, - end: 1.0, - ).animate( - CurvedAnimation( - parent: animation, - curve: Curves.fastOutSlowIn, - ), - ), - child: child, - ), - ); -} - -class FadeRoute extends PageRouteBuilder { - final Widget page; - FadeRoute({this.page}) - : super( - pageBuilder: ( - context, - animation, - secondaryAnimation, - ) => - page, - transitionsBuilder: ( - context, - animation, - secondaryAnimation, - child, - ) => - FadeTransition( - opacity: Tween( - begin: 0.0, - end: 1.0, - ).animate( - CurvedAnimation( - parent: animation, - curve: Curves.easeInCubic, - ), - ), - child: child, - ), - ); -} +import 'package:flutter/material.dart'; + +//Slide Transition +class SlideLeftRoute extends PageRouteBuilder { + final Widget page; + SlideLeftRoute({this.page}) + : super( + pageBuilder: ( + context, + animation, + secondaryAnimation, + ) => + page, + transitionsBuilder: ( + context, + animation, + secondaryAnimation, + child, + ) { + var begin = Offset(1.0, 0.0); + var end = Offset.zero; + var curve = Curves.easeOutQuart; + var tween = + Tween(begin: begin, end: end).chain(CurveTween(curve: curve)); + var tweenSequence = TweenSequence(>[ + TweenSequenceItem( + tween: tween, + weight: 90.0, + ), + TweenSequenceItem( + tween: ConstantTween(Offset.zero), + weight: 10.0, + ), + ]); + return SlideTransition( + position: animation.drive(tweenSequence), + child: child, + ); + }); +} + +class SlideLeftHideRoute extends PageRouteBuilder { + final Widget page; + // final Widget transitionPage; + SlideLeftHideRoute({this.page}) + : super( + pageBuilder: ( + context, + animation, + secondaryAnimation, + ) => + page, + // transitionDuration: Duration(milliseconds: 300), + transitionsBuilder: ( + context, + animation, + secondaryAnimation, + child, + ) { + return SlideTransition( + position: Tween( + begin: const Offset(1, 0), + end: Offset.zero, + ).animate(animation), + child: child); + }, + ); +} + +class SlideUptRoute extends PageRouteBuilder { + final Widget page; + SlideUptRoute({this.page}) + : super( + pageBuilder: ( + context, + animation, + secondaryAnimation, + ) => + page, + transitionsBuilder: ( + context, + animation, + secondaryAnimation, + child, + ) => + SlideTransition( + position: Tween( + begin: const Offset(0, 1), + end: Offset.zero, + ).animate(animation), + child: child, + ), + ); +} + +//Scale Pageroute +class ScaleRoute extends PageRouteBuilder { + final Widget page; + ScaleRoute({this.page}) + : super( + pageBuilder: ( + context, + animation, + secondaryAnimation, + ) => + page, + transitionsBuilder: ( + context, + animation, + secondaryAnimation, + child, + ) => + ScaleTransition( + scale: Tween( + begin: 0.0, + end: 1.0, + ).animate( + CurvedAnimation( + parent: animation, + curve: Curves.fastOutSlowIn, + ), + ), + child: child, + ), + ); +} + +class FadeRoute extends PageRouteBuilder { + final Widget page; + FadeRoute({this.page}) + : super( + pageBuilder: ( + context, + animation, + secondaryAnimation, + ) => + page, + transitionsBuilder: ( + context, + animation, + secondaryAnimation, + child, + ) => + FadeTransition( + opacity: Tween( + begin: 0.0, + end: 1.0, + ).animate( + CurvedAnimation( + parent: animation, + curve: Curves.easeInCubic, + ), + ), + child: child, + ), + ); +} diff --git a/lib/util/settings_sheet.dart b/lib/util/settings_sheet.dart index 7112b0b..2da937d 100644 --- a/lib/util/settings_sheet.dart +++ b/lib/util/settings_sheet.dart @@ -1,125 +1,125 @@ -import 'dart:math' as math; -import 'package:flutter/material.dart'; -import '../util/extension_helper.dart'; - -class SettingsSheet extends StatefulWidget { - SettingsSheet({this.height, Key key}) : super(key: key); - final double height; - @override - _SettingsSheetState createState() => _SettingsSheetState(); -} - -class _SettingsSheetState extends State - with TickerProviderStateMixin { - Animation _animation; - AnimationController _controller; - AnimationController _slowController; - double _initSize; - double _startdy; - double _move = 0; - - @override - void initState() { - _initSize = widget.height; - _controller = - AnimationController(vsync: this, duration: Duration(milliseconds: 50)) - ..addListener(() { - if (mounted) setState(() {}); - }); - _slowController = - AnimationController(vsync: this, duration: Duration(milliseconds: 200)) - ..addListener(() { - if (mounted) setState(() {}); - }); - _animation = - Tween(begin: 0, end: _initSize).animate(_slowController); - _slowController.forward(); - super.initState(); - } - - @override - void dispose() { - _slowController.dispose(); - _controller.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - return Scaffold( - backgroundColor: Colors.transparent, - body: Container( - height: context.height, - child: Stack(alignment: Alignment.bottomCenter, children: [ - Positioned.fill( - child: GestureDetector( - onTap: () { - _backToMini(); - Navigator.pop(context); - }, - child: Container( - color: context.scaffoldBackgroundColor.withOpacity( - 0.8 * math.min(_animation.value / widget.height, 1.0)), - ), - ), - ), - GestureDetector( - onVerticalDragStart: _start, - onVerticalDragUpdate: _update, - onVerticalDragEnd: (event) => _end(), - child: Container( - height: math.min(_animation.value, widget.height), - color: Colors.white, - ), - ) - ]), - ), - ); - } - - _backToMini() { - setState(() { - _animation = - Tween(begin: _initSize, end: 0).animate(_slowController); - _initSize = 0; - }); - _slowController.forward(); - } - - _start(DragStartDetails event) { - setState(() { - _startdy = event.localPosition.dy; - _animation = - Tween(begin: _initSize, end: _initSize).animate(_controller); - }); - _controller.forward(); - } - - _update(DragUpdateDetails event) { - setState(() { - _move = _startdy - event.localPosition.dy; - _animation = Tween(begin: _initSize, end: _initSize + _move) - .animate(_controller); - }); - _controller.forward(); - } - - _end() async { - if (_move < -50) { - setState(() { - _animation = - Tween(begin: _animation.value, end: 0).animate(_controller); - _initSize = 0; - }); - _controller.forward(); - Navigator.pop(context); - } else { - setState(() { - _animation = Tween(begin: _animation.value, end: widget.height) - .animate(_controller); - _initSize = widget.height; - }); - _controller.forward(); - } - } -} +import 'dart:math' as math; +import 'package:flutter/material.dart'; +import '../util/extension_helper.dart'; + +class SettingsSheet extends StatefulWidget { + SettingsSheet({this.height, Key key}) : super(key: key); + final double height; + @override + _SettingsSheetState createState() => _SettingsSheetState(); +} + +class _SettingsSheetState extends State + with TickerProviderStateMixin { + Animation _animation; + AnimationController _controller; + AnimationController _slowController; + double _initSize; + double _startdy; + double _move = 0; + + @override + void initState() { + _initSize = widget.height; + _controller = + AnimationController(vsync: this, duration: Duration(milliseconds: 50)) + ..addListener(() { + if (mounted) setState(() {}); + }); + _slowController = + AnimationController(vsync: this, duration: Duration(milliseconds: 200)) + ..addListener(() { + if (mounted) setState(() {}); + }); + _animation = + Tween(begin: 0, end: _initSize).animate(_slowController); + _slowController.forward(); + super.initState(); + } + + @override + void dispose() { + _slowController.dispose(); + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.transparent, + body: Container( + height: context.height, + child: Stack(alignment: Alignment.bottomCenter, children: [ + Positioned.fill( + child: GestureDetector( + onTap: () { + _backToMini(); + Navigator.pop(context); + }, + child: Container( + color: context.scaffoldBackgroundColor.withOpacity( + 0.8 * math.min(_animation.value / widget.height, 1.0)), + ), + ), + ), + GestureDetector( + onVerticalDragStart: _start, + onVerticalDragUpdate: _update, + onVerticalDragEnd: (event) => _end(), + child: Container( + height: math.min(_animation.value, widget.height), + color: Colors.white, + ), + ) + ]), + ), + ); + } + + _backToMini() { + setState(() { + _animation = + Tween(begin: _initSize, end: 0).animate(_slowController); + _initSize = 0; + }); + _slowController.forward(); + } + + _start(DragStartDetails event) { + setState(() { + _startdy = event.localPosition.dy; + _animation = + Tween(begin: _initSize, end: _initSize).animate(_controller); + }); + _controller.forward(); + } + + _update(DragUpdateDetails event) { + setState(() { + _move = _startdy - event.localPosition.dy; + _animation = Tween(begin: _initSize, end: _initSize + _move) + .animate(_controller); + }); + _controller.forward(); + } + + _end() async { + if (_move < -50) { + setState(() { + _animation = + Tween(begin: _animation.value, end: 0).animate(_controller); + _initSize = 0; + }); + _controller.forward(); + Navigator.pop(context); + } else { + setState(() { + _animation = Tween(begin: _animation.value, end: widget.height) + .animate(_controller); + _initSize = widget.height; + }); + _controller.forward(); + } + } +} diff --git a/test/widget_test.dart b/test/widget_test.dart index 20eeb83..94f2c1f 100644 --- a/test/widget_test.dart +++ b/test/widget_test.dart @@ -1,29 +1,29 @@ -// 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_test/flutter_test.dart'; - -import 'package:tsacdop/main.dart'; - -void main() { - testWidgets('Counter increments smoke test', (tester) async { - // Build our app and trigger a frame. - await tester.pumpWidget(MyApp()); - - // Verify that our counter starts at 0. - expect(find.text('Favorites'), findsOneWidget); - expect(find.text('Next'), 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); - }); -} +// 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_test/flutter_test.dart'; + +import 'package:tsacdop/main.dart'; + +void main() { + testWidgets('Counter increments smoke test', (tester) async { + // Build our app and trigger a frame. + await tester.pumpWidget(MyApp()); + + // Verify that our counter starts at 0. + expect(find.text('Favorites'), findsOneWidget); + expect(find.text('Next'), 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/tool/env.dart b/tool/env.dart index 0a57d22..47686f3 100644 --- a/tool/env.dart +++ b/tool/env.dart @@ -1,14 +1,14 @@ -import 'dart:convert'; -import 'dart:io'; - -Future main() async { - final config = { - 'apiKey': Platform.environment['API_KEY'], - 'podcastIndexApiKey': Platform.environment['PI_API_KEY'], - 'podcastIndexApiSecret': Platform.environment['PI_API_SECRET'] - }; - - final filename = 'lib/.env.dart'; - File(filename).writeAsString('final environment = ${json.encode(config)};'); - print('Write successfully'); -} +import 'dart:convert'; +import 'dart:io'; + +Future main() async { + final config = { + 'apiKey': Platform.environment['API_KEY'], + 'podcastIndexApiKey': Platform.environment['PI_API_KEY'], + 'podcastIndexApiSecret': Platform.environment['PI_API_SECRET'] + }; + + final filename = 'lib/.env.dart'; + File(filename).writeAsString('final environment = ${json.encode(config)};'); + print('Write successfully'); +}