├── .github └── workflows │ └── android-emulator-test.yml ├── .gitignore ├── .idea ├── codeStyles │ ├── Project.xml │ └── codeStyleConfig.xml ├── compiler.xml ├── copyright │ ├── Apache.xml │ └── profiles_settings.xml ├── gradle.xml ├── jarRepositories.xml ├── misc.xml ├── scopes │ └── library.xml └── vcs.xml ├── LICENSE ├── README.md ├── build.gradle.kts ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── library ├── .gitignore ├── build.gradle.kts ├── consumer-rules.pro ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── xyz │ │ └── quaver │ │ └── io │ │ └── ExampleInstrumentedTest.kt │ ├── main │ ├── AndroidManifest.xml │ └── java │ │ └── xyz │ │ └── quaver │ │ └── io │ │ ├── DocumentFileX.kt │ │ ├── ExternalTreeFileX.kt │ │ ├── FileX.kt │ │ ├── RawFileX.kt │ │ ├── SAFileX.kt │ │ ├── TreeFileX.kt │ │ └── util │ │ ├── DeleteOnExitHook.kt │ │ ├── DocumentUtil.kt │ │ ├── FileUtil.kt │ │ ├── FileXReadWrite.kt │ │ ├── FileXUtil.kt │ │ └── SAFileXReadWrite.kt │ └── test │ └── java │ └── xyz │ └── quaver │ └── io │ └── ExampleUnitTest.kt ├── sample ├── .gitignore ├── build.gradle.kts ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── xyz │ │ └── quaver │ │ └── io │ │ └── sample │ │ └── ExampleInstrumentedTest.kt │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── xyz │ │ │ └── quaver │ │ │ └── io │ │ │ └── sample │ │ │ ├── MainActivity.kt │ │ │ └── MainActivityViewModel.kt │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ └── ic_launcher_background.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── xyz │ └── quaver │ └── io │ └── sample │ └── ExampleUnitTest.kt └── settings.gradle /.github/workflows/android-emulator-test.yml: -------------------------------------------------------------------------------- 1 | name: Android Emulator Test 2 | 3 | on: 4 | workflow_dispatch: 5 | 6 | # A workflow run is made up of one or more jobs that can run sequentially or in parallel 7 | jobs: 8 | test: 9 | runs-on: macos-latest 10 | steps: 11 | - name: checkout 12 | uses: actions/checkout@v2 13 | 14 | - name: setup java 15 | uses: actions/setup-java@v2 16 | with: 17 | distribution: 'temurin' 18 | java-version: '11' 19 | 20 | - name: run tests 21 | uses: reactivecircus/android-emulator-runner@v2 22 | with: 23 | api-level: 21 24 | script: ./gradlew connectedAndroidTest 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/caches 5 | /.idea/libraries 6 | /.idea/modules.xml 7 | /.idea/workspace.xml 8 | /.idea/navEditor.xml 9 | /.idea/assetWizardSettings.xml 10 | .DS_Store 11 | /build 12 | /captures 13 | .externalNativeBuild 14 | .cxx 15 | -------------------------------------------------------------------------------- /.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 20 | 22 | 23 | 24 | 26 | 27 | 28 |
29 | 30 | 31 | 32 | xmlns:android 33 | 34 | ^$ 35 | 36 | 37 | 38 |
39 |
40 | 41 | 42 | 43 | xmlns:.* 44 | 45 | ^$ 46 | 47 | 48 | BY_NAME 49 | 50 |
51 |
52 | 53 | 54 | 55 | .*:id 56 | 57 | http://schemas.android.com/apk/res/android 58 | 59 | 60 | 61 |
62 |
63 | 64 | 65 | 66 | .*:name 67 | 68 | http://schemas.android.com/apk/res/android 69 | 70 | 71 | 72 |
73 |
74 | 75 | 76 | 77 | name 78 | 79 | ^$ 80 | 81 | 82 | 83 |
84 |
85 | 86 | 87 | 88 | style 89 | 90 | ^$ 91 | 92 | 93 | 94 |
95 |
96 | 97 | 98 | 99 | .* 100 | 101 | ^$ 102 | 103 | 104 | BY_NAME 105 | 106 |
107 |
108 | 109 | 110 | 111 | .* 112 | 113 | http://schemas.android.com/apk/res/android 114 | 115 | 116 | ANDROID_ATTRIBUTE_ORDER 117 | 118 |
119 |
120 | 121 | 122 | 123 | .* 124 | 125 | .* 126 | 127 | 128 | BY_NAME 129 | 130 |
131 |
132 |
133 |
134 | 135 | 137 |
138 |
-------------------------------------------------------------------------------- /.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/copyright/Apache.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 21 | 22 | -------------------------------------------------------------------------------- /.idea/jarRepositories.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | 10 | 14 | 15 | 19 | 20 | 24 | 25 | 29 | 30 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 9 | -------------------------------------------------------------------------------- /.idea/scopes/library.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2020 tom5079 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DocumentFileX 2 | java.io.File compatible SAF implementation 3 | 4 | Tired of SAF bullshits? Implement SAF with ease! 5 | 6 | ### Features 7 | - Interoperable with java.io.File with some exceptions 8 | - File.getName() without overhead 9 | - Faster Directory IO 10 | - Get child FileX without overhead 11 | - _Slightly_ improved listFiles() //√evil 12 | - Automatic URI type detection 13 | - File metadata caching 14 | - Useful URI extensions 15 | - (WIP) kotlin-stdlib File extension compatible extension methods 16 | 17 | ## Setup 18 | ```gradle 19 | dependencies { 20 | implementation 'xyz.quaver:documentfilex:0.7.1' 21 | } 22 | ``` 23 | 24 | ## Invalid Characters 25 | 26 | Android Scoped Storage Framework doesn't allow following characters and automatically converts them to underscore(\_) for some bizarre reason. 27 | Filter out these characters before creating any file or folder! 28 | Invalid characters are: `<"> <*> <:> <<> <>> <\> <|>` and `` 29 | 30 | ## Sample Code 31 | 32 | ### File I/O 33 | > :warning: **You have to use File I/O methods declared in `xyz.quaver.io.util.*` 34 | Default kotlin extension methods do not work with SAFileX Instances.** 35 | ```kotlin 36 | val file = FileX(context, uri) 37 | 38 | file.writeText("Hello, SAF! You're dumb.") 39 | val text = file.readText() // "Hello, SAF! You're dumb." 40 | 41 | val data = listOf(0x82, 0x72, 0x82, 0x60, 0x82, 0x65, 0x82, 0xA4, 0x82, 0xF1, 0x82, 0xBF).map { 42 | it.toByte() 43 | }.toByteArray() 44 | 45 | file.writeBytes(data) 46 | val text = file.readText(data, Charset.forName()) 47 | ``` 48 | 49 | ### Directory I/O 50 | Directory I/O is supported by `tree://...` URI 51 | 52 | ```kotlin 53 | val folder = FileX(context, uri, "akita") // No overhead 54 | val child = folder.getChild("daisen") // No overhead 55 | val neighbor = FileX(context, folder.parent, "yamagata") // No overhead 56 | val neice = folder.getNeighbor("iwate/morioka/nakano.txt") // No overhead 57 | 58 | if (neice.parent.mkdirs()) { 59 | neice.createNewFile() 60 | neice.renameTo(FileX(context, neice.parent, "kurokawa.json")) 61 | } 62 | 63 | folder.listFiles().forEach { sichouson -> // Returns FileX 64 | sichouson.list().forEach { // Returns Uri string 65 | .... 66 | } 67 | } 68 | ``` 69 | 70 | ## Caching 71 | 72 | Cache is only available for the Documents URI and Tree URI 73 | 74 | ### Enabling the Cache 75 | 76 | With constructor: 77 | ```kotlin 78 | FileX(..., cached=true) 79 | ``` 80 | With an instance: 81 | You can call `invalidate()` anytime you want to update Cache even when `cached` is false. 82 | However, cached data will only be used by the FileX instance when the property `cached` is true. 83 | Alternatively you can directly access the cache with `FileX.cache` 84 | ```kotlin 85 | file.cached = true 86 | file.invalidate() 87 | ``` 88 | 89 | You can update the cache with `FileX.invalidate()` or `Cache.invalidate` 90 | 91 | Caching might impact the performance when large amounts of instances are created. 92 | Enable cache when both of these criteria are met: 93 | - Frequent Access to the File properties 94 | - Not a lot of instances are crated at the same time 95 | 96 | Also note that the cache of the instances created by `listFiles()` are disabled to improve performance. 97 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | buildscript { 3 | repositories { 4 | google() 5 | mavenCentral() 6 | } 7 | dependencies { 8 | classpath("com.android.tools.build:gradle:7.0.2") 9 | classpath(kotlin("gradle-plugin", version = "1.5.21")) 10 | 11 | // NOTE: Do not place your application dependencies here; they belong 12 | // in the individual module build.gradle files 13 | } 14 | } 15 | 16 | allprojects { 17 | repositories { 18 | google() 19 | mavenCentral() 20 | } 21 | } 22 | 23 | tasks.register("clean", Delete::class) { 24 | delete(rootProject.buildDir) 25 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx2048m 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | # AndroidX package structure to make it clearer which packages are bundled with the 15 | # Android operating system, and which are packaged with your app"s APK 16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 17 | android.useAndroidX=true 18 | # Automatically convert third-party libraries to use AndroidX 19 | android.enableJetifier=true 20 | # Kotlin code style for this project: "official" or "obsolete": 21 | kotlin.code.style=official 22 | 23 | org.gradle.configureondemand=false 24 | 25 | version=0.4-alpha02 26 | 27 | dokka_version=1.4.0-rc -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tom5079/DocumentFileX/4d41e7e8838416eac1595ee84ace2d4451724f34/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Tue Oct 13 22:29:27 KST 2020 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | # Determine the Java command to use to start the JVM. 86 | if [ -n "$JAVA_HOME" ] ; then 87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 88 | # IBM's JDK on AIX uses strange locations for the executables 89 | JAVACMD="$JAVA_HOME/jre/sh/java" 90 | else 91 | JAVACMD="$JAVA_HOME/bin/java" 92 | fi 93 | if [ ! -x "$JAVACMD" ] ; then 94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 95 | 96 | Please set the JAVA_HOME variable in your environment to match the 97 | location of your Java installation." 98 | fi 99 | else 100 | JAVACMD="java" 101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 102 | 103 | Please set the JAVA_HOME variable in your environment to match the 104 | location of your Java installation." 105 | fi 106 | 107 | # Increase the maximum file descriptors if we can. 108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 109 | MAX_FD_LIMIT=`ulimit -H -n` 110 | if [ $? -eq 0 ] ; then 111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 112 | MAX_FD="$MAX_FD_LIMIT" 113 | fi 114 | ulimit -n $MAX_FD 115 | if [ $? -ne 0 ] ; then 116 | warn "Could not set maximum file descriptor limit: $MAX_FD" 117 | fi 118 | else 119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 120 | fi 121 | fi 122 | 123 | # For Darwin, add options to specify how the application appears in the dock 124 | if $darwin; then 125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 126 | fi 127 | 128 | # For Cygwin or MSYS, switch paths to Windows format before running java 129 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 132 | JAVACMD=`cygpath --unix "$JAVACMD"` 133 | 134 | # We build the pattern for arguments to be converted via cygpath 135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 136 | SEP="" 137 | for dir in $ROOTDIRSRAW ; do 138 | ROOTDIRS="$ROOTDIRS$SEP$dir" 139 | SEP="|" 140 | done 141 | OURCYGPATTERN="(^($ROOTDIRS))" 142 | # Add a user-defined pattern to the cygpath arguments 143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 145 | fi 146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 147 | i=0 148 | for arg in "$@" ; do 149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 151 | 152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 154 | else 155 | eval `echo args$i`="\"$arg\"" 156 | fi 157 | i=`expr $i + 1` 158 | done 159 | case $i in 160 | 0) set -- ;; 161 | 1) set -- "$args0" ;; 162 | 2) set -- "$args0" "$args1" ;; 163 | 3) set -- "$args0" "$args1" "$args2" ;; 164 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 165 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 166 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 167 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 168 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 169 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 170 | esac 171 | fi 172 | 173 | # Escape application args 174 | save () { 175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 176 | echo " " 177 | } 178 | APP_ARGS=`save "$@"` 179 | 180 | # Collect all arguments for the java command, following the shell quoting and substitution rules 181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 182 | 183 | exec "$JAVACMD" "$@" 184 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 33 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 34 | 35 | @rem Find java.exe 36 | if defined JAVA_HOME goto findJavaFromJavaHome 37 | 38 | set JAVA_EXE=java.exe 39 | %JAVA_EXE% -version >NUL 2>&1 40 | if "%ERRORLEVEL%" == "0" goto init 41 | 42 | echo. 43 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 44 | echo. 45 | echo Please set the JAVA_HOME variable in your environment to match the 46 | echo location of your Java installation. 47 | 48 | goto fail 49 | 50 | :findJavaFromJavaHome 51 | set JAVA_HOME=%JAVA_HOME:"=% 52 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 53 | 54 | if exist "%JAVA_EXE%" goto init 55 | 56 | echo. 57 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 58 | echo. 59 | echo Please set the JAVA_HOME variable in your environment to match the 60 | echo location of your Java installation. 61 | 62 | goto fail 63 | 64 | :init 65 | @rem Get command-line arguments, handling Windows variants 66 | 67 | if not "%OS%" == "Windows_NT" goto win9xME_args 68 | 69 | :win9xME_args 70 | @rem Slurp the command line arguments. 71 | set CMD_LINE_ARGS= 72 | set _SKIP=2 73 | 74 | :win9xME_args_slurp 75 | if "x%~1" == "x" goto execute 76 | 77 | set CMD_LINE_ARGS=%* 78 | 79 | :execute 80 | @rem Setup the command line 81 | 82 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 83 | 84 | @rem Execute Gradle 85 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 86 | 87 | :end 88 | @rem End local scope for the variables with windows NT shell 89 | if "%ERRORLEVEL%"=="0" goto mainEnd 90 | 91 | :fail 92 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 93 | rem the _cmd.exe /c_ return code! 94 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 95 | exit /b 1 96 | 97 | :mainEnd 98 | if "%OS%"=="Windows_NT" endlocal 99 | 100 | :omega 101 | -------------------------------------------------------------------------------- /library/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /library/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | id("com.android.library") 3 | id("kotlin-android") 4 | id("org.jetbrains.dokka") version "1.4.32" 5 | `maven-publish` 6 | signing 7 | } 8 | 9 | group = "xyz.quaver" 10 | version = "0.7.1" 11 | 12 | android { 13 | compileSdk = 30 14 | buildToolsVersion = "30.0.3" 15 | 16 | defaultConfig { 17 | minSdk = 14 18 | targetSdk = 30 19 | 20 | testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" 21 | consumerProguardFiles("consumer-rules.pro") 22 | } 23 | 24 | buildTypes { 25 | getByName("release") { 26 | isMinifyEnabled = false 27 | proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") 28 | } 29 | } 30 | 31 | kotlinOptions { 32 | moduleName = "xyz.quaver.io.documentfilex" 33 | } 34 | } 35 | 36 | dependencies { 37 | implementation("org.jetbrains.kotlin:kotlin-stdlib") 38 | implementation("androidx.core:core-ktx:1.6.0") 39 | testImplementation("junit:junit:4.13.2") 40 | androidTestImplementation("androidx.test.ext:junit:1.1.3") 41 | androidTestImplementation("androidx.test.espresso:espresso-core:3.4.0") 42 | androidTestImplementation("androidx.test.espresso:espresso-intents:3.4.0") 43 | } 44 | 45 | val ossrhUsername: String? by project 46 | val ossrhPassword: String? by project 47 | 48 | val sourceJar by tasks.registering(Jar::class) { 49 | archiveClassifier.set("sources") 50 | from(android.sourceSets["main"].java.srcDirs) 51 | } 52 | 53 | afterEvaluate { 54 | publishing { 55 | publications { 56 | create("release") { 57 | groupId = group.toString() 58 | artifactId = "documentfilex" 59 | version = project.version as String 60 | 61 | from(components["release"]) 62 | artifact(sourceJar) 63 | 64 | pom { 65 | name.set("documentfilex") 66 | description.set("java.io.File compatible SAF implementation") 67 | url.set("https://github.com/tom5079/DocumentFileX") 68 | 69 | licenses { 70 | license { 71 | name.set("The Apache License, Version 2.0") 72 | url.set("http://www.apache.org/licenses/LICENSE-2.0.txt") 73 | } 74 | } 75 | developers { 76 | developer { 77 | id.set("tom5079") 78 | name.set("Minseok Son") 79 | email.set("tom5079@naver.com") 80 | } 81 | } 82 | scm { 83 | connection.set("scm:git:git://github.com/tom5079/DocumentFileX.git") 84 | developerConnection.set("scm:git:ssh://github.com:tom5079/DocumentFileX.git") 85 | url.set("https://github.com/tom5079/DocumentFileX") 86 | } 87 | } 88 | } 89 | } 90 | 91 | repositories { 92 | maven { 93 | val releasesRepoUrl = uri("https://oss.sonatype.org/service/local/staging/deploy/maven2/") 94 | val snapshotRepoUrl = uri("https://oss.sonatype.org/content/repositories/snapshots/") 95 | 96 | url = if (version.toString().endsWith("SNAPSHOT")) snapshotRepoUrl else releasesRepoUrl 97 | 98 | credentials { 99 | username = ossrhUsername 100 | password = ossrhPassword 101 | } 102 | } 103 | } 104 | } 105 | 106 | signing { 107 | sign(publishing.publications) 108 | } 109 | } -------------------------------------------------------------------------------- /library/consumer-rules.pro: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tom5079/DocumentFileX/4d41e7e8838416eac1595ee84ace2d4451724f34/library/consumer-rules.pro -------------------------------------------------------------------------------- /library/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle.kts. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile -------------------------------------------------------------------------------- /library/src/androidTest/java/xyz/quaver/io/ExampleInstrumentedTest.kt: -------------------------------------------------------------------------------- 1 | package xyz.quaver.io 2 | 3 | import androidx.test.ext.junit.runners.AndroidJUnit4 4 | import androidx.test.platform.app.InstrumentationRegistry 5 | import org.junit.Assert.assertEquals 6 | import org.junit.Test 7 | import org.junit.runner.RunWith 8 | 9 | /** 10 | * Instrumented test, which will execute on an Android device. 11 | * 12 | * See [testing documentation](http://d.android.com/tools/testing). 13 | */ 14 | @RunWith(AndroidJUnit4::class) 15 | class ExampleInstrumentedTest { 16 | @Test 17 | fun useAppContext() { 18 | // Context of the app under test. 19 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext 20 | assertEquals("xyz.quaver.io.test", appContext.packageName) 21 | } 22 | 23 | @Test 24 | fun test() { 25 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext 26 | } 27 | } -------------------------------------------------------------------------------- /library/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | / 5 | -------------------------------------------------------------------------------- /library/src/main/java/xyz/quaver/io/DocumentFileX.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * ____ _ _____ _ _ __ __ 3 | * | _ \ ___ ___ _ _ _ __ ___ ___ _ __ | |_| ___(_) | ___\ \/ / 4 | * | | | |/ _ \ / __| | | | '_ ` _ \ / _ \ '_ \| __| |_ | | |/ _ \\ / 5 | * | |_| | (_) | (__| |_| | | | | | | __/ | | | |_| _| | | | __// \ 6 | * |____/ \___/ \___|\__,_|_| |_| |_|\___|_| |_|\__|_| |_|_|\___/_/\_\ 7 | * 8 | * Copyright 2020 tom5079 9 | * 10 | * Licensed under the Apache License, Version 2.0 (the "License"); 11 | * you may not use this file except in compliance with the License. 12 | * You may obtain a copy of the License at 13 | * 14 | * http://www.apache.org/licenses/LICENSE-2.0 15 | * 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | */ 22 | 23 | package xyz.quaver.io 24 | 25 | import android.annotation.SuppressLint 26 | import android.content.Context 27 | import android.net.Uri 28 | import androidx.annotation.RequiresApi 29 | import xyz.quaver.io.util.delete 30 | import xyz.quaver.io.util.exists 31 | import java.io.File 32 | import java.io.FileFilter 33 | import java.io.FilenameFilter 34 | 35 | @RequiresApi(19) 36 | class DocumentFileX : SAFileX { 37 | @SuppressWarnings("unused") 38 | private constructor() : super("") { 39 | throw UnsupportedOperationException("STOP! You violated the law.") 40 | } 41 | 42 | constructor(context: Context, uri: Uri, cached: Boolean) : super(uri.path.let { 43 | it ?: throw NullPointerException("URI path should not be null") 44 | }) { 45 | this.context = context 46 | this.uri = uri 47 | 48 | this.cached = cached 49 | this.cache = Cache(context, uri) 50 | if (cached) 51 | invalidate() 52 | } 53 | 54 | override fun createNewFile() = 55 | throw UnsupportedOperationException() 56 | 57 | override fun delete() = uri.delete(context) 58 | 59 | override fun getParent() = 60 | throw UnsupportedOperationException() 61 | 62 | override fun getParentFile() = 63 | throw UnsupportedOperationException() 64 | 65 | override fun list() = 66 | throw UnsupportedOperationException() 67 | 68 | override fun list(filter: FilenameFilter?) = 69 | throw UnsupportedOperationException() 70 | 71 | override fun listFiles() = 72 | throw UnsupportedOperationException() 73 | 74 | override fun listFiles(filter: FileFilter?) = 75 | throw UnsupportedOperationException() 76 | 77 | override fun listFiles(filter: FilenameFilter?) = 78 | throw UnsupportedOperationException() 79 | 80 | override fun mkdir() = 81 | throw UnsupportedOperationException() 82 | 83 | override fun mkdirs() = 84 | throw UnsupportedOperationException() 85 | 86 | override fun renameTo(dest: File) = 87 | throw UnsupportedOperationException() 88 | } -------------------------------------------------------------------------------- /library/src/main/java/xyz/quaver/io/ExternalTreeFileX.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * ____ _ _____ _ _ __ __ 3 | * | _ \ ___ ___ _ _ _ __ ___ ___ _ __ | |_| ___(_) | ___\ \/ / 4 | * | | | |/ _ \ / __| | | | '_ ` _ \ / _ \ '_ \| __| |_ | | |/ _ \\ / 5 | * | |_| | (_) | (__| |_| | | | | | | __/ | | | |_| _| | | | __// \ 6 | * |____/ \___/ \___|\__,_|_| |_| |_|\___|_| |_|\__|_| |_|_|\___/_/\_\ 7 | * 8 | * Copyright 2020 tom5079 9 | * 10 | * Licensed under the Apache License, Version 2.0 (the "License"); 11 | * you may not use this file except in compliance with the License. 12 | * You may obtain a copy of the License at 13 | * 14 | * http://www.apache.org/licenses/LICENSE-2.0 15 | * 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | */ 22 | 23 | package xyz.quaver.io 24 | 25 | import android.content.Context 26 | import android.net.Uri 27 | import android.provider.DocumentsContract 28 | import android.webkit.MimeTypeMap 29 | import androidx.annotation.RequiresApi 30 | import xyz.quaver.io.util.* 31 | import java.io.File 32 | import java.io.FileFilter 33 | import java.io.FilenameFilter 34 | 35 | @RequiresApi(21) 36 | class ExternalTreeFileX : SAFileX { 37 | private constructor() : super("") { 38 | throw UnsupportedOperationException("STOP! You violated the law.") 39 | } 40 | 41 | constructor(context: Context, parent: Uri, child: String, cached: Boolean) 42 | : this(context, parent.getChildUri(context, child)!!, cached) 43 | 44 | constructor(context: Context, uri: Uri, cached: Boolean) : super(uri.path.let { 45 | it ?: throw NullPointerException("URI path should not be null") 46 | }) { 47 | this.context = context 48 | this.uri = uri 49 | 50 | this.uri = DocumentsContract.buildDocumentUriUsingTree(uri, when { 51 | uri.isDocumentUri -> uri.documentId 52 | else -> uri.treeDocumentId 53 | }) 54 | 55 | this.cached = cached 56 | this.cache = Cache(context, uri) 57 | if (cached) 58 | invalidate() 59 | } 60 | 61 | override fun createNewFile(): Boolean { 62 | if (uri.exists(context)) 63 | return false 64 | 65 | val extension = uri.extension 66 | val mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) 67 | val name = when(mimeType) { 68 | null -> 69 | uri.getName(context) 70 | else -> 71 | uri.getName(context)?.takeWhile { it != '.' } 72 | } ?: throw Exception("Unable to get name from Uri") 73 | 74 | if (parentFile.exists()) 75 | return uri.parent.create(context, mimeType ?: "application/octet-stream", name)?.let { 76 | this.uri = it 77 | } != null 78 | 79 | return false 80 | } 81 | 82 | override fun delete(): Boolean = 83 | if (this.isDirectory) { 84 | if (this.list().isEmpty()) 85 | uri.delete(context) 86 | else 87 | false 88 | } else 89 | uri.delete(context) 90 | 91 | override fun getParent() = 92 | uri.parent.toString() 93 | 94 | override fun getParentFile() = 95 | FileX(context, uri.parent, cached = cached) 96 | 97 | override fun list() = 98 | uri.list(context).map { it.toString() }.toTypedArray() 99 | 100 | override fun list(filter: FilenameFilter): Array { 101 | return list().filter { uri -> 102 | FileX(context, uri).let { file -> 103 | filter.accept(file, file.name) 104 | } 105 | }.toTypedArray() 106 | } 107 | 108 | override fun listFiles() = 109 | uri.list(context).map { FileX(context, it) }.toTypedArray() 110 | 111 | override fun listFiles(filter: FileFilter): Array { 112 | return listFiles().filter { 113 | filter.accept(it) 114 | }.toTypedArray() 115 | } 116 | 117 | override fun listFiles(filter: FilenameFilter): Array { 118 | return listFiles().filter { 119 | filter.accept(it, it.name) 120 | }.toTypedArray() 121 | } 122 | 123 | override fun mkdir(): Boolean { 124 | if (uri.exists(context)) 125 | return false 126 | 127 | val name = this.name ?: return false 128 | 129 | if (parentFile.exists()) 130 | return uri.parent.create(context, DocumentsContract.Document.MIME_TYPE_DIR, name)?.let { 131 | this.uri = it 132 | } != null 133 | 134 | return false 135 | } 136 | 137 | override fun mkdirs(): Boolean { 138 | if (uri.isRoot) 139 | return false 140 | 141 | if (uri.exists(context)) 142 | return false 143 | 144 | return this.parentFile.let { 145 | (it.mkdirs() || it.exists()) && mkdir() 146 | } 147 | } 148 | 149 | override fun renameTo(dest: File): Boolean { 150 | if (dest !is SAFileX) 151 | throw UnsupportedOperationException("dest should be SAFileX") 152 | 153 | val name = dest.name ?: throw Exception("Unable to get name from Uri") 154 | 155 | return DocumentsContract.renameDocument(context.contentResolver, this.uri, name)?.also { 156 | this.uri = it 157 | } != null 158 | } 159 | 160 | } -------------------------------------------------------------------------------- /library/src/main/java/xyz/quaver/io/FileX.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * ____ _ _____ _ _ __ __ 3 | * | _ \ ___ ___ _ _ _ __ ___ ___ _ __ | |_| ___(_) | ___\ \/ / 4 | * | | | |/ _ \ / __| | | | '_ ` _ \ / _ \ '_ \| __| |_ | | |/ _ \\ / 5 | * | |_| | (_) | (__| |_| | | | | | | __/ | | | |_| _| | | | __// \ 6 | * |____/ \___/ \___|\__,_|_| |_| |_|\___|_| |_|\__|_| |_|_|\___/_/\_\ 7 | * 8 | * Copyright 2020 tom5079 9 | * 10 | * Licensed under the Apache License, Version 2.0 (the "License"); 11 | * you may not use this file except in compliance with the License. 12 | * You may obtain a copy of the License at 13 | * 14 | * http://www.apache.org/licenses/LICENSE-2.0 15 | * 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | */ 22 | 23 | @file:SuppressWarnings("unused") 24 | 25 | package xyz.quaver.io 26 | 27 | import android.content.Context 28 | import android.net.Uri 29 | import android.os.Build 30 | import android.provider.DocumentsContract 31 | import androidx.annotation.RequiresApi 32 | import androidx.core.net.toUri 33 | import xyz.quaver.io.util.* 34 | import java.io.File 35 | 36 | @RequiresApi(19) 37 | class Cache(private val context: Context, private val uri: Uri) { 38 | private var type: String? = null 39 | private var flags: Int? = null 40 | private var documentID: String? = null 41 | 42 | var name: String? = null 43 | private set 44 | var lastModified: Long = 0L 45 | private set 46 | var length: Long = 0L 47 | private set 48 | 49 | val canRead: Boolean 50 | get() = 51 | uri.hasPermission(context) && canRead(type) 52 | val canWrite: Boolean 53 | get() = 54 | uri.hasPermission(context) && canWrite(type, flags) 55 | val isDirectory: Boolean 56 | get() = 57 | type == DocumentsContract.Document.MIME_TYPE_DIR 58 | val isFile: Boolean 59 | get() = !isDirectory 60 | 61 | val exists: Boolean 62 | get() = documentID != null 63 | 64 | fun invalidate() { 65 | context.contentResolver.query(uri, null, null, null, null)?.use { 66 | if (it.moveToFirst()) { 67 | type = it.getString(it.getColumnIndex(DocumentsContract.Document.COLUMN_MIME_TYPE)) 68 | flags = it.getInt(it.getColumnIndex(DocumentsContract.Document.COLUMN_FLAGS)) 69 | name = it.getString(it.getColumnIndex(DocumentsContract.Document.COLUMN_DISPLAY_NAME)) 70 | lastModified = it.getLong(it.getColumnIndex(DocumentsContract.Document.COLUMN_LAST_MODIFIED)) 71 | length = it.getLong(it.getColumnIndex(DocumentsContract.Document.COLUMN_SIZE)) 72 | documentID = it.getString(it.getColumnIndex(DocumentsContract.Document.COLUMN_DOCUMENT_ID)) 73 | } 74 | } 75 | } 76 | } 77 | 78 | @Suppress("ConvertSecondaryConstructorToPrimary") 79 | abstract class FileX : File { 80 | internal constructor(path: String) : super(path) 81 | 82 | internal lateinit var context: Context 83 | var uri: Uri = Uri.EMPTY 84 | 85 | var cached = false 86 | lateinit var cache: Cache 87 | protected set 88 | 89 | @RequiresApi(19) 90 | open fun invalidate() { 91 | cache.invalidate() 92 | } 93 | 94 | fun compareTo(other: FileX) = 95 | uri.compareTo(other.uri) 96 | } 97 | 98 | fun FileX(context: Context, parent: File, child: String? = null, cached: Boolean = false): FileX { 99 | return when (parent) { 100 | is FileX -> 101 | FileX(context, parent.uri, child, cached) 102 | else -> 103 | FileX(context, parent.toUri(), child, cached) 104 | } 105 | } 106 | 107 | fun FileX(context: Context, parent: Uri, child: String? = null, cached: Boolean = false): FileX { 108 | return when { 109 | parent.isTreeUri && parent.isExternalStorageDocument && Build.VERSION.SDK_INT >= 21 -> 110 | if (child == null) 111 | ExternalTreeFileX(context, parent, cached) 112 | else 113 | ExternalTreeFileX(context, parent, child, cached) 114 | parent.isTreeUri && Build.VERSION.SDK_INT >= 21 -> 115 | if (child == null) 116 | TreeFileX(context, parent, cached) 117 | else 118 | TreeFileX(context, parent, child, cached) 119 | parent.isDocumentUri && Build.VERSION.SDK_INT >= 19 -> 120 | if (child == null) 121 | DocumentFileX(context, parent, cached) 122 | else 123 | throw UnsupportedOperationException("Getting child of the Single URI is not supported") 124 | parent.isFileUri -> 125 | if (child == null) 126 | RawFileX(context, parent) 127 | else 128 | RawFileX(context, parent, child) 129 | else -> 130 | throw UnsupportedOperationException("Unsupported URI / Android API Level is too low for this device") 131 | } 132 | } 133 | 134 | fun FileX(context: Context, parentUri: String, child: String? = null, cached: Boolean = false) = 135 | FileX(context, Uri.parse(parentUri), child, cached) -------------------------------------------------------------------------------- /library/src/main/java/xyz/quaver/io/RawFileX.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * ____ _ _____ _ _ __ __ 3 | * | _ \ ___ ___ _ _ _ __ ___ ___ _ __ | |_| ___(_) | ___\ \/ / 4 | * | | | |/ _ \ / __| | | | '_ ` _ \ / _ \ '_ \| __| |_ | | |/ _ \\ / 5 | * | |_| | (_) | (__| |_| | | | | | | __/ | | | |_| _| | | | __// \ 6 | * |____/ \___/ \___|\__,_|_| |_| |_|\___|_| |_|\__|_| |_|_|\___/_/\_\ 7 | * 8 | * Copyright 2020 tom5079 9 | * 10 | * Licensed under the Apache License, Version 2.0 (the "License"); 11 | * you may not use this file except in compliance with the License. 12 | * You may obtain a copy of the License at 13 | * 14 | * http://www.apache.org/licenses/LICENSE-2.0 15 | * 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | */ 22 | 23 | package xyz.quaver.io 24 | 25 | import android.content.Context 26 | import android.net.Uri 27 | import xyz.quaver.io.util.isFileUri 28 | 29 | class RawFileX : FileX { 30 | 31 | constructor(context: Context, parent: Uri, child: String) 32 | : this(context, Uri.withAppendedPath(parent, child)) 33 | 34 | constructor(context: Context, uri: Uri) : super(uri.path.let { 35 | it ?: throw NullPointerException("URI path should not be null") 36 | }) { 37 | if (!uri.isFileUri) 38 | throw UnsupportedOperationException("RawFileX can only be created with file uri") 39 | 40 | this.context = context 41 | this.uri = uri 42 | } 43 | 44 | override fun invalidate() { 45 | // Does nothing 46 | } 47 | 48 | } -------------------------------------------------------------------------------- /library/src/main/java/xyz/quaver/io/SAFileX.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * ____ _ _____ _ _ __ __ 3 | * | _ \ ___ ___ _ _ _ __ ___ ___ _ __ | |_| ___(_) | ___\ \/ / 4 | * | | | |/ _ \ / __| | | | '_ ` _ \ / _ \ '_ \| __| |_ | | |/ _ \\ / 5 | * | |_| | (_) | (__| |_| | | | | | | __/ | | | |_| _| | | | __// \ 6 | * |____/ \___/ \___|\__,_|_| |_| |_|\___|_| |_|\__|_| |_|_|\___/_/\_\ 7 | * 8 | * Copyright 2020 tom5079 9 | * 10 | * Licensed under the Apache License, Version 2.0 (the "License"); 11 | * you may not use this file except in compliance with the License. 12 | * You may obtain a copy of the License at 13 | * 14 | * http://www.apache.org/licenses/LICENSE-2.0 15 | * 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | */ 22 | 23 | package xyz.quaver.io 24 | 25 | import android.annotation.SuppressLint 26 | import androidx.annotation.RequiresApi 27 | import xyz.quaver.io.util.* 28 | import java.io.File 29 | import java.net.URI 30 | import java.nio.file.Path 31 | 32 | @RequiresApi(19) 33 | abstract class SAFileX : FileX { 34 | @SuppressWarnings("unused") 35 | private constructor() : super("") { 36 | throw UnsupportedOperationException("STOP! You violated the law.") 37 | } 38 | 39 | internal constructor(path: String) : super(path) 40 | 41 | override fun canExecute() = false 42 | 43 | override fun canRead(): Boolean = when { 44 | cached -> cache.canRead 45 | else -> uri.canRead(context) 46 | } 47 | 48 | override fun canWrite(): Boolean = when { 49 | cached -> cache.canWrite 50 | else -> uri.canWrite(context) 51 | } 52 | 53 | override fun deleteOnExit(): Unit = 54 | DeleteOnExitHook.add(this) 55 | 56 | override fun exists(): Boolean = when { 57 | cached -> cache.exists 58 | else -> uri.exists(context) 59 | } 60 | 61 | override fun getAbsoluteFile() = canonicalFile 62 | override fun getAbsolutePath() = canonicalPath 63 | 64 | override fun getCanonicalFile(): File? = uri.toFile(context) 65 | override fun getCanonicalPath(): String? = canonicalFile?.canonicalPath 66 | 67 | override fun getName(): String? = uri.getName(context) 68 | override fun getPath(): String? = uri.path 69 | 70 | override fun getFreeSpace(): Long = kotlin.runCatching { 71 | canonicalFile?.freeSpace 72 | }.getOrNull() ?: throw UnsupportedOperationException() 73 | 74 | override fun getTotalSpace(): Long = kotlin.runCatching { 75 | canonicalFile?.totalSpace 76 | }.getOrNull() ?: throw UnsupportedOperationException() 77 | 78 | @SuppressLint("UsableSpace") 79 | override fun getUsableSpace(): Long = kotlin.runCatching { 80 | canonicalFile?.usableSpace 81 | }.getOrNull() ?: throw UnsupportedOperationException() 82 | 83 | override fun hashCode(): Int = 84 | uri.hashCode() 85 | 86 | override fun equals(other: Any?): Boolean = 87 | this.hashCode() == other.hashCode() 88 | 89 | override fun isAbsolute() = true 90 | 91 | override fun isDirectory(): Boolean = when { 92 | cached -> cache.isDirectory 93 | else -> uri.isDirectory(context) 94 | } 95 | 96 | override fun isFile(): Boolean = !isDirectory 97 | 98 | override fun isHidden(): Boolean = name?.startsWith('.') ?: false 99 | 100 | override fun lastModified(): Long = when { 101 | cached -> cache.lastModified 102 | else -> uri.lastModified(context) 103 | } ?: 0L 104 | 105 | override fun length(): Long = when { 106 | cached -> cache.length 107 | else -> uri.length(context) 108 | } ?: 0L 109 | 110 | override fun setExecutable(executable: Boolean) = throw UnsupportedOperationException() 111 | override fun setExecutable(executable: Boolean, ownerOnly: Boolean) = throw UnsupportedOperationException() 112 | override fun setLastModified(time: Long) = throw UnsupportedOperationException() 113 | override fun setReadOnly() = throw UnsupportedOperationException() 114 | override fun setReadable(readable: Boolean) = throw UnsupportedOperationException() 115 | override fun setReadable(readable: Boolean, ownerOnly: Boolean) = throw UnsupportedOperationException() 116 | override fun setWritable(writable: Boolean) = throw UnsupportedOperationException() 117 | override fun setWritable(writable: Boolean, ownerOnly: Boolean) = throw UnsupportedOperationException() 118 | 119 | @RequiresApi(26) 120 | override fun toPath(): Path? = 121 | canonicalFile?.toPath() 122 | 123 | override fun toString(): String = 124 | uri.toString() 125 | 126 | override fun toURI(): URI = URI(uri.toString()) 127 | 128 | } -------------------------------------------------------------------------------- /library/src/main/java/xyz/quaver/io/TreeFileX.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * ____ _ _____ _ _ __ __ 3 | * | _ \ ___ ___ _ _ _ __ ___ ___ _ __ | |_| ___(_) | ___\ \/ / 4 | * | | | |/ _ \ / __| | | | '_ ` _ \ / _ \ '_ \| __| |_ | | |/ _ \\ / 5 | * | |_| | (_) | (__| |_| | | | | | | __/ | | | |_| _| | | | __// \ 6 | * |____/ \___/ \___|\__,_|_| |_| |_|\___|_| |_|\__|_| |_|_|\___/_/\_\ 7 | * 8 | * Copyright 2020 tom5079 9 | * 10 | * Licensed under the Apache License, Version 2.0 (the "License"); 11 | * you may not use this file except in compliance with the License. 12 | * You may obtain a copy of the License at 13 | * 14 | * http://www.apache.org/licenses/LICENSE-2.0 15 | * 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | */ 22 | 23 | package xyz.quaver.io 24 | 25 | import android.content.Context 26 | import android.net.Uri 27 | import android.provider.DocumentsContract 28 | import android.webkit.MimeTypeMap 29 | import androidx.annotation.RequiresApi 30 | import xyz.quaver.io.util.* 31 | import java.io.File 32 | import java.io.FileFilter 33 | import java.io.FilenameFilter 34 | 35 | @RequiresApi(21) 36 | class TreeFileX : SAFileX { 37 | 38 | private var _parent: TreeFileX? = null 39 | private var _name: String? = null 40 | 41 | private constructor() : super("") { 42 | throw UnsupportedOperationException("STOP! You violated the law.") 43 | } 44 | 45 | constructor(context: Context, parent: Uri, child: String, cached: Boolean) : 46 | this(context, TreeFileX(context, parent, cached), child, cached) 47 | 48 | constructor(context: Context, parent: TreeFileX, child: String, cached: Boolean) : super("") { 49 | this.context = context 50 | 51 | child.split('/').let { 52 | if (it.size < 2) { 53 | this._parent = parent 54 | this._name = child 55 | } else { 56 | this._parent = TreeFileX(context, parent, it.dropLast(1).joinToString("/"), cached) 57 | this._name = it.last() 58 | } 59 | } 60 | 61 | parent.uri.getChildUri(context, child)?.let { 62 | this.uri = it 63 | } 64 | 65 | this.cached = cached 66 | this.cache = Cache(context, uri) 67 | if (cached) 68 | invalidate() 69 | } 70 | 71 | constructor(context: Context, uri: Uri, cached: Boolean) : super(uri.path.let { 72 | it ?: throw NullPointerException("URI path should not be null") 73 | }) { 74 | this.context = context 75 | this.uri = DocumentsContract.buildDocumentUriUsingTree(uri, when { 76 | uri.isDocumentUri -> uri.documentId 77 | else -> uri.treeDocumentId 78 | }) 79 | 80 | this.cached = cached 81 | this.cache = Cache(context, uri) 82 | if (cached) 83 | invalidate() 84 | } 85 | 86 | override fun createNewFile(): Boolean { 87 | if (uri != Uri.EMPTY) 88 | return false 89 | 90 | val extension = _name!!.takeLastWhile { it != '.' } 91 | val mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) 92 | val name = _name!! 93 | 94 | if (parentFile.exists()) 95 | return _parent!!.uri.create(context, mimeType ?: "application/octet-stream", name)?.let { 96 | this.uri = it 97 | }?.also { cache = Cache(context, uri); if (cached) cache.invalidate() } != null 98 | 99 | return false 100 | } 101 | 102 | override fun getName(): String? { 103 | if (_name != null) 104 | return _name 105 | 106 | return when { 107 | cached -> cache.name 108 | else -> uri.getName(context) 109 | } 110 | } 111 | 112 | override fun delete(): Boolean = 113 | if (this.isDirectory) { 114 | if (this.list().isEmpty()) 115 | uri.delete(context) 116 | else 117 | false 118 | } else 119 | uri.delete(context) 120 | 121 | override fun getParent(): String = 122 | if (_parent != null) 123 | _parent!!.uri.toString() 124 | else 125 | throw UnsupportedOperationException("getParent() only works with TreeFileX created with child parameter") 126 | 127 | override fun getParentFile() = 128 | if (_parent != null) 129 | _parent!! 130 | else 131 | throw UnsupportedOperationException("getParentFile() only works with TreeFileX created with child parameter") 132 | 133 | override fun list() = 134 | uri.list(context).map { it.toString() }.toTypedArray() 135 | 136 | override fun list(filter: FilenameFilter): Array { 137 | return list().filter { uri -> 138 | FileX(context, uri).let { file -> 139 | filter.accept(file, file.name) 140 | } 141 | }.toTypedArray() 142 | } 143 | 144 | override fun listFiles() = 145 | uri.list(context).map { TreeFileX(context, it, false).also { _parent = this } }.toTypedArray() 146 | 147 | override fun listFiles(filter: FileFilter): Array { 148 | return listFiles().filter { 149 | filter.accept(it) 150 | }.toTypedArray() 151 | } 152 | 153 | override fun listFiles(filter: FilenameFilter): Array { 154 | return listFiles().filter { 155 | filter.accept(it, it.name) 156 | }.toTypedArray() 157 | } 158 | 159 | override fun mkdir(): Boolean { 160 | if (uri != Uri.EMPTY || _parent == null) 161 | return false 162 | 163 | val name = this.name ?: return false 164 | 165 | return _parent!!.uri.create(context, DocumentsContract.Document.MIME_TYPE_DIR, name)?.let { 166 | this.uri = it 167 | } != null 168 | } 169 | 170 | override fun mkdirs(): Boolean { 171 | if (_parent == null) 172 | return false 173 | 174 | if (uri != Uri.EMPTY) 175 | return false 176 | 177 | return this.parentFile.let { 178 | (it.mkdirs() || it.exists()) && mkdir() 179 | } 180 | } 181 | 182 | override fun renameTo(dest: File): Boolean { 183 | if (dest !is SAFileX) 184 | throw UnsupportedOperationException("dest should be SAFileX") 185 | 186 | val name = dest.name ?: throw Exception("Unable to get name from Uri") 187 | 188 | return DocumentsContract.renameDocument(context.contentResolver, this.uri, name)?.also { 189 | this.uri = it 190 | } != null 191 | } 192 | 193 | } -------------------------------------------------------------------------------- /library/src/main/java/xyz/quaver/io/util/DeleteOnExitHook.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * ____ _ _____ _ _ __ __ 3 | * | _ \ ___ ___ _ _ _ __ ___ ___ _ __ | |_| ___(_) | ___\ \/ / 4 | * | | | |/ _ \ / __| | | | '_ ` _ \ / _ \ '_ \| __| |_ | | |/ _ \\ / 5 | * | |_| | (_) | (__| |_| | | | | | | __/ | | | |_| _| | | | __// \ 6 | * |____/ \___/ \___|\__,_|_| |_| |_|\___|_| |_|\__|_| |_|_|\___/_/\_\ 7 | * 8 | * Copyright 2020 tom5079 9 | * 10 | * Licensed under the Apache License, Version 2.0 (the "License"); 11 | * you may not use this file except in compliance with the License. 12 | * You may obtain a copy of the License at 13 | * 14 | * http://www.apache.org/licenses/LICENSE-2.0 15 | * 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | */ 22 | 23 | package xyz.quaver.io.util 24 | 25 | import android.annotation.TargetApi 26 | import android.content.Context 27 | import android.net.Uri 28 | import androidx.annotation.RequiresApi 29 | import xyz.quaver.io.FileX 30 | 31 | @TargetApi(19) 32 | internal class DeleteOnExitHook { 33 | 34 | companion object { 35 | private val files = hashSetOf() 36 | 37 | private fun runHooks() { 38 | val theFiles = hashSetOf() 39 | 40 | synchronized(DeleteOnExitHook::class) { 41 | theFiles.addAll(files) 42 | files.clear() 43 | } 44 | 45 | theFiles.reversed().forEach { 46 | kotlin.runCatching { 47 | it.delete() 48 | } 49 | } 50 | } 51 | 52 | @Synchronized 53 | @RequiresApi(19) 54 | fun add(file: FileX) { 55 | files.add(file) 56 | } 57 | 58 | init { 59 | Runtime.getRuntime().addShutdownHook(object: Thread() { 60 | override fun run() { 61 | runHooks() 62 | } 63 | }) 64 | } 65 | } 66 | } -------------------------------------------------------------------------------- /library/src/main/java/xyz/quaver/io/util/DocumentUtil.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * ____ _ _____ _ _ __ __ 3 | * | _ \ ___ ___ _ _ _ __ ___ ___ _ __ | |_| ___(_) | ___\ \/ / 4 | * | | | |/ _ \ / __| | | | '_ ` _ \ / _ \ '_ \| __| |_ | | |/ _ \\ / 5 | * | |_| | (_) | (__| |_| | | | | | | __/ | | | |_| _| | | | __// \ 6 | * |____/ \___/ \___|\__,_|_| |_| |_|\___|_| |_|\__|_| |_|_|\___/_/\_\ 7 | * 8 | * Copyright 2020 tom5079 9 | * 10 | * Licensed under the Apache License, Version 2.0 (the "License"); 11 | * you may not use this file except in compliance with the License. 12 | * You may obtain a copy of the License at 13 | * 14 | * http://www.apache.org/licenses/LICENSE-2.0 15 | * 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | */ 22 | 23 | @file:SuppressWarnings("unused") 24 | 25 | package xyz.quaver.io.util 26 | 27 | import android.annotation.SuppressLint 28 | import android.content.ContentResolver 29 | import android.content.Context 30 | import android.content.Intent 31 | import android.content.pm.PackageManager 32 | import android.net.Uri 33 | import android.os.Build 34 | import android.os.storage.StorageManager 35 | import android.os.storage.StorageVolume 36 | import android.provider.DocumentsContract 37 | import androidx.annotation.RequiresApi 38 | import androidx.core.content.ContextCompat 39 | import androidx.core.database.getStringOrNull 40 | import java.io.File 41 | import java.lang.reflect.Array 42 | 43 | const val PATH_DOCUMENT = "document" 44 | const val PATH_TREE = "tree" 45 | 46 | const val URL_SLASH = "%2F" 47 | const val URL_COLON = "%3A" 48 | 49 | val Uri?.isExternalStorageDocument: Boolean 50 | get() = this?.authority == "com.android.externalstorage.documents" 51 | 52 | val Uri?.isDownloadsDocument: Boolean 53 | get() = this?.authority == "com.android.providers.downloads.documents" 54 | 55 | val Uri?.isMediaDocument: Boolean 56 | get() = this?.authority == "com.android.providers.media.documents" 57 | 58 | val Uri?.isContentUri: Boolean 59 | get() = this?.scheme == ContentResolver.SCHEME_CONTENT 60 | val Uri?.isFileUri: Boolean 61 | get() = this?.scheme == ContentResolver.SCHEME_FILE 62 | 63 | val Uri.treeDocumentId: String? 64 | get() = this.pathSegments.let { paths -> 65 | if (paths.size >= 2 && paths[0] == PATH_TREE) 66 | paths[1] 67 | else 68 | null 69 | } 70 | 71 | val Uri.isTreeUri: Boolean 72 | get() = this.treeDocumentId != null 73 | 74 | val Uri.documentId: String? 75 | get() = this.pathSegments.let { paths -> 76 | if (paths.size >= 2 && paths[0] == PATH_DOCUMENT) 77 | paths[1] 78 | else if (paths.size >= 4 && paths[0] == PATH_TREE && paths[2] == PATH_DOCUMENT) 79 | paths[3] 80 | else 81 | null 82 | } 83 | 84 | val Uri.isDocumentUri: Boolean 85 | get() = this.documentId != null 86 | 87 | val Uri.isRoot: Boolean 88 | get() = this.niceDocumentId?.split(':')?.getOrNull(1).isNullOrBlank() 89 | 90 | /** 91 | * Returns the segmented DocumentID 92 | * 93 | * ### Example 94 | * `1A19-3B89:Android/data` 95 | * returns `["1A19-3B89", "Android/data"]` 96 | */ 97 | internal val String.documentIdSegments: List 98 | get() = this.split(":") 99 | 100 | val Uri.documentIdSegment: List? 101 | get() = this.niceDocumentId?.documentIdSegments 102 | 103 | /** 104 | * Returns the root of the Uri 105 | * 106 | * ### Example 107 | * `1A19-3B89:Android/data` 108 | * returns `"1A19-3B89"` 109 | */ 110 | internal val String.volumeId: String? 111 | get() = this.documentIdSegments.firstOrNull() 112 | 113 | val Uri.volumeId: String? 114 | get() = this.niceDocumentId?.volumeId 115 | 116 | /** 117 | * Returns a path of the given DocumentID 118 | * 119 | * ### Example 120 | * `1A19-3B89:Android/data` 121 | * returns `Android/data` 122 | */ 123 | internal val String.documentIdPath: String? 124 | get() = this.documentIdSegments.getOrNull(1) 125 | 126 | val Uri.documentIdPath: String? 127 | get() = this.niceDocumentId?.documentIdPath 128 | 129 | /** 130 | * Returns a segmented path of the given DocumentID 131 | * 132 | * ### Example 133 | * `1A19-3B89:Android/data` 134 | * returns `["Android", "data"]` 135 | */ 136 | internal val String.documentIdPathSegments: List? 137 | get() = this.documentIdPath?.split('/') 138 | 139 | val Uri?.documentIdPathSegments: List? 140 | get() = this?.niceDocumentId?.documentIdPathSegments 141 | 142 | /** 143 | * Returns a new Document ID according to the given parameters 144 | * 145 | * @param [volumeId] Root of the URI 146 | * @param [path] Path under the root 147 | * 148 | * @return DocumentID string 149 | */ 150 | fun createNewDocumentId(volumeId: String, path: String) = 151 | "$volumeId:$path" 152 | 153 | val Uri?.niceDocumentId: String? 154 | get() = this?.documentId ?: this?.treeDocumentId 155 | 156 | /** 157 | * Returns a child Uri with a given filename 158 | * 159 | * Only works when the Uri is external storage document. 160 | * 161 | * @see Uri.isExternalStorageDocument 162 | */ 163 | @RequiresApi(21) 164 | fun Uri.getChildUri(context: Context, child: String): Uri? { 165 | if (!this.isTreeUri) 166 | return null 167 | 168 | return if (this.isExternalStorageDocument) { 169 | val childDocumentId = 170 | if (this.isRoot) 171 | "${this.volumeId}:${child}" 172 | else 173 | "${this.niceDocumentId}/$child" 174 | 175 | DocumentsContract.buildDocumentUriUsingTree(this, childDocumentId) 176 | } else { 177 | val childUri = DocumentsContract.buildChildDocumentsUriUsingTree(this, niceDocumentId) 178 | 179 | context.contentResolver.query( 180 | childUri, 181 | arrayOf( 182 | DocumentsContract.Document.COLUMN_DOCUMENT_ID, 183 | DocumentsContract.Document.COLUMN_DISPLAY_NAME 184 | ), 185 | null, null, null 186 | ).use { 187 | while (it?.moveToNext() == true) { 188 | if (it.getStringOrNull(it.getColumnIndex(DocumentsContract.Document.COLUMN_DISPLAY_NAME)) == child) 189 | return DocumentsContract.buildDocumentUriUsingTree( 190 | this, 191 | it.getString(it.getColumnIndex(DocumentsContract.Document.COLUMN_DOCUMENT_ID)) 192 | ) 193 | } 194 | } 195 | return null 196 | } 197 | } 198 | 199 | /** 200 | * Returns a Uri that points a file with a given filename in the same directory 201 | * 202 | * Only works when the Uri is external storage document. 203 | * 204 | * @see Uri.isExternalStorageDocument 205 | */ 206 | @RequiresApi(21) 207 | fun Uri.getNeighborUri(filename: String): Uri { 208 | if (!this.isExternalStorageDocument) 209 | throw UnsupportedOperationException("Only External Storage Document Uri is allowed") 210 | 211 | val neighborDocumentId = this.documentIdPathSegments!!.let { 212 | if (it.isEmpty()) 213 | listOf(filename) 214 | else 215 | it.toMutableList().apply { 216 | this[lastIndex] = filename 217 | } 218 | }.joinToString("/") 219 | 220 | return DocumentsContract.buildDocumentUriUsingTree( 221 | this, 222 | createNewDocumentId(volumeId!!, neighborDocumentId) 223 | ) 224 | } 225 | 226 | @RequiresApi(Build.VERSION_CODES.KITKAT) 227 | fun Uri.getName(context: Context): String? { 228 | return when { 229 | this.isExternalStorageDocument -> { 230 | this.documentIdPathSegments?.let { 231 | if (it.isNotEmpty()) 232 | it.last() 233 | else 234 | null 235 | } 236 | } 237 | this.isTreeUri -> 238 | query(context, DocumentsContract.Document.COLUMN_DISPLAY_NAME) 239 | else -> 240 | null 241 | } 242 | } 243 | 244 | val Uri.extension: String? 245 | get() = this.documentIdPathSegments?.last()?.split('.')?.let { 246 | if (it.size >= 2) 247 | it.last() 248 | else 249 | null 250 | } 251 | 252 | inline fun Uri.query(context: Context, columnName: String): T? { 253 | return kotlin.runCatching { 254 | context.contentResolver.query(this, arrayOf(columnName), null, null, null)?.use { 255 | if (it.moveToFirst()) { 256 | when (T::class) { 257 | String::class -> it.getString(0) 258 | Int::class -> it.getInt(0) 259 | Long::class -> it.getLong(0) 260 | Float::class -> it.getFloat(0) 261 | Double::class -> it.getDouble(0) 262 | Short::class -> it.getShort(0) 263 | ByteArray::class -> it.getBlob(0) 264 | else -> null 265 | } as T 266 | } else null 267 | } 268 | }.getOrNull() 269 | } 270 | 271 | val Uri.parent: Uri 272 | @RequiresApi(21) 273 | get() { 274 | if (!this.isTreeUri) 275 | throw UnsupportedOperationException("Only Tree Uri is allowed") 276 | 277 | val parentDocumentId = 278 | createNewDocumentId( 279 | this.volumeId!!, this.documentIdPathSegments!! 280 | .dropLast(1) 281 | .joinToString("/") 282 | ) 283 | 284 | return DocumentsContract.buildDocumentUriUsingTree(this, parentDocumentId) 285 | } 286 | 287 | fun Uri.writeText(context: Context, str: String) = 288 | context.contentResolver.openOutputStream(this)?.bufferedWriter()?.use { it.write(str) } 289 | 290 | fun Uri.readText(context: Context) = 291 | context.contentResolver.openInputStream(this)?.bufferedReader()?.use { it.readText() } 292 | 293 | @RequiresApi(19) 294 | fun Uri.exists(context: Context): Boolean { 295 | return kotlin.runCatching { 296 | context.contentResolver.query( 297 | this, 298 | arrayOf(DocumentsContract.Document.COLUMN_DOCUMENT_ID), 299 | null, null, null 300 | )?.use { 301 | it.count > 0 302 | } 303 | }.getOrNull() ?: false 304 | } 305 | 306 | @RequiresApi(21) 307 | fun Uri.create(context: Context, mimeType: String, displayName: String): Uri? = 308 | DocumentsContract.createDocument(context.contentResolver, this, mimeType, displayName) 309 | 310 | @RequiresApi(19) 311 | fun Uri.delete(context: Context) = 312 | DocumentsContract.deleteDocument(context.contentResolver, this) 313 | 314 | internal fun Int.checkFlag(flag: Int) = 315 | this.and(flag) != 0 316 | 317 | internal fun Uri.hasPermission(context: Context) = 318 | context.checkCallingOrSelfUriPermission( 319 | this, 320 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION 321 | ) == PackageManager.PERMISSION_GRANTED 322 | 323 | internal fun canRead(type: String?) = type?.isNotEmpty() ?: false 324 | 325 | @RequiresApi(19) 326 | fun Uri.canRead(context: Context): Boolean { 327 | if (!this.hasPermission(context)) 328 | return false 329 | 330 | val type = kotlin.runCatching { 331 | context.contentResolver.query( 332 | this, 333 | arrayOf(DocumentsContract.Document.COLUMN_MIME_TYPE), 334 | null, null, null 335 | )?.use { 336 | if (it.moveToFirst()) 337 | it.getString(0) 338 | else 339 | null 340 | } 341 | }.getOrNull() 342 | 343 | return canRead(type) 344 | } 345 | 346 | internal fun canWrite(type: String?, flags: Int?): Boolean { 347 | type ?: return false 348 | flags ?: return false 349 | 350 | if (type.isEmpty()) 351 | return false 352 | 353 | if (flags.checkFlag(DocumentsContract.Document.FLAG_SUPPORTS_DELETE)) 354 | return true 355 | 356 | if (type == DocumentsContract.Document.MIME_TYPE_DIR 357 | && flags.checkFlag(DocumentsContract.Document.FLAG_DIR_SUPPORTS_CREATE) 358 | ) 359 | return true 360 | if (flags.checkFlag(DocumentsContract.Document.FLAG_SUPPORTS_WRITE)) 361 | return true 362 | 363 | return false 364 | } 365 | 366 | @RequiresApi(19) 367 | fun Uri.canWrite(context: Context): Boolean { 368 | if (!this.hasPermission(context)) 369 | return false 370 | 371 | val (type, flags) = kotlin.runCatching { 372 | context.contentResolver.query( 373 | this, 374 | arrayOf( 375 | DocumentsContract.Document.COLUMN_MIME_TYPE, 376 | DocumentsContract.Document.COLUMN_FLAGS 377 | ), 378 | null, null, null 379 | )?.use { 380 | if (it.moveToFirst()) 381 | Pair(it.getString(0), it.getInt(1)) 382 | else 383 | null 384 | } 385 | }.getOrNull() ?: return false 386 | 387 | return canWrite(type, flags) 388 | } 389 | 390 | @RequiresApi(19) 391 | fun Uri.isDirectory(context: Context): Boolean { 392 | val type = this.query(context, DocumentsContract.Document.COLUMN_MIME_TYPE) 393 | ?: return false 394 | 395 | return type == DocumentsContract.Document.MIME_TYPE_DIR 396 | } 397 | 398 | @RequiresApi(19) 399 | fun Uri.lastModified(context: Context) = 400 | this.query(context, DocumentsContract.Document.COLUMN_LAST_MODIFIED) 401 | 402 | @RequiresApi(19) 403 | fun Uri.length(context: Context) = 404 | this.query(context, DocumentsContract.Document.COLUMN_SIZE) 405 | 406 | @RequiresApi(21) 407 | fun Uri.list(context: Context): List { 408 | if (!this.isTreeUri) 409 | throw UnsupportedOperationException("Only Tree Uri is allowed") 410 | 411 | val children = DocumentsContract.buildChildDocumentsUriUsingTree(this, this.niceDocumentId) 412 | val result = mutableListOf() 413 | 414 | kotlin.runCatching { 415 | context.contentResolver.query( 416 | children, 417 | arrayOf(DocumentsContract.Document.COLUMN_DOCUMENT_ID), 418 | null, null, null 419 | )?.use { 420 | while (it.moveToNext()) 421 | result.add(it.getString(0)) 422 | } 423 | } 424 | 425 | return result.map { childDocumentId -> 426 | DocumentsContract.buildDocumentUriUsingTree(this, childDocumentId) 427 | } 428 | } 429 | 430 | // Huge thanks to avluis(https://github.com/avluis) 431 | // These codes are originated from Hentoid(https://github.com/avluis/Hentoid) under Apache-2.0 license. 432 | private const val PRIMARY_VOLUME_NAME = "primary" 433 | 434 | // Compat functions 435 | private val Context.storageManager: StorageManager 436 | get() = this.getSystemService(Context.STORAGE_SERVICE) as StorageManager 437 | 438 | private val StorageManager.volumeListCompat: List 439 | @SuppressLint("NewApi") 440 | get() = when (Build.VERSION.SDK_INT) { 441 | in 0 until 21 -> emptyList() 442 | in 24 .. Int.MAX_VALUE -> this.storageVolumes 443 | else -> kotlin.runCatching { 444 | javaClass.getMethod("getVolumeList").invoke(this)?.let { arr -> 445 | (0 until Array.getLength(arr)).map { i -> Array.get(arr, i) as StorageVolume } 446 | } 447 | }.getOrNull() ?: emptyList() 448 | } 449 | 450 | private val StorageVolume.directoryCompat: File? 451 | get() = if (Build.VERSION.SDK_INT < 30) javaClass.getMethod("getPathFile").invoke(this) as File? 452 | else this.directory 453 | 454 | /** 455 | * Get the human-readable access path for the given volume ID 456 | * 457 | * @param context Context to use 458 | * @param volumeID Volume ID to get the path from 459 | * @return Human-readable access path of the given volume ID 460 | */ 461 | @SuppressLint("NewApi") 462 | private fun getVolumePath(context: Context, volumeID: String): String? { 463 | val doesVolumeIdMatch = { uuid: String?, isPrimary: Boolean, treeVolumeID: String -> 464 | (uuid == treeVolumeID.replace("/", "")) || (isPrimary && treeVolumeID == PRIMARY_VOLUME_NAME) 465 | } 466 | 467 | return context.storageManager.volumeListCompat.firstOrNull { 468 | doesVolumeIdMatch(it.uuid, it.isPrimary, volumeID) 469 | }?.let { getVolumePath(it) } 470 | } 471 | 472 | /** 473 | * Returns the human-readable access path of the root of the given storage volume 474 | * 475 | * @param storageVolume android.os.storage.StorageVolume to return the path from 476 | * @return Human-readable access path of the root of the given storage volume; empty string if not found 477 | */ 478 | // Access to getPathFile is limited to API<30 479 | private fun getVolumePath(storageVolume: StorageVolume): String? { 480 | val pathFile = storageVolume.directoryCompat ?: return null 481 | 482 | val path = pathFile.path 483 | val absolutePath = pathFile.absolutePath 484 | 485 | return when { 486 | path.isEmpty() and absolutePath.isEmpty() -> pathFile.canonicalPath 487 | path.isEmpty() -> absolutePath 488 | else -> path 489 | } 490 | } 491 | 492 | fun getFullPathFromTreeUri(context: Context, uri: Uri): String? { 493 | val volumePath = getVolumePath(context, uri.volumeId ?: return null).let { 494 | it ?: return File.separator 495 | 496 | if (it.endsWith(File.separator)) 497 | it.dropLast(1) 498 | else 499 | it 500 | } 501 | 502 | val documentPath = uri.documentIdPath?.let { 503 | if (it.endsWith(File.separator)) 504 | it.dropLast(1) 505 | else 506 | it 507 | } ?: return null 508 | 509 | return if (documentPath.isNotEmpty()) { 510 | if (documentPath.startsWith(File.separator)) 511 | volumePath + documentPath 512 | else 513 | volumePath + File.separator + documentPath 514 | } else 515 | volumePath 516 | } 517 | 518 | fun Uri.toFile(context: Context): File? { 519 | return when { 520 | this.isExternalStorageDocument -> { 521 | val externalStorageRoot = context.getExternalStoragePaths() 522 | 523 | val path = this.documentIdPath ?: return null 524 | 525 | /* First test is to compare root names with known roots of removable media 526 | * In many cases, the SD card root name is shared between pre-SAF (File) and SAF (DocumentFile) frameworks 527 | * (e.g. /storage/3437-3934 vs. /tree/3437-3934) 528 | * This is what the following block is trying to do 529 | */ 530 | externalStorageRoot.forEach { 531 | if (it.substringAfterLast(File.separatorChar).equals(this.volumeId, true)) 532 | return File(it, path) 533 | } 534 | 535 | /* In some other cases, there is no common name (e.g. /storage/sdcard1 vs. /tree/3437-3934) 536 | * We can use a slower method to translate the Uri obtained with SAF into a pre-SAF path 537 | * and compare it to the known removable media volume names 538 | */ 539 | val root = getFullPathFromTreeUri(context, this) 540 | 541 | externalStorageRoot.forEach { 542 | if (root?.startsWith(it) == true) 543 | return File(root) 544 | } 545 | 546 | File( 547 | ContextCompat.getExternalFilesDirs(context, null) 548 | .first().canonicalPath.substringBeforeLast("/Android/data"), path 549 | ) 550 | } 551 | this.isDownloadsDocument -> 552 | File(this.documentIdSegment?.last() ?: return null) 553 | else -> 554 | null 555 | } 556 | } -------------------------------------------------------------------------------- /library/src/main/java/xyz/quaver/io/util/FileUtil.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * ____ _ _____ _ _ __ __ 3 | * | _ \ ___ ___ _ _ _ __ ___ ___ _ __ | |_| ___(_) | ___\ \/ / 4 | * | | | |/ _ \ / __| | | | '_ ` _ \ / _ \ '_ \| __| |_ | | |/ _ \\ / 5 | * | |_| | (_) | (__| |_| | | | | | | __/ | | | |_| _| | | | __// \ 6 | * |____/ \___/ \___|\__,_|_| |_| |_|\___|_| |_|\__|_| |_|_|\___/_/\_\ 7 | * 8 | * Copyright 2020 tom5079 9 | * 10 | * Licensed under the Apache License, Version 2.0 (the "License"); 11 | * you may not use this file except in compliance with the License. 12 | * You may obtain a copy of the License at 13 | * 14 | * http://www.apache.org/licenses/LICENSE-2.0 15 | * 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | */ 22 | 23 | package xyz.quaver.io.util 24 | 25 | import android.content.Context 26 | import androidx.core.content.ContextCompat 27 | import xyz.quaver.io.FileX 28 | import java.io.File 29 | import java.io.FileFilter 30 | import java.io.FilenameFilter 31 | 32 | fun Context.getExternalStoragePaths() = 33 | ContextCompat.getExternalFilesDirs(this, null).drop(1).filterNotNull().map { 34 | it.absolutePath.substringBeforeLast("/Android/data").let { path -> 35 | runCatching { 36 | File(path).canonicalPath 37 | }.getOrElse { 38 | path 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /library/src/main/java/xyz/quaver/io/util/FileXReadWrite.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * ____ _ _____ _ _ __ __ 3 | * | _ \ ___ ___ _ _ _ __ ___ ___ _ __ | |_| ___(_) | ___\ \/ / 4 | * | | | |/ _ \ / __| | | | '_ ` _ \ / _ \ '_ \| __| |_ | | |/ _ \\ / 5 | * | |_| | (_) | (__| |_| | | | | | | __/ | | | |_| _| | | | __// \ 6 | * |____/ \___/ \___|\__,_|_| |_| |_|\___|_| |_|\__|_| |_|_|\___/_/\_\ 7 | * 8 | * Copyright 2020 tom5079 9 | * 10 | * Licensed under the Apache License, Version 2.0 (the "License"); 11 | * you may not use this file except in compliance with the License. 12 | * You may obtain a copy of the License at 13 | * 14 | * http://www.apache.org/licenses/LICENSE-2.0 15 | * 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | */ 22 | 23 | @file:SuppressWarnings("unused") 24 | 25 | package xyz.quaver.io.util 26 | 27 | import xyz.quaver.io.FileX 28 | import xyz.quaver.io.RawFileX 29 | import xyz.quaver.io.SAFileX 30 | import java.io.* 31 | import java.nio.charset.Charset 32 | 33 | fun FileX.inputStream(): FileInputStream? = when (this) { 34 | is SAFileX -> this.inputStream() 35 | is RawFileX -> File(this.path).inputStream() 36 | else -> throw UnsupportedOperationException() 37 | } 38 | 39 | fun FileX.outputStream(mode: String = "w"): FileOutputStream? = when (this) { 40 | is SAFileX -> this.outputStream(mode) 41 | is RawFileX -> File(this.path).outputStream() 42 | else -> throw UnsupportedOperationException() 43 | } 44 | 45 | fun FileX.reader(charset: Charset = Charsets.UTF_8): InputStreamReader? = when (this) { 46 | is SAFileX -> this.reader(charset) 47 | is RawFileX -> File(this.path).reader(charset) 48 | else -> throw UnsupportedOperationException() 49 | } 50 | 51 | fun FileX.bufferedReader(charset: Charset = Charsets.UTF_8, bufferSize: Int = DEFAULT_BUFFER_SIZE): BufferedReader? = when (this) { 52 | is SAFileX -> this.bufferedReader(charset, bufferSize) 53 | is RawFileX -> File(this.path).bufferedReader(charset, bufferSize) 54 | else -> throw UnsupportedOperationException() 55 | } 56 | 57 | fun FileX.writer(charset: Charset = Charsets.UTF_8): OutputStreamWriter? = when (this) { 58 | is SAFileX -> this.writer(charset) 59 | is RawFileX -> File(this.path).writer(charset) 60 | else -> throw UnsupportedOperationException() 61 | } 62 | 63 | fun FileX.bufferedWriter(charset: Charset = Charsets.UTF_8, bufferSize: Int = DEFAULT_BUFFER_SIZE): BufferedWriter? = when (this) { 64 | is SAFileX -> this.bufferedWriter(charset, bufferSize) 65 | is RawFileX -> File(this.path).bufferedWriter(charset, bufferSize) 66 | else -> throw UnsupportedOperationException() 67 | } 68 | 69 | fun FileX.printWriter(charset: Charset = Charsets.UTF_8): PrintWriter? = when (this) { 70 | is SAFileX -> this.printWriter(charset) 71 | is RawFileX -> File(this.path).printWriter(charset) 72 | else -> throw UnsupportedOperationException() 73 | } 74 | 75 | fun FileX.readBytes(): ByteArray? = when (this) { 76 | is SAFileX -> this.readBytes() 77 | is RawFileX -> File(this.path).readBytes() 78 | else -> throw UnsupportedOperationException() 79 | } 80 | 81 | fun FileX.writeBytes(array: ByteArray) = when (this) { 82 | is SAFileX -> this.writeBytes(array) 83 | is RawFileX -> File(this.path).writeBytes(array) 84 | else -> throw UnsupportedOperationException() 85 | } 86 | 87 | fun FileX.appendBytes(array: ByteArray) = when (this) { 88 | is SAFileX -> this.appendBytes(array) 89 | is RawFileX -> File(this.path).appendBytes(array) 90 | else -> throw UnsupportedOperationException() 91 | } 92 | 93 | fun FileX.readText(charset: Charset = Charsets.UTF_8): String? = when (this) { 94 | is SAFileX -> this.readText(charset) 95 | is RawFileX -> File(this.path).readText(charset) 96 | else -> throw UnsupportedOperationException() 97 | } 98 | 99 | fun FileX.writeText(text: String, charset: Charset = Charsets.UTF_8) = when (this) { 100 | is SAFileX -> this.writeText(text, charset) 101 | is RawFileX -> File(this.path).writeText(text, charset) 102 | else -> throw UnsupportedOperationException() 103 | } 104 | 105 | fun FileX.appendText(text: String, charset: Charset = Charsets.UTF_8) = when (this) { 106 | is SAFileX -> this.appendText(text, charset) 107 | is RawFileX -> File(this.path).appendText(text, charset) 108 | else -> throw UnsupportedOperationException() 109 | } 110 | 111 | fun FileX.forEachBlock(blockSize: Int = 4096, action: (buffer: ByteArray, bytesRead: Int) -> Unit) = when (this) { 112 | is SAFileX -> this.forEachBlock(blockSize, action) 113 | is RawFileX -> File(this.path).forEachBlock(blockSize, action) 114 | else -> throw UnsupportedOperationException() 115 | } 116 | 117 | fun FileX.forEachLine(charset: Charset = Charsets.UTF_8, action: (line: String) -> Unit) = when (this) { 118 | is SAFileX -> this.forEachLine(charset, action) 119 | is RawFileX -> File(this.path).forEachLine(charset, action) 120 | else -> throw UnsupportedOperationException() 121 | } 122 | 123 | fun FileX.readLines(charset: Charset = Charsets.UTF_8): List = when (this) { 124 | is SAFileX -> this.readLines(charset) 125 | is RawFileX -> File(this.path).readLines(charset) 126 | else -> throw UnsupportedOperationException() 127 | } 128 | 129 | fun FileX.useLines(charset: Charset = Charsets.UTF_8, block: (Sequence) -> T): T? = when (this) { 130 | is SAFileX -> this.useLines(charset, block) 131 | is RawFileX -> File(this.path).useLines(charset, block) 132 | else -> throw UnsupportedOperationException() 133 | } -------------------------------------------------------------------------------- /library/src/main/java/xyz/quaver/io/util/FileXUtil.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * ____ _ _____ _ _ __ __ 3 | * | _ \ ___ ___ _ _ _ __ ___ ___ _ __ | |_| ___(_) | ___\ \/ / 4 | * | | | |/ _ \ / __| | | | '_ ` _ \ / _ \ '_ \| __| |_ | | |/ _ \\ / 5 | * | |_| | (_) | (__| |_| | | | | | | __/ | | | |_| _| | | | __// \ 6 | * |____/ \___/ \___|\__,_|_| |_| |_|\___|_| |_|\__|_| |_|_|\___/_/\_\ 7 | * 8 | * Copyright 2020 tom5079 9 | * 10 | * Licensed under the Apache License, Version 2.0 (the "License"); 11 | * you may not use this file except in compliance with the License. 12 | * You may obtain a copy of the License at 13 | * 14 | * http://www.apache.org/licenses/LICENSE-2.0 15 | * 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | */ 22 | 23 | package xyz.quaver.io.util 24 | 25 | import android.annotation.SuppressLint 26 | import androidx.annotation.RequiresApi 27 | import xyz.quaver.io.FileX 28 | import xyz.quaver.io.RawFileX 29 | import xyz.quaver.io.SAFileX 30 | import java.io.File 31 | import java.io.IOException 32 | 33 | fun FileX.getChild(fileName: String, cached: Boolean = false): FileX = 34 | FileX(this.context, this, fileName, cached = cached) 35 | 36 | @RequiresApi(21) 37 | fun FileX.getNeighbor(fileName: String, cached: Boolean = false): FileX = 38 | FileX(this.context, this.uri.getNeighborUri(fileName), cached = cached) 39 | 40 | @SuppressLint("NewApi") 41 | fun FileX.deleteRecursively(): Boolean = 42 | when (this) { 43 | is SAFileX -> this.uri.delete(this.context) 44 | is RawFileX -> File(this.path).deleteRecursively() 45 | else -> throw UnsupportedOperationException() 46 | } 47 | 48 | fun FileX.copyTo(target: FileX, overwrite: Boolean = false, bufferSize: Int = DEFAULT_BUFFER_SIZE): FileX { 49 | if (!this.exists()) 50 | throw NoSuchFileException(file = this, reason = "The source file doesn't exist") 51 | 52 | if (target.exists()) { 53 | if (!overwrite) 54 | throw FileAlreadyExistsException(file = this, other = target, reason = "The destination file already exists.") 55 | else if (!target.delete()) 56 | throw FileAlreadyExistsException(file = this, other = target, reason = "Tried to overwrite the destination, but failed to delete it.") 57 | } 58 | 59 | if (this.isDirectory) { 60 | if (!target.mkdirs()) 61 | throw FileSystemException(file = this, other = target, reason = "Failed to create target directory.") 62 | } else { 63 | target.parentFile?.mkdirs() 64 | 65 | if (!target.exists()) target.createNewFile() 66 | 67 | this.inputStream().use { input -> 68 | input ?: throw IOException("Failed to open inputStream of file $this") 69 | 70 | target.outputStream().use { output -> 71 | output ?: throw IOException("Failed to open outputStream of file $target") 72 | output.channel.truncate(0) 73 | 74 | input.copyTo(output, bufferSize) 75 | } 76 | } 77 | } 78 | 79 | return target 80 | } 81 | 82 | fun FileX.copyRecursively( 83 | target: FileX, 84 | overwrite: Boolean = false, 85 | onError: (File, IOException) -> OnErrorAction = { _, e -> throw e } 86 | ): Boolean { 87 | if (this is RawFileX && target is RawFileX) 88 | return File(this.path).copyRecursively(target, overwrite, onError) 89 | 90 | if (!exists()) { 91 | return onError(this, NoSuchFileException(file = this, reason = "The source file doesn't exist.")) != 92 | OnErrorAction.TERMINATE 93 | } 94 | 95 | if (target.exists() && !target.isDirectory) 96 | throw IOException("Target is not a folder") 97 | else 98 | target.mkdirs() 99 | 100 | for (src in (listFiles() ?: return false)) { 101 | @Suppress("NAME_SHADOWING") 102 | val src = FileX(context, src) 103 | 104 | if (!src.exists() && onError(src, NoSuchFileException(file = src, reason = "The source file doesn't exist.")) == OnErrorAction.TERMINATE) 105 | return false 106 | 107 | val dstFile = FileX(context, target, src.name) 108 | 109 | if (dstFile.exists() && !(src.isDirectory && dstFile.isDirectory)) { 110 | val stillExists = if (!overwrite) true else !dstFile.deleteRecursively() 111 | 112 | if (stillExists) { 113 | if (onError(dstFile, FileAlreadyExistsException(file = src, 114 | other = dstFile, 115 | reason = "The destination file already exists.")) == OnErrorAction.TERMINATE) 116 | return false 117 | 118 | continue 119 | } 120 | } 121 | 122 | if (src.isDirectory) { 123 | dstFile.mkdirs() 124 | if (!src.copyRecursively(dstFile, overwrite, onError)) 125 | return false 126 | } else { 127 | if (src.copyTo(dstFile, overwrite).length() != src.length()) { 128 | if (onError(src, IOException("Source file wasn't copied completely, length of destination file differs.")) == OnErrorAction.TERMINATE) 129 | return false 130 | } 131 | } 132 | } 133 | 134 | return true; 135 | } -------------------------------------------------------------------------------- /library/src/main/java/xyz/quaver/io/util/SAFileXReadWrite.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * ____ _ _____ _ _ __ __ 3 | * | _ \ ___ ___ _ _ _ __ ___ ___ _ __ | |_| ___(_) | ___\ \/ / 4 | * | | | |/ _ \ / __| | | | '_ ` _ \ / _ \ '_ \| __| |_ | | |/ _ \\ / 5 | * | |_| | (_) | (__| |_| | | | | | | __/ | | | |_| _| | | | __// \ 6 | * |____/ \___/ \___|\__,_|_| |_| |_|\___|_| |_|\__|_| |_|_|\___/_/\_\ 7 | * 8 | * Copyright 2020 tom5079 9 | * 10 | * Licensed under the Apache License, Version 2.0 (the "License"); 11 | * you may not use this file except in compliance with the License. 12 | * You may obtain a copy of the License at 13 | * 14 | * http://www.apache.org/licenses/LICENSE-2.0 15 | * 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | */ 22 | 23 | @file:SuppressWarnings("NewApi", "unused") 24 | 25 | package xyz.quaver.io.util 26 | 27 | import xyz.quaver.io.SAFileX 28 | import java.io.* 29 | import java.nio.charset.Charset 30 | 31 | // ===== EXTENSIONS ==== 32 | // From Kotlin Standard Library (https://github.com/JetBrains/kotlin/blob/master/libraries/stdlib/jvm/src/kotlin/io/FileReadWrite.kt) 33 | fun SAFileX.inputStream(): FileInputStream? = 34 | context.contentResolver.openInputStream(this.uri) as FileInputStream 35 | 36 | fun SAFileX.outputStream(mode: String = "wt"): FileOutputStream? = 37 | context.contentResolver.openOutputStream(this.uri, mode) as FileOutputStream 38 | 39 | fun SAFileX.reader(charset: Charset = Charsets.UTF_8): InputStreamReader? = 40 | inputStream()?.reader(charset) 41 | 42 | fun SAFileX.bufferedReader(charset: Charset = Charsets.UTF_8, bufferSize: Int = DEFAULT_BUFFER_SIZE): BufferedReader? = 43 | reader(charset)?.buffered(bufferSize) 44 | 45 | fun SAFileX.writer(charset: Charset = Charsets.UTF_8): OutputStreamWriter? = 46 | outputStream()?.writer(charset) 47 | 48 | fun SAFileX.bufferedWriter(charset: Charset = Charsets.UTF_8, bufferSize: Int = DEFAULT_BUFFER_SIZE): BufferedWriter? = 49 | writer(charset)?.buffered(bufferSize) 50 | 51 | fun SAFileX.printWriter(charset: Charset = Charsets.UTF_8): PrintWriter? = 52 | bufferedWriter(charset)?.let { PrintWriter(it) } 53 | 54 | fun SAFileX.readBytes(): ByteArray? = inputStream()?.use { input -> 55 | var offset = 0 56 | var remaining = this.length().also { length -> 57 | if (length > Int.MAX_VALUE) throw OutOfMemoryError("File $this is too big ($length bytes) to fit in memory.") 58 | }.toInt() 59 | val result = ByteArray(remaining) 60 | while (remaining > 0) { 61 | val read = input.read(result, offset, remaining) 62 | if (read < 0) break 63 | remaining -= read 64 | offset += read 65 | } 66 | if (remaining > 0) return@use result.copyOf(offset) 67 | 68 | val extraByte = input.read() 69 | if (extraByte == -1) return@use result 70 | 71 | // allocation estimate: (RS + DBS + max(ES, DBS + 1)) + (RS + ES), 72 | // where RS = result.size, ES = extra.size, DBS = DEFAULT_BUFFER_SIZE 73 | // when RS = 0, ES >> DBS => DBS + DBS + 1 + ES + ES = 2DBS + 2ES 74 | // when RS >> ES, ES << DBS => RS + DBS + DBS+1 + RS + ES = 2RS + 2DBS + ES 75 | val extra = object: ByteArrayOutputStream(DEFAULT_BUFFER_SIZE + 1) { 76 | val buffer: ByteArray get() = buf 77 | } 78 | extra.write(extraByte) 79 | input.copyTo(extra) 80 | 81 | val resultingSize = result.size + extra.size() 82 | if (resultingSize < 0) throw OutOfMemoryError("File $this is too big to fit in memory.") 83 | 84 | return@use extra.buffer.copyInto( 85 | destination = result.copyOf(resultingSize), 86 | destinationOffset = result.size, 87 | startIndex = 0, endIndex = extra.size() 88 | ) 89 | } 90 | 91 | fun SAFileX.writeBytes(array: ByteArray) { 92 | outputStream()?.use { 93 | it.write(array) 94 | } 95 | } 96 | 97 | fun SAFileX.appendBytes(array: ByteArray) { 98 | outputStream("wa")?.use { it.write(array) } 99 | } 100 | 101 | fun SAFileX.readText(charset: Charset = Charsets.UTF_8): String? = 102 | reader(charset)?.use { it.readText() } 103 | 104 | fun SAFileX.writeText(text: String, charset: Charset = Charsets.UTF_8) { 105 | writeBytes(text.toByteArray(charset)) 106 | } 107 | 108 | fun SAFileX.appendText(text: String, charset: Charset = Charsets.UTF_8) { 109 | appendBytes(text.toByteArray(charset)) 110 | } 111 | 112 | fun SAFileX.forEachBlock(blockSize: Int = 4096, action: (buffer: ByteArray, bytesRead: Int) -> Unit) { 113 | val arr = ByteArray(blockSize.coerceAtLeast(512)) 114 | 115 | inputStream()?.use { input -> 116 | do { 117 | val size = input.read(arr) 118 | if (size <= 0) { 119 | break 120 | } else { 121 | action(arr, size) 122 | } 123 | } while (true) 124 | } 125 | } 126 | 127 | fun SAFileX.forEachLine(charset: Charset = Charsets.UTF_8, action: (line: String) -> Unit) { 128 | // Note: close is called at forEachLine 129 | bufferedReader(charset)?.forEachLine(action) 130 | } 131 | 132 | fun SAFileX.readLines(charset: Charset = Charsets.UTF_8): List = 133 | mutableListOf().apply { 134 | forEachLine(charset) { 135 | add(it) 136 | } 137 | } 138 | 139 | fun SAFileX.useLines(charset: Charset = Charsets.UTF_8, block: (Sequence) -> T): T? = 140 | bufferedReader(charset)?.use { block(it.lineSequence()) } -------------------------------------------------------------------------------- /library/src/test/java/xyz/quaver/io/ExampleUnitTest.kt: -------------------------------------------------------------------------------- 1 | package xyz.quaver.io 2 | 3 | import org.junit.Test 4 | 5 | import org.junit.Assert.* 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * See [testing documentation](http://d.android.com/tools/testing). 11 | */ 12 | class ExampleUnitTest { 13 | @Test 14 | fun addition_isCorrect() { 15 | assertEquals(4, 2 + 2) 16 | } 17 | } -------------------------------------------------------------------------------- /sample/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /sample/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | id("com.android.application") 3 | id("kotlin-android") 4 | } 5 | 6 | android { 7 | compileSdk = 30 8 | buildToolsVersion = "30.0.3" 9 | 10 | defaultConfig { 11 | applicationId = "xyz.quaver.io.sample" 12 | minSdk = 21 13 | targetSdk = 30 14 | versionCode = 1 15 | versionName = project.version.toString() 16 | 17 | testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" 18 | } 19 | 20 | buildTypes { 21 | getByName("release") { 22 | isMinifyEnabled = false 23 | proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") 24 | } 25 | } 26 | 27 | buildFeatures { 28 | compose = true 29 | } 30 | 31 | composeOptions { 32 | kotlinCompilerExtensionVersion = "1.0.2" 33 | } 34 | } 35 | 36 | dependencies { 37 | implementation("org.jetbrains.kotlin:kotlin-stdlib") 38 | implementation("androidx.core:core-ktx:1.6.0") 39 | 40 | implementation("androidx.activity:activity-compose:1.3.1") 41 | 42 | implementation("androidx.compose.ui:ui:1.0.2") 43 | implementation("androidx.compose.ui:ui-tooling:1.0.2") 44 | implementation("androidx.compose.foundation:foundation:1.0.2") 45 | implementation("androidx.compose.material:material:1.0.2") 46 | implementation("androidx.compose.material:material-icons-core:1.0.2") 47 | implementation("androidx.compose.material:material-icons-extended:1.0.2") 48 | implementation("androidx.compose.animation:animation:1.0.2") 49 | implementation("androidx.compose.runtime:runtime:1.0.2") 50 | implementation("androidx.compose.runtime:runtime-livedata:1.0.2") 51 | implementation("com.google.accompanist:accompanist-appcompat-theme:0.16.0") 52 | 53 | implementation(project(":library")) 54 | testImplementation("junit:junit:4.13.2") 55 | androidTestImplementation("androidx.test.ext:junit:1.1.3") 56 | androidTestImplementation("androidx.test.espresso:espresso-core:3.4.0") 57 | 58 | } 59 | -------------------------------------------------------------------------------- /sample/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle.kts.kts. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile -------------------------------------------------------------------------------- /sample/src/androidTest/java/xyz/quaver/io/sample/ExampleInstrumentedTest.kt: -------------------------------------------------------------------------------- 1 | package xyz.quaver.io.sample 2 | 3 | import androidx.test.platform.app.InstrumentationRegistry 4 | import androidx.test.ext.junit.runners.AndroidJUnit4 5 | 6 | import org.junit.Test 7 | import org.junit.runner.RunWith 8 | 9 | import org.junit.Assert.* 10 | 11 | /** 12 | * Instrumented test, which will execute on an Android device. 13 | * 14 | * See [testing documentation](http://d.android.com/tools/testing). 15 | */ 16 | @RunWith(AndroidJUnit4::class) 17 | class ExampleInstrumentedTest { 18 | @Test 19 | fun useAppContext() { 20 | // Context of the app under test. 21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext 22 | assertEquals("xyz.quaver.io.sample", appContext.packageName) 23 | } 24 | } -------------------------------------------------------------------------------- /sample/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /sample/src/main/java/xyz/quaver/io/sample/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package xyz.quaver.io.sample 2 | 3 | import android.app.Activity 4 | import android.content.Intent 5 | import android.os.Bundle 6 | import androidx.activity.ComponentActivity 7 | import androidx.activity.compose.setContent 8 | import androidx.activity.result.contract.ActivityResultContracts 9 | import androidx.activity.viewModels 10 | import androidx.compose.material.* 11 | import androidx.compose.material.icons.Icons 12 | import androidx.compose.material.icons.filled.PlayArrow 13 | import androidx.compose.runtime.getValue 14 | import androidx.compose.runtime.livedata.observeAsState 15 | 16 | class MainActivity : ComponentActivity() { 17 | 18 | private val viewModel: MainActivityViewModel by viewModels() 19 | 20 | private val requestFolderLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { 21 | if (it.resultCode == Activity.RESULT_OK) { 22 | it.data?.data?.also { uri -> 23 | /* 24 | * Add theese lines to make permissions persist 25 | * val takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION or INTENT.FLAG_GRANT_WRITE_URI_PERMISSION 26 | * contentResolver.takePersistableUriPermission(uri, takeFlags) 27 | */ 28 | 29 | viewModel.registerUri(uri) 30 | } 31 | } 32 | } 33 | 34 | override fun onCreate(savedInstanceState: Bundle?) { 35 | super.onCreate(savedInstanceState) 36 | setContent { 37 | val path: String? by viewModel.path.observeAsState() 38 | 39 | Scaffold( 40 | topBar = { 41 | TopAppBar(title = { Text(getString(applicationInfo.labelRes)) }) 42 | }, 43 | floatingActionButton = { 44 | FloatingActionButton(onClick = { 45 | requestFolderLauncher.launch(Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply { 46 | putExtra("android.content.exta.SHOW_ADVANCED", true) 47 | }) 48 | }) { 49 | Icon(imageVector = Icons.Default.PlayArrow, contentDescription = null) 50 | } 51 | } 52 | ) { 53 | Text(path.toString()) 54 | } 55 | } 56 | } 57 | } -------------------------------------------------------------------------------- /sample/src/main/java/xyz/quaver/io/sample/MainActivityViewModel.kt: -------------------------------------------------------------------------------- 1 | package xyz.quaver.io.sample 2 | 3 | import android.app.Application 4 | import android.net.Uri 5 | import androidx.lifecycle.AndroidViewModel 6 | import androidx.lifecycle.LiveData 7 | import androidx.lifecycle.MutableLiveData 8 | import xyz.quaver.io.FileX 9 | 10 | class MainActivityViewModel(app: Application) : AndroidViewModel(app) { 11 | private val _file = MutableLiveData() 12 | val file = _file as LiveData 13 | 14 | private val _path = MutableLiveData() 15 | val path = _path as LiveData 16 | 17 | fun registerUri(uri: Uri) { 18 | val file = FileX(getApplication(), uri) 19 | 20 | _file.postValue(file) 21 | 22 | _path.postValue(file.canonicalPath) 23 | } 24 | } -------------------------------------------------------------------------------- /sample/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | 15 | 18 | 21 | 22 | 23 | 24 | 30 | -------------------------------------------------------------------------------- /sample/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tom5079/DocumentFileX/4d41e7e8838416eac1595ee84ace2d4451724f34/sample/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tom5079/DocumentFileX/4d41e7e8838416eac1595ee84ace2d4451724f34/sample/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tom5079/DocumentFileX/4d41e7e8838416eac1595ee84ace2d4451724f34/sample/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tom5079/DocumentFileX/4d41e7e8838416eac1595ee84ace2d4451724f34/sample/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tom5079/DocumentFileX/4d41e7e8838416eac1595ee84ace2d4451724f34/sample/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tom5079/DocumentFileX/4d41e7e8838416eac1595ee84ace2d4451724f34/sample/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tom5079/DocumentFileX/4d41e7e8838416eac1595ee84ace2d4451724f34/sample/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tom5079/DocumentFileX/4d41e7e8838416eac1595ee84ace2d4451724f34/sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tom5079/DocumentFileX/4d41e7e8838416eac1595ee84ace2d4451724f34/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tom5079/DocumentFileX/4d41e7e8838416eac1595ee84ace2d4451724f34/sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /sample/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #6200EE 4 | #3700B3 5 | #03DAC5 6 | -------------------------------------------------------------------------------- /sample/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | SAFTest 3 | -------------------------------------------------------------------------------- /sample/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 9 | 10 | -------------------------------------------------------------------------------- /sample/src/test/java/xyz/quaver/io/sample/ExampleUnitTest.kt: -------------------------------------------------------------------------------- 1 | package xyz.quaver.io.sample 2 | 3 | import org.junit.Test 4 | 5 | import org.junit.Assert.* 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * See [testing documentation](http://d.android.com/tools/testing). 11 | */ 12 | class ExampleUnitTest { 13 | @Test 14 | fun addition_isCorrect() { 15 | assertEquals(4, 2 + 2) 16 | } 17 | } -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':sample' 2 | include ':library' 3 | rootProject.name = "DocumentFileX" --------------------------------------------------------------------------------