Full Code of nain-F49FF806/anemo-aer for AI

main a54717d8e7ef cached
90 files
231.2 KB
56.8k tokens
4 symbols
1 requests
Download .txt
Showing preview only (256K chars total). Download the full file or copy to clipboard to get everything.
Repository: nain-F49FF806/anemo-aer
Branch: main
Commit: a54717d8e7ef
Files: 90
Total size: 231.2 KB

Directory structure:
gitextract_so4unp8y/

├── .gitattributes
├── .githooks/
│   └── pre-commit
├── .github/
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug_report.yml
│   │   ├── config.yml
│   │   └── feature_request.yml
│   └── workflows/
│       ├── main.yml
│       └── release.yml
├── .gitignore
├── COPYING
├── README.md
├── app/
│   ├── .gitignore
│   ├── build.gradle.kts
│   ├── code-format.xml
│   ├── proguard-rules.pro
│   └── src/
│       └── main/
│           ├── AndroidManifest.xml
│           ├── java/
│           │   └── alt/
│           │       └── nainapps/
│           │           └── aer/
│           │               ├── config/
│           │               │   ├── ConfigurationActivity.kt
│           │               │   ├── StorageConfigActivity.kt
│           │               │   ├── autolock/
│           │               │   │   └── AutoLockDelayMinutesTextListener.kt
│           │               │   ├── password/
│           │               │   │   ├── ChangePasswordDialog.kt
│           │               │   │   ├── PasswordDialog.kt
│           │               │   │   ├── PasswordTextListener.kt
│           │               │   │   └── SetPasswordDialog.kt
│           │               │   └── ui/
│           │               │       └── theme/
│           │               │           ├── Color.kt
│           │               │           ├── Theme.kt
│           │               │           └── Type.kt
│           │               ├── documents/
│           │               │   ├── home/
│           │               │   │   └── HomeEnvironment.kt
│           │               │   ├── provider/
│           │               │   │   ├── AnemoDocumentProvider.kt
│           │               │   │   ├── EmptyCursor.kt
│           │               │   │   ├── FileSystemProvider.kt
│           │               │   │   └── PathUtils.kt
│           │               │   └── receiver/
│           │               │       └── ReceiverActivity.kt
│           │               ├── lock/
│           │               │   ├── AutoLockJobService.kt
│           │               │   ├── LockStore.kt
│           │               │   ├── LockTileService.kt
│           │               │   └── UnlockActivity.kt
│           │               ├── shell/
│           │               │   ├── AnemoShell.kt
│           │               │   └── LauncherActivity.kt
│           │               └── task/
│           │                   └── TaskExecutor.java
│           └── res/
│               ├── color/
│               │   └── btn_colored_text.xml
│               ├── drawable/
│               │   ├── ic_configuration.xml
│               │   ├── ic_error.xml
│               │   ├── ic_key_tile.xml
│               │   ├── ic_launcher_foreground.xml
│               │   ├── ic_launcher_monochrome.xml
│               │   ├── ic_shortcut_configuration.xml
│               │   └── ic_storage.xml
│               ├── layout/
│               │   ├── configuration.xml
│               │   ├── password_change.xml
│               │   ├── password_first_set.xml
│               │   └── password_input.xml
│               ├── mipmap-anydpi/
│               │   └── ic_launcher.xml
│               ├── values/
│               │   ├── colors.xml
│               │   ├── strings.xml
│               │   ├── styles.xml
│               │   └── themes.xml
│               ├── values-es/
│               │   └── strings.xml
│               ├── values-fr/
│               │   └── strings.xml
│               ├── values-it/
│               │   └── strings.xml
│               ├── values-night/
│               │   ├── colors.xml
│               │   └── styles.xml
│               ├── values-night-v31/
│               │   └── colors.xml
│               ├── values-pt-rBR/
│               │   └── strings.xml
│               ├── values-v27/
│               │   └── styles.xml
│               ├── values-v31/
│               │   └── colors.xml
│               └── xml/
│                   ├── backup_rules.xml
│                   ├── data_extraction_rules.xml
│                   └── shortcuts.xml
├── build.gradle
├── gradle/
│   ├── libs.versions.toml
│   └── wrapper/
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
├── metadata/
│   ├── en-US/
│   │   ├── full_description.txt
│   │   ├── short_description.txt
│   │   └── title.txt
│   ├── es-ES/
│   │   ├── full_description.txt
│   │   ├── short_description.txt
│   │   └── title.txt
│   ├── fr-FR/
│   │   ├── full_description.txt
│   │   ├── short_description.txt
│   │   └── title.txt
│   ├── it-IT/
│   │   ├── full_description.txt
│   │   ├── short_description.txt
│   │   └── title.txt
│   └── pt-rBR/
│       ├── full_description.txt
│       ├── short_description.txt
│       └── title.txt
└── settings.gradle.kts

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitattributes
================================================
# Set the default behavior, in case people don't have core.autocrlf set.
* text=auto eol=lf

# Declare files that will always have CRLF line endings on checkout.
*.cmd text eol=crlf
*.bat text eol=crlf

# Denote all files that are truly binary and should not be modified.
*.png binary


================================================
FILE: .githooks/pre-commit
================================================
#!/bin/bash

# Use unix timestamp, precise to 1000 seconds (~16.7 mins) as versionCode epoch.
# This lets us later generate 999 manual updates to a versionCode epoch if needed.
# Note: This scheme will remain valid for use in Google Play up to value 2100000000,
# or about year 2036 .

# Function to get the current time epoch version code
getCurrentTimeEpochVersionCode() {
    # Get the current Unix timestamp in seconds
    seconds=$(date +%s)
    # Divide the seconds (integer division) by 1000 to get the epoch
    epoch=$(($seconds / 1000))
    # Multiply the epoch by 1000 to get the version code
    epochVersionCode=$(($epoch * 1000))
    echo $epochVersionCode
}

# Function to get the current date version name
getCurrentDateVersionName() {
    # Get the current date in the format yyyy.MM.dd
    currentDateVersionName=$(date +"%Y.%m.%d")
    echo $currentDateVersionName
}

# Check if SKIP_VERSION_AUTO_UPDATE is set
if [ "$SKIP_VERSION_AUTO_UPDATE" = "true" ]; then
    echo "Skipping automatic android app version update."
    exit 0
else
    echo "Incrementing android app version pre-commit."
    echo "Skip by setting environment variable SKIP_VERSION_AUTO_UPDATE=true."
fi

# Get the versionCode and versionName
versionCode=$(getCurrentTimeEpochVersionCode)
versionName=$(getCurrentDateVersionName)

# Store the path to build.gradle.kts in a variable
buildGradleFilePath="app/build.gradle.kts"

# Update the build.gradle.kts file with the new versionCode and versionName
sed -i'' -e "s/versionCode .*/versionCode = $versionCode/" "$buildGradleFilePath"
sed -i'' -e "s/versionName .*/versionName = \"$versionName\"/" "$buildGradleFilePath"

# Add the updated build.gradle.kts file to the staging area
git add "$buildGradleFilePath"

# Proceed with the commit
exit 0


================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.yml
================================================
---
name: Bug report
description: Report a bug
labels: [bug]
title: "[Bug] "
body:
  - type: markdown
    attributes:
      value: |
        Hi! Thanks for reporting a bug.

        To make it easier for people to help you please enter detailed information below.
  - type: textarea
    attributes:
      label: Steps to reproduce
      placeholder: |
        1.
        2.
        3.
    validations:
      required: true
  - type: textarea
    attributes:
      label: Expectations
      placeholder: Tell what you think should happen
    validations:
      required: true
  - type: textarea
    attributes:
      label: Reality
      placeholder: Tell what happened instead
    validations:
      required: true
  - type: input
    attributes:
      label: App version
    validations:
      required: true
  - type: input
    attributes:
      label: Android version
    validations:
      required: true


================================================
FILE: .github/ISSUE_TEMPLATE/config.yml
================================================
blank_issues_enabled: false
contact_links:
  - name: Ask a question
    url: https://github.com/2bllw8/anemo/discussions/new?category=Q-A
    about: Ask and answer questions about the app here


================================================
FILE: .github/ISSUE_TEMPLATE/feature_request.yml
================================================
---
name: Feature request
description: Suggest a feature to add
labels: [enhancement]
title: "[Feature request] "
body:
  - type: textarea
    attributes:
      label: Describe what you'd like to see added to the app
      placeholder: Describe what feature you are requesting and what problems it would solve
    validations:
      required: true
  - type: textarea
    attributes:
      label: Additional information
      placeholder: Add any other information or screenshots about the feature request here
    validations:
      required: false


================================================
FILE: .github/workflows/main.yml
================================================
name: Aer CI

on:
  push:
    branches:
      - 'main'
      - 'revamp'
    paths-ignore:
      - '**.md'
      - '.gitignore'
      - 'Android.bp'
      - '/metadata'
  pull_request:
    paths-ignore:
      - '**.md'
      - '.gitignore'
      - 'Android.bp'
      - '/metadata'

jobs:
  build:
    runs-on: ubuntu-22.04
    steps:
      - name: Project checkout
        uses: actions/checkout@v2
        with:
          fetch-depth: 0
      - name: Set up JDK 17
        uses: actions/setup-java@v1
        with:
          java-version: 17
      - name: Cache Gradle Dependencies
        uses: actions/cache@v2
        with:
          path: |
            ~/.gradle/caches
            ~/.gradle/wrapper
            !~/.gradle/caches/build-cache-*
          key: gradle-deps-core-${{ hashFiles('**/build.gradle*') }}
          restore-keys: |
            gradle-deps
      - name: Cache Gradle Build
        uses: actions/cache@v2
        with:
          path: |
            ~/.gradle/caches/build-cache-*
          key: gradle-builds-core-${{ github.sha }}
          restore-keys: |
            gradle-builds
#      - name: Signing key
#        if: ${{ github.event_name == 'push' }}
#        run: |
#          echo 'androidStorePassword=${{ secrets.KEY_STORE_PASSWORD }}' >> local.properties
#          echo 'androidKeyAlias=${{ secrets.KEY_ALIAS }}' >> local.properties
#          echo 'androidKeyPassword=${{ secrets.KEY_PASSWORD }}' >> local.properties
#          echo 'androidStoreFile=sign_key.jks' >> local.properties
#          echo '${{ secrets.KEY_STORE }}' | base64 --decode > sign_key.jks
      - name: Build
        id: build
        run: |
          echo 'org.gradle.caching=true' >> gradle.properties
          echo 'org.gradle.parallel=true' >> gradle.properties
          echo 'org.gradle.vfs.watch=true' >> gradle.properties
          echo 'org.gradle.jvmargs=-Xmx2048m' >> gradle.properties
          ./gradlew :app:assembleDebug
      - name: Upload artifacts
        if: ${{ github.event_name == 'push' }}
        uses: actions/upload-artifact@v4
        with:
          name: app.apk
          path: "app/build/outputs/apk/debug/app-debug.apk"
          retention-days: 14


================================================
FILE: .github/workflows/release.yml
================================================
name: Release

on:
  workflow_dispatch:
  push:
    tags:
      - '*'
  release:
    types: ["published"]

jobs:
  build:
    runs-on: ubuntu-22.04
    steps:
      - name: Project checkout
        uses: actions/checkout@v2
        with:
          fetch-depth: 0
      - name: Set up JDK 17
        uses: actions/setup-java@v1
        with:
          java-version: 17
      - name: Cache Gradle Dependencies
        uses: actions/cache@v2
        with:
          path: |
            ~/.gradle/caches
            ~/.gradle/wrapper
            !~/.gradle/caches/build-cache-*
          key: gradle-deps-core-${{ hashFiles('**/build.gradle*') }}
          restore-keys: |
            gradle-deps
      - name: Cache Gradle Build
        uses: actions/cache@v2
        with:
          path: |
            ~/.gradle/caches/build-cache-*
          key: gradle-builds-core-${{ github.sha }}
          restore-keys: |
            gradle-builds
      - name: Signing key
        run: |
          echo "androidStorePassword=${{ secrets.KEY_STORE_PASSWORD }}" >> local.properties
          echo "androidKeyAlias=${{ secrets.KEY_ALIAS }}" >> local.properties
          echo "androidKeyPassword=${{ secrets.KEY_PASSWORD }}" >> local.properties
          echo "androidStoreFile=aer_sign_keystore.jks" >> local.properties
          if [ ! -z "${{ secrets.KEY_STORE }}" ]; then
            echo '${{ secrets.KEY_STORE }}' | base64 --decode > aer_sign_keystore.jks
          fi
      - name: Build
        id: build
        run: |
          echo 'org.gradle.caching=true' >> gradle.properties
          echo 'org.gradle.parallel=true' >> gradle.properties
          echo 'org.gradle.vfs.watch=true' >> gradle.properties
          echo 'org.gradle.jvmargs=-Xmx2048m' >> gradle.properties
          ./gradlew :app:assembleRelease
      - name: Upload mappings
        if: ${{ github.event_name == 'push' }}
        uses: actions/upload-artifact@v4
        with:
          name: mappings
          path: "app/build/outputs/mapping/release"
      - name: Upload apks to release assets
        if: ${{ (github.event_name == 'release') }}
        run: |
          curl --fail -L \
            -X POST \
            -H "Accept: application/vnd.github+json" \
            -H "Authorization: Bearer ${{ secrets.RELEASE_UPLOAD_PAT }}" \
            -H "X-GitHub-Api-Version: 2022-11-28" \
            -H "Content-Type: application/octet-stream" \
            "https://uploads.github.com/repos/${{ github.repository }}/releases/${{ github.event.release.id }}/assets?name=aer-app-release.apk" \
            --data-binary "@app/build/outputs/apk/release/app-release.apk"


================================================
FILE: .gitignore
================================================
.DS_Store

# Android Studio
*.iml
.idea

# Bazel
/.aswb
/.ijwb
/bazel-*

# Gradle
.gradle
local.properties
/build

# Sign key
*.jks
*.jks.base64

# VSCode
*/.classpath
*/.project
*/.settings


================================================
FILE: COPYING
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.


================================================
FILE: README.md
================================================
# Aer - fork of [Anemo]

> [!NOTE]  
> - This fork focuses on supporting app's *private location* on external storage (~ SD card)  
> - If no external storage exists it'll gracefully fall back to using internal storage  
> - Anemo and Aer can be used side by side for maximal profit

[Anemo]: https://github.com/2bllw8/anemo

[![Aer CI](https://github.com/nain-F49FF806/anemo-aer/actions/workflows/main.yml/badge.svg)](https://github.com/nain-F49FF806/anemo-aer/actions/workflows/main.yml)
[![Latest release](https://img.shields.io/github/v/release/nain-F49FF806/anemo-aer?label=download)](https://github.com/nain-F49FF806/anemo-aer/releases/latest)

Aer is a private local storage utility application for android.
Instead of being a stand-alone file manager user interface, it hooks into various components of
Android making it feel like a native part of the operating system.
Moreover it provides ways for the user to export contents from other apps and save them as files.

## Features

- Create folders and organize files freely
- All files in the private storage won't appear in the other apps
- Access in the system Files application (the _DocumentsProviderUI_)
    - An optional shortcut for devices that do not expose the system Files app is offered
- Lock access to the private storage
  - Quick tile
  - **Auto lock after set delay**
  - Password for locking access to the files
- Import content using the share Android functionality
- **Option to select which private storage location to use**

## Download

[<img src="https://fdroid.gitlab.io/artwork/badge/get-it-on.png"
     alt="Get it on F-Droid"
     height="90">](https://f-droid.org/en/packages/alt.nainapps.aer/)

Alternatively, get it from github [releases](https://github.com/nain-F49FF806/anemo-aer/releases)

## Build

With Gradle:
- `./gradlew :app:assembleRelease`
- `./gradlew :app:assembleDebug`

## Get help

Open an discussion [on github](https://github.com/2bllw8/anemo/discussions/new?category=Q-A)

## Contributions

**Every contributions, including ideas, bug reports and Pull Requests are welcome!**

- **Solve bug(s)**, add **feature(s)** or **translate** Aer to your native language by making a **[pull request](https://help.github.com/articles/about-pull-requests/)**
- You have an idea for improvement or a new feature? Open a feature request **[upstream](https://github.com/2bllw8/anemo/issues/new?assignees=&labels=enhancement&template=feature_request.yml&title=[Feature+request]+)** or specifically **[for Aer](https://github.com/nain-F49FF806/anemo-aer/issues/new?assignees=&labels=enhancement&template=feature_request.yml&title=[Feature+request]+)**
- You faced a bug, let us know by opening a **[bug report](https://github.com/nain-F49FF806/anemo-aer/issues/new?assignees=&labels=bug&template=bug_report.yml&title=%5BBug%5D+)**

## License

Aer is licensed under the [GNU General Public License v3 (GPL-3)](http://www.gnu.org/copyleft/gpl.html).


================================================
FILE: app/.gitignore
================================================
/build
/release


================================================
FILE: app/build.gradle.kts
================================================
/*
 * Copyright (c) 2021 2bllw8
 * SPDX-License-Identifier: GPL-3.0-only
 */
plugins {
    alias(libs.plugins.android.application)
    alias(libs.plugins.compose.compiler)
    id("org.jetbrains.kotlin.android")
    id("com.diffplug.spotless") version "6.5.1"
}

android {
    compileSdk = rootProject.extra["targetSdkVersion"] as Int
    defaultConfig {
        minSdk = rootProject.extra["minSdkVersion"] as Int
        targetSdk = rootProject.extra["targetSdkVersion"] as Int
        versionCode = 1735160000
        versionName = "2024.12.25"
        applicationId = "alt.nainapps.aer"
        vectorDrawables {
            useSupportLibrary = true
        }
    }

    buildFeatures {
        buildConfig = false
        compose = true
    }

    compileOptions {
        sourceCompatibility = rootProject.extra["sourceCompatibilityVersion"] as JavaVersion
        targetCompatibility = rootProject.extra["targetCompatibilityVersion"] as JavaVersion
    }

    dependenciesInfo {
        includeInApk = false
    }

    signingConfigs {
        if (rootProject.ext.get("keyStoreFile") != null && (rootProject.ext.get("keyStoreFile") as File).exists()) {
            create("aer") {
                storeFile = file(rootProject.ext.get("keyStoreFile") as File)
                storePassword = rootProject.ext.get("keyStorePassword") as String
                keyAlias = rootProject.ext.get("keyAlias") as String
                keyPassword = rootProject.ext.get("keyPassword") as String
            }
        }
    }

    buildTypes {
        val useAerSignConfig = rootProject.ext.get("keyStoreFile") != null && (rootProject.ext.get("keyStoreFile") as File).exists()

        getByName("release") {
            isMinifyEnabled = true
            proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
            signingConfig = signingConfigs.getByName("debug")

            if (useAerSignConfig) {
                signingConfig = signingConfigs.getByName("aer")
            }
        }
        getByName("debug") {
            applicationIdSuffix = ".debug"
            signingConfig = signingConfigs.getByName("debug")

            if (useAerSignConfig) {
                signingConfig = signingConfigs.getByName("aer")
            }
        }
    }
    kotlinOptions {
        jvmTarget = "17"
    }
    namespace = "alt.nainapps.aer"
    composeOptions {
        kotlinCompilerExtensionVersion = "1.5.1"
    }
    packaging {
        resources {
            excludes += "/META-INF/{AL2.0,LGPL2.1}"
        }
    }
}

dependencies {
    implementation(libs.androidx.core.ktx)
    implementation(libs.androidx.annotation)
    implementation(libs.eitherLib)
    implementation(libs.androidx.exifinterface)
    implementation(libs.androidx.lifecycle.runtime.ktx)
    implementation(libs.androidx.activity.compose)
    implementation(platform(libs.androidx.compose.bom))
    implementation(libs.androidx.ui)
    implementation(libs.androidx.ui.graphics)
    implementation(libs.androidx.ui.tooling.preview)
    implementation(libs.androidx.material3)
    implementation(libs.reorderable)
    androidTestImplementation(platform(libs.androidx.compose.bom))
    androidTestImplementation(libs.androidx.ui.test.junit4)
    debugImplementation(libs.androidx.ui.tooling)
    debugImplementation(libs.androidx.ui.test.manifest)
}

afterEvaluate {
    val spotlessCheck = tasks.named("spotlessCheck")
    if (spotlessCheck.isPresent) {
        tasks.withType<JavaCompile>().configureEach {
            finalizedBy(spotlessCheck)
        }
    }
}


================================================
FILE: app/code-format.xml
================================================
<!--
  ~ Copyright (c) 2022 2bllw8
  ~ SPDX-License-Identifier: GPL-3.0-only
  -->

<profiles version="15">
    <profile kind="CodeFormatterProfile" name="CodeStyle" version="15">
        <setting id="org.eclipse.jdt.core.formatter.disabling_tag" value="@formatter:off"/>
        <setting id="org.eclipse.jdt.core.formatter.use_on_off_tags" value="true"/>
        <setting id="org.eclipse.jdt.core.formatter.comment.line_length" value="100"/>
        <setting id="org.eclipse.jdt.core.formatter.lineSplit" value="100"/>
        <setting id="org.eclipse.jdt.core.formatter.indentation.size" value="4"/>
        <setting id="org.eclipse.jdt.core.formatter.tabulation.char" value="space"/>
        <setting id="org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation" value="80" />
    </profile>
</profiles>


================================================
FILE: app/proguard-rules.pro
================================================
-assumenosideeffects class android.util.Log {
    public static *** v(...);
    public static *** d(...);
}

-repackageclasses
-allowaccessmodification
-overloadaggressively


================================================
FILE: app/src/main/AndroidManifest.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.USE_BIOMETRIC" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
        tools:ignore="ScopedStorage" />


    <queries>
        <package android:name="com.android.documentsui" />
        <package android:name="com.google.android.documentsui" />
    </queries>

    <application
        android:allowBackup="true"
        android:allowClearUserData="false"
        android:appCategory="productivity"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        tools:targetApi="s">
        <activity
            android:name=".config.StorageConfigActivity"
            android:exported="false"
            android:label="@string/title_activity_storage_pref"
            android:theme="@style/Theme.Anemoaer">
            <intent-filter>
                <action android:name="alt.nainapps.aer.STORAGE_CONFIG" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <!-- Shell -->
        <activity
            android:name=".shell.LauncherActivity"
            android:excludeFromRecents="true"
            android:exported="true"
            android:stateNotNeeded="true"
            android:theme="@android:style/Theme.NoDisplay">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <meta-data
                android:name="android.app.shortcuts"
                android:resource="@xml/shortcuts" />
        </activity> <!-- Configuration -->
        <activity
            android:name=".config.ConfigurationActivity"
            android:exported="true"
            android:label="@string/configuration_label"
            android:theme="@style/AppTheme">
            <intent-filter>
                <action android:name="android.intent.action.APPLICATION_PREFERENCES" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
            </intent-filter>
        </activity> <!-- Lock -->
        <service
            android:name=".lock.AutoLockJobService"
            android:exported="false"
            android:permission="android.permission.BIND_JOB_SERVICE" />
        <service
            android:name=".lock.LockTileService"
            android:exported="true"
            android:icon="@drawable/ic_key_tile"
            android:label="@string/tile_title"
            android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
            <intent-filter>
                <action android:name="android.service.quicksettings.action.QS_TILE" />
            </intent-filter>
        </service> <!-- Password -->
        <activity
            android:name=".lock.UnlockActivity"
            android:excludeFromRecents="true"
            android:label="@string/password_label"
            android:theme="@style/DialogTheme" /> <!-- Provider -->
        <provider
            android:name=".documents.provider.AnemoDocumentProvider"
            android:authorities="alt.nainapps.aer.documents"
            android:enabled="true"
            android:exported="true"
            android:grantUriPermissions="true"
            android:permission="android.permission.MANAGE_DOCUMENTS">
            <intent-filter>
                <action android:name="android.content.action.DOCUMENTS_PROVIDER" />
            </intent-filter>
        </provider> <!-- Receiver -->
        <activity
            android:name=".documents.receiver.ReceiverActivity"
            android:configChanges=""
            android:excludeFromRecents="true"
            android:exported="true"
            android:label="@string/receiver_label"
            android:stateNotNeeded="true"
            android:theme="@android:style/Theme.Translucent.NoTitleBar">
            <intent-filter>
                <action android:name="android.intent.action.SEND" />

                <category android:name="android.intent.category.DEFAULT" />

                <data android:mimeType="application/*" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.SEND" />

                <category android:name="android.intent.category.DEFAULT" />

                <data android:mimeType="audio/*" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.SEND" />

                <category android:name="android.intent.category.DEFAULT" />

                <data android:mimeType="image/*" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.SEND" />

                <category android:name="android.intent.category.DEFAULT" />

                <data android:mimeType="video/*" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.SEND" />

                <category android:name="android.intent.category.DEFAULT" />

                <data android:mimeType="text/*" />
            </intent-filter>
        </activity>
    </application>

</manifest>

================================================
FILE: app/src/main/java/alt/nainapps/aer/config/ConfigurationActivity.kt
================================================
/*
 * Copyright (c) 2022 2bllw8
 * Copyright (c) 2024 nain
 * SPDX-License-Identifier: GPL-3.0-only
 */
package alt.nainapps.aer.config

import alt.nainapps.aer.R
import alt.nainapps.aer.config.autolock.buildValidatedAutoLockDelayListener
import alt.nainapps.aer.config.password.ChangePasswordDialog
import alt.nainapps.aer.config.password.SetPasswordDialog
import alt.nainapps.aer.lock.LockStore
import alt.nainapps.aer.lock.UnlockActivity
import alt.nainapps.aer.shell.AnemoShell
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.view.View
import android.widget.CompoundButton
import android.widget.EditText
import android.widget.Switch
import android.widget.TextView
import java.util.function.Consumer

class ConfigurationActivity : Activity() {
    private var passwordSetView: TextView? = null
    private var changeLockView: TextView? = null
    private var biometricSwitch: Switch? = null

    private lateinit var lockStore: LockStore

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        lockStore = LockStore.getInstance(applicationContext)!!
        lockStore.addListener(onLockChanged)

        setContentView(R.layout.configuration)

        passwordSetView = findViewById(R.id.configuration_password_set)

        val shortcutSwitch = findViewById<Switch>(R.id.configuration_show_shortcut)
        shortcutSwitch.isChecked = AnemoShell.isEnabled(application)
        shortcutSwitch.setOnCheckedChangeListener { _: CompoundButton?, isChecked: Boolean ->
            AnemoShell.setEnabled(
                application,
                isChecked,
            )
        }

        changeLockView = findViewById(R.id.configuration_lock)
        changeLockView!!.setText(
            if (lockStore.isLocked
            ) {
                R.string.configuration_storage_unlock
            } else {
                R.string.configuration_storage_lock
            },
        )
        changeLockView!!.setOnClickListener {
            if (lockStore.isLocked) {
                startActivity(Intent(this, UnlockActivity::class.java))
            } else {
                lockStore.lock()
            }
        }

        val autoLockSwitch = findViewById<Switch>(R.id.configuration_auto_lock)
        autoLockSwitch.isChecked = lockStore.isAutoLockEnabled
        autoLockSwitch.setOnCheckedChangeListener { _: CompoundButton?, isChecked: Boolean ->
            lockStore.isAutoLockEnabled = isChecked
        }

        val autoLockDelayMinutesEditable = findViewById<EditText>(R.id.config_auto_lock_delay_minutes)
        autoLockDelayMinutesEditable.text = Editable.Factory.getInstance().newEditable(
            lockStore.autoLockDelayMinutes.toString()
        )
        val autoLockDelayListener = buildValidatedAutoLockDelayListener(this.baseContext, lockStore, autoLockDelayMinutesEditable)
        autoLockDelayMinutesEditable.addTextChangedListener(autoLockDelayListener)

        biometricSwitch = findViewById(R.id.configuration_biometric_unlock)
        biometricSwitch!!.visibility = if (lockStore.canAuthenticateBiometric()) View.VISIBLE else View.GONE
        biometricSwitch!!.isChecked = lockStore.isBiometricUnlockEnabled
        biometricSwitch!!.setOnCheckedChangeListener { _: CompoundButton?, isChecked: Boolean ->
            lockStore.isBiometricUnlockEnabled = isChecked
        }

        setupPasswordViews()
    }

    override fun onDestroy() {
        super.onDestroy()
        lockStore.removeListener(onLockChanged)
    }

    private fun setupPasswordViews() {
        if (lockStore.hasPassword()) {
            passwordSetView!!.setText(R.string.configuration_password_change)
            passwordSetView!!.setOnClickListener {
                ChangePasswordDialog(
                    this,
                    lockStore,
                ) { this.setupPasswordViews() }
                    .show()
            }
        } else {
            passwordSetView!!.setText(R.string.configuration_password_set)
            passwordSetView!!.setOnClickListener {
                SetPasswordDialog(
                    this,
                    lockStore,
                ) { this.setupPasswordViews() }.show()
            }
        }
        val enableViews = !lockStore.isLocked
        passwordSetView!!.isEnabled = enableViews
        biometricSwitch!!.isEnabled = enableViews
    }

    private val onLockChanged =
        Consumer { isLocked: Boolean ->
            passwordSetView!!.isEnabled = !isLocked
            biometricSwitch!!.isEnabled = !isLocked
            changeLockView!!.setText(
                if (isLocked
                ) {
                    R.string.configuration_storage_unlock
                } else {
                    R.string.configuration_storage_lock
                },
            )
        }
}

================================================
FILE: app/src/main/java/alt/nainapps/aer/config/StorageConfigActivity.kt
================================================
package alt.nainapps.aer.config

import alt.nainapps.aer.R
import alt.nainapps.aer.config.ui.theme.AnemoaerTheme
import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
import android.os.Bundle
import android.os.Environment
import android.os.StatFs
import android.preference.PreferenceManager.getDefaultSharedPreferences
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.sizeIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.rounded.List
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SuggestionChip
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import sh.calvin.reorderable.ReorderableItem
import sh.calvin.reorderable.rememberReorderableLazyListState
import java.io.File

class StorageConfigActivity : ComponentActivity() {

    @OptIn(ExperimentalMaterial3Api::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        // At the top level of your kotlin file:
        val sharedPrefs = getDefaultSharedPreferences(this)
        setContent {
            AnemoaerTheme {
                Scaffold(modifier = Modifier.fillMaxSize(),
                        topBar = {
                    TopAppBar(
                        title = {
                            // Text("Aer Storage Backend priority")
                            Text(stringResource(R.string.storage_config_screen_title))
                        }
                    )
                }) { innerPadding ->
                    var selectedStorageDir by rememberSaveable { mutableStateOf(getPreferredStorageDir(sharedPrefs)) }
                    var storageInfos = fetchExternalStorageDirectories(this.applicationContext)
                    val internalStorageInfo =  StorageInfo(
                        filesDir.toString(),
                        getTotalSpace(filesDir),
                        getFreeSpace(filesDir),
                        isEmulated = false,
                        isRemoveAble = false,
                        isInternal = true
                    )
                    storageInfos = listOf(*storageInfos.toTypedArray(), internalStorageInfo)

                    Column (Modifier.padding(paddingValues = innerPadding)) {
                        selectedStorageDir?.let {
                            Card(modifier = Modifier.padding(8.dp)) {
                                Text(
                                    text = "Selected: $it",
                                    modifier = Modifier.padding(8.dp)
                                )
                            }
                        }

                        Text(
                            text = stringResource(R.string.storage_config_select_help),
                            fontStyle = FontStyle.Italic,
                            modifier = Modifier.padding(8.dp)
                        )

                        StorageInfoListReorderable(storageInfos, sharedPrefs) {
                            selected -> selectedStorageDir = selected
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun StorageInfoList(storageInfos: List<StorageInfo>) {
    Log.i("live", "about to begin")
    Column(modifier = Modifier.padding(16.dp)) {
        for (info in storageInfos) {
            Log.i("live", "$info")
            Card(modifier = Modifier.padding(8.dp)) {
                Text(text = info.dir)
                Text(text = "Total Space: ${ bytesToHumanReadableSize(info.totalSpace) }")
                Text(text = "Free Space: ${ bytesToHumanReadableSize(info.freeSpace) }")
                Text(text = "Is Emulated: ${if (info.isEmulated) "Yes" else "No"}")
            }
        }
    }
}



@OptIn(ExperimentalFoundationApi::class)
@Composable
fun StorageInfoListReorderable(storageInfos: List<StorageInfo>, sharedPrefs: SharedPreferences,
                               onFreshStorageSelect: (String?) -> Unit) {
    val mutableStorageInfosList = remember { mutableStateListOf(*storageInfos.toTypedArray()) }
    val lazyListState = rememberLazyListState()
    val reorderableLazyListState =
        rememberReorderableLazyListState(lazyListState) { from, to ->
            mutableStorageInfosList.apply { add(to.index, removeAt(from.index)) }
            if (to.index == 0  || from.index == 0 ) {
                // Save it to settings
                savePreferredStorageDir(sharedPrefs, mutableStorageInfosList.first().dir)
                // callback to let parent compose update
                onFreshStorageSelect(getPreferredStorageDir(sharedPrefs))
            }
        }
    LazyColumn(
        state = lazyListState,
        verticalArrangement = Arrangement.spacedBy(8.dp),
    ) {
        items(mutableStorageInfosList, key = { it.dir }) { info ->
            ReorderableItem(reorderableLazyListState, key = info.dir) {
                val interactionSource = remember { MutableInteractionSource() }
                val longPressDraggable = Modifier.longPressDraggableHandle(interactionSource = interactionSource)
                val draggable = Modifier.draggableHandle(interactionSource = interactionSource)
                StorageInfoCard(info = info, longPressDraggable, draggable) {
                    savePreferredStorageDir(sharedPrefs, info.dir)
                    onFreshStorageSelect(getPreferredStorageDir(sharedPrefs))
                }
            }
        }
    }
}

// Pass either longPressDraggableModifier or draggableModifier to make it draggable
@Composable
fun StorageInfoCard(
    info: StorageInfo,
    @SuppressLint("ModifierParameter")
    longPressDraggableModifier: Modifier? = null,
    draggableModifier: Modifier? = null,
    onClick: () -> Unit = {}
) {
    Card(onClick = onClick, modifier = (longPressDraggableModifier ?: Modifier).padding(horizontal = 8.dp)) {
        Row (Modifier.padding(4.dp)) {
            (draggableModifier ?: longPressDraggableModifier)?.let {
                IconButton( modifier = it, onClick = {}) {
                    Icon(Icons.AutoMirrored.Rounded.List, contentDescription = "Reorder")
                }
            }

            Column {
                Row (
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Text(text = if (info.isInternal) "Internal" else "External", fontWeight = FontWeight.Bold )
                    Row {
                        if (info.isRemoveAble) {
                            SuggestionChip(
                                onClick = { },
                                modifier = Modifier.sizeIn(maxHeight = 20.dp).padding(horizontal = 2.dp),
                                label = { Text(text = "Removable", fontSize = 10.sp)}

                            )
                        }
                        if (info.isEmulated) {
                            SuggestionChip(
                                onClick = { },
                                modifier = Modifier.sizeIn(maxHeight = 20.dp).padding(horizontal = 2.dp),
                                label = { Text(text = "Emulated", fontSize = 10.sp )}
                            )
                        }
                    }

                }
                val totalSpace = bytesToHumanReadableSize(info.totalSpace)
                val freeSpace = bytesToHumanReadableSize(info.freeSpace)
                Column (Modifier.padding(vertical = 4.dp)) {
                    Text(text = info.dir, fontWeight = FontWeight.Medium)
                    Text(text = "Total Space: $totalSpace")
                    Text(text = "Free Space: $freeSpace")
                    Spacer(Modifier.size(2.dp))
                }


            }
        }
    }

}

//@Composable
//fun DraggableHandleIcon(draggableModifier: Modifier) {
//    IconButton(
//        modifier = draggableModifier,
//        onClick = {},
//    ) {
//        Icon(Icons.Rounded.Menu, contentDescription = "Reorder")
//    }
//}

data class StorageInfo(
    val dir: String,
    val totalSpace: Long,
    val freeSpace: Long,
    val isEmulated: Boolean,
    val isRemoveAble: Boolean,
    val isInternal: Boolean
)

fun fetchExternalStorageDirectories(context: Context): List<StorageInfo> {
    val directories = mutableListOf<StorageInfo>()
    val externalDirs = context.getExternalFilesDirs(null)

    for (dir in externalDirs.reversed()) {
        if (dir != null) {
            val totalSpace = getTotalSpace(dir)
            val freeSpace = getFreeSpace(dir)

            val isEmulated = Environment.isExternalStorageEmulated(dir)
            val isRemovable = Environment.isExternalStorageRemovable(dir)
            val isInternal = false

            directories.add(StorageInfo(dir.path, totalSpace, freeSpace, isEmulated, isRemovable, isInternal))
        }
    }

    return directories
}

private fun getTotalSpace(path: File): Long {
    val statFs = StatFs(path.absolutePath)
    return statFs.blockCountLong * statFs.blockSizeLong
}

private fun getFreeSpace(path: File): Long {
    val statFs = StatFs(path.absolutePath)
    return statFs.availableBlocksLong * statFs.blockSizeLong
}

fun bytesToHumanReadableSize(bytes: Long) =
    when {
        bytes >= 1 shl 30 -> "%.1f GB".format(bytes.toDouble() / (1 shl 30))
        bytes >= 1 shl 20 -> "%.1f MB".format(bytes.toDouble() / (1 shl 20))
        bytes >= 1 shl 10 -> "%.0f kB".format(bytes.toDouble() / (1 shl 10))
        else -> "$bytes bytes"
    }

fun savePreferredStorageDir(sharedPrefs: SharedPreferences, dir: String) {
    with (sharedPrefs.edit()) {
        putString("selected_storage_dir", dir)
        apply()
    }
}

fun getPreferredStorageDir(sharedPrefs: SharedPreferences): String? {
    return sharedPrefs.getString("selected_storage_dir", null)
}

@Composable
fun Greeting(
    name: String,
    modifier: Modifier = Modifier,
) {
    Text(
        text = "Hello $name!",
        modifier = modifier,
    )
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    AnemoaerTheme {
        Greeting("Android")
    }
}


================================================
FILE: app/src/main/java/alt/nainapps/aer/config/autolock/AutoLockDelayMinutesTextListener.kt
================================================
/*
 * Copyright (c) 2024 nain
 * SPDX-License-Identifier: GPL-3.0-only
 */

package alt.nainapps.aer.config.autolock

import alt.nainapps.aer.R
import alt.nainapps.aer.lock.LockStore
import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText

fun interface AutoLockDelayMinutesTextListener : TextWatcher {

    override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
    }
    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
    }
    override fun afterTextChanged(s: Editable) {
        afterTextChanged(s.toString())
    }
    // this will be provided as lambda
    fun afterTextChanged(text: String)
}

fun buildValidatedAutoLockDelayListener(context: Context, lockstore: LockStore, input: EditText): AutoLockDelayMinutesTextListener {
    return AutoLockDelayMinutesTextListener { text ->
        // validate text isNumber
        try {
            text.toLong()
        } catch (error: NumberFormatException) {
            input.setError("NaN: Not a Number",
                context.getDrawable(R.drawable.ic_error))
            return@AutoLockDelayMinutesTextListener
        }
        val minutes: Long = text.toLong()
        // validate not zero
        if (minutes == 0L) {
            input.setError("Auto lock delay can't be zero",
                context.getDrawable(R.drawable.ic_error))
        }
        lockstore.autoLockDelayMinutes = minutes
    }
}

================================================
FILE: app/src/main/java/alt/nainapps/aer/config/password/ChangePasswordDialog.kt
================================================
/*
 * Copyright (c) 2021 2bllw8
 * SPDX-License-Identifier: GPL-3.0-only
 */
package alt.nainapps.aer.config.password

import alt.nainapps.aer.R
import alt.nainapps.aer.lock.LockStore
import android.app.Activity
import android.content.DialogInterface
import android.view.View
import android.widget.Button
import android.widget.EditText

class ChangePasswordDialog(activity: Activity, lockStore: LockStore, onSuccess: Runnable) :
    PasswordDialog(
        activity, lockStore, onSuccess, R.string.password_change_title,
        R.layout.password_change
    ) {
    override fun build() {
        val currentField = dialog.findViewById<EditText>(R.id.currentFieldView)
        val passwordField = dialog.findViewById<EditText>(R.id.passwordFieldView)
        val repeatField = dialog.findViewById<EditText>(R.id.repeatFieldView)
        val positiveBtn = dialog.getButton(DialogInterface.BUTTON_POSITIVE)
        val neutralBtn = dialog.getButton(DialogInterface.BUTTON_NEUTRAL)

        val validator = buildTextListener(passwordField, repeatField, positiveBtn)
        passwordField.addTextChangedListener(validator)
        repeatField.addTextChangedListener(validator)

        positiveBtn.visibility = View.VISIBLE
        positiveBtn.setText(R.string.password_change_action)
        positiveBtn.isEnabled = false
        positiveBtn.setOnClickListener { v: View? ->
            val currentPassword = currentField.text.toString()
            val newPassword = passwordField.text.toString()
            if (lockStore.passwordMatch(currentPassword)) {
                if (lockStore.setPassword(newPassword)) {
                    dismiss()
                    lockStore.unlock()
                    onSuccess.run()
                }
            } else {
                currentField.setError(res.getString(R.string.password_error_wrong), errorIcon)
            }
        }

        neutralBtn.visibility = View.VISIBLE
        neutralBtn.setText(R.string.password_change_remove)
        neutralBtn.setOnClickListener { v: View? ->
            lockStore.removePassword()
            onSuccess.run()
            dismiss()
        }
    }

    private fun buildTextListener(
        passwordField: EditText, repeatField: EditText,
        positiveBtn: Button
    ): PasswordTextListener {
        return PasswordTextListener {
            val passwordValue = passwordField.text.toString()
            val repeatValue = repeatField.text.toString()
            if (passwordValue.length < MIN_PASSWORD_LENGTH) {
                positiveBtn.isEnabled = false
                passwordField.setError(
                    res.getString(R.string.password_error_length, MIN_PASSWORD_LENGTH),
                    errorIcon
                )
                repeatField.error = null
            } else if (passwordValue != repeatValue) {
                positiveBtn.isEnabled = false
                passwordField.error = null
                repeatField.setError(
                    res.getString(R.string.password_error_mismatch),
                    errorIcon
                )
            } else {
                positiveBtn.isEnabled = true
                passwordField.error = null
                repeatField.error = null
            }
        }
    }
}


================================================
FILE: app/src/main/java/alt/nainapps/aer/config/password/PasswordDialog.kt
================================================
/*
 * Copyright (c) 2021 2bllw8
 * SPDX-License-Identifier: GPL-3.0-only
 */
package alt.nainapps.aer.config.password

import alt.nainapps.aer.R
import alt.nainapps.aer.lock.LockStore
import android.app.Activity
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.res.Resources
import android.graphics.drawable.Drawable
import androidx.annotation.LayoutRes
import androidx.annotation.StringRes

abstract class PasswordDialog(
    activity: Activity, @JvmField protected val lockStore: LockStore, @JvmField protected val onSuccess: Runnable,
    @StringRes title: Int, @LayoutRes layout: Int
) {
    @JvmField
    protected val res: Resources = activity.resources
    @JvmField
    protected val dialog: AlertDialog
    @JvmField
    protected val MIN_PASSWORD_LENGTH: Int = 4

    init {
        this.dialog = AlertDialog.Builder(activity, R.style.DialogTheme).setTitle(title)
            .setView(layout)
            .setCancelable(false)
            .setNegativeButton(android.R.string.cancel) { d: DialogInterface?, which: Int -> dismiss() }
            .create()
    }

    fun dismiss() {
        if (dialog.isShowing) {
            dialog.dismiss()
        }
    }

    fun show() {
        dialog.show()
        build()
    }

    protected val errorIcon: Drawable
        get() {
            val drawable = dialog.context.getDrawable(R.drawable.ic_error)
            drawable!!.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
            return drawable
        }

    protected abstract fun build()
}


================================================
FILE: app/src/main/java/alt/nainapps/aer/config/password/PasswordTextListener.kt
================================================
/*
 * Copyright (c) 2022 2bllw8
 * SPDX-License-Identifier: GPL-3.0-only
 */
package alt.nainapps.aer.config.password

import android.text.Editable
import android.text.TextWatcher

fun interface PasswordTextListener : TextWatcher {
    override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
    }

    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
    }

    override fun afterTextChanged(s: Editable) {
        onTextChanged(s.toString())
    }

    fun onTextChanged(text: String?)
}


================================================
FILE: app/src/main/java/alt/nainapps/aer/config/password/SetPasswordDialog.kt
================================================
/*
 * Copyright (c) 2021 2bllw8
 * SPDX-License-Identifier: GPL-3.0-only
 */
package alt.nainapps.aer.config.password

import alt.nainapps.aer.R
import alt.nainapps.aer.lock.LockStore
import android.app.Activity
import android.content.DialogInterface
import android.view.View
import android.widget.Button
import android.widget.EditText

class SetPasswordDialog(activity: Activity, lockStore: LockStore, onSuccess: Runnable) :
    PasswordDialog(
        activity, lockStore, onSuccess, R.string.password_set_title,
        R.layout.password_first_set
    ) {
    override fun build() {
        val passwordField = dialog.findViewById<EditText>(R.id.passwordFieldView)
        val repeatField = dialog.findViewById<EditText>(R.id.repeatFieldView)
        val positiveBtn = dialog.getButton(DialogInterface.BUTTON_POSITIVE)

        val validator = buildValidator(passwordField, repeatField, positiveBtn)
        passwordField.addTextChangedListener(validator)
        repeatField.addTextChangedListener(validator)

        positiveBtn.visibility = View.VISIBLE
        positiveBtn.setText(R.string.password_set_action)
        positiveBtn.isEnabled = false
        positiveBtn.setOnClickListener { v: View? ->
            val passwordValue = passwordField.text.toString()
            if (lockStore.setPassword(passwordValue)) {
                dismiss()
                lockStore.unlock()
                onSuccess.run()
            }
        }
    }

    private fun buildValidator(
        passwordField: EditText, repeatField: EditText,
        positiveBtn: Button
    ): PasswordTextListener {
        return PasswordTextListener {
            val passwordValue = passwordField.text.toString()
            val repeatValue = repeatField.text.toString()
            if (passwordValue.length < MIN_PASSWORD_LENGTH) {
                positiveBtn.isEnabled = false
                passwordField.setError(
                    res.getString(R.string.password_error_length, MIN_PASSWORD_LENGTH),
                    errorIcon
                )
                repeatField.error = null
            } else if (passwordValue != repeatValue) {
                positiveBtn.isEnabled = false
                passwordField.error = null
                repeatField.setError(
                    res.getString(R.string.password_error_mismatch),
                    errorIcon
                )
            } else {
                positiveBtn.isEnabled = true
                passwordField.error = null
                repeatField.error = null
            }
        }
    }
}


================================================
FILE: app/src/main/java/alt/nainapps/aer/config/ui/theme/Color.kt
================================================
package alt.nainapps.aer.config.ui.theme

import androidx.compose.ui.graphics.Color

val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)

val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)

================================================
FILE: app/src/main/java/alt/nainapps/aer/config/ui/theme/Theme.kt
================================================
package alt.nainapps.aer.config.ui.theme

import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext

private val DarkColorScheme = darkColorScheme(
    primary = Purple80,
    secondary = PurpleGrey80,
    tertiary = Pink80
)

private val LightColorScheme = lightColorScheme(
    primary = Purple40,
    secondary = PurpleGrey40,
    tertiary = Pink40

    /* Other default colors to override
    background = Color(0xFFFFFBFE),
    surface = Color(0xFFFFFBFE),
    onPrimary = Color.White,
    onSecondary = Color.White,
    onTertiary = Color.White,
    onBackground = Color(0xFF1C1B1F),
    onSurface = Color(0xFF1C1B1F),
    */
)

@Composable
fun AnemoaerTheme(
    darkTheme: Boolean = isSystemInDarkTheme(),
    // Dynamic color is available on Android 12+
    dynamicColor: Boolean = true,
    content: @Composable () -> Unit
) {
    val colorScheme = when {
        dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
            val context = LocalContext.current
            if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
        }

        darkTheme -> DarkColorScheme
        else -> LightColorScheme
    }

    MaterialTheme(
        colorScheme = colorScheme,
        typography = Typography,
        content = content
    )
}

================================================
FILE: app/src/main/java/alt/nainapps/aer/config/ui/theme/Type.kt
================================================
package alt.nainapps.aer.config.ui.theme

import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp

// Set of Material typography styles to start with
val Typography = Typography(
    bodyLarge = TextStyle(
        fontFamily = FontFamily.Default,
        fontWeight = FontWeight.Normal,
        fontSize = 16.sp,
        lineHeight = 24.sp,
        letterSpacing = 0.5.sp
    )
    /* Other default text styles to override
    titleLarge = TextStyle(
        fontFamily = FontFamily.Default,
        fontWeight = FontWeight.Normal,
        fontSize = 22.sp,
        lineHeight = 28.sp,
        letterSpacing = 0.sp
    ),
    labelSmall = TextStyle(
        fontFamily = FontFamily.Default,
        fontWeight = FontWeight.Medium,
        fontSize = 11.sp,
        lineHeight = 16.sp,
        letterSpacing = 0.5.sp
    )
    */
)

================================================
FILE: app/src/main/java/alt/nainapps/aer/documents/home/HomeEnvironment.kt
================================================
/*
 * Copyright (c) 2021 2bllw8
 * SPDX-License-Identifier: GPL-3.0-only
 */
package alt.nainapps.aer.documents.home

import android.content.Context
import android.os.Build
import android.os.Environment
import android.preference.PreferenceManager.getDefaultSharedPreferences
import java.io.File
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import kotlin.concurrent.Volatile

class HomeEnvironment private constructor(
    context: Context,
) {
    val baseDir: Path =
            getPreferredStorageFilesDir(context)?.toPath() // manual config
                ?: getSelectExternalFilesDir(context)?.toPath()
                ?: context.filesDir.toPath() // internal

    init {
        if (!Files.exists(baseDir)) {
            Files.createDirectory(baseDir)
        } else if (!Files.isDirectory(baseDir)) {
            throw IOException("$baseDir is not a directory")
        }
    }

    fun isRoot(path: Path): Boolean = baseDir == path

    private fun getPreferredStorageFilesDir(context: Context): File? {
        val sharedPrefs = getDefaultSharedPreferences(context)
        return sharedPrefs.getString("selected_storage_dir",null)?.let {
            File(it)
        }
    }

    private fun getSelectExternalFilesDir(context: Context): File? {
        // Below Android 11 (API 30) we do not prefer external storage
        // as privacy of external filedir is guaranteed from Android 11 only.
        // https://developer.android.com/about/versions/11/privacy/storage#other-app-specific-dirs
        if (Build.VERSION.SDK_INT < 30) {
            return null
        }
        val externalFilesDirs = context.getExternalFilesDirs(null)
        // The first few (in forward order) may be on primary storage,
        // so we traverse in reverse order to find first available externalFilesDir
        for (i in externalFilesDirs.indices.reversed()) {
            if (externalFilesDirs[i] != null) {
                if (Environment.getExternalStorageState(externalFilesDirs[i]) == Environment.MEDIA_MOUNTED) {
                    return externalFilesDirs[i]
                }
            }
        }
        return null
    }

    companion object {
        const val AUTHORITY: String = "alt.nainapps.aer.documents"
        const val ROOT: String = "alt.nainapps.aer.documents.root"
        const val ROOT_DOC_ID: String = "aer_root"

        @Volatile
        private var instance: HomeEnvironment? = null

        @Throws(IOException::class)
        fun getInstance(context: Context): HomeEnvironment? {
            if (instance == null) {
                synchronized(HomeEnvironment::class.java) {
                    if (instance == null) {
                        instance = HomeEnvironment(context.applicationContext)
                    }
                }
            }
            return instance
        }
    }
}


================================================
FILE: app/src/main/java/alt/nainapps/aer/documents/provider/AnemoDocumentProvider.kt
================================================
/*
 * Copyright (c) 2021 2bllw8
 * SPDX-License-Identifier: GPL-3.0-only
 */
package alt.nainapps.aer.documents.provider

import alt.nainapps.aer.R
import alt.nainapps.aer.documents.home.HomeEnvironment
import alt.nainapps.aer.documents.home.HomeEnvironment.Companion.getInstance
import alt.nainapps.aer.lock.LockStore
import alt.nainapps.aer.lock.UnlockActivity
import android.app.AuthenticationRequiredException
import android.app.PendingIntent
import android.content.Intent
import android.content.res.AssetFileDescriptor
import android.database.Cursor
import android.database.MatrixCursor
import android.graphics.Point
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.CancellationSignal
import android.os.ParcelFileDescriptor
import android.provider.DocumentsContract
import android.provider.DocumentsContract.Root
import android.util.Log
import exe.bbllw8.either.Failure
import exe.bbllw8.either.Success
import exe.bbllw8.either.Try
import java.io.FileNotFoundException
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.function.Consumer

class AnemoDocumentProvider : FileSystemProvider() {
    private var homeEnvironment: HomeEnvironment? = null
    private var lockStore: LockStore? = null

    private var showInfo = true

    override fun onCreate(): Boolean {
        if (!super.onCreate()) {
            return false
        }

        val context = context
        lockStore = context?.let { LockStore.getInstance(it) }
        lockStore!!.addListener(onLockChanged)

        return Try
            .from {
                getInstance(
                    context!!,
                )
            }.fold(
                { failure: Throwable? ->
                    Log.e(TAG, "Failed to setup", failure)
                    false
                },
                { homeEnvironment: HomeEnvironment? ->
                    this.homeEnvironment = homeEnvironment
                    true
                },
            )
    }

    override fun shutdown() {
        lockStore!!.removeListener(onLockChanged)
        super.shutdown()
    }

    override fun queryRoots(projection: Array<String?>?): Cursor {
        if (lockStore!!.isLocked) {
            return EmptyCursor()
        }

        val context = context
        val result = MatrixCursor(resolveRootProjection(projection))
        val row = result.newRow()

        var flags = Root.FLAG_LOCAL_ONLY
        flags = flags or Root.FLAG_SUPPORTS_CREATE
        flags = flags or Root.FLAG_SUPPORTS_IS_CHILD
        flags = flags or Root.FLAG_SUPPORTS_EJECT
        if (Build.VERSION.SDK_INT >= 29) {
            flags = flags or Root.FLAG_SUPPORTS_SEARCH
        }

        row
            .add(Root.COLUMN_ROOT_ID, HomeEnvironment.ROOT)
            .add(Root.COLUMN_DOCUMENT_ID, HomeEnvironment.ROOT_DOC_ID)
            .add(Root.COLUMN_FLAGS, flags)
            .add(Root.COLUMN_ICON, R.drawable.ic_storage)
            .add(Root.COLUMN_TITLE, context!!.getString(R.string.app_name))
            .add(
                Root.COLUMN_SUMMARY,
                context.getString(R.string.anemo_description),
            )
        return result
    }

    @Throws(FileNotFoundException::class)
    override fun queryChildDocuments(
        parentDocumentId: String,
        projection: Array<String?>?,
        sortOrder: String?,
    ): Cursor {
        if (lockStore!!.isLocked) {
            return EmptyCursor()
        }

        val c = super.queryChildDocuments(parentDocumentId, projection, sortOrder)
        if (showInfo && HomeEnvironment.ROOT_DOC_ID == parentDocumentId) {
            // Hide from now on
            // showInfo = false
            // Show info in root dir
            val extras = Bundle()
            extras.putCharSequence(
                DocumentsContract.EXTRA_INFO,
                context!!.getText(R.string.anemo_info),
            )
            // If below Android 11 warn about reduced privacy of external storage
            if (Build.VERSION.SDK_INT < 30) {
                val baseDir = homeEnvironment?.baseDir?.toFile()
                val externalDirs = context!!.getExternalFilesDirs(null)
                if (baseDir in externalDirs) {
                    extras.remove(DocumentsContract.EXTRA_INFO)
                    extras.putCharSequence(
                        DocumentsContract.EXTRA_ERROR,
                        context!!.getText(R.string.anemo_error),
                    )
                }
            }
            c.extras = extras
        }
        return c
    }

    @Throws(FileNotFoundException::class)
    override fun queryDocument(
        documentId: String,
        projection: Array<String?>?,
    ): Cursor =
        if (lockStore!!.isLocked) {
            EmptyCursor()
        } else {
            super.queryDocument(documentId, projection)
        }

    @Throws(FileNotFoundException::class)
    override fun querySearchDocuments(
        rootId: String,
        projection: Array<String?>?,
        queryArgs: Bundle,
    ): Cursor? =
        if (lockStore!!.isLocked) {
            EmptyCursor()
        } else {
            super.querySearchDocuments(rootId, projection, queryArgs)
        }

    override fun findDocumentPath(
        parentDocumentId: String?,
        childDocumentId: String,
    ): DocumentsContract.Path =
        if (lockStore!!.isLocked) {
            DocumentsContract.Path(null, emptyList())
        } else {
            super.findDocumentPath(parentDocumentId, childDocumentId)
        }

    @Throws(FileNotFoundException::class)
    override fun openDocument(
        documentId: String,
        mode: String,
        signal: CancellationSignal?,
    ): ParcelFileDescriptor {
        assertUnlocked()
        return super.openDocument(documentId, mode, signal)
    }

    @Throws(FileNotFoundException::class)
    override fun openDocumentThumbnail(
        docId: String,
        sizeHint: Point,
        signal: CancellationSignal,
    ): AssetFileDescriptor {
        assertUnlocked()
        return super.openDocumentThumbnail(docId, sizeHint, signal)
    }

    override fun createDocument(
        parentDocumentId: String,
        mimeType: String,
        displayName: String,
    ): String {
        assertUnlocked()
        return super.createDocument(parentDocumentId, mimeType, displayName)
    }

    override fun deleteDocument(documentId: String) {
        assertUnlocked()
        super.deleteDocument(documentId)
    }

    override fun removeDocument(
        documentId: String,
        parentDocumentId: String,
    ) {
        deleteDocument(documentId)
    }

//    @Throws(FileNotFoundException::class)
    override fun copyDocument(
        sourceDocumentId: String,
        targetParentDocumentId: String,
    ): String {
        assertUnlocked()
        return super.copyDocument(sourceDocumentId, targetParentDocumentId)
    }

    override fun moveDocument(
        sourceDocumentId: String,
        sourceParentDocumentId: String,
        targetParentDocumentId: String,
    ): String {
        assertUnlocked()
        return super.moveDocument(sourceDocumentId, sourceParentDocumentId, targetParentDocumentId)
    }

    override fun renameDocument(
        documentId: String,
        displayName: String,
    ): String {
        assertUnlocked()
        return super.renameDocument(documentId, displayName)
    }

    override fun ejectRoot(rootId: String) {
        if (HomeEnvironment.ROOT == rootId) {
            lockStore!!.lock()
        }
    }

    override fun buildNotificationUri(docId: String?): Uri = DocumentsContract.buildChildDocumentsUri(HomeEnvironment.AUTHORITY, docId)

    override fun getPathForId(docId: String?): Try<Path> {
        val baseDir = homeEnvironment!!.baseDir
        if (HomeEnvironment.ROOT_DOC_ID == docId) {
            return Success(baseDir)
        } else {
            if (docId == null) {
                return Failure(FileNotFoundException("No root for $docId"))
            }
            val splitIndex = docId.indexOf('/', 1)
            if (splitIndex < 0) {
                return Failure(FileNotFoundException("No root for $docId"))
            } else {
                val targetPath = docId.substring(splitIndex + 1)
                val target = Paths.get(baseDir.toString(), targetPath)
                return if (Files.exists(target)) {
                    Success(target)
                } else {
                    Failure(
                        FileNotFoundException("No path for $docId at $target"),
                    )
                }
            }
        }
    }

    override fun getDocIdForPath(path: Path?): String {
        val rootPath = homeEnvironment!!.baseDir
        return if (rootPath == path) {
            HomeEnvironment.ROOT_DOC_ID
        } else {
            (
                HomeEnvironment.ROOT_DOC_ID +
                    path.toString().replaceFirst(rootPath.toString().toRegex(), "")
            )
        }
    }

    override fun isNotEssential(path: Path?): Boolean = !homeEnvironment!!.isRoot(path!!)

    override fun onDocIdChanged(docId: String?) {
        // no-op
    }

    override fun onDocIdDeleted(docId: String?) {
        // no-op
    }

    /**
     * @throws AuthenticationRequiredException
     * if [LockStore.isLocked] is true.
     */
    private fun assertUnlocked() {
        if (lockStore!!.isLocked) {
            val context = context
            val intent =
                Intent(context, UnlockActivity::class.java)
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            throw AuthenticationRequiredException(
                Throwable("Locked storage"),
                PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE),
            )
        }
    }

    private val onLockChanged =
        Consumer { _: Boolean ->
            cr
                ?.notifyChange(DocumentsContract.buildRootsUri(HomeEnvironment.AUTHORITY), null)
        }

    companion object {
        private const val TAG = "AerDocumentProvider"

        private val DEFAULT_ROOT_PROJECTION =
            arrayOf(
                Root.COLUMN_ROOT_ID,
                Root.COLUMN_FLAGS,
                Root.COLUMN_ICON,
                Root.COLUMN_TITLE,
                Root.COLUMN_DOCUMENT_ID,
            )

        private fun resolveRootProjection(projection: Array<String?>?): Array<out String?> = projection ?: DEFAULT_ROOT_PROJECTION
    }
}


================================================
FILE: app/src/main/java/alt/nainapps/aer/documents/provider/EmptyCursor.kt
================================================
/*
 * Copyright (c) 2022 2bllw8
 * SPDX-License-Identifier: GPL-3.0-only
 */
package alt.nainapps.aer.documents.provider

import android.database.AbstractCursor

class EmptyCursor : AbstractCursor() {
    override fun getCount(): Int {
        return 0
    }

    override fun getColumnNames(): Array<String?> {
        return arrayOfNulls(0)
    }

    override fun getString(column: Int): String? {
        return null
    }

    override fun getShort(column: Int): Short {
        return 0
    }

    override fun getInt(column: Int): Int {
        return 0
    }

    override fun getLong(column: Int): Long {
        return 0L
    }

    override fun getFloat(column: Int): Float {
        return 0f
    }

    override fun getDouble(column: Int): Double {
        return 0.0
    }

    override fun isNull(column: Int): Boolean {
        return true
    }
}


================================================
FILE: app/src/main/java/alt/nainapps/aer/documents/provider/FileSystemProvider.kt
================================================
/*
 * Copyright (c) 2022 2bllw8
 * SPDX-License-Identifier: GPL-3.0-only
 */
package alt.nainapps.aer.documents.provider

import alt.nainapps.aer.documents.provider.PathUtils.buildUniquePath
import alt.nainapps.aer.documents.provider.PathUtils.buildValidFileName
import alt.nainapps.aer.documents.provider.PathUtils.deleteContents
import alt.nainapps.aer.documents.provider.PathUtils.getDocumentType
import android.annotation.SuppressLint
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.content.res.AssetFileDescriptor
import android.database.Cursor
import android.database.MatrixCursor
import android.database.MatrixCursor.RowBuilder
import android.graphics.Point
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.CancellationSignal
import android.os.FileObserver
import android.os.Handler
import android.os.Looper
import android.os.ParcelFileDescriptor
import android.provider.DocumentsContract
import android.provider.DocumentsProvider
import android.system.Int64Ref
import android.text.TextUtils
import android.util.ArrayMap
import android.util.Log
import android.webkit.MimeTypeMap
import androidx.annotation.RequiresApi
import androidx.exifinterface.media.ExifInterface
import exe.bbllw8.either.Try
import java.io.FileNotFoundException
import java.io.IOException
import java.nio.file.FileVisitResult
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.SimpleFileVisitor
import java.nio.file.attribute.BasicFileAttributes
import java.nio.file.attribute.FileTime
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.atomic.AtomicInteger

/**
 * A helper class for [android.provider.DocumentsProvider] to perform file operations on local
 * files.
 *
 *
 * Based on `com.android.internal.content.FileSystemProvider`.
 */
abstract class FileSystemProvider : DocumentsProvider() {
    private val observers = ArrayMap<Path, DirectoryObserver>()

    private var handler: Handler? = null
    protected var cr: ContentResolver? = null

    override fun onCreate(): Boolean {
        handler = Handler(Looper.myLooper()!!)
        cr = context!!.contentResolver
        return true
    }

    override fun getDocumentMetadata(documentId: String): Bundle? {
        return getPathForId(documentId)
            .filter { path: Path? -> Files.exists(path) }
            .filter { path: Path? -> Files.isReadable(path) }
            .map<Bundle?> { path: Path? ->
                if (Build.VERSION.SDK_INT >= 29 && Files.isDirectory(path)) {
                    val treeSize = Int64Ref(0)
                    val treeCount = Int64Ref(0)

                    Files.walkFileTree(
                        path,
                        object : SimpleFileVisitor<Path>() {
                            override fun visitFile(
                                file: Path,
                                attrs: BasicFileAttributes,
                            ): FileVisitResult {
                                treeSize.value += attrs.size()
                                treeCount.value += 1
                                return FileVisitResult.CONTINUE
                            }
                        },
                    )

                    val bundle = Bundle()
                    bundle.putLong(DocumentsContract.METADATA_TREE_SIZE, treeSize.value)
                    bundle.putLong(DocumentsContract.METADATA_TREE_COUNT, treeCount.value)
                    return@map bundle
                } else {
                    return@map null
                }
            }.getOrElse(null)
    }

    override fun createDocument(
        parentDocumentId: String,
        mimeType: String,
        displayName: String,
    ): String {
        val docName = buildValidFileName(displayName)
        val result =
            getPathForId(parentDocumentId)
                .filter { path: Path? -> Files.isDirectory(path) }
                .map { parent: Path? ->
                    val path =
                        buildUniquePath(
                            parent!!,
                            mimeType,
                            docName,
                        )
                    if (DocumentsContract.Document.MIME_TYPE_DIR == mimeType) {
                        Files.createDirectory(path)
                    } else {
                        Files.createFile(path)
                    }
                    val childId = getDocIdForPath(path)
                    onDocIdChanged(childId)
                    updateMediaStore(context, path)
                    childId
                }
        if (result.isSuccess) {
            return result.get()
        } else {
            Log.e(TAG, "Failed to create document", result.failed().get())
            throw IllegalStateException()
        }
    }

    @Throws(FileNotFoundException::class)
    override fun copyDocument(
        sourceDocumentId: String,
        targetParentDocumentId: String,
    ): String {
        Log.d(TAG, "${getPathForId(sourceDocumentId)}")
        val result =
            getPathForId(sourceDocumentId)
                .flatMap { source: Path ->
                    getPathForId(targetParentDocumentId).map<String> { parent: Path? ->
                        val fileName = source.fileName.toString()
                        val target =
                            buildUniquePath(
                                parent!!,
                                fileName,
                            )
                        Log.d(TAG, "Copying document: $fileName from $source to $parent")

                        if (Files.isDirectory(source)) {
                            // Recursive copy
                            Files.walkFileTree(
                                source,
                                object : SimpleFileVisitor<Path>() {
                                    @Throws(IOException::class)
                                    override fun preVisitDirectory(
                                        dir: Path,
                                        attrs: BasicFileAttributes,
                                    ): FileVisitResult {
                                        Log.d(TAG, "Creating directories: ${target.resolve(dir.relativize(source))}")
                                        Files.createDirectories(target.resolve(dir.relativize(source)))
                                        return FileVisitResult.CONTINUE
                                    }

                                    @Throws(IOException::class)
                                    override fun visitFile(
                                        file: Path,
                                        attrs: BasicFileAttributes,
                                    ): FileVisitResult {
                                        Files.copy(file, target.resolve(file.relativize(source)))
                                        return FileVisitResult.CONTINUE
                                    }
                                },
                            )
                        } else {
                            // Simple copy
                            Log.d(TAG, "File.copy document:  $source to $target")
                            Files.copy(source, target)
                        }

                        val context = context
                        updateMediaStore(context, target)

                        val targetId = getDocIdForPath(target)
                        onDocIdChanged(targetId)
                        targetId
                    }
                }
        if (result.isSuccess) {
            return result.get()
        } else {
            Log.e(TAG, "Failed to copy document", result.failed().get())
            throw IllegalStateException()
        }
    }

    override fun renameDocument(
        documentId: String,
        displayName: String,
    ): String {
        val docName = buildValidFileName(displayName)
        val result =
            getPathForId(documentId).map { before: Path ->
                val after = buildUniquePath(before.parent, docName)
                Files.move(before, after)

                val context = context
                updateMediaStore(context, before)
                updateMediaStore(context, after)

                onDocIdChanged(documentId)
                onDocIdDeleted(documentId)

                val afterId = getDocIdForPath(after)
                if (TextUtils.equals(documentId, afterId)) {
                    // Null is used when the source and destination are equal
                    // according to the Android API specification
                    return@map null
                } else {
                    onDocIdChanged(afterId)
                    return@map afterId
                }
            }
        if (result.isSuccess) {
            return result.get()!!
        } else {
            Log.e(TAG, "Failed to rename document", result.failed().get())
            throw IllegalStateException()
        }
    }

    override fun moveDocument(
        sourceDocumentId: String,
        sourceParentDocumentId: String,
        targetParentDocumentId: String,
    ): String {
        val result =
            getPathForId(sourceDocumentId)
                .flatMap { before: Path ->
                    getPathForId(targetParentDocumentId).map { parent: Path ->
                        val documentName = before.fileName.toString()
                        val after = parent.resolve(documentName)
                        Files.move(before, after)

                        val context = context
                        updateMediaStore(context, before)
                        updateMediaStore(context, after)

                        onDocIdChanged(sourceDocumentId)
                        onDocIdDeleted(sourceDocumentId)

                        val afterId = getDocIdForPath(after)
                        onDocIdChanged(afterId)
                        afterId
                    }
                }
        if (result.isSuccess) {
            return result.get()
        } else {
            Log.e(TAG, "Failed to move document", result.failed().get())
            throw IllegalStateException()
        }
    }

    override fun deleteDocument(documentId: String) {
        getPathForId(documentId)
            .map { path: Path ->
                if (Files.isDirectory(path)) {
                    deleteContents(path)
                } else {
                    Files.deleteIfExists(path)
                }
                path
            }.forEach { path: Path ->
                onDocIdChanged(documentId)
                onDocIdDeleted(documentId)
                updateMediaStore(context, path)
            }
    }

    @Throws(FileNotFoundException::class)
    override fun openDocument(
        documentId: String,
        mode: String,
        signal: CancellationSignal?,
    ): ParcelFileDescriptor {
        val result =
            getPathForId(documentId).map { path: Path ->
                val pfdMode = ParcelFileDescriptor.parseMode(mode)
                if (pfdMode == ParcelFileDescriptor.MODE_READ_ONLY) {
                    return@map ParcelFileDescriptor.open(path.toFile(), pfdMode)
                } else {
                    // When finished writing, kick off media scanner
                    return@map ParcelFileDescriptor.open(
                        path.toFile(),
                        pfdMode,
                        handler,
                    ) { failure: IOException? ->
                        onDocIdChanged(documentId)
                        updateMediaStore(
                            context,
                            path,
                        )
                    }
                }
            }
        if (result.isFailure) {
            Log.e(TAG, "Failed to open document $documentId", result.failed().get())
            throw FileNotFoundException("Couldn't open $documentId")
        }
        return result.get()
    }

    @Throws(FileNotFoundException::class)
    override fun queryDocument(
        documentId: String,
        projection: Array<String?>?,
    ): Cursor {
        val result = MatrixCursor(resolveProjection(projection))
        includePath(result, documentId)
        return result
    }

    @Throws(FileNotFoundException::class)
    override fun queryChildDocuments(
        parentDocumentId: String,
        projection: Array<String?>?,
        sortOrder: String?,
    ): Cursor {
        val parentTry = getPathForId(parentDocumentId)
        if (parentTry.isFailure) {
            throw FileNotFoundException("Couldn't find $parentDocumentId")
        }
        val parent = parentTry.get()
        val result: MatrixCursor =
            DirectoryCursor(
                resolveProjection(projection),
                parentDocumentId,
                parent,
            )
        if (Files.isDirectory(parent)) {
            Try.from<Any?> {
                Files.list(parent).forEach { file: Path -> includePath(result, file) }
                null
            }
        } else {
            Log.w(TAG, "$parentDocumentId: not a directory")
        }
        return result
    }

    override fun findDocumentPath(
        parentDocumentId: String?,
        childDocumentId: String,
    ): DocumentsContract.Path {
        val pathStr =
            if (parentDocumentId == null) {
                childDocumentId
            } else {
                childDocumentId.substring(parentDocumentId.length)
            }

        val segments =
            listOf(
                *pathStr
                    .split("/".toRegex())
                    .dropLastWhile { it.isEmpty() }
                    .toTypedArray(),
            )
        return DocumentsContract.Path(parentDocumentId, segments)
    }

    @Throws(FileNotFoundException::class)
    override fun getDocumentType(documentId: String): String {
        val pathTry = getPathForId(documentId)
        if (pathTry.isFailure) {
            throw FileNotFoundException("Can't find $documentId")
        }
        return getDocumentType(documentId, pathTry.get())
    }

    @Throws(FileNotFoundException::class)
    override fun openDocumentThumbnail(
        docId: String,
        sizeHint: Point,
        signal: CancellationSignal,
    ): AssetFileDescriptor {
        val pathTry =
            getPathForId(docId)
                .filter { path: Path? -> getDocumentType(docId, path).startsWith("image/") }
                .map { path: Path ->
                    val pfd =
                        ParcelFileDescriptor.open(
                            path.toFile(),
                            ParcelFileDescriptor.MODE_READ_ONLY,
                        )
                    val exif = ExifInterface(path.toFile().absolutePath)

                    val thumb = exif.thumbnailRange
                    if (thumb == null) {
                        // Do full file decoding, we don't need to handle the orientation
                        return@map AssetFileDescriptor(
                            pfd,
                            0,
                            AssetFileDescriptor.UNKNOWN_LENGTH,
                            null,
                        )
                    } else {
                        // If we use thumb to decode, we need to handle the rotation by ourselves.
                        var extras: Bundle? = null
                        when (exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1)) {
                            ExifInterface.ORIENTATION_ROTATE_90 -> {
                                extras = Bundle(1)
                                extras.putInt(DocumentsContract.EXTRA_ORIENTATION, 90)
                            }

                            ExifInterface.ORIENTATION_ROTATE_180 -> {
                                extras = Bundle(1)
                                extras.putInt(DocumentsContract.EXTRA_ORIENTATION, 180)
                            }

                            ExifInterface.ORIENTATION_ROTATE_270 -> {
                                extras = Bundle(1)
                                extras.putInt(DocumentsContract.EXTRA_ORIENTATION, 270)
                            }
                        }
                        return@map AssetFileDescriptor(pfd, thumb[0], thumb[1], extras)
                    }
                }
        if (pathTry.isFailure) {
            throw FileNotFoundException("Couldn't open $docId")
        }
        return pathTry.get()
    }

    @SuppressLint("NewApi")
    @Throws(FileNotFoundException::class)
    override fun querySearchDocuments(
        rootId: String,
        projection: Array<String?>?,
        queryArgs: Bundle,
    ): Cursor? {
        val result =
            getPathForId(rootId)
                .filter { _: Path? -> Build.VERSION.SDK_INT > 29 }
                .map { path: Path? -> querySearchDocuments(path, projection, queryArgs) }
        if (result.isFailure) {
            throw FileNotFoundException()
        }
        return result.get()
    }

    @RequiresApi(29)
    protected fun querySearchDocuments(
        parent: Path?,
        projection: Array<String?>?,
        queryArgs: Bundle?,
    ): Cursor {
        val result = MatrixCursor(resolveProjection(projection))
        val count = AtomicInteger(MAX_QUERY_RESULTS)
        Try.from<Path> {
            Files.walkFileTree(
                parent,
                object : SimpleFileVisitor<Path>() {
                    @Throws(IOException::class)
                    override fun visitFile(
                        file: Path,
                        attrs: BasicFileAttributes,
                    ): FileVisitResult {
                        if (matchSearchQueryArguments(file, queryArgs)) {
                            includePath(result, file)
                        }
                        return if (count.decrementAndGet() == 0
                        ) {
                            FileVisitResult.TERMINATE
                        } else {
                            FileVisitResult.CONTINUE
                        }
                    }

                    @Throws(IOException::class)
                    override fun preVisitDirectory(
                        dir: Path,
                        attrs: BasicFileAttributes,
                    ): FileVisitResult {
                        if (matchSearchQueryArguments(dir, queryArgs)) {
                            includePath(result, dir)
                        }
                        return if (count.decrementAndGet() == 0
                        ) {
                            FileVisitResult.TERMINATE
                        } else {
                            FileVisitResult.CONTINUE
                        }
                    }
                },
            )
        }
        return result
    }

    override fun isChildDocument(
        parentDocumentId: String,
        documentId: String,
    ): Boolean = documentId.contains(parentDocumentId)

    /**
     * Callback indicating that the given document has been modified. This gives the provider a hook
     * to invalidate cached data, such as `sdcardfs`.
     */
    protected abstract fun onDocIdChanged(docId: String?)

    /**
     * Callback indicating that the given document has been deleted or moved. This gives the
     * provider a hook to revoke the uri permissions.
     */
    protected abstract fun onDocIdDeleted(docId: String?)

    protected open fun isNotEssential(path: Path?): Boolean = true

    @Throws(FileNotFoundException::class)
    protected fun includePath(
        result: MatrixCursor,
        docId: String,
    ): RowBuilder {
        val pathTry = getPathForId(docId)
        if (pathTry.isFailure) {
            throw FileNotFoundException("Couldn't find $docId")
        }
        return includePath(result, pathTry.get(), docId)
    }

    protected fun includePath(
        result: MatrixCursor,
        path: Path,
        docId: String? = getDocIdForPath(path),
    ): RowBuilder {
        val columns = result.columnNames
        val row = result.newRow()

        val mimeType =
            getDocumentType(
                docId!!,
                path,
            )
        row.add(DocumentsContract.Document.COLUMN_DOCUMENT_ID, docId)
        row.add(DocumentsContract.Document.COLUMN_MIME_TYPE, mimeType)

        val flagIndex = indexOf(columns, DocumentsContract.Document.COLUMN_FLAGS)
        if (flagIndex != -1) {
            var flags = 0
            if (Files.isWritable(path)) {
                if (DocumentsContract.Document.MIME_TYPE_DIR == mimeType) {
                    flags = flags or DocumentsContract.Document.FLAG_DIR_SUPPORTS_CREATE
                    if (isNotEssential(path)) {
                        flags = flags or DocumentsContract.Document.FLAG_SUPPORTS_WRITE
                        flags = flags or DocumentsContract.Document.FLAG_SUPPORTS_DELETE
                        flags = flags or DocumentsContract.Document.FLAG_SUPPORTS_RENAME
                        flags = flags or DocumentsContract.Document.FLAG_SUPPORTS_COPY
                        flags = flags or DocumentsContract.Document.FLAG_SUPPORTS_MOVE
                        Log.d(TAG, "Flag $flags for: $path")
                    }
                } else {
                    flags = flags or DocumentsContract.Document.FLAG_SUPPORTS_WRITE
                    flags = flags or DocumentsContract.Document.FLAG_SUPPORTS_DELETE
                    flags = flags or DocumentsContract.Document.FLAG_SUPPORTS_RENAME
                    flags = flags or DocumentsContract.Document.FLAG_SUPPORTS_COPY
                    flags = flags or DocumentsContract.Document.FLAG_SUPPORTS_MOVE
                    Log.d(TAG, "Flag $flags for: $path")
                }
            }

            if (mimeType.startsWith("image/")) {
                flags = flags or DocumentsContract.Document.FLAG_SUPPORTS_THUMBNAIL
            }
            row.add(DocumentsContract.Document.COLUMN_FLAGS, flags)
        }

        val displayNameIndex = indexOf(columns, DocumentsContract.Document.COLUMN_DISPLAY_NAME)
        if (displayNameIndex != -1) {
            row.add(DocumentsContract.Document.COLUMN_DISPLAY_NAME, path.fileName.toString())
        }

        val lastModifiedIndex = indexOf(columns, DocumentsContract.Document.COLUMN_LAST_MODIFIED)
        if (lastModifiedIndex != -1) {
            Try
                .from { Files.getLastModifiedTime(path) }
                .map { obj: FileTime -> obj.toMillis() } // Only publish dates reasonably after epoch
                .filter { lastModified: Long -> lastModified > 31536000000L }
                .forEach { lastModified: Long? ->
                    row.add(
                        DocumentsContract.Document.COLUMN_LAST_MODIFIED,
                        lastModified,
                    )
                }
        }

        val sizeIndex = indexOf(columns, DocumentsContract.Document.COLUMN_SIZE)
        if (sizeIndex != -1) {
            Try
                .from { Files.size(path) }
                .forEach { size: Long? -> row.add(DocumentsContract.Document.COLUMN_SIZE, size) }
        }

        // Return the row builder just in case any subclass want to add more stuff to it.
        return row
    }

    protected abstract fun getPathForId(docId: String?): Try<Path>

    protected abstract fun getDocIdForPath(path: Path?): String

    protected abstract fun buildNotificationUri(docId: String?): Uri

    private fun resolveProjection(projection: Array<String?>?): Array<String?> = ((projection ?: DEFAULT_PROJECTION))

    private fun startObserving(
        path: Path,
        notifyUri: Uri,
        cursor: DirectoryCursor,
    ) {
        synchronized(observers) {
            var observer = observers[path]
            if (observer == null) {
                observer =
                    if (Build.VERSION.SDK_INT >= 29) {
                        DirectoryObserver(path, cr, notifyUri)
                    } else {
                        DirectoryObserver(
                            path.toFile().absolutePath,
                            cr,
                            notifyUri,
                        )
                    }
                observer.startWatching()
                observers[path] = observer
            }
            observer.cursors.add(cursor)
        }
    }

    private fun stopObserving(
        path: Path,
        cursor: DirectoryCursor,
    ) {
        synchronized(observers) {
            val observer = observers[path] ?: return
            observer.cursors.remove(cursor)
            if (observer.cursors.isEmpty()) {
                observers.remove(path)
                observer.stopWatching()
            }
        }
    }

    /**
     * Test if the file matches the query arguments.
     *
     * @param path
     * the file to test
     * @param queryArgs
     * the query arguments
     */
    @RequiresApi(29)
    @Throws(IOException::class)
    private fun matchSearchQueryArguments(
        path: Path,
        queryArgs: Bundle?,
    ): Boolean {
        if (queryArgs == null) {
            return true
        }

        val fileName = path.fileName.toString().lowercase()
        val argDisplayName =
            queryArgs.getString(
                DocumentsContract.QUERY_ARG_DISPLAY_NAME,
                "",
            )
        if (argDisplayName.isNotEmpty()) {
            if (!fileName.contains(argDisplayName.lowercase())) {
                return false
            }
        }

        val argFileSize = queryArgs.getLong(DocumentsContract.QUERY_ARG_FILE_SIZE_OVER, -1)
        if (argFileSize != -1L && Files.size(path) < argFileSize) {
            return false
        }

        val argLastModified =
            queryArgs
                .getLong(DocumentsContract.QUERY_ARG_LAST_MODIFIED_AFTER, -1)
        if (argLastModified != -1L &&
            Files
                .getLastModifiedTime(path)
                .toMillis() < argLastModified
        ) {
            return false
        }

        val argMimeTypes =
            queryArgs
                .getStringArray(DocumentsContract.QUERY_ARG_MIME_TYPES)
        if (!argMimeTypes.isNullOrEmpty()) {
            val fileMimeType: String?
            if (Files.isDirectory(path)) {
                fileMimeType = DocumentsContract.Document.MIME_TYPE_DIR
            } else {
                val dotPos = fileName.lastIndexOf('.')
                if (dotPos < 0) {
                    return false
                }
                val extension = fileName.substring(dotPos + 1)
                fileMimeType =
                    Intent.normalizeMimeType(
                        MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension),
                    )
            }

            for (type in argMimeTypes) {
                if (mimeTypeMatches(fileMimeType, type)) {
                    return true
                }
            }
            return false
        }
        return true
    }

    private inner class DirectoryCursor(
        columnNames: Array<String?>,
        docId: String?,
        private val path: Path,
    ) : MatrixCursor(columnNames) {
        init {
            val notifyUri = buildNotificationUri(docId)
            setNotificationUri(cr, notifyUri)
            startObserving(path, notifyUri, this)
        }

        fun notifyChanged() {
            onChange(false)
        }

        override fun close() {
            super.close()
            stopObserving(path, this)
        }
    }

    private class DirectoryObserver : FileObserver {
        private val resolver: ContentResolver?
        private val notifyUri: Uri
        val cursors: CopyOnWriteArrayList<DirectoryCursor>

        @Suppress("deprecation")
        constructor(absolutePath: String?, resolver: ContentResolver?, notifyUri: Uri) : super(
            absolutePath,
            NOTIFY_EVENTS,
        ) {
            this.resolver = resolver
            this.notifyUri = notifyUri
            this.cursors = CopyOnWriteArrayList()
        }

        @RequiresApi(29)
        constructor(path: Path, resolver: ContentResolver?, notifyUri: Uri) : super(
            path.toFile(),
            NOTIFY_EVENTS,
        ) {
            this.resolver = resolver
            this.notifyUri = notifyUri
            this.cursors = CopyOnWriteArrayList()
        }

        override fun onEvent(
            event: Int,
            path: String?,
        ) {
            if ((event and NOTIFY_EVENTS) != 0) {
                for (cursor in cursors) {
                    cursor.notifyChanged()
                }
                resolver!!.notifyChange(notifyUri, null, 0)
            }
        }

        companion object {
            private const val NOTIFY_EVENTS = (
                ATTRIB or CLOSE_WRITE or MOVED_FROM or MOVED_TO
                    or CREATE or DELETE or DELETE_SELF or MOVE_SELF
            )
        }
    }

    companion object {
        private const val TAG = "FileSystemProvider"
        private const val MAX_QUERY_RESULTS = 23
        private val DEFAULT_PROJECTION =
            arrayOf<String?>(
                DocumentsContract.Document.COLUMN_DOCUMENT_ID,
                DocumentsContract.Document.COLUMN_MIME_TYPE,
                DocumentsContract.Document.COLUMN_DISPLAY_NAME,
                DocumentsContract.Document.COLUMN_LAST_MODIFIED,
                DocumentsContract.Document.COLUMN_FLAGS,
                DocumentsContract.Document.COLUMN_SIZE,
            )

        @Suppress("deprecation")
        private fun updateMediaStore(
            context: Context?,
            path: Path,
        ) {
            val intent =
                if (!Files.isDirectory(path) &&
                    path.fileName
                        .toString()
                        .endsWith("nomedia")
                ) {
                    Intent(
                        Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                        Uri.fromFile(path.parent.toFile()),
                    )
                } else {
                    Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(path.toFile()))
                }
            context!!.sendBroadcast(intent)
        }

        fun mimeTypeMatches(
            mimeType: String?,
            filter: String,
        ): Boolean {
            if (mimeType == null) {
                return false
            }

            val mimeTypeParts =
                mimeType.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
            val filterParts =
                filter.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()

            require(filterParts.size == 2) { "Ill-formatted MIME type filter. Must be type/subtype" }
            require(!(filterParts[0].isEmpty() || filterParts[1].isEmpty())) { "Ill-formatted MIME type filter. Type or subtype empty" }
            if (mimeTypeParts.size != 2) {
                return false
            }
            if ("*" != filterParts[0] && filterParts[0] != mimeTypeParts[0]) {
                return false
            }
            return "*" == filterParts[1] || filterParts[1] == mimeTypeParts[1]
        }

        private fun <T> indexOf(
            array: Array<T>?,
            target: T,
        ): Int {
            if (array == null) {
                return -1
            }
            for (i in array.indices) {
                if (array[i] == target) {
                    return i
                }
            }
            return -1
        }
    }
}


================================================
FILE: app/src/main/java/alt/nainapps/aer/documents/provider/PathUtils.kt
================================================
/*
 * Copyright (c) 2022 2bllw8
 * SPDX-License-Identifier: GPL-3.0-only
 */
package alt.nainapps.aer.documents.provider

import android.provider.DocumentsContract
import android.text.TextUtils
import android.webkit.MimeTypeMap
import java.io.FileNotFoundException
import java.io.IOException
import java.nio.file.FileVisitResult
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.SimpleFileVisitor
import java.nio.file.attribute.BasicFileAttributes
import java.util.Locale

object PathUtils {
    private const val MIME_TYPE_DEFAULT = "application/octet-stream"

    /**
     * Mutate the given filename to make it valid for a FAT filesystem, replacing any invalid
     * characters with "_".
     *
     *
     * Based on `android.os.FileUtils#buildUniqueFile#buildValidFilename`
     */
    @JvmStatic
    fun buildValidFileName(name: String): String {
        if (TextUtils.isEmpty(name) || "." == name) {
            return "(invalid)"
        }

        val res = StringBuilder(name.length)
        for (i in 0 until name.length) {
            val c = name[i]
            if (isValidFatFilenameChar(c.code)) {
                res.append(c)
            } else {
                res.append('_')
            }
        }
        return res.toString()
    }

    /**
     * Generates a unique file name under the given parent directory, keeping any extension intact.
     *
     *
     * Based on `android.os.FileUtils#buildUniqueFile`
     */
    @JvmStatic
    @Throws(FileNotFoundException::class)
    fun buildUniquePath(parent: Path, displayName: String): Path {
        val name: String
        val ext: String?

        // Extract requested extension from display name
        val lastDot = displayName.lastIndexOf('.')
        if (lastDot >= 0) {
            name = displayName.substring(0, lastDot)
            ext = displayName.substring(lastDot + 1)
        } else {
            name = displayName
            ext = null
        }

        return buildUniquePathWithExtension(parent, name, ext)
    }

    /**
     * Generates a unique file name under the given parent directory. If the display name doesn't
     * have an extension that matches the requested MIME type, the default extension for that MIME
     * type is appended. If a file already exists, the name is appended with a numerical value to
     * make it unique.
     *
     *
     * For example, the display name 'example' with 'text/plain' MIME might produce 'example.txt' or
     * 'example (1).txt', etc.
     *
     *
     * Based on `android.os.FileUtils#buildUniqueFile#buildUniqueFile`
     */
    @JvmStatic
    @Throws(FileNotFoundException::class)
    fun buildUniquePath(parent: Path, mimeType: String, displayName: String): Path {
        val parts = splitFileName(mimeType, displayName)
        return buildUniquePathWithExtension(parent, parts[0], parts[1])
    }

    /**
     * Splits file name into base name and extension. If the display name doesn't have an extension
     * that matches the requested MIME type, the extension is regarded as a part of filename and
     * default extension for that MIME type is appended.
     *
     *
     * Based on `android.os.FileUtils#buildUniqueFile#splitFileName`
     */
    fun splitFileName(mimeType: String, displayName: String): Array<String> {
        var name: String
        var ext: String?

        if (DocumentsContract.Document.MIME_TYPE_DIR == mimeType) {
            name = displayName
            ext = null
        } else {
            var mimeTypeFromExt: String?

            // Extract requested extension from display name
            val lastDot = displayName.lastIndexOf('.')
            if (lastDot >= 0) {
                name = displayName.substring(0, lastDot)
                ext = displayName.substring(lastDot + 1)
                mimeTypeFromExt = MimeTypeMap.getSingleton()
                    .getMimeTypeFromExtension(ext.lowercase(Locale.getDefault()))
            } else {
                name = displayName
                ext = null
                mimeTypeFromExt = null
            }

            if (mimeTypeFromExt == null) {
                mimeTypeFromExt = MIME_TYPE_DEFAULT
            }
            val extFromMimeType =
                if (MIME_TYPE_DEFAULT == mimeType) {
                    null
                } else {
                    MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType)
                }

            if (!(mimeType == mimeTypeFromExt || ext == extFromMimeType)) {
                // No match; insist that create file matches requested MIME
                name = displayName
                ext = extFromMimeType
            }
        }

        if (ext == null) {
            ext = ""
        }

        return arrayOf(name, ext)
    }

    /**
     * Recursively delete a directory.
     */
    @JvmStatic
    @Throws(IOException::class)
    fun deleteContents(path: Path?) {
        Files.walkFileTree(path, object : SimpleFileVisitor<Path>() {
            @Throws(IOException::class)
            override fun postVisitDirectory(dir: Path, exc: IOException): FileVisitResult {
                Files.deleteIfExists(dir)
                return FileVisitResult.CONTINUE
            }

            @Throws(IOException::class)
            override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
                Files.delete(file)
                return FileVisitResult.CONTINUE
            }
        })
    }

    /**
     * Get the mime-type of a given path document.
     */
    @JvmStatic
    fun getDocumentType(documentId: String, path: Path?): String {
        if (Files.isDirectory(path)) {
            return DocumentsContract.Document.MIME_TYPE_DIR
        } else {
            val lastDot = documentId.lastIndexOf('.')
            if (lastDot >= 0) {
                val extension = documentId.substring(lastDot + 1).lowercase(Locale.getDefault())
                val mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension)
                if (mime != null) {
                    return mime
                }
            }
            return MIME_TYPE_DEFAULT
        }
    }

    private fun isValidFatFilenameChar(c: Int): Boolean {
        if (c in 0x00..0x1f) {
            return false
        }
        return when (c) {
            '"'.code, '*'.code, '/'.code, ':'.code, '<'.code, '>'.code, '?'.code, '\\'.code, '|'.code, 0x7F -> false
            else -> true
        }
    }

    @Throws(FileNotFoundException::class)
    private fun buildUniquePathWithExtension(parent: Path, name: String, ext: String?): Path {
        var path = buildPath(parent, name, ext)

        // If conflicting path, try adding counter suffix
        var n = 0
        while (Files.exists(path)) {
            if (n++ >= 32) {
                throw FileNotFoundException("Failed to create unique file")
            }
            path = buildPath(parent, "$name ($n)", ext)
        }

        return path
    }

    private fun buildPath(parent: Path, name: String, ext: String?): Path {
        return if (TextUtils.isEmpty(ext)) {
            parent.resolve(name)
        } else {
            parent.resolve("$name.$ext")
        }
    }
}


================================================
FILE: app/src/main/java/alt/nainapps/aer/documents/receiver/ReceiverActivity.kt
================================================
/*
 * Copyright (c) 2022 2bllw8
 * SPDX-License-Identifier: GPL-3.0-only
 */
package alt.nainapps.aer.documents.receiver

import android.app.Activity
import android.app.AlertDialog
import android.app.Dialog
import android.content.ContentResolver
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.DocumentsContract
import android.provider.OpenableColumns
import android.util.Log
import alt.nainapps.aer.R
import alt.nainapps.aer.documents.home.HomeEnvironment
import alt.nainapps.aer.task.TaskExecutor
import exe.bbllw8.either.Try
import java.util.Optional
import java.util.concurrent.atomic.AtomicReference

class ReceiverActivity : Activity() {
    private val taskExecutor = TaskExecutor()
    private val dialogRef = AtomicReference(
        Optional.empty<Dialog>()
    )
    private val importRef = AtomicReference<Optional<Uri>>(
        Optional.empty()
    )


    private var contentResolver: ContentResolver? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        contentResolver = getContentResolver()

        val intent = intent
        if (intent == null || Intent.ACTION_SEND != intent.action) {
            Log.e(TAG, "Nothing to do")
            finish()
            return
        }

        val type = intent.type
        if (type == null) {
            Log.e(TAG, "Can't determine type of sent content")
            finish()
            return
        }

        val source = intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM)!!
        importRef.set(Optional.of(source))

        val pickerIntent = Intent(Intent.ACTION_CREATE_DOCUMENT).setType(type)
            .putExtra(
                Intent.EXTRA_TITLE,
                getFileName(source).orElse(getString(R.string.receiver_default_file_name))
            )
            .putExtra(
                DocumentsContract.EXTRA_INITIAL_URI,
                DocumentsContract.buildRootsUri(HomeEnvironment.AUTHORITY)
            )
        startActivityForResult(pickerIntent, DOCUMENT_PICKER_REQ_CODE)
    }

    override fun onDestroy() {
        dialogRef.getAndSet(null)!!.ifPresent { obj: Dialog -> obj.dismiss() }
        importRef.set(null)
        taskExecutor.terminate()
        super.onDestroy()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
        if (requestCode == DOCUMENT_PICKER_REQ_CODE) {
            if (resultCode == RESULT_OK) {
                doImport(data.data)
            } else {
                Log.d(TAG, "Action canceled")
                finish()
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data)
        }
    }

    private fun doImport(destination: Uri?) {
        val sourceOpt = importRef.get()
        // No Optional#isEmpty() in android
        // noinspection SimplifyOptionalCallChains
        if (!sourceOpt!!.isPresent) {
            Log.e(TAG, "Nothing to import")
            return
        }
        val source = sourceOpt.get()

        onImportStarted()
        taskExecutor.runTask({ copyUriToUri(source, destination) }, { result: Try<Void?> ->
            result
                .forEach(
                    { success: Void? -> onImportSucceeded() },
                    { failure: Throwable? -> onImportFailed() })
        })
    }

    private fun onImportStarted() {
        val dialog: Dialog = AlertDialog.Builder(this, R.style.DialogTheme)
            .setMessage(getString(R.string.receiver_importing_message))
            .setCancelable(false)
            .create()
        dialogRef.getAndSet(Optional.of(dialog))!!
            .ifPresent { obj: Dialog -> obj.dismiss() }
    }

    private fun onImportSucceeded() {
        val dialog: Dialog = AlertDialog.Builder(this, R.style.DialogTheme)
            .setMessage(getString(R.string.receiver_importing_done_ok))
            .setPositiveButton(android.R.string.ok) { d: DialogInterface, which: Int -> d.dismiss() }
            .setOnDismissListener { d: DialogInterface? -> finish() }
            .create()
        dialogRef.getAndSet(Optional.of(dialog))!!
            .ifPresent { obj: Dialog -> obj.dismiss() }
        dialog.show()
    }

    private fun onImportFailed() {
        val dialog: Dialog = AlertDialog.Builder(this, R.style.DialogTheme)
            .setMessage(getString(R.string.receiver_importing_done_fail))
            .setPositiveButton(android.R.string.ok) { d: DialogInterface, which: Int -> d.dismiss() }
            .setOnDismissListener { d: DialogInterface? -> finish() }
            .create()
        dialogRef.getAndSet(Optional.of(dialog))!!
            .ifPresent { obj: Dialog -> obj.dismiss() }
        dialog.show()
    }

    private fun copyUriToUri(source: Uri, destination: Uri?): Try<Void?> {
        return Try.from {
            contentResolver!!.openInputStream(source).use { iStream ->
                contentResolver!!.openOutputStream(
                    destination!!
                ).use { oStream ->
                    val buffer = ByteArray(4096)
                    assert(iStream != null)
                    var read = iStream!!.read(buffer)
                    while (read > 0) {
                        assert(oStream != null)
                        oStream!!.write(buffer, 0, read)
                        read = iStream.read(buffer)
                    }
                }
            }
            null
        }
    }

    private fun getFileName(uri: Uri?): Optional<String> {
        contentResolver!!.query(uri!!, NAME_PROJECTION, null, null, null).use { cursor ->
            if (cursor == null || !cursor.moveToFirst()) {
                return Optional.empty()
            } else {
                val nameIndex = cursor.getColumnIndex(NAME_PROJECTION[0])
                if (nameIndex >= 0) {
                    val name = cursor.getString(nameIndex)
                    return Optional.ofNullable(name)
                } else {
                    return Optional.empty()
                }
            }
        }
    }

    companion object {
        private const val TAG = "ReceiverActivity"
        private const val DOCUMENT_PICKER_REQ_CODE = 7
        private val NAME_PROJECTION = arrayOf(OpenableColumns.DISPLAY_NAME)
    }
}


================================================
FILE: app/src/main/java/alt/nainapps/aer/lock/AutoLockJobService.kt
================================================
/*
 * Copyright (c) 2021 2bllw8
 * SPDX-License-Identifier: GPL-3.0-only
 */
package alt.nainapps.aer.lock

import android.app.job.JobParameters
import android.app.job.JobService
import android.widget.Toast
import alt.nainapps.aer.R

class AutoLockJobService : JobService() {
    override fun onStartJob(params: JobParameters?): Boolean {
        val lockStore = LockStore.getInstance(applicationContext)
        if (lockStore != null) {
            if (!lockStore.isLocked) {
                lockStore.lock()
                Toast.makeText(this, getString(R.string.tile_auto_lock), Toast.LENGTH_LONG).show()
            }
        }
        return false
    }

    override fun onStopJob(params: JobParameters?): Boolean {
        return false
    }
}


================================================
FILE: app/src/main/java/alt/nainapps/aer/lock/LockStore.kt
================================================
/*
 * Copyright (c) 2021 2bllw8
 * Copyright (c) 2024 nain
 * SPDX-License-Identifier: GPL-3.0-only
 */
package alt.nainapps.aer.lock

import android.app.job.JobInfo
import android.app.job.JobScheduler
import android.content.ComponentName
import android.content.Context
import android.content.SharedPreferences
import android.content.SharedPreferences.OnSharedPreferenceChangeListener
import android.hardware.biometrics.BiometricManager
import android.os.Build
import android.util.Log
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.util.Optional
import java.util.function.Consumer
import kotlin.concurrent.Volatile

class LockStore private constructor(context: Context) : OnSharedPreferenceChangeListener {
    private val preferences: SharedPreferences
    private val listeners: MutableList<Consumer<Boolean>> = ArrayList()
    private val biometricManager: BiometricManager?

    private val jobScheduler: JobScheduler
    private val autoLockComponent: ComponentName

    init {
        preferences = context.getSharedPreferences(LOCK_PREFERENCES, Context.MODE_PRIVATE)
        preferences.registerOnSharedPreferenceChangeListener(this)

        jobScheduler = context.getSystemService(JobScheduler::class.java)
        biometricManager = if (Build.VERSION.SDK_INT >= 29
        ) context.getSystemService(BiometricManager::class.java)
        else null
        autoLockComponent = ComponentName(context, AutoLockJobService::class.java)
    }

    @Throws(Throwable::class)
    protected fun finalize() {
        preferences.unregisterOnSharedPreferenceChangeListener(this)
        cancelAutoLock()
    }

    override fun onSharedPreferenceChanged(
        sharedPreferences: SharedPreferences,
        key: String?
    ) {
        if (KEY_LOCK == key) {
            onLockChanged()
        }
    }

    @get:Synchronized
    val isLocked: Boolean
        get() = preferences.getBoolean(KEY_LOCK, DEFAULT_LOCK_VALUE)

    @Synchronized
    fun lock() {
        preferences.edit().putBoolean(KEY_LOCK, true).apply()
        cancelAutoLock()
    }

    @Synchronized
    fun unlock() {
        preferences.edit().putBoolean(KEY_LOCK, false).apply()
        if (isAutoLockEnabled) {
            scheduleAutoLock()
        }
    }

    @Synchronized
    fun setPassword(password: String): Boolean {
        return hashString(password).map { hashedPwd: String? ->
            preferences.edit().putString(KEY_PASSWORD, hashedPwd).apply()
            hashedPwd
        }.isPresent
    }

    @Synchronized
    fun passwordMatch(password: String): Boolean {
        return hashString(password)
            .map { hashedPwd: String -> hashedPwd == preferences.getString(KEY_PASSWORD, null) }
            .orElse(false)
    }

    @Synchronized
    fun hasPassword(): Boolean {
        return preferences.getString(KEY_PASSWORD, null) != null
    }

    @Synchronized
    fun removePassword() {
        preferences.edit().remove(KEY_PASSWORD).apply()
    }

    @get:Synchronized
    @set:Synchronized
    var isAutoLockEnabled: Boolean
        get() = preferences.getBoolean(KEY_AUTO_LOCK, DEFAULT_AUTO_LOCK_VALUE)
        set(enabled) {
            preferences.edit().putBoolean(KEY_AUTO_LOCK, enabled).apply()

            if (!isLocked) {
                if (enabled) {
                    // If auto-lock is enabled while the storage is unlocked, schedule the job
                    scheduleAutoLock()
                } else {
                    // If auto-lock is disabled while the storage is unlocked, cancel the job
                    cancelAutoLock()
                }
            }
        }

    @get:Synchronized
    @set:Synchronized
    var autoLockDelayMinutes: Long
        get() = preferences.getLong(KEY_AUTO_LOCK_DELAY_MINUTES, DEFAULT_AUTO_LOCK_DELAY_MINUTES)
        set(delayMinutes) {
            preferences.edit().putLong(KEY_AUTO_LOCK_DELAY_MINUTES, delayMinutes).apply()

            if (!isLocked) {
                if (isAutoLockEnabled) {
                    // If auto-lock is enabled while the storage is unlocked, schedule new job
                    cancelAutoLock()
                    scheduleAutoLock()
                }
            }
        }

    fun canAuthenticateBiometric(): Boolean {
        return Build.VERSION.SDK_INT >= 29 && biometricManager != null && biometricManager.canAuthenticate() == BiometricManager.BIOMETRIC_SUCCESS
    }

    @get:Synchronized
    @set:Synchronized
    var isBiometricUnlockEnabled: Boolean
        get() = canAuthenticateBiometric() && preferences.getBoolean(KEY_BIOMETRIC_UNLOCK, false)
        set(enabled) {
            preferences.edit().putBoolean(KEY_BIOMETRIC_UNLOCK, enabled).apply()
        }

    fun addListener(listener: Consumer<Boolean>) {
        synchronized(listeners) {
            listeners.add(listener)
        }
    }

    fun removeListener(listener: Consumer<Boolean>) {
        synchronized(listeners) {
            listeners.remove(listener)
        }
    }

    private fun onLockChanged() {
        val newValue = preferences.getBoolean(KEY_LOCK, DEFAULT_LOCK_VALUE)
        listeners.forEach(Consumer { listener: Consumer<Boolean> -> listener.accept(newValue) })
    }

    private fun scheduleAutoLock() {
        jobScheduler.schedule(
            JobInfo.Builder(AUTO_LOCK_JOB_ID, autoLockComponent)
                .setMinimumLatency(millisFromMinutes(autoLockDelayMinutes))
                .build()
        )
    }

    private fun cancelAutoLock() {
        jobScheduler.cancel(AUTO_LOCK_JOB_ID)
    }

    private fun hashString(string: String): Optional<String> {
        try {
            val digest = MessageDigest.getInstance(HASH_ALGORITHM)
            digest.update(string.toByteArray())
            return Optional.of(String(digest.digest()))
        } catch (e: NoSuchAlgorithmException) {
            Log.e(TAG, "Couldn't get hash", e)
            return Optional.empty()
        }
    }

    // convert minutes to milliseconds
    private fun millisFromMinutes(minutes: Long): Long {
        return minutes * 60L * 1000L
    }

    companion object {
        private const val TAG = "LockStore"

        private const val LOCK_PREFERENCES = "lock_store"
        private const val KEY_LOCK = "is_locked"
        private const val KEY_PASSWORD = "password_hash"
        private const val KEY_AUTO_LOCK = "auto_lock"
        private const val KEY_AUTO_LOCK_DELAY_MINUTES = "auto_lock_delay_minutes"
        private const val KEY_BIOMETRIC_UNLOCK = "biometric_unlock"
        private const val DEFAULT_LOCK_VALUE = false
        private const val DEFAULT_AUTO_LOCK_VALUE = false
        private const val DEFAULT_AUTO_LOCK_DELAY_MINUTES = 15L

        private const val HASH_ALGORITHM = "SHA-256"

        private const val AUTO_LOCK_JOB_ID = 64

        @Volatile
        private var instance: LockStore? = null

        @JvmStatic
        fun getInstance(context: Context): LockStore? {
            if (instance == null) {
                synchronized(LockStore::class.java) {
                    if (instance == null) {
                        instance = LockStore(context.applicationContext)
                    }
                }
            }
            return instance
        }
    }
}


================================================
FILE: app/src/main/java/alt/nainapps/aer/lock/LockTileService.kt
================================================
/*
 * Copyright (c) 2021 2bllw8
 * SPDX-License-Identifier: GPL-3.0-only
 */
package alt.nainapps.aer.lock

import android.content.ComponentName
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.drawable.Icon
import android.os.Build
import android.os.IBinder
import android.service.quicksettings.Tile
import android.service.quicksettings.TileService
import alt.nainapps.aer.R
import alt.nainapps.aer.lock.LockStore.Companion.getInstance
import java.util.function.Consumer

class LockTileService : TileService() {
    private var hasUnlockActivity = false
    private var lockStore: LockStore? = null

    override fun onBind(intent: Intent): IBinder? {
        lockStore = getInstance(this)

        val status = packageManager
            .getComponentEnabledSetting(ComponentName(this, UnlockActivity::class.java))
        hasUnlockActivity = PackageManager.COMPONENT_ENABLED_STATE_DISABLED != status

        return super.onBind(intent)
    }

    override fun onStartListening() {
        super.onStartListening()

        initializeTile()
        updateTile.accept(lockStore!!.isLocked)
        lockStore!!.addListener(updateTile)
    }

    override fun onStopListening() {
        super.onStopListening()
        lockStore!!.removeListener(updateTile)
    }

    override fun onClick() {
        super.onClick()

        if (lockStore!!.isLocked) {
            if (hasUnlockActivity) {
                val intent = Intent(this, UnlockActivity::class.java)
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                startActivityAndCollapse(intent)
            } else {
                lockStore!!.unlock()
            }
        } else {
            lockStore!!.lock()
        }
    }

    private fun initializeTile() {
        val tile = qsTile
        tile.icon = Icon.createWithResource(
            this,
            R.drawable.ic_key_tile
        )
    }

    private val updateTile = Consumer { isLocked: Boolean ->
        val tile = qsTile
        if (isLocked) {
            tile.label = getString(R.string.tile_unlock)
            tile.state = Tile.STATE_INACTIVE
            if (Build.VERSION.SDK_INT >= 30) {
                tile.stateDescription = getString(R.string.tile_status_locked)
            }
        } else {
            tile.label = getString(R.string.tile_lock)
            tile.state = Tile.STATE_ACTIVE
            if (Build.VERSION.SDK_INT >= 30) {
                tile.stateDescription = getString(R.string.tile_status_unlocked)
            }
        }
        tile.updateTile()
    }
}


================================================
FILE: app/src/main/java/alt/nainapps/aer/lock/UnlockActivity.kt
================================================
/*
 * Copyright (c) 2022 2bllw8
 * SPDX-License-Identifier: GPL-3.0-only
 */
package alt.nainapps.aer.lock

import alt.nainapps.aer.R
import alt.nainapps.aer.config.ConfigurationActivity
import alt.nainapps.aer.config.password.PasswordTextListener
import alt.nainapps.aer.lock.LockStore.Companion.getInstance
import alt.nainapps.aer.shell.LauncherActivity
import android.app.Activity
import android.content.DialogInterface
import android.content.Intent
import android.hardware.biometrics.BiometricPrompt
import android.os.Bundle
import android.os.CancellationSignal
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import androidx.annotation.RequiresApi

class UnlockActivity : Activity() {
    private var lockStore: LockStore? = null
    private var onUnlocked: Runnable? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        lockStore = getInstance(this)
        onUnlocked = getOnUnlocked(intent)
        if (lockStore!!.hasPassword()) {
            if (lockStore!!.isBiometricUnlockEnabled) {
                unlockViaBiometricAuthentication()
            } else {
                setupUI()
            }
        } else {
            doUnlock()
        }
    }

    private fun setupUI() {
        setContentView(R.layout.password_input)
        setFinishOnTouchOutside(true)

        val passwordField = findViewById<EditText>(R.id.passwordFieldView)
        val configBtn = findViewById<ImageView>(R.id.configurationButton)
        val unlockBtn = findViewById<Button>(R.id.unlockButton)
        val cancelBtn = findViewById<Button>(R.id.cancelButton)

        passwordField.addTextChangedListener(PasswordTextListener { text: String? ->
            unlockBtn.isEnabled = passwordField.text.length >= MIN_PASSWORD_LENGTH
        })

        configBtn.setOnClickListener { v: View? ->
            startActivity(Intent(this, ConfigurationActivity::class.java))
            setResult(RESULT_CANCELED)
            finish()
        }

        unlockBtn.isEnabled = false
        unlockBtn.setOnClickListener { v: View? ->
            val value = passwordField.text.toString()
            if (lockStore!!.passwordMatch(value)) {
                doUnlock()
            } else {
                passwordField.error = getString(R.string.password_error_wrong)
            }
        }

        cancelBtn.setOnClickListener { v: View? ->
            setResult(RESULT_CANCELED)
            finish()
        }
    }

    private fun doUnlock() {
        lockStore!!.unlock()
        onUnlocked!!.run()
    }

    @RequiresApi(29)
    private fun unlockViaBiometricAuthentication() {
        val executor = mainExecutor
        val cancellationSignal = CancellationSignal()
        cancellationSignal.setOnCancelListener { this.finish() }

        val prompt = BiometricPrompt.Builder(this)
            .setTitle(getString(R.string.tile_unlock))
            .setDescription(getString(R.string.password_input_biometric_message))
            .setNegativeButton(
                getString(R.string.password_input_biometric_fallback), executor
            ) { dialog: DialogInterface?, which: Int -> setupUI() }
            .build()
        prompt.authenticate(cancellationSignal, executor,
            object : BiometricPrompt.AuthenticationCallback() {
                override fun onAuthenticationSucceeded(
                    result: BiometricPrompt.AuthenticationResult
                ) {
                    doUnlock()
                }

                override fun onAuthenticationFailed() {
                    setResult(RESULT_CANCELED)
                    finish()
                }
            })
    }

    private fun getOnUnlocked(intent: Intent): Runnable {
        return if (intent.getBooleanExtra(OPEN_AFTER_UNLOCK, false)) {
            Runnable {
                startActivity(
                    Intent(
                        this,
                        LauncherActivity::class.java
                    )
                )
                setResult(RESULT_OK)
                finish()
            }
        } else {
            Runnable {
                setResult(RESULT_OK)
                finish()
            }
        }
    }

    companion object {
        const val OPEN_AFTER_UNLOCK: String = "open_after_unlock"
        private const val MIN_PASSWORD_LENGTH = 4
    }
}


================================================
FILE: app/src/main/java/alt/nainapps/aer/shell/AnemoShell.kt
================================================
/*
 * Copyright (c) 2022 2bllw8
 * SPDX-License-Identifier: GPL-3.0-only
 */
package alt.nainapps.aer.shell

import android.content.ComponentName
import android.content.Context
import android.content.pm.PackageManager

object AnemoShell {
    fun isEnabled(context: Context): Boolean {
        val packageManager = context.packageManager
        val status = packageManager
            .getComponentEnabledSetting(ComponentName(context, LauncherActivity::class.java))
        return PackageManager.COMPONENT_ENABLED_STATE_DISABLED > status
    }

    fun setEnabled(context: Context, enabled: Boolean) {
        val packageManager = context.packageManager
        val newStatus = if (enabled
        ) PackageManager.COMPONENT_ENABLED_STATE_ENABLED
        else PackageManager.COMPONENT_ENABLED_STATE_DISABLED
        packageManager.setComponentEnabledSetting(
            ComponentName(context, LauncherActivity::class.java), newStatus,
            PackageManager.DONT_KILL_APP
        )
    }
}


================================================
FILE: app/src/main/java/alt/nainapps/aer/shell/LauncherActivity.kt
================================================
/*
 * Copyright (c) 2022 2bllw8
 * SPDX-License-Identifier: GPL-3.0-only
 */
package alt.nainapps.aer.shell

import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.DocumentsContract
import android.widget.Toast
import alt.nainapps.aer.R
import alt.nainapps.aer.documents.home.HomeEnvironment
import alt.nainapps.aer.lock.LockStore
import alt.nainapps.aer.lock.UnlockActivity
import java.util.Arrays

class LauncherActivity : Activity() {
    private val LAUNCHER_INTENTS = arrayOf(
        // AOSP, up to Android 11
        Intent(Intent.ACTION_VIEW, ANEMO_URI).setClassName(
            DOCUMENTS_UI_PACKAGE,
            DOCUMENTS_UI_ACTIVITY
        ),
        Intent(Intent.ACTION_VIEW, ANEMO_URI).setClassName(
            DOCUMENTS_UI_PACKAGE,
            DOCUMENTS_UI_ALIAS_ACTIVITY
        ),  // Pixels, Android 12+
        Intent(Intent.ACTION_VIEW, ANEMO_URI).setClassName(
            GOOGLE_DOCUMENTS_UI_PACKAGE,
            DOCUMENTS_UI_ACTIVITY
        ),  // Android 13+
        Intent(Intent.ACTION_VIEW, ANEMO_URI).setType(TYPE_DOCS_DIRECTORY)
            .setFlags(
                Intent.FLAG_ACTIVITY_FORWARD_RESULT
                        or Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP
            ),
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (LockStore.getInstance(this)?.isLocked == true) {
            startActivity(
                Intent(this, UnlockActivity::class.java)
                    .putExtra(UnlockActivity.OPEN_AFTER_UNLOCK, true)
            )
        } else {
            val pm = packageManager
            val fileIntent = Arrays.stream(LAUNCHER_INTENTS)
                .filter { intent: Intent -> canHandle(pm, intent) }
                .findAny()
            if (fileIntent.isPresent) {
                startActivity(fileIntent.get())
                overridePendingTransition(0, 0)
            } else {
                Toast.makeText(this, R.string.launcher_no_activity, Toast.LENGTH_LONG).show()
            }
        }
        finish()
    }

    private fun canHandle(pm: PackageManager, intent: Intent): Boolean {
        return pm.resolveActivity(intent, PackageManager.MATCH_ALL) != null
    }

    companion object {
        // https://cs.android.com/android/platform/superproject/+/master:packages/apps/DocumentsUI/AndroidManifest.xml
        private const val DOCUMENTS_UI_PACKAGE = "com.android.documentsui"
        private const val DOCUMENTS_UI_ACTIVITY = (DOCUMENTS_UI_PACKAGE
                + ".files.FilesActivity")
        private const val DOCUMENTS_UI_ALIAS_ACTIVITY = (DOCUMENTS_UI_PACKAGE
                + ".FilesActivity")
        private const val GOOGLE_DOCUMENTS_UI_PACKAGE = "com.google.android.documentsui"
        private const val TYPE_DOCS_DIRECTORY = "vnd.android.document/directory"
        private val ANEMO_URI: Uri = DocumentsContract.buildRootsUri(HomeEnvironment.AUTHORITY)
    }
}


================================================
FILE: app/src/main/java/alt/nainapps/aer/task/TaskExecutor.java
================================================
/*
 * Copyright (c) 2021 2bllw8
 * SPDX-License-Identifier: GPL-3.0-only
 */
package alt.nainapps.aer.task;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import androidx.annotation.MainThread;
import androidx.annotation.WorkerThread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Consumer;

public final class TaskExecutor {
    private static final String TAG = "TaskExecutor";

    private final ExecutorService executor = Executors.newFixedThreadPool(2);
    private final Handler handler = new Handler(Looper.getMainLooper());
    private final List<Future<?>> execFutures = new ArrayList<>(4);

    public synchronized <T> void runTask(@WorkerThread Callable<T> callable,
            @MainThread Consumer<T> consumer) {
        final Future<T> future = executor.submit(callable);
        execFutures.add(future);
        try {
            final T result = future.get(1, TimeUnit.MINUTES);
            // It's completed, remove to free memory
            execFutures.remove(future);
            // Post result
            handler.post(() -> consumer.accept(result));
        } catch (InterruptedException e) {
            Log.w(TAG, e);
        } catch (ExecutionException | TimeoutException e) {
            throw new RuntimeException("An error occurred while executing task", e.getCause());
        }
    }

    public void terminate() {
        executor.shutdown();
        if (hasUnfinishedTasks()) {
            try {
                if (!executor.awaitTermination(250, TimeUnit.MILLISECONDS)) {
                    executor.shutdownNow();
                    //@formatter:off
                    //noinspection ResultOfMethodCallIgnored
                    executor.awaitTermination(100, TimeUnit.MILLISECONDS);
                    //@formatter:on
                }
            } catch (InterruptedException e) {
                Log.e(TAG, "Interrupted", e);
                // (Re-)Cancel if current thread also interrupted
                executor.shutdownNow();
                // Preserve interrupt status
                Thread.currentThread().interrupt();
            }
        }
    }

    private boolean hasUnfinishedTasks() {
        for (final Future<?> future : execFutures) {
            if (!future.isDone()) {
                return true;
            }
        }
        return false;
    }
}


================================================
FILE: app/src/main/res/color/btn_colored_text.xml
================================================
<!-- Copyright (C) 2015 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<!-- Used for the text of a bordered colored button. -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:alpha="?android:attr/disabledAlpha" android:color="?android:attr/colorAccent" android:state_enabled="false" />
    <item android:color="?android:attr/colorAccent" />
</selector>


================================================
FILE: app/src/main/res/drawable/ic_configuration.xml
================================================
<!--
  ~ Copyright (c) 2022 2bllw8
  ~ SPDX-License-Identifier: GPL-3.0-only
  -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:autoMirrored="true"
    android:tint="?android:textColorPrimary"
    android:viewportWidth="24"
    android:viewportHeight="24">
    <path
        android:fillColor="@android:color/white"
        android:pathData="M19.43,12.98c0.04,-0.32 0.07,-0.64 0.07,-0.98s-0.03,-0.66 -0.07,-0.98l2.11,-1.65c0.19,-0.15 0.24,-0.42 0.12,-0.64l-2,-3.46c-0.12,-0.22 -0.39,-0.3 -0.61,-0.22l-2.49,1c-0.52,-0.4 -1.08,-0.73 -1.69,-0.98l-0.38,-2.65C14.46,2.18 14.25,2 14,2h-4c-0.25,0 -0.46,0.18 -0.49,0.42l-0.38,2.65c-0.61,0.25 -1.17,0.59 -1.69,0.98l-2.49,-1c-0.23,-0.09 -0.49,0 -0.61,0.22l-2,3.46c-0.13,0.22 -0.07,0.49 0.12,0.64l2.11,1.65c-0.04,0.32 -0.07,0.65 -0.07,0.98s0.03,0.66 0.07,0.98l-2.11,1.65c-0.19,0.15 -0.24,0.42 -0.12,0.64l2,3.46c0.12,0.22 0.39,0.3 0.61,0.22l2.49,-1c0.52,0.4 1.08,0.73 1.69,0.98l0.38,2.65c0.03,0.24 0.24,0.42 0.49,0.42h4c0.25,0 0.46,-0.18 0.49,-0.42l0.38,-2.65c0.61,-0.25 1.17,-0.59 1.69,-0.98l2.49,1c0.23,0.09 0.49,0 0.61,-0.22l2,-3.46c0.12,-0.22 0.07,-0.49 -0.12,-0.64l-2.11,-1.65zM12,15.5c-1.93,0 -3.5,-1.57 -3.5,-3.5s1.57,-3.5 3.5,-3.5 3.5,1.57 3.5,3.5 -1.57,3.5 -3.5,3.5z" />
</vector>


================================================
FILE: app/src/main/res/drawable/ic_error.xml
================================================
<!--
  ~ Copyright (c) 2023 2bllw8
  ~ SPDX-License-Identifier: GPL-3.0-only
  -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:tint="?android:colorError"
    android:viewportWidth="24"
    android:viewportHeight="24">
    <path
        android:fillColor="@android:color/white"
        android:pathData="M11,15h2v2h-2zM11,7h2v6h-2zM11.99,2C6.47,2 2,6.48 2,12s4.47,10 9.99,10C17.52,22 22,17.52 22,12S17.52,2 11.99,2zM12,20c-4.42,0 -8,-3.58 -8,-8s3.58,-8 8,-8 8,3.58 8,8 -3.58,8 -8,8z" />
</vector>


================================================
FILE: app/src/main/res/drawable/ic_key_tile.xml
================================================
<!--
  ~ Copyright (c) 2021 2bllw8
  ~ SPDX-License-Identifier: GPL-3.0-only
  -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="48dp"
    android:height="48dp"
    android:viewportWidth="24"
    android:viewportHeight="24">
    <path
        android:fillColor="@android:color/white"
        android:pathData="M4,10A1,1 0,0 1,3 9A1,1 0,0 1,4 8H12A2,2 0,0 0,14 6A2,2 0,0 0,12 4C11.45,4 10.95,4.22 10.59,4.59C10.2,5 9.56,5 9.17,4.59C8.78,4.2 8.78,3.56 9.17,3.17C9.9,2.45 10.9,2 12,2A4,4 0,0 1,16 6A4,4 0,0 1,12 10H4M19,12A1,1 0,0 0,20 11A1,1 0,0 0,19 10C18.72,10 18.47,10.11 18.29,10.29C17.9,10.68 17.27,10.68 16.88,10.29C16.5,9.9 16.5,9.27 16.88,8.88C17.42,8.34 18.17,8 19,8A3,3 0,0 1,22 11A3,3 0,0 1,19 14H5A1,1 0,0 1,4 13A1,1 0,0 1,5 12H19M18,18H4A1,1 0,0 1,3 17A1,1 0,0 1,4 16H18A3,3 0,0 1,21 19A3,3 0,0 1,18 22C17.17,22 16.42,21.66 15.88,21.12C15.5,20.73 15.5,20.1 15.88,19.71C16.27,19.32 16.9,19.32 17.29,19.71C17.47,19.89 17.72,20 18,20A1,1 0,0 0,19 19A1,1 0,0 0,18 18Z" />
</vector>


================================================
FILE: app/src/main/res/drawable/ic_launcher_foreground.xml
================================================
<!--
  ~ Copyright (c) 2021 2bllw8
  ~ SPDX-License-Identifier: GPL-3.0-only
  -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="108dp"
    android:height="108dp"
    android:viewportWidth="108"
    android:viewportHeight="108">
  <group
      android:scaleX="2.178"
      android:scaleY="2.178"
      android:translateX="26.896"
      android:translateY="27.864">
    <path
        android:fillColor="@color/launcher_foreground"
        android:pathData="M4,10A1,1 0,0 1,3 9A1,1 0,0 1,4 8H12A2,2 0,0 0,14 6A2,2 0,0 0,12 4C11.45,4 10.95,4.22 10.59,4.59C10.2,5 9.56,5 9.17,4.59C8.78,4.2 8.78,3.56 9.17,3.17C9.9,2.45 10.9,2 12,2A4,4 0,0 1,16 6A4,4 0,0 1,12 10H4M19,12A1,1 0,0 0,20 11A1,1 0,0 0,19 10C18.72,10 18.47,10.11 18.29,10.29C17.9,10.68 17.27,10.68 16.88,10.29C16.5,9.9 16.5,9.27 16.88,8.88C17.42,8.34 18.17,8 19,8A3,3 0,0 1,22 11A3,3 0,0 1,19 14H5A1,1 0,0 1,4 13A1,1 0,0 1,5 12H19M18,18H4A1,1 0,0 1,3 17A1,1 0,0 1,4 16H18A3,3 0,0 1,21 19A3,3 0,0 1,18 22C17.17,22 16.42,21.66 15.88,21.12C15.5,20.73 15.5,20.1 15.88,19.71C16.27,19.32 16.9,19.32 17.29,19.71C17.47,19.89 17.72,20 18,20A1,1 0,0 0,19 19A1,1 0,0 0,18 18Z" />
  </group>
</vector>


================================================
FILE: app/src/main/res/drawable/ic_launcher_monochrome.xml
================================================
<!--
  ~ Copyright (c) 2022 2bllw8
  ~ SPDX-License-Identifier: GPL-3.0-only
  -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="108dp"
    android:height="108dp"
    android:viewportWidth="108"
    android:viewportHeight="108">
  <group
      android:scaleX="2.178"
      android:scaleY="2.178"
      android:translateX="26.896"
      android:translateY="27.864">
    <path
        android:fillColor="#000000"
        android:pathData="M4,10A1,1 0,0 1,3 9A1,1 0,0 1,4 8H12A2,2 0,0 0,14 6A2,2 0,0 0,12 4C11.45,4 10.95,4.22 10.59,4.59C10.2,5 9.56,5 9.17,4.59C8.78,4.2 8.78,3.56 9.17,3.17C9.9,2.45 10.9,2 12,2A4,4 0,0 1,16 6A4,4 0,0 1,12 10H4M19,12A1,1 0,0 0,20 11A1,1 0,0 0,19 10C18.72,10 18.47,10.11 18.29,10.29C17.9,10.68 17.27,10.68 16.88,10.29C16.5,9.9 16.5,9.27 16.88,8.88C17.42,8.34 18.17,8 19,8A3,3 0,0 1,22 11A3,3 0,0 1,19 14H5A1,1 0,0 1,4 13A1,1 0,0 1,5 12H19M18,18H4A1,1 0,0 1,3 17A1,1 0,0 1,4 16H18A3,3 0,0 1,21 19A3,3 0,0 1,18 22C17.17,22 16.42,21.66 15.88,21.12C15.5,20.73 15.5,20.1 15.88,19.71C16.27,19.32 16.9,19.32 17.29,19.71C17.47,19.89 17.72,20 18,20A1,1 0,0 0,19 19A1,1 0,0 0,18 18Z" />
  </group>
</vector>


================================================
FILE: app/src/main/res/drawable/ic_shortcut_configuration.xml
================================================
<!--
  ~ Copyright (c) 2022 2bllw8
  ~ SPDX-License-Identifier: GPL-3.0-only
  -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:autoMirrored="true"
    android:tint="@color/launcher_background"
    android:viewportWidth="24"
    android:viewportHeight="24">
    <path
        android:fillColor="@android:color/white"
        android:pathData="M19.43,12.98c0.04,-0.32 0.07,-0.64 0.07,-0.98s-0.03,-0.66 -0.07,-0.98l2.11,-1.65c0.19,-0.15 0.24,-0.42 0.12,-0.64l-2,-3.46c-0.12,-0.22 -0.39,-0.3 -0.61,-0.22l-2.49,1c-0.52,-0.4 -1.08,-0.73 -1.69,-0.98l-0.38,-2.65C14.46,2.18 14.25,2 14,2h-4c-0.25,0 -0.46,0.18 -0.49,0.42l-0.38,2.65c-0.61,0.25 -1.17,0.59 -1.69,0.98l-2.49,-1c-0.23,-0.09 -0.49,0 -0.61,0.22l-2,3.46c-0.13,0.22 -0.07,0.49 0.12,0.64l2.11,1.65c-0.04,0.32 -0.07,0.65 -0.07,0.98s0.03,0.66 0.07,0.98l-2.11,1.65c-0.19,0.15 -0.24,0.42 -0.12,0.64l2,3.46c0.12,0.22 0.39,0.3 0.61,0.22l2.49,-1c0.52,0.4 1.08,0.73 1.69,0.98l0.38,2.65c0.03,0.24 0.24,0.42 0.49,0.42h4c0.25,0 0.46,-0.18 0.49,-0.42l0.38,-2.65c0.61,-0.25 1.17,-0.59 1.69,-0.98l2.49,1c0.23,0.09 0.49,0 0.61,-0.22l2,-3.46c0.12,-0.22 0.07,-0.49 -0.12,-0.64l-2.11,-1.65zM12,15.5c-1.93,0 -3.5,-1.57 -3.5,-3.5s1.57,-3.5 3.5,-3.5 3.5,1.57 3.5,3.5 -1.57,3.5 -3.5,3.5z" />
</vector>


================================================
FILE: app/src/main/res/drawable/ic_storage.xml
================================================
<!--
  ~ Copyright (c) 2021 2bllw8
  ~ SPDX-License-Identifier: GPL-3.0-only
  -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24">
  <path
      android:fillColor="@color/anemo_accent"
      android:pathData="M4,10A1,1 0,0 1,3 9A1,1 0,0 1,4 8H12A2,2 0,0 0,14 6A2,2 0,0 0,12 4C11.45,4 10.95,4.22 10.59,4.59C10.2,5 9.56,5 9.17,4.59C8.78,4.2 8.78,3.56 9.17,3.17C9.9,2.45 10.9,2 12,2A4,4 0,0 1,16 6A4,4 0,0 1,12 10H4M19,12A1,1 0,0 0,20 11A1,1 0,0 0,19 10C18.72,10 18.47,10.11 18.29,10.29C17.9,10.68 17.27,10.68 16.88,10.29C16.5,9.9 16.5,9.27 16.88,8.88C17.42,8.34 18.17,8 19,8A3,3 0,0 1,22 11A3,3 0,0 1,19 14H5A1,1 0,0 1,4 13A1,1 0,0 1,5 12H19M18,18H4A1,1 0,0 1,3 17A1,1 0,0 1,4 16H18A3,3 0,0 1,21 19A3,3 0,0 1,18 22C17.17,22 16.42,21.66 15.88,21.12C15.5,20.73 15.5,20.1 15.88,19.71C16.27,19.32 16.9,19.32 17.29,19.71C17.47,19.89 17.72,20 18,20A1,1 0,0 0,19 19A1,1 0,0 0,18 18Z" />
</vector>


================================================
FILE: app/src/main/res/layout/configuration.xml
================================================
<!--
  ~ Copyright (c) 2022 2bllw8
  ~ Copyright (c) 2024 nain
  ~ SPDX-License-Identifier: GPL-3.0-only
  -->
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingVertical="8dp">

        <Switch
            android:id="@+id/configuration_show_shortcut"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:foreground="?android:attr/selectableItemBackground"
            android:minHeight="56dp"
            android:paddingHorizontal="16dp"
            android:text="@string/configuration_shortcut"
            android:textSize="16sp" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:paddingHorizontal="16dp"
            android:text="@string/configuration_protection"
            android:textColor="?android:attr/colorAccent" />

        <TextView
            android:id="@+id/configuration_lock"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:foreground="?android:attr/selectableItemBackground"
            android:gravity="center_vertical"
            android:minHeight="56dp"
            android:paddingHorizontal="16dp"
            android:textColor="?android:textColorPrimary"
            android:textSize="16sp"
            tools:text="@string/configuration_storage_lock" />

        <TextView
            android:id="@+id/configuration_password_set"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:foreground="?android:attr/selectableItemBackground"
            android:gravity="center_vertical"
            android:minHeight="56dp"
            android:paddingHorizontal="16dp"
            android:textColor="?android:textColorPrimary"
            android:textSize="16sp"
            tools:text="@string/configuration_password_set" />

        <Switch
            android:id="@+id/configuration_biometric_unlock"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:foreground="?android:attr/selectableItemBackground"
            android:minHeight="56dp"
            android:paddingHorizontal="16dp"
            android:text="@string/configuration_storage_unlock_biometric"
            android:textSize="16sp" />

        <Switch
            android:id="@+id/configuration_auto_lock"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:foreground="?android:attr/selectableItemBackground"
            android:minHeight="56dp"
            android:paddingHorizontal="16dp"
            android:text="@string/configuration_storage_lock_auto"
            android:textSize="16sp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/configuration_auto_lock_delay_label"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:labelFor="@+id/config_auto_lock_delay_minutes"
                android:paddingHorizontal="16dp"
                android:text="@string/configuration_auto_lock_delay_minutes_label"
                android:textColor="?android:textColorPrimary"
                android:textSize="16sp"
                tools:text="@string/configuration_auto_lock_delay_minutes_label" />

            <EditText
                android:id="@+id/config_auto_lock_delay_minutes"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:autofillHints="autoLockDelayMinutes"
                android:minHeight="56dp"
                android:minEms="3"
                android:maxEms="5"
                android:inputType="number" />
        </LinearLayout>


    </LinearLayout>
</ScrollView>


================================================
FILE: app/src/main/res/layout/password_change.xml
================================================
<!--
  ~ Copyright (c) 2021 2bllw8
  ~ SPDX-License-Identifier: GPL-3.0-only
  -->
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingHorizontal="?android:attr/dialogPreferredPadding"
        android:paddingTop="6dp">

        <TextView
            style="@android:style/TextAppearance.Material.Body1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="12dp"
            android:text="@string/password_change_message"
            android:textColor="?android:attr/textColorSecondary" />

        <TextView
            style="@android:style/TextAppearance.Material.Caption"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:labelFor="@id/currentFieldView"
            android:text="@string/password_hint_current" />

        <EditText
            android:id="@+id/currentFieldView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="12dp"
            android:importantForAutofill="no"
            android:inputType="textPassword"
            android:maxLength="128"
            android:maxLines="1"
            android:singleLine="true" />

        <TextView
            style="@android:style/TextAppearance.Material.Caption"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:labelFor="@id/passwordFieldView"
            android:text="@string/password_hint_field" />

        <EditText
            android:id="@+id/passwordFieldView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="12dp"
            android:importantForAutofill="no"
            android:inputType="textPassword"
            android:maxLength="128"
            android:maxLines="1"
            android:singleLine="true" />

        <TextView
            style="@android:style/TextAppearance.Material.Caption"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:labelFor="@id/repeatFieldView"
            android:text="@string/password_hint_repeat" />

        <EditText
            android:id="@+id/repeatFieldView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="12dp"
            android:importantForAutofill="no"
            android:inputType="textPassword"
            android:maxLength="128"
            android:maxLines="1"
            android:singleLine="true" />
    </LinearLayout>
</ScrollView>


================================================
FILE: app/src/main/res/layout/password_first_set.xml
================================================
<!--
  ~ Copyright (c) 2021 2bllw8
  ~ SPDX-License-Identifier: GPL-3.0-only
  -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingHorizontal="?android:attr/dialogPreferredPadding"
    android:paddingTop="6dp">

    <TextView
        style="@android:style/TextAppearance.Material.Body1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="12dp"
        android:text="@string/password_set_message"
        android:textColor="?android:attr/textColorSecondary" />

    <TextView
        style="@android:style/TextAppearance.Material.Caption"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:labelFor="@id/passwordFieldView"
        android:text="@string/password_hint_field" />

    <EditText
        android:id="@+id/passwordFieldView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="12dp"
        android:importantForAutofill="no"
        android:inputType="textPassword"
        android:maxLength="128"
        android:maxLines="1"
        android:singleLine="true" />

    <TextView
        style="@android:style/TextAppearance.Material.Caption"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:labelFor="@id/repeatFieldView"
        android:text="@string/password_hint_repeat" />

    <EditText
        android:id="@+id/repeatFieldView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="12dp"
        android:importantForAutofill="no"
        android:inputType="textPassword"
        android:maxLength="128"
        android:maxLines="1"
        android:singleLine="true" />
</LinearLayout>


================================================
FILE: app/src/main/res/layout/password_input.xml
================================================
<!--
  ~ Copyright (c) 2021 2bllw8
  ~ SPDX-License-Identifier: GPL-3.0-only
  -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingHorizontal="?android:attr/dialogPreferredPadding"
    android:paddingTop="?android:attr/dialogPreferredPadding"
    android:paddingBottom="6dp">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="12dp">

        <TextView
            style="@android:style/TextAppearance.Material.WindowTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/tile_unlock" />

        <ImageView
            android:id="@+id/configurationButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="end|center_vertical"
            android:contentDescription="@string/configuration_label"
            android:foreground="?android:attr/selectableItemBackgroundBorderless"
            android:src="@drawable/ic_configuration"
            android:tooltipText="@string/configuration_label" />
    </FrameLayout>

    <TextView
        style="@android:style/TextAppearance.Material.Body1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="12dp"
        android:text="@string/password_input_message"
        android:textColor="?android:attr/textColorSecondary" />

    <TextView
        style="@android:style/TextAppearance.Material.Caption"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:labelFor="@id/passwordFieldView"
        android:text="@string/password_hint_field" />

    <EditText
        android:id="@+id/passwordFieldView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="12dp"
        android:importantForAutofill="no"
        android:inputType="textPassword"
        android:maxLength="128"
        android:maxLines="1"
        android:singleLine="true" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="end|center_vertical"
        android:orientation="horizontal">

        <Button
            android:id="@+id/cancelButton"
            style="@android:style/Widget.DeviceDefault.Button.Borderless.Small"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@android:string/cancel"
            android:textColor="@color/btn_colored_text" />

        <Button
            android:id="@+id/unlockButton"
            style="@android:style/Widget.DeviceDefault.Button.Borderless.Small"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/password_input_action"
            android:textColor="@color/btn_colored_text" />
    </LinearLayout>
</LinearLayout>


================================================
FILE: app/src/main/res/mipmap-anydpi/ic_launcher.xml
================================================
<!--
  ~ Copyright (c) 2021 2bllw8
  ~ SPDX-License-Identifier: GPL-3.0-only
  -->
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
    <background android:drawable="@color/launcher_background" />
    <foreground android:drawable="@drawable/ic_launcher_foreground" />
    <monochrome android:drawable="@drawable/ic_launcher_monochrome" />
</adaptive-icon>


================================================
FILE: app/src/main/res/values/colors.xml
================================================
<!--
  ~ Copyright (c) 2021 2bllw8
  ~ SPDX-License-Identifier: GPL-3.0-only
  -->
<resources>
    <color name="anemo_primary">#f0f0f0</color>
    <color name="anemo_primary_dark">#f0f0f0</color>
    <color name="anemo_accent">@color/launcher_background</color>

    <color name="launcher_background">#2196F3</color>
    <color name="launcher_foreground">#F9EBF0</color>
</resources>


================================================
FILE: app/src/main/res/values/strings.xml
================================================
<!--
  ~ Copyright (c) 2021 2bllw8
  ~ SPDX-License-Identifier: GPL-3.0-only
  -->
<resources>
    <string name="app_name">Aer</string>

    <string name="anemo_description">Local private storage</string>
    <string name="anemo_info">Files in Aer storage are not directly accessible to other apps.\n\nNote that Aer is in development 🏗️. Accidents happen. Please keeps backups 👷‍♀️ for your protection.</string>
    <string name="anemo_error">Prior to Android 11, external storage is readily visible to other apps. Prefer Internal storage for better privacy.</string>

    <string name="password_label">Aer password</string>

    <string name="password_hint_field">Password</string>
    <string name="password_hint_repeat">Type again to confirm</string>
    <string name="password_hint_current">Current password</string>

    <string name="password_error_length">The password should have length at least %1$d</string>
    <string name="password_error_mismatch">The passwords do not match</string>
    <string name="password_error_wrong">Wrong password</string>

    <string name="password_input_message">Type your Aer password to unlock the Aer Storage</string>
    <string name="password_input_action">Unlock</string>
    <string name="password_input_biometric_message">Authenticate to unlock the Aer Storage</string>
    <string name="password_input_biometric_fallback">Use password</string>

    <string name="password_set_title">Add password protection</string>
    <string name="password_set_message">Set a password to lock the access to the Aer Storage</string>
    <string name="password_set_action">Set password</string>

    <string name="password_change_title">Change password</string>
    <string name="password_change_message">Change the password to unlock the Aer Storage</string>
    <string name="password_change_action">Change</string>
    <string name="password_change_remove">Remove</string>

    <string name="receiver_label">Import into Aer</string>

    <string name="receiver_importing_message">Importing the file…<
Download .txt
gitextract_so4unp8y/

├── .gitattributes
├── .githooks/
│   └── pre-commit
├── .github/
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug_report.yml
│   │   ├── config.yml
│   │   └── feature_request.yml
│   └── workflows/
│       ├── main.yml
│       └── release.yml
├── .gitignore
├── COPYING
├── README.md
├── app/
│   ├── .gitignore
│   ├── build.gradle.kts
│   ├── code-format.xml
│   ├── proguard-rules.pro
│   └── src/
│       └── main/
│           ├── AndroidManifest.xml
│           ├── java/
│           │   └── alt/
│           │       └── nainapps/
│           │           └── aer/
│           │               ├── config/
│           │               │   ├── ConfigurationActivity.kt
│           │               │   ├── StorageConfigActivity.kt
│           │               │   ├── autolock/
│           │               │   │   └── AutoLockDelayMinutesTextListener.kt
│           │               │   ├── password/
│           │               │   │   ├── ChangePasswordDialog.kt
│           │               │   │   ├── PasswordDialog.kt
│           │               │   │   ├── PasswordTextListener.kt
│           │               │   │   └── SetPasswordDialog.kt
│           │               │   └── ui/
│           │               │       └── theme/
│           │               │           ├── Color.kt
│           │               │           ├── Theme.kt
│           │               │           └── Type.kt
│           │               ├── documents/
│           │               │   ├── home/
│           │               │   │   └── HomeEnvironment.kt
│           │               │   ├── provider/
│           │               │   │   ├── AnemoDocumentProvider.kt
│           │               │   │   ├── EmptyCursor.kt
│           │               │   │   ├── FileSystemProvider.kt
│           │               │   │   └── PathUtils.kt
│           │               │   └── receiver/
│           │               │       └── ReceiverActivity.kt
│           │               ├── lock/
│           │               │   ├── AutoLockJobService.kt
│           │               │   ├── LockStore.kt
│           │               │   ├── LockTileService.kt
│           │               │   └── UnlockActivity.kt
│           │               ├── shell/
│           │               │   ├── AnemoShell.kt
│           │               │   └── LauncherActivity.kt
│           │               └── task/
│           │                   └── TaskExecutor.java
│           └── res/
│               ├── color/
│               │   └── btn_colored_text.xml
│               ├── drawable/
│               │   ├── ic_configuration.xml
│               │   ├── ic_error.xml
│               │   ├── ic_key_tile.xml
│               │   ├── ic_launcher_foreground.xml
│               │   ├── ic_launcher_monochrome.xml
│               │   ├── ic_shortcut_configuration.xml
│               │   └── ic_storage.xml
│               ├── layout/
│               │   ├── configuration.xml
│               │   ├── password_change.xml
│               │   ├── password_first_set.xml
│               │   └── password_input.xml
│               ├── mipmap-anydpi/
│               │   └── ic_launcher.xml
│               ├── values/
│               │   ├── colors.xml
│               │   ├── strings.xml
│               │   ├── styles.xml
│               │   └── themes.xml
│               ├── values-es/
│               │   └── strings.xml
│               ├── values-fr/
│               │   └── strings.xml
│               ├── values-it/
│               │   └── strings.xml
│               ├── values-night/
│               │   ├── colors.xml
│               │   └── styles.xml
│               ├── values-night-v31/
│               │   └── colors.xml
│               ├── values-pt-rBR/
│               │   └── strings.xml
│               ├── values-v27/
│               │   └── styles.xml
│               ├── values-v31/
│               │   └── colors.xml
│               └── xml/
│                   ├── backup_rules.xml
│                   ├── data_extraction_rules.xml
│                   └── shortcuts.xml
├── build.gradle
├── gradle/
│   ├── libs.versions.toml
│   └── wrapper/
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
├── metadata/
│   ├── en-US/
│   │   ├── full_description.txt
│   │   ├── short_description.txt
│   │   └── title.txt
│   ├── es-ES/
│   │   ├── full_description.txt
│   │   ├── short_description.txt
│   │   └── title.txt
│   ├── fr-FR/
│   │   ├── full_description.txt
│   │   ├── short_description.txt
│   │   └── title.txt
│   ├── it-IT/
│   │   ├── full_description.txt
│   │   ├── short_description.txt
│   │   └── title.txt
│   └── pt-rBR/
│       ├── full_description.txt
│       ├── short_description.txt
│       └── title.txt
└── settings.gradle.kts
Download .txt
SYMBOL INDEX (4 symbols across 1 files)

FILE: app/src/main/java/alt/nainapps/aer/task/TaskExecutor.java
  class TaskExecutor (line 25) | public final class TaskExecutor {
    method runTask (line 32) | public synchronized <T> void runTask(@WorkerThread Callable<T> callable,
    method terminate (line 49) | public void terminate() {
    method hasUnfinishedTasks (line 70) | private boolean hasUnfinishedTasks() {
Condensed preview — 90 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (251K chars).
[
  {
    "path": ".gitattributes",
    "chars": 285,
    "preview": "# Set the default behavior, in case people don't have core.autocrlf set.\n* text=auto eol=lf\n\n# Declare files that will a"
  },
  {
    "path": ".githooks/pre-commit",
    "chars": 1784,
    "preview": "#!/bin/bash\n\n# Use unix timestamp, precise to 1000 seconds (~16.7 mins) as versionCode epoch.\n# This lets us later gener"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.yml",
    "chars": 909,
    "preview": "---\nname: Bug report\ndescription: Report a bug\nlabels: [bug]\ntitle: \"[Bug] \"\nbody:\n  - type: markdown\n    attributes:\n  "
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "chars": 193,
    "preview": "blank_issues_enabled: false\ncontact_links:\n  - name: Ask a question\n    url: https://github.com/2bllw8/anemo/discussions"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.yml",
    "chars": 549,
    "preview": "---\nname: Feature request\ndescription: Suggest a feature to add\nlabels: [enhancement]\ntitle: \"[Feature request] \"\nbody:\n"
  },
  {
    "path": ".github/workflows/main.yml",
    "chars": 2196,
    "preview": "name: Aer CI\n\non:\n  push:\n    branches:\n      - 'main'\n      - 'revamp'\n    paths-ignore:\n      - '**.md'\n      - '.giti"
  },
  {
    "path": ".github/workflows/release.yml",
    "chars": 2641,
    "preview": "name: Release\n\non:\n  workflow_dispatch:\n  push:\n    tags:\n      - '*'\n  release:\n    types: [\"published\"]\n\njobs:\n  build"
  },
  {
    "path": ".gitignore",
    "chars": 191,
    "preview": ".DS_Store\n\n# Android Studio\n*.iml\n.idea\n\n# Bazel\n/.aswb\n/.ijwb\n/bazel-*\n\n# Gradle\n.gradle\nlocal.properties\n/build\n\n# Sig"
  },
  {
    "path": "COPYING",
    "chars": 35149,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "README.md",
    "chars": 2941,
    "preview": "# Aer - fork of [Anemo]\n\n> [!NOTE]  \n> - This fork focuses on supporting app's *private location* on external storage (~"
  },
  {
    "path": "app/.gitignore",
    "chars": 16,
    "preview": "/build\n/release\n"
  },
  {
    "path": "app/build.gradle.kts",
    "chars": 3581,
    "preview": "/*\n * Copyright (c) 2021 2bllw8\n * SPDX-License-Identifier: GPL-3.0-only\n */\nplugins {\n    alias(libs.plugins.android.ap"
  },
  {
    "path": "app/code-format.xml",
    "chars": 825,
    "preview": "<!--\n  ~ Copyright (c) 2022 2bllw8\n  ~ SPDX-License-Identifier: GPL-3.0-only\n  -->\n\n<profiles version=\"15\">\n    <profile"
  },
  {
    "path": "app/proguard-rules.pro",
    "chars": 174,
    "preview": "-assumenosideeffects class android.util.Log {\n    public static *** v(...);\n    public static *** d(...);\n}\n\n-repackagec"
  },
  {
    "path": "app/src/main/AndroidManifest.xml",
    "chars": 5860,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:to"
  },
  {
    "path": "app/src/main/java/alt/nainapps/aer/config/ConfigurationActivity.kt",
    "chars": 4899,
    "preview": "/*\n * Copyright (c) 2022 2bllw8\n * Copyright (c) 2024 nain\n * SPDX-License-Identifier: GPL-3.0-only\n */\npackage alt.nain"
  },
  {
    "path": "app/src/main/java/alt/nainapps/aer/config/StorageConfigActivity.kt",
    "chars": 12024,
    "preview": "package alt.nainapps.aer.config\n\nimport alt.nainapps.aer.R\nimport alt.nainapps.aer.config.ui.theme.AnemoaerTheme\nimport "
  },
  {
    "path": "app/src/main/java/alt/nainapps/aer/config/autolock/AutoLockDelayMinutesTextListener.kt",
    "chars": 1497,
    "preview": "/*\n * Copyright (c) 2024 nain\n * SPDX-License-Identifier: GPL-3.0-only\n */\n\npackage alt.nainapps.aer.config.autolock\n\nim"
  },
  {
    "path": "app/src/main/java/alt/nainapps/aer/config/password/ChangePasswordDialog.kt",
    "chars": 3253,
    "preview": "/*\n * Copyright (c) 2021 2bllw8\n * SPDX-License-Identifier: GPL-3.0-only\n */\npackage alt.nainapps.aer.config.password\n\ni"
  },
  {
    "path": "app/src/main/java/alt/nainapps/aer/config/password/PasswordDialog.kt",
    "chars": 1570,
    "preview": "/*\n * Copyright (c) 2021 2bllw8\n * SPDX-License-Identifier: GPL-3.0-only\n */\npackage alt.nainapps.aer.config.password\n\ni"
  },
  {
    "path": "app/src/main/java/alt/nainapps/aer/config/password/PasswordTextListener.kt",
    "chars": 554,
    "preview": "/*\n * Copyright (c) 2022 2bllw8\n * SPDX-License-Identifier: GPL-3.0-only\n */\npackage alt.nainapps.aer.config.password\n\ni"
  },
  {
    "path": "app/src/main/java/alt/nainapps/aer/config/password/SetPasswordDialog.kt",
    "chars": 2561,
    "preview": "/*\n * Copyright (c) 2021 2bllw8\n * SPDX-License-Identifier: GPL-3.0-only\n */\npackage alt.nainapps.aer.config.password\n\ni"
  },
  {
    "path": "app/src/main/java/alt/nainapps/aer/config/ui/theme/Color.kt",
    "chars": 287,
    "preview": "package alt.nainapps.aer.config.ui.theme\n\nimport androidx.compose.ui.graphics.Color\n\nval Purple80 = Color(0xFFD0BCFF)\nva"
  },
  {
    "path": "app/src/main/java/alt/nainapps/aer/config/ui/theme/Theme.kt",
    "chars": 1699,
    "preview": "package alt.nainapps.aer.config.ui.theme\n\nimport android.app.Activity\nimport android.os.Build\nimport androidx.compose.fo"
  },
  {
    "path": "app/src/main/java/alt/nainapps/aer/config/ui/theme/Type.kt",
    "chars": 992,
    "preview": "package alt.nainapps.aer.config.ui.theme\n\nimport androidx.compose.material3.Typography\nimport androidx.compose.ui.text.T"
  },
  {
    "path": "app/src/main/java/alt/nainapps/aer/documents/home/HomeEnvironment.kt",
    "chars": 2868,
    "preview": "/*\n * Copyright (c) 2021 2bllw8\n * SPDX-License-Identifier: GPL-3.0-only\n */\npackage alt.nainapps.aer.documents.home\n\nim"
  },
  {
    "path": "app/src/main/java/alt/nainapps/aer/documents/provider/AnemoDocumentProvider.kt",
    "chars": 10496,
    "preview": "/*\n * Copyright (c) 2021 2bllw8\n * SPDX-License-Identifier: GPL-3.0-only\n */\npackage alt.nainapps.aer.documents.provider"
  },
  {
    "path": "app/src/main/java/alt/nainapps/aer/documents/provider/EmptyCursor.kt",
    "chars": 864,
    "preview": "/*\n * Copyright (c) 2022 2bllw8\n * SPDX-License-Identifier: GPL-3.0-only\n */\npackage alt.nainapps.aer.documents.provider"
  },
  {
    "path": "app/src/main/java/alt/nainapps/aer/documents/provider/FileSystemProvider.kt",
    "chars": 31687,
    "preview": "/*\n * Copyright (c) 2022 2bllw8\n * SPDX-License-Identifier: GPL-3.0-only\n */\npackage alt.nainapps.aer.documents.provider"
  },
  {
    "path": "app/src/main/java/alt/nainapps/aer/documents/provider/PathUtils.kt",
    "chars": 7220,
    "preview": "/*\n * Copyright (c) 2022 2bllw8\n * SPDX-License-Identifier: GPL-3.0-only\n */\npackage alt.nainapps.aer.documents.provider"
  },
  {
    "path": "app/src/main/java/alt/nainapps/aer/documents/receiver/ReceiverActivity.kt",
    "chars": 6334,
    "preview": "/*\n * Copyright (c) 2022 2bllw8\n * SPDX-License-Identifier: GPL-3.0-only\n */\npackage alt.nainapps.aer.documents.receiver"
  },
  {
    "path": "app/src/main/java/alt/nainapps/aer/lock/AutoLockJobService.kt",
    "chars": 752,
    "preview": "/*\n * Copyright (c) 2021 2bllw8\n * SPDX-License-Identifier: GPL-3.0-only\n */\npackage alt.nainapps.aer.lock\n\nimport andro"
  },
  {
    "path": "app/src/main/java/alt/nainapps/aer/lock/LockStore.kt",
    "chars": 7263,
    "preview": "/*\n * Copyright (c) 2021 2bllw8\n * Copyright (c) 2024 nain\n * SPDX-License-Identifier: GPL-3.0-only\n */\npackage alt.nain"
  },
  {
    "path": "app/src/main/java/alt/nainapps/aer/lock/LockTileService.kt",
    "chars": 2585,
    "preview": "/*\n * Copyright (c) 2021 2bllw8\n * SPDX-License-Identifier: GPL-3.0-only\n */\npackage alt.nainapps.aer.lock\n\nimport andro"
  },
  {
    "path": "app/src/main/java/alt/nainapps/aer/lock/UnlockActivity.kt",
    "chars": 4427,
    "preview": "/*\n * Copyright (c) 2022 2bllw8\n * SPDX-License-Identifier: GPL-3.0-only\n */\npackage alt.nainapps.aer.lock\n\nimport alt.n"
  },
  {
    "path": "app/src/main/java/alt/nainapps/aer/shell/AnemoShell.kt",
    "chars": 997,
    "preview": "/*\n * Copyright (c) 2022 2bllw8\n * SPDX-License-Identifier: GPL-3.0-only\n */\npackage alt.nainapps.aer.shell\n\nimport andr"
  },
  {
    "path": "app/src/main/java/alt/nainapps/aer/shell/LauncherActivity.kt",
    "chars": 3050,
    "preview": "/*\n * Copyright (c) 2022 2bllw8\n * SPDX-License-Identifier: GPL-3.0-only\n */\npackage alt.nainapps.aer.shell\n\nimport andr"
  },
  {
    "path": "app/src/main/java/alt/nainapps/aer/task/TaskExecutor.java",
    "chars": 2674,
    "preview": "/*\n * Copyright (c) 2021 2bllw8\n * SPDX-License-Identifier: GPL-3.0-only\n */\npackage alt.nainapps.aer.task;\n\nimport andr"
  },
  {
    "path": "app/src/main/res/color/btn_colored_text.xml",
    "chars": 955,
    "preview": "<!-- Copyright (C) 2015 The Android Open Source Project\n\n     Licensed under the Apache License, Version 2.0 (the \"Licen"
  },
  {
    "path": "app/src/main/res/drawable/ic_configuration.xml",
    "chars": 1313,
    "preview": "<!--\n  ~ Copyright (c) 2022 2bllw8\n  ~ SPDX-License-Identifier: GPL-3.0-only\n  -->\n<vector xmlns:android=\"http://schemas"
  },
  {
    "path": "app/src/main/res/drawable/ic_error.xml",
    "chars": 582,
    "preview": "<!--\n  ~ Copyright (c) 2023 2bllw8\n  ~ SPDX-License-Identifier: GPL-3.0-only\n  -->\n<vector xmlns:android=\"http://schemas"
  },
  {
    "path": "app/src/main/res/drawable/ic_key_tile.xml",
    "chars": 1029,
    "preview": "<!--\n  ~ Copyright (c) 2021 2bllw8\n  ~ SPDX-License-Identifier: GPL-3.0-only\n  -->\n<vector xmlns:android=\"http://schemas"
  },
  {
    "path": "app/src/main/res/drawable/ic_launcher_foreground.xml",
    "chars": 1186,
    "preview": "<!--\n  ~ Copyright (c) 2021 2bllw8\n  ~ SPDX-License-Identifier: GPL-3.0-only\n  -->\n<vector xmlns:android=\"http://schemas"
  },
  {
    "path": "app/src/main/res/drawable/ic_launcher_monochrome.xml",
    "chars": 1167,
    "preview": "<!--\n  ~ Copyright (c) 2022 2bllw8\n  ~ SPDX-License-Identifier: GPL-3.0-only\n  -->\n<vector xmlns:android=\"http://schemas"
  },
  {
    "path": "app/src/main/res/drawable/ic_shortcut_configuration.xml",
    "chars": 1314,
    "preview": "<!--\n  ~ Copyright (c) 2022 2bllw8\n  ~ SPDX-License-Identifier: GPL-3.0-only\n  -->\n<vector xmlns:android=\"http://schemas"
  },
  {
    "path": "app/src/main/res/drawable/ic_storage.xml",
    "chars": 1022,
    "preview": "<!--\n  ~ Copyright (c) 2021 2bllw8\n  ~ SPDX-License-Identifier: GPL-3.0-only\n  -->\n<vector xmlns:android=\"http://schemas"
  },
  {
    "path": "app/src/main/res/layout/configuration.xml",
    "chars": 4396,
    "preview": "<!--\n  ~ Copyright (c) 2022 2bllw8\n  ~ Copyright (c) 2024 nain\n  ~ SPDX-License-Identifier: GPL-3.0-only\n  -->\n<ScrollVi"
  },
  {
    "path": "app/src/main/res/layout/password_change.xml",
    "chars": 2994,
    "preview": "<!--\n  ~ Copyright (c) 2021 2bllw8\n  ~ SPDX-License-Identifier: GPL-3.0-only\n  -->\n<ScrollView xmlns:android=\"http://sch"
  },
  {
    "path": "app/src/main/res/layout/password_first_set.xml",
    "chars": 1992,
    "preview": "<!--\n  ~ Copyright (c) 2021 2bllw8\n  ~ SPDX-License-Identifier: GPL-3.0-only\n  -->\n<LinearLayout xmlns:android=\"http://s"
  },
  {
    "path": "app/src/main/res/layout/password_input.xml",
    "chars": 3235,
    "preview": "<!--\n  ~ Copyright (c) 2021 2bllw8\n  ~ SPDX-License-Identifier: GPL-3.0-only\n  -->\n<LinearLayout xmlns:android=\"http://s"
  },
  {
    "path": "app/src/main/res/mipmap-anydpi/ic_launcher.xml",
    "chars": 382,
    "preview": "<!--\n  ~ Copyright (c) 2021 2bllw8\n  ~ SPDX-License-Identifier: GPL-3.0-only\n  -->\n<adaptive-icon xmlns:android=\"http://"
  },
  {
    "path": "app/src/main/res/values/colors.xml",
    "chars": 384,
    "preview": "<!--\n  ~ Copyright (c) 2021 2bllw8\n  ~ SPDX-License-Identifier: GPL-3.0-only\n  -->\n<resources>\n    <color name=\"anemo_pr"
  },
  {
    "path": "app/src/main/res/values/strings.xml",
    "chars": 4228,
    "preview": "<!--\n  ~ Copyright (c) 2021 2bllw8\n  ~ SPDX-License-Identifier: GPL-3.0-only\n  -->\n<resources>\n    <string name=\"app_nam"
  },
  {
    "path": "app/src/main/res/values/styles.xml",
    "chars": 858,
    "preview": "<!--\n  ~ Copyright (c) 2021 2bllw8\n  ~ SPDX-License-Identifier: GPL-3.0-only\n  -->\n<resources>\n    <style name=\"AppTheme"
  },
  {
    "path": "app/src/main/res/values/themes.xml",
    "chars": 150,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n\n    <style name=\"Theme.Anemoaer\" parent=\"android:Theme.Material.Ligh"
  },
  {
    "path": "app/src/main/res/values-es/strings.xml",
    "chars": 3462,
    "preview": "<!--\n  ~ Copyright (c) 2021 2bllw8\n  ~ SPDX-License-Identifier: GPL-3.0-only\n  -->\n<resources>\n    <string name=\"app_nam"
  },
  {
    "path": "app/src/main/res/values-fr/strings.xml",
    "chars": 3446,
    "preview": "<!--\n  ~ Copyright (c) 2022 2bllw8\n  ~ SPDX-License-Identifier: GPL-3.0-only\n  -->\n<resources>\n    <string name=\"app_nam"
  },
  {
    "path": "app/src/main/res/values-it/strings.xml",
    "chars": 3378,
    "preview": "<!--\n  ~ Copyright (c) 2022 2bllw8\n  ~ SPDX-License-Identifier: GPL-3.0-only\n  -->\n<resources>\n    <string name=\"app_nam"
  },
  {
    "path": "app/src/main/res/values-night/colors.xml",
    "chars": 256,
    "preview": "<!--\n  ~ Copyright (c) 2022 2bllw8\n  ~ SPDX-License-Identifier: GPL-3.0-only\n  -->\n<resources>\n    <color name=\"anemo_pr"
  },
  {
    "path": "app/src/main/res/values-night/styles.xml",
    "chars": 783,
    "preview": "<!--\n  ~ Copyright (c) 2021 2bllw8\n  ~ SPDX-License-Identifier: GPL-3.0-only\n  -->\n<resources>\n    <style name=\"AppTheme"
  },
  {
    "path": "app/src/main/res/values-night-v31/colors.xml",
    "chars": 336,
    "preview": "<!--\n  ~ Copyright (c) 2022 2bllw8\n  ~ SPDX-License-Identifier: GPL-3.0-only\n  -->\n<resources>\n    <color name=\"anemo_pr"
  },
  {
    "path": "app/src/main/res/values-pt-rBR/strings.xml",
    "chars": 4236,
    "preview": "<resources>\n    <string name=\"app_name\">Aer</string>\n\n    <string name=\"anemo_description\">Armazenamento privado local</"
  },
  {
    "path": "app/src/main/res/values-v27/styles.xml",
    "chars": 538,
    "preview": "<!--\n  ~ Copyright (c) 2022 2bllw8\n  ~ SPDX-License-Identifier: GPL-3.0-only\n  -->\n<resources>\n    <style name=\"AppTheme"
  },
  {
    "path": "app/src/main/res/values-v31/colors.xml",
    "chars": 335,
    "preview": "<!--\n  ~ Copyright (c) 2021 2bllw8\n  ~ SPDX-License-Identifier: GPL-3.0-only\n  -->\n<resources>\n    <color name=\"anemo_pr"
  },
  {
    "path": "app/src/main/res/xml/backup_rules.xml",
    "chars": 189,
    "preview": "<!--\n  ~ Copyright (c) 2022 2bllw8\n  ~ SPDX-License-Identifier: GPL-3.0-only\n  -->\n<full-backup-content>\n    <include\n  "
  },
  {
    "path": "app/src/main/res/xml/data_extraction_rules.xml",
    "chars": 244,
    "preview": "<!--\n  ~ Copyright (c) 2022 2bllw8\n  ~ SPDX-License-Identifier: GPL-3.0-only\n  -->\n<data-extraction-rules>\n    <cloud-ba"
  },
  {
    "path": "app/src/main/res/xml/shortcuts.xml",
    "chars": 1315,
    "preview": "<!--\n  ~ Copyright (c) 2022 2bllw8\n  ~ SPDX-License-Identifier: GPL-3.0-only\n  -->\n<shortcuts xmlns:android=\"http://sche"
  },
  {
    "path": "build.gradle",
    "chars": 1371,
    "preview": "/*\n * Copyright (c) 2021 2bllw8\n * SPDX-License-Identifier: GPL-3.0-only\n */\nbuildscript {\n    repositories {\n        gr"
  },
  {
    "path": "gradle/libs.versions.toml",
    "chars": 2105,
    "preview": "[versions]\nannotation = \"1.9.1\"\ncoreKtx = \"1.15.0\"\neitherLib = \"3.4.0\"\nagp = \"8.6.1\"\nkotlin = \"2.0.20\"\nexifinterface = \""
  },
  {
    "path": "gradle/wrapper/gradle-wrapper.properties",
    "chars": 200,
    "preview": "distributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributi"
  },
  {
    "path": "gradle.properties",
    "chars": 1209,
    "preview": "#\n# Copyright (c) 2021 2bllw8\n# SPDX-License-Identifier: GPL-3.0-only\n#\n\n## For more details on how to configure your bu"
  },
  {
    "path": "gradlew",
    "chars": 8045,
    "preview": "#!/bin/sh\n\n#\n# Copyright 2015-2021 the original authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"Licens"
  },
  {
    "path": "gradlew.bat",
    "chars": 2763,
    "preview": "@rem\r\n@rem Copyright 2015 the original author or authors.\r\n@rem\r\n@rem Licensed under the Apache License, Version 2.0 (th"
  },
  {
    "path": "metadata/en-US/full_description.txt",
    "chars": 1621,
    "preview": "Aer is a private local (+secondary) storage utility application for android.\n\nDo you worry about your private pictures o"
  },
  {
    "path": "metadata/en-US/short_description.txt",
    "chars": 76,
    "preview": "Private storage utility for android with support for external storage media\n"
  },
  {
    "path": "metadata/en-US/title.txt",
    "chars": 20,
    "preview": "Aer - Fork of Anemo\n"
  },
  {
    "path": "metadata/es-ES/full_description.txt",
    "chars": 963,
    "preview": "Anemo es una aplicación de utilidad de almacenamiento local privado para Android.\nEn lugar de ser una interfaz de usuari"
  },
  {
    "path": "metadata/es-ES/short_description.txt",
    "chars": 73,
    "preview": "Una aplicación de utilidad de almacenamiento local privado para Android.\n"
  },
  {
    "path": "metadata/es-ES/title.txt",
    "chars": 5,
    "preview": "Anemo"
  },
  {
    "path": "metadata/fr-FR/full_description.txt",
    "chars": 962,
    "preview": "Anemo est un utilitaire de stockage local privé pour Android.\nAu lieu de n'être qu'une interface de gestion de fichiers "
  },
  {
    "path": "metadata/fr-FR/short_description.txt",
    "chars": 52,
    "preview": "Un utilitaire de stockage local privé pour Android.\n"
  },
  {
    "path": "metadata/fr-FR/title.txt",
    "chars": 6,
    "preview": "Anemo\n"
  },
  {
    "path": "metadata/it-IT/full_description.txt",
    "chars": 880,
    "preview": "Anemo è un'applicazione di archiviazione locale privata per Android.\nInvece di essere un'interfaccia utente di gestione "
  },
  {
    "path": "metadata/it-IT/short_description.txt",
    "chars": 60,
    "preview": "Un'applicazione di archiviazione locale privata per Android."
  },
  {
    "path": "metadata/it-IT/title.txt",
    "chars": 6,
    "preview": "Anemo\n"
  },
  {
    "path": "metadata/pt-rBR/full_description.txt",
    "chars": 1866,
    "preview": "Aer é um aplicativo utilitário de armazenamento (+secundário) local privado para Android.\n\nVocê se preocupa com suas fot"
  },
  {
    "path": "metadata/pt-rBR/short_description.txt",
    "chars": 97,
    "preview": "Utilitário de armazenamento privado para Android com suporte para mídia de armazenamento externa\n"
  },
  {
    "path": "metadata/pt-rBR/title.txt",
    "chars": 19,
    "preview": "Aer - Fork do Anemo"
  },
  {
    "path": "settings.gradle.kts",
    "chars": 787,
    "preview": "/*\n * Copyright (c) 2021 2bllw8\n * SPDX-License-Identifier: GPL-3.0-only\n */\npluginManagement {\n\n    /**\n     * The plug"
  }
]

// ... and 1 more files (download for full content)

About this extraction

This page contains the full source code of the nain-F49FF806/anemo-aer GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 90 files (231.2 KB), approximately 56.8k tokens, and a symbol index with 4 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!