diff --git a/.env.example b/.env.example new file mode 100644 index 00000000..8609a88b --- /dev/null +++ b/.env.example @@ -0,0 +1,7 @@ +# GEMINI_API_KEY: Required for Gemini AI API calls. +# This is a placeholder key. +# AI Studio automatically injects this at runtime from user secrets. +# Users configure this via the Secrets panel in the AI Studio UI. +# IMPORTANT: Uncomment the line below if your app uses the Gemini API. +# If left commented out, the key will NOT be packaged in the APK. +# GEMINI_API_KEY=MY_GEMINI_API_KEY diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml deleted file mode 100644 index fdb57a5d..00000000 --- a/.github/FUNDING.yml +++ /dev/null @@ -1 +0,0 @@ -custom: ['https://donatello.to/truefedex'] \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md deleted file mode 100644 index 0cf7266a..00000000 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -name: Bug report -about: Create a report to help us improve -title: '' -labels: bug, enhancement -assignees: truefedex - ---- - -**Describe the bug** -A clear and concise description of what the bug is. - -**To Reproduce** -Steps to reproduce the behavior: -1. Go to '...' -2. Click on '....' -3. Scroll down to '....' -4. See error - -**Expected behavior** -A clear and concise description of what you expected to happen. - -**Screenshots** -If applicable, add screenshots to help explain your problem. - -**Environment (please complete the following information):** - - OS version: [e.g. Android TV 10] - - Device [e.g. NVidia Shield Pro 2015] - - Browser version [e.g. v1.8.1] - - URL or domain name where problem can be reproduced [optional, e.g. https://google.com] - -**Additional context** -Add any other context about the problem here. - -### 💡 A note on project maintenance - -This is an open-source project built and maintained in my free time. Because issue tracking and support take significant effort, priority for reviewing and debugging is given to supporters. - -If you would like to support the project and increase the visibility of your issue: -1. Consider making a donation via [Donatello](https://donatello.to/truefedex). -2. Include a link to this issue in your donation message. - -*Note: While donations help me allocate more time to the project, they act as a tip and voluntary support. A donation does not guarantee a fix, ETA, or resolution, but it ensures your issue gets extra attention.* diff --git a/.github/ISSUE_TEMPLATE/custom.md b/.github/ISSUE_TEMPLATE/custom.md deleted file mode 100644 index 5b441e18..00000000 --- a/.github/ISSUE_TEMPLATE/custom.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -name: Custom issue template -about: Describe this issue template's purpose here. -title: '' -labels: '' -assignees: '' - ---- - -### 💡 A note on project maintenance - -This is an open-source project built and maintained in my free time. Because issue tracking and support take significant effort, priority for reviewing and debugging is given to supporters. - -If you would like to support the project and increase the visibility of your issue: -1. Consider making a donation via [Donatello](https://donatello.to/truefedex). -2. Include a link to this issue in your donation message. - -*Note: While donations help me allocate more time to the project, they act as a tip and voluntary support. A donation does not guarantee a fix, ETA, or resolution, but it ensures your issue gets extra attention.* diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md deleted file mode 100644 index 6f013928..00000000 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -name: Feature request -about: Suggest an idea for this project -title: '' -labels: enhancement -assignees: truefedex - ---- - -**Is your feature request related to a problem? Please describe.** -A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] - -**Describe the solution you'd like** -A clear and concise description of what you want to happen. - -**Additional context** -Add any other context or screenshots about the feature request here. - -### 💡 A note on project maintenance - -This is an open-source project built and maintained in my free time. Because issue tracking and support take significant effort, priority for reviewing and debugging is given to supporters. - -If you would like to support the project and increase the visibility of your issue: -1. Consider making a donation via [Donatello](https://donatello.to/truefedex). -2. Include a link to this issue in your donation message. - -*Note: While donations help me allocate more time to the project, they act as a tip and voluntary support. A donation does not guarantee a fix, ETA, or resolution, but it ensures your issue gets extra attention.* diff --git a/.github/workflows/android-ci.yml b/.github/workflows/android-ci.yml new file mode 100644 index 00000000..b15b03d2 --- /dev/null +++ b/.github/workflows/android-ci.yml @@ -0,0 +1,43 @@ +name: Android CI + +# Compiles the app on every pull request and on main, so a change that does not build +# can never land. The signed release pipeline is separate and still to be re-wired for +# this project layout. +on: + push: + branches: [ main, master ] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +jobs: + build: + name: Assemble debug APK + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Set up JDK 21 + uses: actions/setup-java@v4 + with: + java-version: '21' + distribution: 'temurin' + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@v4 + + - name: Make Gradle wrapper executable + run: chmod +x ./gradlew + + - name: Assemble debug + run: ./gradlew :app:assembleDebug --no-daemon --stacktrace + + - name: Upload debug APK + if: always() + uses: actions/upload-artifact@v4 + with: + name: app-debug-apk + path: app/build/outputs/apk/debug/*.apk + if-no-files-found: warn diff --git a/.github/workflows/build_apk.yml b/.github/workflows/build_apk.yml deleted file mode 100644 index 99d3fb53..00000000 --- a/.github/workflows/build_apk.yml +++ /dev/null @@ -1,237 +0,0 @@ -name: Build Signed Release APK & Play Store AAB - -on: - push: - branches: [ main, master ] - workflow_dispatch: - inputs: - version_name: - description: 'Version Name (e.g. 1.0.2 - leave empty for auto 1.0.X)' - required: false - default: '' - version_code: - description: 'Version Code (Integer, e.g. 12 - leave blank for auto increment)' - required: false - default: '' - -permissions: - contents: write - -jobs: - build: - name: Build & Sign APK & AAB - runs-on: ubuntu-latest - - steps: - - name: Checkout Source Code - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - - name: Set up Java 17 (JDK) - uses: actions/setup-java@v4 - with: - java-version: '17' - distribution: 'temurin' - - - name: Make Gradle Wrapper Executable - run: chmod +x ./gradlew - - - name: Determine Version Code and Name - id: versioning - run: | - if [ -n "${{ inputs.version_code }}" ]; then - V_CODE="${{ inputs.version_code }}" - else - # Uses github.run_number directly so each build automatically increments (1, 2, 3...) - V_CODE="${{ github.run_number }}" - fi - - if [ -n "${{ inputs.version_name }}" ]; then - V_NAME="${{ inputs.version_name }}" - else - # Auto-incrementing version name based on version code - V_NAME="1.0.${V_CODE}" - fi - - echo "Determined Version Code: $V_CODE" - echo "Determined Version Name: $V_NAME" - echo "v_code=$V_CODE" >> $GITHUB_OUTPUT - echo "v_name=$V_NAME" >> $GITHUB_OUTPUT - - - name: Ensure Debug Keystore Exists - run: | - if [ -f "debug.keystore.base64" ]; then - echo "Restoring debug.keystore from debug.keystore.base64..." - base64 -d debug.keystore.base64 > debug.keystore - elif [ ! -f "debug.keystore" ]; then - echo "Generating fallback debug.keystore..." - keytool -genkey -v -keystore debug.keystore \ - -storepass android -keypass android \ - -keyalg RSA -keysize 2048 -validity 10000 \ - -dname "CN=Android Debug,O=Android,C=US" \ - -alias androiddebugkey - fi - - - name: Build Release APK, Debug APK and AAB Bundle with Gradle - run: | - ./gradlew assembleRelease assembleDebug bundleRelease \ - -PversionCode=${{ steps.versioning.outputs.v_code }} \ - -PversionName=${{ steps.versioning.outputs.v_name }} \ - --no-daemon - - - name: Sign Release APK & AAB - env: - KEYSTORE_BASE64: ${{ secrets.RELEASE_KEYSTORE_BASE64 }} - KEYSTORE_PASS: ${{ secrets.KEYSTORE_PASSWORD || 'android123' }} - KEY_ALIAS: ${{ secrets.KEY_ALIAS || '' }} - KEY_PASS: ${{ secrets.KEY_PASSWORD || 'android123' }} - V_NAME: ${{ steps.versioning.outputs.v_name }} - run: | - echo "Locating generated Release APK, Debug APK, and AAB..." - UNSIGNED_APK=$(find app/build/outputs/apk/release/ -name "*.apk" | head -n 1) - DEBUG_APK=$(find app/build/outputs/apk/debug/ -name "*.apk" | head -n 1) - UNSIGNED_AAB=$(find app/build/outputs/bundle/release/ -name "*.aab" | head -n 1) - - mkdir -p output_release - - # 0. Copy Debug APK directly (already signed with debug keystore) - if [ -n "$DEBUG_APK" ]; then - cp "$DEBUG_APK" output_release/GothwadTVBrowser-v${V_NAME}-Debug.apk - echo "Successfully included Debug APK: output_release/GothwadTVBrowser-v${V_NAME}-Debug.apk" - fi - - # Store keystore in secure temporary location outside release outputs - KS_PATH="/tmp/gothwad_release_key.jks" - - if [ -n "$KEYSTORE_BASE64" ]; then - echo "Using Permanent Keystore from GitHub Secrets..." - echo "$KEYSTORE_BASE64" | tr -d '\r\n ' | base64 -d > "$KS_PATH" - if ! keytool -list -keystore "$KS_PATH" -storepass "$KEYSTORE_PASS" > /tmp/kt_diag.log 2>&1; then - echo "⚠️ WARNING: keytool failed to verify keystore with provided password!" - cat /tmp/kt_diag.log - fi - else - echo "⚠️ No GitHub Secret found! Generating temporary keystore..." - DEFAULT_ALIAS="${KEY_ALIAS:-gothwad_tv_key}" - keytool -genkey -v \ - -keystore "$KS_PATH" \ - -keyalg RSA -keysize 2048 -validity 10000 \ - -alias "$DEFAULT_ALIAS" \ - -dname "CN=Gothwad TV Browser, OU=AppDev, O=Gothwad, C=IN" \ - -storepass "$KEYSTORE_PASS" -keypass "$KEY_PASS" - fi - - # Dynamically detect exact Alias name from the keystore - DETECTED_ALIAS=$(keytool -list -v -keystore "$KS_PATH" -storepass "$KEYSTORE_PASS" 2>/dev/null | grep -i "Alias name:" | head -n 1 | sed 's/.*Alias name: //I' | tr -d '\r' | xargs) - - if [ -n "$KEY_ALIAS" ]; then - ACTUAL_ALIAS="$KEY_ALIAS" - elif [ -n "$DETECTED_ALIAS" ]; then - ACTUAL_ALIAS="$DETECTED_ALIAS" - else - ACTUAL_ALIAS="gothwad_tv_key" - fi - - echo "Using Keystore Alias: $ACTUAL_ALIAS" - - # Find latest zipalign and apksigner dynamically - ZIPALIGN=$(find $ANDROID_HOME/build-tools/ -name "zipalign" | sort -V | tail -n 1) - APKSIGNER=$(find $ANDROID_HOME/build-tools/ -name "apksigner" | sort -V | tail -n 1) - - # 1. Sign APK - if [ -n "$UNSIGNED_APK" ]; then - UNALIGNED_TEMP="/tmp/unaligned_temp.apk" - if [ -n "$ZIPALIGN" ]; then - $ZIPALIGN -v -p 4 "$UNSIGNED_APK" "$UNALIGNED_TEMP" || cp "$UNSIGNED_APK" "$UNALIGNED_TEMP" - else - cp "$UNSIGNED_APK" "$UNALIGNED_TEMP" - fi - - $APKSIGNER sign \ - --ks "$KS_PATH" \ - --ks-key-alias "$ACTUAL_ALIAS" \ - --ks-pass "pass:$KEYSTORE_PASS" \ - --key-pass "pass:$KEY_PASS" \ - --out output_release/GothwadTVBrowser-v${V_NAME}-Release.apk \ - "$UNALIGNED_TEMP" - - $APKSIGNER verify --verbose output_release/GothwadTVBrowser-v${V_NAME}-Release.apk - rm -f "$UNALIGNED_TEMP" - fi - - # 2. Sign Play Store AAB Bundle using jarsigner - if [ -n "$UNSIGNED_AAB" ]; then - cp "$UNSIGNED_AAB" output_release/GothwadTVBrowser-v${V_NAME}-PlayStore.aab - jarsigner -verbose -sigalg SHA256withRSA -digestalg SHA-256 \ - -keystore "$KS_PATH" \ - -storepass "$KEYSTORE_PASS" -keypass "$KEY_PASS" \ - output_release/GothwadTVBrowser-v${V_NAME}-PlayStore.aab \ - "$ACTUAL_ALIAS" - echo "Successfully signed Play Store AAB!" - fi - - # Securely destroy the temporary keystore file so it is never exposed or uploaded - rm -f "$KS_PATH" - echo "Keystore securely cleaned up." - - - name: Build Linux Packages (.deb & .tar.gz) - run: | - chmod +x packaging/linux/build-linux-packages.sh - RELEASE_APK="output_release/GothwadTVBrowser-v${{ steps.versioning.outputs.v_name }}-Release.apk" - if [ ! -f "$RELEASE_APK" ]; then - RELEASE_APK="output_release/GothwadTVBrowser-v${{ steps.versioning.outputs.v_name }}-Debug.apk" - fi - ./packaging/linux/build-linux-packages.sh \ - "$RELEASE_APK" \ - "${{ steps.versioning.outputs.v_name }}" \ - "output_release" - - - name: Build Windows Package (.zip) - run: | - chmod +x packaging/windows/build-windows-package.sh - RELEASE_APK="output_release/GothwadTVBrowser-v${{ steps.versioning.outputs.v_name }}-Release.apk" - if [ ! -f "$RELEASE_APK" ]; then - RELEASE_APK="output_release/GothwadTVBrowser-v${{ steps.versioning.outputs.v_name }}-Debug.apk" - fi - ./packaging/windows/build-windows-package.sh \ - "$RELEASE_APK" \ - "${{ steps.versioning.outputs.v_name }}" \ - "output_release" - - - name: Build macOS Package (.app in .zip) - run: | - chmod +x packaging/macos/build-macos-package.sh - RELEASE_APK="output_release/GothwadTVBrowser-v${{ steps.versioning.outputs.v_name }}-Release.apk" - if [ ! -f "$RELEASE_APK" ]; then - RELEASE_APK="output_release/GothwadTVBrowser-v${{ steps.versioning.outputs.v_name }}-Debug.apk" - fi - ./packaging/macos/build-macos-package.sh \ - "$RELEASE_APK" \ - "${{ steps.versioning.outputs.v_name }}" \ - "output_release" - - - name: Upload Signed Release APK, Debug APK, AAB, Linux, Windows & macOS Packages - uses: actions/upload-artifact@v4 - with: - name: Gothwad-TV-Browser-v${{ steps.versioning.outputs.v_name }}-Build${{ steps.versioning.outputs.v_code }} - path: output_release/ - - - name: Create Automatic GitHub Release - uses: softprops/action-gh-release@v2 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - tag_name: v${{ steps.versioning.outputs.v_name }} - name: v${{ steps.versioning.outputs.v_name }} - draft: false - prerelease: false - generate_release_notes: true - files: | - output_release/GothwadTVBrowser-v${{ steps.versioning.outputs.v_name }}-Release.apk - output_release/GothwadTVBrowser-v${{ steps.versioning.outputs.v_name }}-Debug.apk - output_release/GothwadTVBrowser-v${{ steps.versioning.outputs.v_name }}-PlayStore.aab - output_release/gothwad-browser_${{ steps.versioning.outputs.v_name }}_all.deb - output_release/gothwad-browser-linux-v${{ steps.versioning.outputs.v_name }}.tar.gz - output_release/gothwad-browser-windows-${{ steps.versioning.outputs.v_name }}.zip - output_release/gothwad-browser-macos-${{ steps.versioning.outputs.v_name }}.zip diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml deleted file mode 100644 index afe7f8d3..00000000 --- a/.github/workflows/quality.yml +++ /dev/null @@ -1,116 +0,0 @@ -name: Quality Gate & Tests - -# The release pipeline (build_apk.yml) only runs on main and only builds. This workflow is the -# cheap, always-on half: the mechanical AGENTS.md rules, the JVM unit tests, and a compile so a -# PR can never land something that does not even build. - -on: - pull_request: - push: - branches: [ main, master ] - workflow_dispatch: - -permissions: - contents: read - -concurrency: - group: quality-${{ github.ref }} - cancel-in-progress: true - -jobs: - rules: - name: AGENTS.md rules (grep gate) - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - - # No JDK, no SDK: this is the feedback loop that should answer in seconds. - - name: Run quality gate - run: bash scripts/quality-gate.sh - - test: - name: Unit tests - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Make Gradle Wrapper Executable - run: chmod +x ./gradlew - - - name: Set up JDK 17 - uses: actions/setup-java@v4 - with: - java-version: '17' - distribution: 'temurin' - - - name: Set up Gradle - uses: gradle/actions/setup-gradle@v4 - with: - cache-read-only: ${{ github.ref != 'refs/heads/main' }} - - - name: Unit tests (app + common) - run: | - set -o pipefail - ./gradlew :app:common:testDebugUnitTest testDebugUnitTest --no-daemon --continue --stacktrace 2>&1 | tee gradle.log - - # The raw log lives behind an endpoint a sandboxed runner often cannot reach, and a red X - # with no message teaches nobody anything: put the useful lines in the job summary. - - name: Publish the failure in the job summary - if: failure() - run: bash scripts/ci-summarize-gradle.sh - - build: - name: Compile (debug) + Android lint - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Make Gradle Wrapper Executable - run: chmod +x ./gradlew - - - name: Set up JDK 17 - uses: actions/setup-java@v4 - with: - java-version: '17' - distribution: 'temurin' - - - name: Set up Gradle - uses: gradle/actions/setup-gradle@v4 - with: - cache-read-only: ${{ github.ref != 'refs/heads/main' }} - - # debug builds are wired to debug.keystore in app/build.gradle.kts; generate the standard - # debug key when the repo copy is absent, same as build_apk.yml does. - - name: Ensure debug keystore exists - run: | - if [ ! -f debug.keystore ]; then - keytool -genkey -v -keystore debug.keystore \ - -storepass android -keypass android \ - -keyalg RSA -keysize 2048 -validity 10000 \ - -dname "CN=Android Debug,O=Android,C=US" \ - -alias androiddebugkey - fi - - - name: Compile debug - run: | - set -o pipefail - ./gradlew :app:compileDebugKotlin :app:common:compileDebugKotlin --no-daemon --continue --stacktrace 2>&1 | tee gradle.log - - - name: Publish the failure in the job summary - if: failure() - run: bash scripts/ci-summarize-gradle.sh - - - name: Android lint - continue-on-error: true - run: ./gradlew :app:lintDebug --no-daemon - - - name: Upload lint report - if: always() - uses: actions/upload-artifact@v4 - with: - name: lint-report - path: app/build/reports/lint-results-*.html - if-no-files-found: ignore diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml deleted file mode 100644 index b116f1ea..00000000 --- a/.github/workflows/release.yml +++ /dev/null @@ -1,214 +0,0 @@ -name: Release to GitHub Releases - -on: - push: - tags: - - 'v*' - workflow_dispatch: - inputs: - version: - description: 'Version Name (e.g. 1.0.2 - leave empty for auto 1.0.X)' - required: false - default: '' - version_code: - description: 'Version Code (Integer, e.g. 12 - leave blank for auto increment)' - required: false - default: '' - -permissions: - contents: write - -jobs: - build_release: - name: Build & Publish Release - runs-on: ubuntu-latest - - steps: - - name: Checkout Source Code - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - - name: Set up Java 17 - uses: actions/setup-java@v4 - with: - java-version: '17' - distribution: 'temurin' - - - name: Make Gradle Executable - run: chmod +x ./gradlew - - - name: Determine Version Code and Name - id: versioning - run: | - if [ -n "${{ inputs.version_code }}" ]; then - V_CODE="${{ inputs.version_code }}" - else - # Uses github.run_number directly so each build automatically increments (1, 2, 3...) - V_CODE="${{ github.run_number }}" - fi - - if [ -n "${{ inputs.version }}" ]; then - V_NAME="${{ inputs.version }}" - elif [[ "${{ github.ref }}" == refs/tags/v* ]]; then - V_NAME="${GITHUB_REF_NAME#v}" - else - V_NAME="1.0.${V_CODE}" - fi - - echo "Determined Version Code: $V_CODE" - echo "Determined Version Name: $V_NAME" - echo "v_code=$V_CODE" >> $GITHUB_OUTPUT - echo "v_name=$V_NAME" >> $GITHUB_OUTPUT - - - name: Ensure Debug Keystore Exists - run: | - if [ -f "debug.keystore.base64" ]; then - echo "Restoring debug.keystore from debug.keystore.base64..." - base64 -d debug.keystore.base64 > debug.keystore - elif [ ! -f "debug.keystore" ]; then - echo "Generating fallback debug.keystore..." - keytool -genkey -v -keystore debug.keystore \ - -storepass android -keypass android \ - -keyalg RSA -keysize 2048 -validity 10000 \ - -dname "CN=Android Debug,O=Android,C=US" \ - -alias androiddebugkey - fi - - - name: Build Release APK, Debug APK and AAB - run: | - ./gradlew assembleRelease assembleDebug bundleRelease \ - -PversionCode=${{ steps.versioning.outputs.v_code }} \ - -PversionName=${{ steps.versioning.outputs.v_name }} \ - --no-daemon - - - name: Sign Release APK & AAB - env: - KEYSTORE_BASE64: ${{ secrets.RELEASE_KEYSTORE_BASE64 }} - KEYSTORE_PASS: ${{ secrets.KEYSTORE_PASSWORD || 'android123' }} - KEY_ALIAS: ${{ secrets.KEY_ALIAS || '' }} - KEY_PASS: ${{ secrets.KEY_PASSWORD || 'android123' }} - V_NAME: ${{ steps.versioning.outputs.v_name }} - run: | - mkdir -p release_out - APK=$(find app/build/outputs/apk/release/ -name "*.apk" | head -n 1) - DEBUG_APK=$(find app/build/outputs/apk/debug/ -name "*.apk" | head -n 1) - AAB=$(find app/build/outputs/bundle/release/ -name "*.aab" | head -n 1) - - if [ -n "$DEBUG_APK" ]; then - cp "$DEBUG_APK" release_out/GothwadTVBrowser-v${V_NAME}-Debug.apk - echo "Copied Debug APK: release_out/GothwadTVBrowser-v${V_NAME}-Debug.apk" - fi - - # Store keystore in secure temporary location outside release outputs - KS_PATH="/tmp/release_key.jks" - - if [ -n "$KEYSTORE_BASE64" ]; then - echo "Using Permanent Keystore from GitHub Secrets..." - echo "$KEYSTORE_BASE64" | tr -d '\r\n ' | base64 -d > "$KS_PATH" - if ! keytool -list -keystore "$KS_PATH" -storepass "$KEYSTORE_PASS" > /tmp/kt_diag.log 2>&1; then - echo "⚠️ WARNING: keytool failed to verify keystore with provided password!" - cat /tmp/kt_diag.log - fi - else - echo "⚠️ No GitHub Secret found! Generating temporary keystore..." - DEFAULT_ALIAS="${KEY_ALIAS:-gothwad_key}" - keytool -genkey -v \ - -keystore "$KS_PATH" \ - -keyalg RSA -keysize 2048 -validity 10000 \ - -alias "$DEFAULT_ALIAS" \ - -dname "CN=Gothwad TV Browser, O=Gothwad, C=IN" \ - -storepass "$KEYSTORE_PASS" -keypass "$KEY_PASS" - fi - - # Dynamically detect exact Alias name from the keystore - DETECTED_ALIAS=$(keytool -list -v -keystore "$KS_PATH" -storepass "$KEYSTORE_PASS" 2>/dev/null | grep -i "Alias name:" | head -n 1 | sed 's/.*Alias name: //I' | tr -d '\r' | xargs) - - if [ -n "$KEY_ALIAS" ]; then - ACTUAL_ALIAS="$KEY_ALIAS" - elif [ -n "$DETECTED_ALIAS" ]; then - ACTUAL_ALIAS="$DETECTED_ALIAS" - else - ACTUAL_ALIAS="gothwad_key" - fi - - echo "Using Keystore Alias: $ACTUAL_ALIAS" - - APKSIGNER=$(find $ANDROID_HOME/build-tools/ -name "apksigner" | sort -V | tail -n 1) - if [ -n "$APK" ]; then - $APKSIGNER sign \ - --ks "$KS_PATH" \ - --ks-key-alias "$ACTUAL_ALIAS" \ - --ks-pass "pass:$KEYSTORE_PASS" \ - --key-pass "pass:$KEY_PASS" \ - --out release_out/GothwadTVBrowser-v${V_NAME}-Release.apk \ - "$APK" - fi - - if [ -n "$AAB" ]; then - cp "$AAB" release_out/GothwadTVBrowser-v${V_NAME}-PlayStore.aab - jarsigner -verbose -sigalg SHA256withRSA -digestalg SHA-256 \ - -keystore "$KS_PATH" \ - -storepass "$KEYSTORE_PASS" -keypass "$KEY_PASS" \ - release_out/GothwadTVBrowser-v${V_NAME}-PlayStore.aab \ - "$ACTUAL_ALIAS" - fi - - # Securely destroy the temporary keystore file so it is never exposed or uploaded - rm -f "$KS_PATH" - echo "Keystore securely cleaned up." - - - name: Build Linux Packages (.deb & .tar.gz) - run: | - chmod +x packaging/linux/build-linux-packages.sh - RELEASE_APK="release_out/GothwadTVBrowser-v${{ steps.versioning.outputs.v_name }}-Release.apk" - if [ ! -f "$RELEASE_APK" ]; then - RELEASE_APK="release_out/GothwadTVBrowser-v${{ steps.versioning.outputs.v_name }}-Debug.apk" - fi - ./packaging/linux/build-linux-packages.sh \ - "$RELEASE_APK" \ - "${{ steps.versioning.outputs.v_name }}" \ - "release_out" - - - name: Build Windows Package (.zip) - run: | - chmod +x packaging/windows/build-windows-package.sh - RELEASE_APK="release_out/GothwadTVBrowser-v${{ steps.versioning.outputs.v_name }}-Release.apk" - if [ ! -f "$RELEASE_APK" ]; then - RELEASE_APK="release_out/GothwadTVBrowser-v${{ steps.versioning.outputs.v_name }}-Debug.apk" - fi - ./packaging/windows/build-windows-package.sh \ - "$RELEASE_APK" \ - "${{ steps.versioning.outputs.v_name }}" \ - "release_out" - - - name: Build macOS Package (.app in .zip) - run: | - chmod +x packaging/macos/build-macos-package.sh - RELEASE_APK="release_out/GothwadTVBrowser-v${{ steps.versioning.outputs.v_name }}-Release.apk" - if [ ! -f "$RELEASE_APK" ]; then - RELEASE_APK="release_out/GothwadTVBrowser-v${{ steps.versioning.outputs.v_name }}-Debug.apk" - fi - ./packaging/macos/build-macos-package.sh \ - "$RELEASE_APK" \ - "${{ steps.versioning.outputs.v_name }}" \ - "release_out" - - - name: Create GitHub Release - uses: softprops/action-gh-release@v2 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - tag_name: v${{ steps.versioning.outputs.v_name }} - name: v${{ steps.versioning.outputs.v_name }} - draft: false - prerelease: false - generate_release_notes: true - files: | - release_out/GothwadTVBrowser-v${{ steps.versioning.outputs.v_name }}-Release.apk - release_out/GothwadTVBrowser-v${{ steps.versioning.outputs.v_name }}-Debug.apk - release_out/GothwadTVBrowser-v${{ steps.versioning.outputs.v_name }}-PlayStore.aab - release_out/gothwad-browser_${{ steps.versioning.outputs.v_name }}_all.deb - release_out/gothwad-browser-linux-v${{ steps.versioning.outputs.v_name }}.tar.gz - release_out/gothwad-browser-windows-${{ steps.versioning.outputs.v_name }}.zip - release_out/gothwad-browser-macos-${{ steps.versioning.outputs.v_name }}.zip diff --git a/.gitignore b/.gitignore index 8bdeab49..2cbead96 100644 --- a/.gitignore +++ b/.gitignore @@ -1,16 +1,18 @@ *.iml .gradle +.kotlin /local.properties -/.idea +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml .DS_Store /build /captures -*.keystore -!debug.keystore -*.hprof -/buildSrc/build - -/.kotlin -/local.properties -/app/build -/app/common/build +.externalNativeBuild +.cxx +local.properties +.env +debug.keystore diff --git a/AGENTS.md b/AGENTS.md deleted file mode 100644 index 0faad1cd..00000000 --- a/AGENTS.md +++ /dev/null @@ -1,221 +0,0 @@ -# AGENTS.md — Gothwad TV Browser - -This file is the single source of truth for any AI agent (Google AI Studio, or any other) working on this codebase. Read this fully before making any change. It exists because this project has repeatedly suffered from the same class of mistake: quick hacks that "look fixed" in one narrow test but quietly break something else (page rendering, input handling, memory, or crash safety). The rules below exist to prevent that pattern from recurring. - ---- - -## 0. Mission Statement — Read This First - -**This is not a "TV app that happens to browse the web." This is a full-grade web browser.** It must behave, render, and perform to the same standard as Chrome on a PC/desktop — not a diminished, TV-specific, best-effort approximation of a browser. - -The non-negotiable engineering principle for every change made to this project: - -> **Prefer the native platform capability over a custom workaround, always.** Android, WebView, and the underlying Chromium engine already solve almost every problem this app will ever face — zoom, scrolling, text selection, dark mode, input handling, memory management. When something doesn't work, the correct fix is almost always "stop interfering with the native mechanism" or "use the native API correctly," not "write custom code to fake the native behavior." - -Every custom workaround this project has ever added ("jugaad") has caused a worse bug than the one it tried to fix: -- A custom CSS `zoom` hack (to work around not wiring up native zoom controls) broke fixed-position page elements site-wide. -- A custom mouse-to-touch event conversion (to work around one device's broken click delivery) broke text selection and mouse drag on every device. -- A custom "force dark" toggle (left on by default) silently repainted every website's colors incorrectly. -- A custom shortcut-recording routine (that didn't account for modifier keys generating their own key-up events) silently corrupted every recorded shortcut. - -**The pattern is always the same: a workaround was added instead of using/fixing the native mechanism, and it caused collateral damage elsewhere.** Do not repeat this pattern. If you find yourself about to inject JavaScript/CSS to fake a browser feature, intercept and re-synthesize an input event, or special-case a device/chipset — stop, and find the native API that already does this correctly. - -If a genuine device-specific or OS-level bug is discovered that cannot be fixed with a native API, document it clearly as a known limitation rather than papering over it with a hack that affects all devices. - ---- - -## 1. What This App Is - -- **Product:** Gothwad TV Browser — a full-featured Android web browser. -- **Platforms it must work correctly on, using the *same* codebase:** - - **Android TV** (D-pad/remote as the primary input; large-screen, 10-foot UI) - - **Android tablets** (touch as the primary input, keyboard/mouse optional) -- **Input devices it must support simultaneously and correctly, without any one input mode breaking another:** - - TV remote / D-pad navigation - - Physical USB or Bluetooth keyboard (typing, shortcuts, modifier combos) - - Physical USB or Bluetooth mouse (hover, left-click, right-click, click-drag text selection, scroll wheel) - - Touchscreen (tablets) -- **Engine:** Android System WebView (Chromium-based). This app does not ship its own rendering engine — it relies on the OS-provided WebView, so behavior should match what that WebView/Chromium version does natively unless there's a specific, justified reason to differ. -- **Tech stack:** Kotlin, Gradle (Kotlin DSL), Room (local DB), Coroutines (background work), scaffolded/maintained via Google AI Studio. -- **Distinct feature set beyond "just a browser":** tabbed browsing (top-tab bar + row/grid tab views), ad blocking, a virtual cursor system (for D-pad-driven pointer navigation), downloads manager, TV Notes, File Manager, App Lock (PIN), Clipboard Manager (with history), configurable keyboard shortcuts, multi-language UI (10+ languages), sidebar-based navigation for History/Downloads/Favorites/Notes/Clipboard/Tabs/File Manager. - ---- - -## 2. Architecture Map - -### WebView / rendering engine layer -| File | Responsibility | -|---|---| -| `webengine/webview/WebViewEx.kt` | The core `WebView` subclass. WebSettings configuration, zoom, desktop-mode, dark-mode/color settings, native input event entry points (`dispatchGenericMotionEvent`, `dispatchTouchEvent`, `setOnContextClickListener`), context-menu triggering. | -| `webengine/webview/WebViewExClients.kt` | `WebViewClient` / `WebChromeClient` implementations — page load callbacks, `onRenderProcessGone` crash handling, console messages, file chooser, download interception. | -| `webengine/webview/WebViewWebEngine.kt` | Wraps `WebViewEx` behind the app's `WebEngine` abstraction; owns per-tab WebView lifecycle, crash-recovery/reload logic, `trimMemory()`. | -| `webengine/webview/HomePageHelper.kt` | Custom handling for the app's internal home page (favicon interception, etc). | -| `assets/generic_injects.js` | JavaScript injected into every loaded page. Keep this minimal — anything here runs on every page load and, if it attaches scroll/touch listeners, can affect scroll smoothness site-wide. | - -### Tabs & state -| File | Responsibility | -|---|---| -| `activity/main/TabsModel.kt` | Tab collection, tab switching, per-host config caching (async, non-blocking), memory-pressure and LRU-based tab trimming. | -| `model/WebTabState.kt` (common module) | Per-tab persisted state: URL, title, thumbnail, saved WebView state, `trimMemory()`/restore logic, `lastActiveTimestamp`. | -| `Config.kt` (common module) | All user-configurable preferences (SharedPreferences-backed), including `maxLiveTabs`, `keepAliveInBackground`, ad-block settings, etc. | - -### Input handling (the most fragile area historically — read carefully before touching) -| File | Responsibility | -|---|---| -| `utils/HardwareInputManager.kt` (common module) | Central point for hardware input device policy: user-configurable per-device blocking (`isDeviceBlocked`). **Must never contain event-type conversion logic** (e.g. mouse→touch) — see §3. | -| `utils/DPADNavigationEventsAdapter.kt` (common module) | Translates D-pad/remote key events into virtual-cursor motion for the on-screen cursor system. | -| `utils/BackNavigationEventsAdapter.kt` (common module) | Handles BACK-equivalent input (remote back button, gamepad B) only. Must never be repurposed to intercept unrelated input (e.g. mouse buttons). | -| `widgets/cursor/CursorLayout.kt` (common module) | The `FrameLayout` overlay that hosts the virtual D-pad-driven cursor and dispatches touch/motion/key events to the WebView beneath it. **Any code path here that can call back into its own `dispatchTouchEvent`/`dispatchGenericMotionEvent` (directly or indirectly) must guarantee the recursion terminates — see the historical StackOverflow bug in §5.** | -| `widgets/cursor/CursorDrawerDelegate.kt` (common module) | Draws the virtual cursor, handles D-pad-to-cursor-motion translation, synthesizes `MotionEvent`s for D-pad "click" (`dispatchMotionEvent` → `surface.dispatchTouchEvent`). Any state flag guarding a synthetic-event dispatch must be updated *before* the dispatch call that can re-enter this code, not after. | -| `activity/main/MainActivityDpad.kt` | Window-level `dispatchKeyEvent` interception (runs before the WebView or any view gets the event) — this is where keyboard shortcuts and D-pad focus-navigation between header/home/webview are resolved. | -| `singleton/shortcuts/Shortcut.kt` / `ShortcutMgr.kt` | Shortcut definitions and runtime matching (key-down + key-up modifier matching). Must reject pure-modifier keycodes as a shortcut's "main" key (defense already added — do not remove). | -| `activity/main/dialogs/ShortcutDialog.kt` | UI for recording a new shortcut. Must ignore modifier keys' own key-up events when recording a combo — only the non-modifier key's release finalizes the recording. | - -**Golden rule for this whole area:** real mouse input must always be delivered to the WebView as real mouse `MotionEvent`s (`SOURCE_MOUSE`, correct `TOOL_TYPE`), real touch input as real touch events, real keyboard input as real key events. Never intercept an event and re-emit it as a different event type. Chromium's own input handling (click, hover, drag-select, scroll) is far more correct than anything this app could reimplement. - -### Memory / process lifecycle -| File | Responsibility | -|---|---| -| `BrowserApp.kt` | `Application` class. Wires `ProcessLifecycleOwner` observers for the keep-alive foreground service and the system clipboard listener. Registers `UncaughtExceptionHandler` if/when crash logging is added. | -| `service/keepalive/BrowserKeepAliveService.kt` | Lightweight foreground service, started when the app backgrounds and stopped when it foregrounds, to reduce (not guarantee) the chance of the OS killing the process. Must remain lightweight — no real background work here. | - -### Ad blocking -| File | Responsibility | -|---|---| -| `activity/main/AdblockModel.kt` | Real filter-list-based ad/tracker blocking engine (Brave's `AdBlockClient`), background-thread list loading/parsing/caching. | -| `activity/main/MainActivityAdBlock.kt` | Wires the WebView's resource-request interception to `AdblockModel`, plus popup/new-window blocking (uses cached, non-blocking host-config lookups). | - -### Clipboard -| File | Responsibility | -|---|---| -| `notes/clipboard/ClipboardRepository.kt` | Clipboard-history persistence, feedback-loop guarding (`isInternalClipboardWrite`, `markCopiedByApp`) so the app's own clipboard writes don't create duplicate history entries. | -| `notes/clipboard/ClipboardDao.kt` | Room DAO for clipboard history. | -| System `ClipboardManager.OnPrimaryClipChangedListener` (registered in `BrowserApp.kt`) | Captures *any* text copied anywhere — including WebView's native page-text-selection copy — into the app's clipboard history, respecting foreground-only reads and incognito mode. | - -### Favicons -| File | Responsibility | -|---|---| -| `singleton/FaviconsPool.kt` (common module) | Favicon fetch/cache, with an in-memory `LruCache` to avoid repeated disk stats, background-thread fetch-on-miss. | - -### UI shell / DPAD navigation -| File | Responsibility | -|---|---| -| `activity/main/MainActivityDpad.kt` | Header ↔ native-home-grid ↔ top-tab-bar D-pad focus routing. Any focus-mapping logic added here must be symmetric (moving down then up returns focus to the same control) and must only target currently-visible views. | -| `activity/main/dialogs/*SidebarPopup.kt` | Newer sidebar-based UI for History/Downloads/Favorites/Notes/Clipboard/Tabs/File Manager. | - ---- - -## 3. Hard Rules — Do Not Violate These - -These are not style preferences. Each one maps to a real, previously-shipped bug (see §5 for the full incident log). Violating any of these is very likely to reintroduce a fixed bug. - -1. **Never inject custom CSS/JS to fake a native browser feature** (zoom, dark mode, layout scaling, etc.) if WebView/Chromium already exposes a native API for it. Use WebView's native `prefers-color-scheme`/theme handling, not forced algorithmic darkening; never patch page prototypes (`HTMLMediaElement.prototype`), never synthesize duplicate DOM events, never match obfuscated site class names. Zoom is the one documented exception and is *only* allowed through `PageZoomController` (see rule 15) — no other file may inject layout/CSS. -2. **Never convert a real input event into a synthetic event of a different type** (e.g., mouse `MotionEvent` → synthetic touch `MotionEvent`). Deliver events to WebView exactly as the OS reports them. If a specific device has a broken input driver, that is an OS/OEM-level bug outside this app's ability to safely work around without breaking other devices — do not add conversion/interception logic to compensate for it. -3. **Never add device-, chipset-, OEM-, or box-brand-specific logic anywhere.** All input, rendering, and performance fixes must be generic and based on documented, standard Android/WebView APIs. If a bug only reproduces on one brand of set-top box, investigate whether it's actually a general bug being *masked* on other devices (it usually is) before assuming it needs device-specific handling. -4. **Every WebView instance must have `onRenderProcessGone` handled**, recovering gracefully (recreate WebView + reload for the foreground tab, silent state-clear for background tabs) rather than letting a renderer crash take down the whole app. -5. **Never use `RecyclerView.Adapter.notifyDataSetChanged()`** for anything other than a genuine full-list replacement (e.g., "clear all"). Use `notifyItemChanged`/`Inserted`/`Removed`/`RangeChanged`, or `DiffUtil` for arbitrary list changes, computed off the main thread for large lists. -6. **Never perform blocking I/O (`runBlocking`, synchronous disk/DB/network calls) on the main thread or on a WebView callback thread** (`shouldInterceptRequest`, `onPageStarted`, etc.). Use coroutines with proper dispatchers and, where a fast synchronous answer is needed, an in-memory cache checked first. -7. **Any event-dispatch or drawing code that can re-enter itself** (directly or through a chain of helper calls) **must update its guard/state flag *before* the call that can cause re-entry, not after.** (See §5, CursorLayout StackOverflow incident — this exact ordering mistake caused an infinite-recursion crash.) -8. **Modifier-key handling (Ctrl/Alt/Shift/Meta) in any key-recording or key-matching code must explicitly treat pure-modifier keycodes specially.** A modifier key generates its own key-down/key-up events; code that records "the last key event" naively will get overwritten by the modifier's own release. Always ignore pure-modifier keycodes when determining the "main" key of a combo. -9. **Ad/tracker blocking must always be a real, functioning engine** — never a stub that returns `false` unconditionally while the Settings UI implies it's active. If disabling ad blocking is ever needed for debugging, gate it behind an explicit debug flag, never ship it silently disabled. -10. **Background tab memory management must be LRU-based and configurable, never fully disabled and never fully unbounded.** Tabs beyond `Config.maxLiveTabs` should be trimmed (state-saved, WebView released) oldest-first, transparently restored on revisit. The OS-level `onTrimMemory`/`onLowMemory` reactive safety net must always remain in place regardless of any proactive LRU logic. -11. **The system clipboard listener must guard against feedback loops** (the app's own clipboard writes must not create duplicate history entries) **and must respect incognito mode and foreground-only clipboard access** (Android 10+ restricts background clipboard reads — do not attempt them). -12. **Any new UI list, popup, or dialog added to the app (including new Sidebar popups) must follow the same standards as the rest of the app** — precise RecyclerView updates (rule 5), no blocking calls (rule 6), and must be reachable/dismissible correctly via D-pad, keyboard, and mouse alike. -13. **Phone vs TV layout is decided in exactly one place: `MainActivityUI.isCompactChromeLayout()`** (`!Utils.isTV() && smallestScreenWidthDp < 600`). The phone layout is *top address pill + bottom Chrome toolbar* (`llBottomPanel`), the TV/tablet layout is the full top header plus the optional top tab bar. Never hide a header control by hand in another file, never give a layout branch its own visibility logic, and never `requestFocus()` on a control that the current layout switched off — use `requestHeaderFocus()`. `getHeaderFocusableViews()` must keep returning only *currently visible* controls so D-pad/keyboard focus can never land on a hidden view. -14. **A menu entry must do the real thing or not exist.** "Find in page" uses `setFindListener`/`findNext`/`clearMatches`; "Translate this page" uses the `*.translate.goog` page proxy (`PageTranslate.kt`) — not a dead `translate.google.com/translate?u=` URL, not a toast that just says "searching". Any future "boost/clean/optimize" UI must call a real API (e.g. `TabsModel.onTrimMemory()`); `System.gc()` is not a feature and must not be presented as one. -16. **The native home screen is an overlay, never a navigation.** `showHomeScreen()` must not call `clearHistory()` or `loadUrl("about:blank")`: the tab keeps its document and back/forward list, playback is paused, and `hideHomeScreen()` reveals it again. "On home" is answered only via `isHomeUrl()` / `isHomeScreenShown()`, and `WebTabState.lastUrlBeforeHome` means "the page currently covered", never a fake forward entry. -17. **All user-visible text and every colour must come from resources.** No `android:text`/`contentDescription`/`hint` literal in a layout, no `Toast.makeText(ctx, "...")`/`setMessage("...")` literal, no hex colour in a layout, drawable or `.kt` file. Colours come from the semantic palette in `values/colors.xml` + `values-night/colors.xml` (day *and* night), so a light theme can never end up with white-on-white text; text that shows a count uses `plurals`. `scripts/quality-gate.sh` (run by `.github/workflows/quality.yml`) enforces this mechanically — do not "fix" a gate by deleting the rule, mark a deliberate exception with `quality-gate: allow` and say why. -18. **Input devices are handled through the platform only, and one `Config.InputMode` decides the coherent bundle** (virtual cursor on/off, joystick-axis D-pad translation, desktop-view default). Never patch page JS, synthesize events, or branch on a device brand to make a remote or a mouse work; if a mode is added, it must map onto existing native flags and be re-applied when devices come and go. - -15. **Page zoom logic lives exclusively in `PageZoomController.kt` and implements Chrome-desktop-style density zoom via dynamic `` width override injected at document-start and on zoom changes. Native `WebView.zoomIn()`/`zoomOut()`/`zoomBy()` was replaced because it performed photo-style magnification without responsive layout reflow. Do NOT reintroduce `textZoom`, `setInitialScale()`, custom CSS `zoom` property injection, or switch back to native `zoomIn()`/`zoomOut()` as the primary zoom mechanism.** - ---- - -## 4. Quality Bar — "PC Chrome Level" - -Before considering any browsing-related feature "done," it must pass this bar: - -- **Rendering:** A website must look pixel-identical (modulo the WebView/Chromium version's own rendering) to how it looks in desktop Chrome or stock mobile Chrome — no color shifts, no layout shifts, no missing/misplaced elements caused by this app's own code. -- **Zoom:** Must feel as smooth as native Chrome pinch-zoom (GPU-scale, not layout-reflow), and must never displace page elements. -- **Scrolling:** Must feel as smooth as stock WebView/Chrome scrolling — no jank introduced by app-level touch/scroll interception or heavy injected JS. -- **Text selection & copy/paste:** Click-drag mouse selection must show the native blue highlight and must copy correctly, exactly like desktop Chrome. Selected/copied text must also appear in the app's own Clipboard Manager. -- **Right-click:** Must behave predictably and be clearly either (a) the app's own page-action menu (Refresh/Share/Copy/Open External/etc., current behavior) or (b) deferring to page-native context behavior — whichever direction is chosen, it must be intentional and documented here, not an accidental side effect of input-handling code elsewhere. -- **Keyboard shortcuts:** Every shortcut configurable in Settings must actually fire reliably on a physical keyboard, matching what was recorded. -- **Multi-input parity:** Every core browsing action (click, scroll, zoom, select text, switch tabs, open new tab, navigate back) must work correctly via D-pad/remote, physical keyboard, and physical mouse — and via touch on tablets — without any one input method's handling code interfering with another's. -- **Stability:** No crashes from heavy JS/WASM sites (AI chat apps, etc.), no crashes from input-handling recursion, no crashes from popup/window teardown races. -- **Performance under load:** Opening 8+ tabs, switching between them, and scrolling long lists (history, downloads) must stay smooth; memory must stay bounded via the LRU tab-trimming policy, not by never releasing anything. - ---- - -## 5. Incident Log — Bugs Already Found & Fixed (do not reintroduce) - -Keep this list updated whenever a significant bug is found and fixed. This is the project's institutional memory. - -| # | Bug | Root cause | Fix applied | Status | -|---|---|---|---|---| -| 1 | App crash when opening JS/WASM-heavy sites (AI Studio, Claude.ai, Gemini) | `onRenderProcessGone` was never overridden; renderer OOM crash took down the whole app | Implemented `onRenderProcessGone`: destroy crashed WebView safely, recreate + reload for foreground tab, silent state-clear for background tabs | ✅ Fixed | -| 2 | Ad blocking did nothing despite a Settings toggle | `isAd()`/`isAdBlockingEnabled()` hardcoded to return `false`/`false` | Real engine (Brave `AdBlockClient`) wired up, EasyList loaded/parsed/cached on a background thread | ✅ Fixed | -| 3 | Header ↔ native-home-grid D-pad navigation was asymmetric (down then up didn't return to the same control) | Two different, inconsistent column-mapping formulas used for the down vs. up direction | Both directions now use the same `headerViews` list and consistent ratio-mapping | ✅ Fixed | -| 4 | Top-tab-bar DOWN always focused the Home icon, even if hidden | No visibility check before requesting focus | Now uses only currently-visible header views | ✅ Fixed | -| 5 | Popup/new-window check blocked the main thread | `runBlocking(Dispatchers.Main.immediate)` around a DB query in `shouldBlockNewWindow` | In-memory cache checked first; async background fetch on cache miss | ✅ Fixed | -| 6 | Home-page favicon loading blocked the WebView resource thread | `runBlocking` around a favicon fetch | Fast local cache/disk check first; async fallback fetch on miss | ✅ Fixed | -| 7 | Home-button press felt laggy | `onPause()` saved tab state via `runBlocking` on the main thread | Changed to an async coroutine (`Dispatchers.IO`) | ✅ Fixed | -| 8 | App/tabs could be killed quickly in the background, with no "recent apps" concept on Android TV | No foreground service existed to raise process priority | Added `BrowserKeepAliveService`, lifecycle-driven via `ProcessLifecycleOwner`, configurable via `Config.keepAliveInBackground` | ✅ Fixed | -| 9 | Background tabs never released memory proactively | `trimMemory()` only ran reactively on OS `onTrimMemory` callbacks | Added LRU-based proactive trimming beyond `Config.maxLiveTabs`, with state-save-then-restore; OS reactive trimming kept as a safety net | ✅ Fixed | -| 10 | Mouse click-drag text selection showed no blue highlight; drag gestures could freeze/crash the WebView | `HardwareInputManager` converted real mouse `MotionEvent`s into synthetic finger-touch events, breaking Chromium's native mouse-drag-select handling and creating inconsistent pointer-type semantics (native hover as mouse, click/drag as fake touch) | Removed the synthetic-touch-conversion layer entirely; native mouse events now reach WebView unmodified | ✅ Fixed | -| 11 | Text/links copied from a webpage never appeared in the app's own Clipboard Manager | Only "Copy Link" (context menu) and manual entries were recorded; WebView's native page-text copy went straight to the OS clipboard, bypassing the app entirely | Added an app-level `OnPrimaryClipChangedListener`, with feedback-loop guarding and incognito/foreground-only safety | ✅ Fixed | -| 12 | Recorded keyboard shortcuts using a modifier (Ctrl+T, Ctrl+Tab, etc.) silently failed to fire | The shortcut-recording dialog's `onKeyUp` fired for every key release, including the modifier key's own release, which overwrote the just-recorded correct combo with `keyCode=, modifiers=0` | Recording logic now explicitly ignores pure-modifier keycodes as the "main" recorded key; added a runtime safety-net that treats any already-corrupted saved shortcut as invalid, plus a one-time migration to clear pre-existing corrupted entries | ✅ Fixed | -| 13 | App crashed with `StackOverflowError` in `CursorLayout.dispatchTouchEvent` during certain D-pad-cursor-then-input sequences | `CursorDrawerDelegate.hideCursor()` called `dispatchMotionEvent()` → `surface.dispatchTouchEvent()` (re-entering `CursorLayout.dispatchTouchEvent`, which unconditionally calls `hideCursor()` again) *before* resetting the `dpadCenterPressed` guard flag to `false`, causing unbounded recursion | Moved `dpadCenterPressed = false` to before the recursive `dispatchMotionEvent()` call | ✅ Fixed | -| 14 | Certain interactive web elements (dropdowns/buttons in JS-heavy sites) failed to register mouse clicks on some devices, while scrolling and simple clicks worked fine | Root cause not fully isolated at the app level — evidence pointed at a system/driver-level input-delivery quirk on specific hardware (out of this app's control), compounded by the now-removed synthetic-touch-conversion hack which was an incomplete attempt to work around it | The device-specific workaround was removed per the "no jugaad" principle (see §3, rule 3); any remaining device-specific click issues are treated as a platform/OEM limitation, not something to special-case in app code | 🟡 Accepted limitation — do not reintroduce device-specific workarounds for this | -| 15 | Websites rendered with visibly wrong colors (inverted/dark navy backgrounds, discolored images) | Chromium's "Algorithmic Darkening"/Force Dark was applied automatically whenever the device's system UI was in night/dark mode, defaulted to enabled | Removed entirely — websites now always render their true, unmodified colors regardless of system theme | ✅ Fixed | -| 16 | Zoomed pages had page elements (e.g. Google's account/apps dropdown) rendering in the wrong screen position; zoom/scroll felt less smooth than stock Chrome | Custom JS-injected CSS `zoom` property on ``, forcing width/min-width percentage overrides, broke `position: fixed`/`absolute` coordinate math and forced layout reflow instead of using native GPU-scale zoom | Removed the CSS-zoom injection; TV-remote zoom controls now call WebView's native `zoomIn()`/`zoomOut()`/`zoomBy()` (already enabled via `setSupportZoom`/`builtInZoomControls`) | ✅ Fixed | -| 17 | `notifyDataSetChanged()` still used in several adapters (History, Downloads, Favorites, and multiple new `*SidebarPopup.kt` files) | Precise-update fix was only applied to the highest-frequency adapters (`TopTabsAdapter`, `TabsRowAdapter`); newer sidebar UI was added afterward using the old pattern | `utils/ListDiff.kt` (shared DiffUtil helper with move-detection disabled above 200 rows) now backs the favourites / downloads / tabs sidebars and the Chrome tab grid. The only remaining `notifyDataSetChanged()` calls in the app are on `BaseAdapter`/`ArrayAdapter` (ListView) classes — `HistoryAdapter`, `DownloadListAdapter`, `FavoritesListAdapter`, `ShortcutsSettingsView` — where no finer API exists; rule 5 is about `RecyclerView.Adapter` and those are exempt by design. Enforced by `scripts/quality-gate.sh` | ✅ Fixed | -| 18 | Page zoom felt like photo magnification instead of desktop-Chrome-style density change; responsive pages never reflowed into desktop layouts | `WebView.zoomIn()`/`zoomOut()`/`zoomBy()` perform photo-style uniform magnification of the rendered bitmap without changing layout viewport width | Rewrote `PageZoomController.kt` to dynamically overwrite `` with target CSS viewport width injected at document-start and on zoom changes, matching desktop Chrome's Ctrl+/Ctrl- density reflow behavior without breaking fixed-position elements | ✅ Fixed | - -| 19 | Desktop mode toggle stuck in desktop loop; switching back to mobile mode failed to clear desktop user agent or restore mobile zoom | `WebViewEx.isDesktopModeEnabled()` checked `settings.userAgentString?.contains("Windows")`, which remained true after user untoggled desktop mode; also `applyDesktopMode()` skipped setting userAgentString when null, preventing WebView default UA restoration | Centralized desktop mode detection in `Config.isDesktopMode()`, unconditionally cleared `settings.userAgentString = null` to restore WebView default mobile UA, aligned initialization sequence in `WebViewWebEngine`, and fortified `PageZoomController` runtime script with `MutationObserver` | ✅ Fixed | -| 20 | On a phone the "Chrome" header was 9 widgets in one 52dp row: the omnibox collapsed to a few dp, and the bottom toolbar that the layout already declared (`llBottomPanel`) was a permanently-GONE `0dp` `ConstraintLayout`. `toggleMenu()`/`hideMenuOverlay(hideBottomButtons)` were no-ops, so the "toggle toolbar" shortcut did nothing and focus could be dropped on a GONE button | The mobile layout was grown out of the TV header instead of a real responsive layout; the bottom-bar parameter was never read | `activity_main.xml` now owns a real Chrome bottom toolbar (back · home · new tab · tabs badge · menu) and the page container sits `layout_above` it. `MainActivityUI.isCompactChromeLayout()` (not-TV && `smallestScreenWidthDp < 600`) selects phone-vs-TV layout, `requestHeaderFocus()` only focuses visible controls, `getHeaderFocusableViews()` includes the bottom row so D-pad/keyboard focus still cycles | ✅ Fixed | -| 21 | Settings labels were invisible in a light theme | `view_settings_main.xml` pinned `textColor="#FFFFFF"` (×31) and `#38BDF8` (×25) on cards whose `google_card_bg` is white by day; `SettingsRemoteSection` used `Color.WHITE` for the device list | All settings labels routed to `google_text_primary` / `google_text_secondary` / `google_accent` (which do have night variants). Every layout, drawable and Kotlin colour literal in the app now resolves through the semantic palette in `values/colors.xml` + `values-night/colors.xml` (`app_surface_elevated`, `app_surface_sunken`, `app_on_surface`, `app_on_surface_muted`, `app_outline`, `app_accent`, `app_error`, `app_warning`, `app_success`, `app_on_accent`). Focus rings on `bg_card_sleek` / `bg_card_tab_selector` were the same colour as the fill — invisible on a TV — and are now accent strokes. A grep gate keeps it that way | ✅ Fixed | -| 22 | "Find in page" only highlighted internally: no match count, no next/previous, highlights left behind | `ChromeMenuPopup.showFindInPageDialog()` called `findAllAsync()` and never used `setFindListener`/`findNext`/`clearMatches` | New `FindInPageDialog.kt` wires the three native WebView APIs (debounced `findAllAsync`, "n of m" counter, prev/next, cleanup on dismiss). Native mechanism, no injected JS | ✅ Fixed | -| 23 | "Translate this page" opened a dead endpoint | `https://translate.google.com/translate?sl=..&tl=..&u=..` has been shut down by Google for years | `PageTranslate.kt` builds the `*.translate.goog` page proxy URL that Chrome itself uses, with `_x_tr_pto=wapp` so no Google toolbar is injected, a remembered target language (`Config.translateTargetLanguage`) and a "Show original" toggle | ✅ Fixed | -| 24 | Safe Browsing was silently disabled app-wide while the README claimed "the securest browser" | `WebViewEx` set `safeBrowsingEnabled = false` and the manifest set `android.webkit.WebView.EnableSafeBrowsing=false` | Both now follow `Config.safeBrowsingEnabled` (default **on**) with a real switch under *Settings → Web Engine & Rendering*. Related follow-ups (mixed content, `allowFileAccess`) = W3 | ✅ Fixed | -| 25 | "Clear cache" leaked a whole WebView renderer; the home-screen dashboard did `ActivityManager` IPC + `StatFs` on the UI thread every second; `onTrimMemory` threw away the favicon cache on every backgrounding; connectivity used the deprecated `CONNECTIVITY_CHANGE` broadcast | throwaway `WebView(ctx)` never destroyed; a 1s main-thread `Handler` ticker; `level >= TRIM_MEMORY_RUNNING_LOW` also matched `TRIM_MEMORY_UI_HIDDEN`; `activeNetworkInfo` deprecated/undelivered | `clearCache` runs on Main and destroys the view; dashboard sampling moved to `Dispatchers.Default` (storage 1-in-5 ticks, no stacking, stops when hidden); trim-level check made explicit; `registerDefaultNetworkCallback` replaces the broadcast; `offscreenPreRaster` is enabled only for the attached tab (background tabs no longer hold an extra paint buffer each — matters on 1–2 GB boxes) | ✅ Fixed | -| 26 | Plugging a USB keyboard into a TV (or toggling system dark mode) destroyed every incognito tab | `.activity.IncognitoModeMainActivity` declared `configChanges="orientation|screenSize|screenLayout"` while the main activity also declares `keyboard|keyboardHidden|navigation|…` | Incognito activity now declares the same configChanges set | ✅ Fixed | -| 27 (open) | `QUERY_ALL_PACKAGES` requested (Play-restricted) though only `VIEW`/speech/install intents are resolved; app's own update/filter-list requests could run over cleartext | permission added by reflex; `usesCleartextTraffic="true"` is needed for browsing `http://` but was also applied to first-party calls | Permission removed, explicit `` added, `network_security_config.xml` pins first-party hosts to TLS. **Also open:** the repo is a derivative of the GPL-3.0-or-later **TV Bro** project (`Config.HOME_PAGE_URL` still points at `tvbrowser.phlox.dev`) while `README.md` declares "all rights reserved / no licence" and the About screen declares "100% open source" — see `docs/AUDIT-2026-10-14.md` §0. This must be resolved before publishing | 🟡 Open — needs the owner's decision | -| 28 | The app lock was theatre: the PIN was stored in **plaintext** (twice — `desktop_mode` prefs key `app_lock_pin` and `files/app_lock_pin.dat`), any 4-digit guess was accepted forever after the first unlock, and there was no throttle on guessing | `verifyPin()` compared a stored string; `isSessionUnlocked()` only checked that a token file *existed* (`AppLockActivity.onCreate` wrote it whenever no unlock was required), so the file never expired | `AppLockManager` rewritten: PBKDF2-HmacSHA256 (25 000 iterations, 16-byte `SecureRandom` salt) stored as `pbkdf2:iters:salt:hash`, constant-time compare, lockout after 5 failures (15 s base, doubling, capped at 15 min), the session token now stores an **expiry** (60 s grace), legacy plaintext records are upgraded on the next successful unlock and the plaintext file is deleted. `AppLockActivity`/`TvPinDialog` show the lockout countdown | ✅ Fixed | -| 29 | App-lock notifications and the keep-alive/download notifications rendered as a grey blob on Android 8+ | `setSmallIcon(R.mipmap.ic_launcher)` — a launcher mipmap is not a valid small icon (must be a monochrome drawable) | `DownloadService` uses `ic_file_download_grey_900`, `BrowserKeepAliveService` uses `ic_stat_network` | ✅ Fixed | -| 30 | One accidental press of the Home button cost a full reload of the page and destroyed its history | `showHomeScreen()` called `webEngine.clearHistory()` + `loadUrl("about:blank")`, and the "forward" button was a fake entry that re-fetched `lastUrlBeforeHome` over the network | Home is now an **overlay** on top of the live page: playback is paused, the WebView keeps its document and its back/forward list, and `hideHomeScreen()` reveals it again. `navigateInternal()` likewise stopped clearing history when leaving Home; the fake forward entry is gone and `navigateBackInternal()` no longer carries an ignored `goHomeIfNoHistory` flag. `isHomeUrl()` / `isHomeScreenShown()` are now the single definitions of "on home" | ✅ Fixed | -| 31 | "Desktop site" was one global switch: toggling it in a menu reloaded *every* live tab, and three menu entry points each had their own copy of that loop | `Config.desktopMode` was both the per-tab state and the app default; `ChromeMenuPopup`, `WebsiteMenuPopup`, `BrowserSidebarPopup` each applied it to all tabs | `WebTabState.desktopMode: Boolean?` (per-tab override, `null` = follow the default, persisted via Room v22 migration `ALTER TABLE tabs ADD COLUMN desktop_mode`), `WebViewEx.desktopModeOverride` so UA/zoom follow the *displayed* tab, and one shared implementation in `activity/main/DesktopMode.kt` that all three menus call. Settings → User Agent & Identity gained the real "desktop by default" switch | ✅ Fixed | -| 32 | Pointer/layout behaviour was scattered over four settings sub-screens; keyboard+mouse mode drew a second cursor over the real one; nothing reacted to a mouse being plugged in | `enableVirtualCursor` / `disableMotionAxesDpadNavigation` / `desktopMode` were independent toggles with no coherence, and no mode concept existed | `Config.InputMode` (`AUTO`/`TV_REMOTE`/`KEYBOARD_MOUSE`/`TOUCH`) with a segmented switch at the top of Settings, resolved against `Utils.isTV()` + `HardwareInputManager.isPhysicalMouseConnected()`, re-applied on every resume and on device add/remove. It writes only existing native flags — no new mechanism | ✅ Fixed | -| 33 | The home screen's "⚡ Click to Boost RAM" card promised a RAM boost and reported `System.gc()`'s delta as memory "freed" | A gimmick: `performRamBoost()` measured free RAM before/after `gc()`, which the OS may or may not honour, and the UI presented it as a feature | `performRamBoost()` deleted. The card opens a real memory panel (device RAM, this app's heap, live page views vs the adaptive cap) whose two actions are real: release detached background page views (`TabsModel.onTrimMemory()`) and clear the WebView cache. Rule 14 extended accordingly | ✅ Fixed | -| 34 | `generic_injects.js` patched `HTMLMediaElement.prototype.playing` globally, and a "TV precision click engine" synthesised a second `click()` on every pointer-up while matching Google's obfuscated class names (`gb_d`, `gb_wa`) | Page-level workarounds for input quirks — exactly what rules 1/2/3 forbid; the synthetic click risked double-activating controls on every site | Both removed. Media keys use local helpers and drive the element that is actually playing (with the autoplay-promise rejection swallowed); clicks are left to the platform. If a device really drops clicks, the fix belongs in the native input path, not in page JS | ✅ Fixed | -| 35 | Almost no UI text was translatable and section headers were emoji-decorated: ~300 `android:text`/`contentDescription` literals across 64 layouts, 44 toasts/dialog titles in Kotlin, "🖥️ Display & UI Scaling"-style headers, plus a settings search that matched hard-coded English keyword blobs | UI text was typed inline as screens were added | Everything moved to `res/values/strings.xml` (560+ entries, existing strings reused instead of duplicated), counts converted to `plurals`, emoji stripped from labels and `string-array` items, and `SettingsDialog`/`openMainCategory` now take `@StringRes` ids so a row label and its detail header cannot drift apart | ✅ Fixed | - ---- - -## 6. Verification Checklist — Run After *Any* Change - -Because this app has a history of one fix quietly breaking another area, treat this as mandatory regression testing after any non-trivial change, not just for the specific feature touched: - -- [ ] Open a heavy JS/WASM site (an AI chat app, etc.) — no crash, no freeze. -- [ ] Ads/trackers are actually blocked on a known ad-heavy site. -- [ ] D-pad navigation: header ↔ home-grid ↔ top-tab-bar, in both directions, lands on sensible/expected focus targets. -- [ ] Physical mouse: hover, left-click, right-click, and click-drag text selection (blue highlight appears) all work on a real webpage; copied text appears in Clipboard Manager. -- [ ] Physical keyboard: at least one modifier-based shortcut (e.g. Ctrl+T) fires correctly. -- [ ] Open 8+ tabs, switch between them rapidly — no visible jank, no crash. -- [ ] Background the app for a few minutes and resume — process should still be alive under normal conditions. -- [ ] Zoom in/out on a site with a fixed-position dropdown/menu (e.g. google.com's account menu) — menu stays correctly positioned at every zoom level. -- [ ] Load a page in both system light mode and system dark mode — page colors are identical (true to the site) in both. -- [ ] Scroll a long page — feels smooth, no stutter. -- [ ] No new `runBlocking`, synchronous I/O on main/WebView threads, or `notifyDataSetChanged()` introduced by the change — run `bash scripts/quality-gate.sh` (it also checks hard-coded text/colours and dangling `@string`/`@color` references; CI runs the same script). -- [ ] Home button on a real page, then Back: the page must still be loaded (no reload, no lost scroll position), and Back/Forward must both behave. -- [ ] "Desktop site" toggled in one tab while another tab shows a different site: only that tab changes, and the other tab keeps its layout/zoom. -- [ ] Settings → input mode: switch between remote / keyboard+mouse / touch and check the pointer, D-pad focus and page identity all follow it on both TV and phone. -- [ ] Phone (portrait, 360dp) and TV layouts both checked: bottom toolbar visible only on phones, no white-on-white text in either theme, search overlay + find-in-page + translate reachable by touch, D-pad and keyboard. -- [ ] Settings screen opened in BOTH light and dark theme — every label readable. -- [ ] No device/chipset/OEM-specific code introduced. - ---- - -## 7. When In Doubt - -If a requested feature or fix seems like it would require faking, intercepting, or re-implementing something the Android/WebView/Chromium platform already does — **stop and find the native API first.** State explicitly in your response which native API/mechanism you're using and why, before writing any custom logic. If no native mechanism exists for a genuine edge case, implement the smallest, most general fix possible, and add an entry to the Incident Log (§5) so future work doesn't reverse it. diff --git a/README.md b/README.md deleted file mode 100644 index e8d2a411..00000000 --- a/README.md +++ /dev/null @@ -1,316 +0,0 @@ -
- -# 🌐 Bansify Browser -### *The Ultimate Desktop-Grade Web Browser for Android TVs, Tablets, Phones, Linux, Windows & macOS* - -[![Platform](https://img.shields.io/badge/Platforms-Android%20TV%20%7C%20Tablets%20%7C%20Linux%20%7C%20Windows%20%7C%20macOS-4CAF50?style=for-the-badge&logo=android)](https://github.com/GothwadTech/browser) -[![Engine](https://img.shields.io/badge/Engine-Native%20Chromium%20WebView-4285F4?style=for-the-badge&logo=google-chrome)](https://developer.android.com/develop/ui/views/layout/webapps/webview) -[![Language](https://img.shields.io/badge/Language-Kotlin-7F52FF?style=for-the-badge&logo=kotlin)](https://kotlinlang.org) -[![Target Size](https://img.shields.io/badge/APK%20Footprint-%3C%2010%20MB-FF5722?style=for-the-badge)](#-engineering-journey--vision) -[![Made in India](https://img.shields.io/badge/Made%20in%20India-🇮🇳%20With%20Love-FF9933?style=for-the-badge)](#-author--credits) -[![License: Proprietary](https://img.shields.io/badge/License-Source--Available%20%2F%20All%20Rights%20Reserved-red.svg?style=for-the-badge)](#-proprietary-notice--usage-terms) - -
- -### 📥 Get Bansify Browser - -[![Get on Google Play](https://img.shields.io/badge/Google_Play-Get%20it%20on%20Play%20Store-00875A?style=for-the-badge&logo=google-play&logoColor=white)](https://play.google.com/store/apps/details?id=com.bansify.internet) -[![Get on JioStore](https://img.shields.io/badge/JioStore-Available%20on%20Jio%20Set--Top%20Box-0A2885?style=for-the-badge&logo=reliance&logoColor=white)](https://www.jio.com/fiber/services/set-top-box) -[![Official Website](https://img.shields.io/badge/Official_Website-Visit%20gothwad.com-FF6F00?style=for-the-badge&logo=google-chrome&logoColor=white)](https://gothwad.com) -[![Direct Download](https://img.shields.io/badge/GitHub-Download%20Latest%20Release-181717?style=for-the-badge&logo=github&logoColor=white)](https://github.com/GothwadTech/browser/releases) - -
- -> **"Bansify Browser is the fastest, securest, and most lightweight browser for Android Phones, TVs, Linux, Windows, and macOS you have ever seen. Engineered with full keyboard and mouse parity, industry-leading TV remote D-Pad navigation, an inbuilt File Manager, TV Notepad, AdBlocker, and Clipboard Manager. Try first, then believe."** -> — *Made in India with ❤️ by Bansify* - -> **Status note (2026-10-14).** The app is in a pre-release hardening pass. Claims below are being -> converted one by one from "aspirational" into "measured": the APK-size figure is a **target**, not a -> CI measurement yet, and the 10+ language claim is qualified under *Global Accessibility* below. -> **Do not publish a build before the licence/attribution question in -> [`docs/AUDIT-2026-10-14.md`](docs/AUDIT-2026-10-14.md) §0 is settled**: this tree derives from the -> GPL-3.0-or-later *TV Bro* project, which cannot be reconciled with the "All Rights Reserved / -> NO OPEN SOURCE LICENSE IS GRANTED" notice below while the in-app About screen advertises "100% Open -> Source Software" — and the repo carries no `LICENSE` file at all. Settling that is the owner's -> decision, not a code fix; nothing here changes the licence terms. - -
- ---- - -## ⚡ Quick Download & Installation Matrix - -| Platform | Format | How to Install | -|---|---|---| -| **📱 Android TV / Google TV / Phone / Tablet** | `.apk` / `.aab` | • Install from **Google Play Store** or **JioStore** on your TV
• Or download `GothwadTVBrowser-vX.X.X-Release.apk` and side-load | -| **🐧 Linux (Ubuntu, Debian, Mint)** | `.deb` | `sudo dpkg -i gothwad-browser_*_all.deb`
*(Installs launcher, icon, and desktop entry automatically)* | -| **🐧 Linux (Arch, Fedora, Universal)** | `.tar.gz` | Extract `gothwad-browser-linux-v*.tar.gz` and run `./install.sh` | -| **🪟 Windows (10 & 11)** | `.zip` (Portable / Installer) | Extract `gothwad-browser-windows-*.zip` and double-click **`Install.bat`**
*(Creates Desktop + Start Menu shortcuts with icon)* | -| **🍎 macOS (Apple Silicon & Intel)** | `.zip` (`.app` bundle) | Extract `gothwad-browser-macos-*.zip` and drag **`Bansify Browser.app`** to `/Applications` | - ---- - -> [!CAUTION] -> ### ⚖️ PROPRIETARY NOTICE & USAGE RESTRICTIONS -> **Copyright © Bansify. All Rights Reserved.** -> The source code in this repository is published strictly as **Source-Available for inspection, security auditing, and viewing purposes only**. -> **NO OPEN SOURCE LICENSE IS GRANTED.** -> - You **MAY NOT** copy, clone, distribute, redistribute, modify, sub-license, reverse-engineer, publish, or monetize this code or any part of it. -> - You **MAY NOT** use this software or its components in any commercial, open-source, or non-commercial product or project. -> - Any unauthorized use, extraction, reproduction, or redistribution of this codebase is strictly prohibited and constitutes an infringement of copyright laws. - ---- - -## 📑 Table of Contents -- [⚡ Quick Download Matrix](#-quick-download--installation-matrix) -- [✨ Core Highlights](#-core-highlights) -- [💻 Multi-Platform Installation Guide](#-multi-platform-installation-guide) - - [📱 Android (TV, Phones, Tablets)](#-1-android-tv-phones--tablets) - - [🐧 Linux (Debian, Ubuntu, Fedora, Arch)](#-2-linux-ubuntu-debian-fedora-arch) - - [🪟 Windows (10 & 11)](#-3-windows-10--11) - - [🍎 macOS (Apple Silicon & Intel)](#-4-macos-apple-silicon--intel) -- [🎮 Complete Input & Hardware Parity](#-complete-input--hardware-parity) -- [🧰 Integrated Productivity Suite](#-integrated-productivity-suite) -- [🚀 Genesis & Engineering Journey](#-genesis--engineering-journey) -- [🏗️ Architecture & Philosophy](#️-architecture--philosophy) -- [🗺️ Development Roadmap](#️-development-roadmap) -- [⚖️ Proprietary Notice & Usage Terms](#-proprietary-notice--usage-terms) -- [❤️ Author & Credits](#️-author--credits) - ---- - -## ✨ Core Highlights - -Bansify Browser is built with a singular mission: **bring desktop PC Chrome-grade browsing to Android TV, mobile screens, Linux, Windows, and macOS without the bloat.** - -- ⚡ **Ultra-Fast & Featherweight:** Engineered around a **sub-10 MB APK target**, with the live-page cap, snapshot thumbnails and cache behaviour sized for budget TV streaming sticks (1–2 GB RAM, slow eMMC). The size figure is a target, not a measured CI number yet. -- 🖥️ **PC-Grade Chromium Engine:** Native Chromium rendering fidelity. No synthetic CSS zooms, no layout reflow compromises, and no artificial color shifts—pages render exactly as intended. -- 🛡️ **Integrated Ad & Tracker Protection:** Fast, real-time filter-list ad blocking (Brave `AdBlockClient` engine) directly intercepting network resources asynchronously without degrading render performance. -- 🗂️ **Advanced Tab Architecture:** Dynamic top-tab bar and row/grid tab switchers with proactive LRU memory trimming so you can keep 10+ tabs without background crashes. -- 🔒 **App Lock & Privacy:** PIN lock (PBKDF2-hashed, never stored in plaintext, with attempt lockout and an expiring unlock session), Chromium Safe Browsing **enabled by default**, incognito tabs that never hit disk, and a clipboard manager that respects it. -- 🌐 **Global Accessibility:** Responsive 10-foot TV UI ergonomics, with translated string resources for **11 locales** (de, fa, it, iw, pl, ru, uk, vi, zh, zh-TW + English default). Coverage is currently partial (~150 of ~660 strings per locale): every UI label now lives in `values/strings.xml`, so translations can be added file-by-file instead of chasing hard-coded text — new strings land in English first and are translated on request. - ---- - -## 💻 Multi-Platform Installation Guide - -### 📱 1. Android (TV, Phones & Tablets) - -**Android package / application ID:** `com.bansify.internet` (common-module resource namespace: -`com.bansify.internet.common`). App and common-module sources and tests live under -`src/main/java/com/bansify/internet/` and `src/test/java/com/bansify/internet/` in their respective modules. - -> **Package change:** Android treats this package as a separate app from builds using the previous -> package ID. It can be installed alongside the old app, but existing app data, preferences and -> permissions are not automatically migrated. - -1. **Google Play Store / JioStore:** Search for **"Bansify Browser"** and install with 1-click. -2. **Direct APK Side-loading:** - - Download `GothwadTVBrowser-vX.X.X-Release.apk` from [GitHub Releases](https://github.com/GothwadTech/browser/releases). - - Use a file manager, USB drive, or "Send Files to TV" app to install the APK directly on your TV box or phone. - ---- - -### 🐧 2. Linux (Ubuntu, Debian, Fedora, Arch) - -#### For Debian / Ubuntu / Mint (`.deb`): -```bash -# 1. Download the .deb from Releases -wget https://github.com/GothwadTech/browser/releases/latest/download/gothwad-browser_all.deb - -# 2. Install package -sudo dpkg -i gothwad-browser_all.deb -sudo apt-get install -f # resolve any optional dependencies -``` - -#### For Arch / Fedora / Universal (`.tar.gz`): -```bash -tar -xzf gothwad-browser-linux-v*.tar.gz -cd gothwad-browser-linux-* -./install.sh -``` -*Bansify Browser will be added to your desktop application launcher with its native high-res icon.* - ---- - -### 🪟 3. Windows (10 & 11) - -1. Download **`gothwad-browser-windows-vX.X.X.zip`** from [GitHub Releases](https://github.com/GothwadTech/browser/releases). -2. Extract the folder on your PC. -3. Double-click **`Install.bat`**. - - It will automatically create a **Desktop shortcut** and **Start Menu entry** with the official browser icon. - - If Windows Subsystem for Android (WSA) or ADB is active, the app will install directly. -4. Launch from your desktop shortcut at any time! -5. To uninstall cleanly, simply run **`Uninstall.bat`**. - ---- - -### 🍎 4. macOS (Apple Silicon & Intel) - -1. Download **`gothwad-browser-macos-vX.X.X.zip`** from [GitHub Releases](https://github.com/GothwadTech/browser/releases). -2. Extract the archive. -3. Drag **`Bansify Browser.app`** into your **`/Applications`** folder (or run `./install.sh`). -4. Launch via **Launchpad**, **Spotlight**, or your **Dock**. -5. To uninstall, simply run `./uninstall.sh` or move the app to Trash. - ---- - -## 🎮 Complete Input & Hardware Parity - -Browsing on Android TV is often plagued by clunky remote controls or broken mouse input. Bansify Browser is engineered with a **triple-input pipeline** where every input mechanism functions at full fidelity without interfering with another: - -| Input Method | Supported Behaviors & Capabilities | -|---|---| -| **TV Remote / D-Pad** | Smooth on-screen virtual cursor with proportional acceleration, intelligent directional focus navigation across headers, tabs, and web elements. | -| **Physical USB / Bluetooth Mouse** | Native Chromium mouse events (`SOURCE_MOUSE`), pixel-accurate hover states, right-click contextual menus, native click-drag blue text selection, and fluid scroll-wheel physics. | -| **Physical Keyboard** | Full hardware shortcut suite (`Ctrl+T` new tab, `Ctrl+W` close tab, `Ctrl+Tab` switch tabs, `Ctrl+R` refresh, etc.) with pure-modifier release protection. | -| **Touchscreen (Tablets & Phones)** | Multi-touch gestures, fluid pinch-to-zoom (GPU-accelerated), and responsive edge-to-edge touch layouts. | - ---- - -## 🧰 Integrated Productivity Suite - -Bansify Browser eliminates the need to switch between multiple utility apps on your TV: - -1. **📁 Inbuilt File Manager:** - - Explore local TV storage, external USB drives, and download directories directly from the browser sidebar. - - Quick preview, file deletion, and direct APK/media launching on large screens. -2. **📝 TV Notepad & Notes:** - - Jot down quick thoughts, recipes, URLs, streaming links, or cheat codes while browsing. - - Accessible at any time via the quick-action sidebar without losing your current web tab. -3. **📋 Smart Clipboard Manager:** - - Automatically captures copied text and links from web pages. - - Quick-access snippets and history with duplicate suppression and incognito-mode safety. -4. **📥 Robust Downloads Manager:** - - Dedicated download orchestrator with background service persistence (`BrowserKeepAliveService`) preventing the TV OS from killing long downloads. - ---- - -## 🚀 Genesis & Engineering Journey - -Bansify Browser was born out of frustration with existing TV browsers that were either sluggish, filled with intrusive ads, or incapable of handling basic mouse and keyboard inputs. - -``` -┌──────────────────────────────┐ -│ Phase 1: Inception │ Prototyped in Google AI Studio -│ (First 2 Weeks) │ Rapid concept validation & architectural foundations -└──────────────┬───────────────┘ - │ - ▼ -┌──────────────────────────────┐ -│ Phase 2: Deep Hardening │ Shifted to Antigravity & Native Android Studio -│ (~60% AI + Human Synergy) │ Native Chromium hooks, zero-jugaad input pipelines, Room DB -└──────────────┬───────────────┘ - │ - ▼ -┌──────────────────────────────┐ -│ Phase 3: Rigorous Testing │ 1 Month of continuous testing on Emulators -│ (Pre-Launch Validation) │ 100+ Real Devices (Android TV boxes, sticks, tablets) Passed -└──────────────┬───────────────┘ - │ - ▼ -┌──────────────────────────────┐ -│ Target Outcome │ Blazing-fast, feature-packed browser -│ (Production Standard) │ Ultra-lightweight under 10MB APK -└──────────────────────────────┘ -``` - -- **The AI Studio Foundation:** The initial architecture was scaffolded in **Google AI Studio** during the first two weeks, quickly validating the tab management, input routing, and core UI abstractions. -- **The Shift to Antigravity & Android Studio:** Development was transitioned to **Antigravity** and local **Android Studio** for deep native optimization. Over 60% of the codebase was developed through precision AI-augmented engineering, coupled with rigorous human systems programming. -- **Battle-Tested Across 100+ Real Devices:** Before its first public release, Bansify Browser underwent over a month of stress testing on emulators and **100+ physical hardware configurations**—including low-end Amlogic, Allwinner, and Rockchip TV boxes, certified Google TV dongles, Fire OS streaming devices, and Android tablets. -- **The Golden Engineering Rule:** **"Zero Jugaad — Native Platform First."** Every workaround (synthetic touch conversion, CSS zoom hacks, forced algorithmic dark mode) was eradicated in favor of clean, native Android and Chromium APIs. -- **The Grand Vision:** An all-in-one, productive, feature-dense web browser that never compromises on performance and stays strictly **under 10 MB**. - ---- - -## 🏗️ Architecture & Philosophy - -``` -app/src/main/java/ - ├── webengine/ # Chromium WebView encapsulation & lifecycle - │ ├── WebViewEx.kt # Native event dispatch, zoom, desktop mode - │ └── WebViewClients.kt # onRenderProcessGone crash resilience & page hooks - ├── activity/main/ # Core TV & Mobile UI Activities & Sidebars - │ ├── TabsModel.kt # LRU memory management & proactive tab trimming - │ └── MainActivityDpad.kt# TV remote focus-routing & shortcut mapping - ├── widgets/cursor/ # Precision virtual D-Pad cursor overlay - ├── notes/ # Inbuilt TV Notepad & Room database - ├── clipboard/ # Clipboard Manager with feedback-loop guarding - └── service/keepalive/ # Foreground keep-alive service for TV multitasking -``` - -- **Clean MVVM + Clean Architecture:** High cohesion, low coupling, and zero blocking calls on the UI or WebView threads. -- **Crash Immunity:** Full recovery via `onRenderProcessGone`—if a heavy JavaScript/WASM tab crashes the renderer, the foreground tab is safely reloaded while background tabs are silently trimmed. -- **Memory Bounded:** Proactive LRU tab unloading keeps memory usage within safe thresholds, even on 1GB RAM TV boxes. - ---- - -## 🗺️ Development Roadmap - -- [x] **Milestone 1: Core Navigation & Big-Screen Foundations** *(Completed)* - - Native Chromium WebView engine with hardware acceleration. - - Virtual D-Pad cursor for TV remotes with proportional speed. - - Full hardware keyboard and mouse event passthrough. - - Inbuilt TV Notepad, Clipboard History, and File Manager. -- [x] **Milestone 2: Real-Device Hardening & Ad-Blocking** *(Completed)* - - Filter-list-based AdBlock integration. - - LRU memory tab trimming & crash recovery. - - 100+ real Android TV hardware validation. -- [ ] **Milestone 3: Performance Hardening & Sub-10MB Seal** *(Current Focus)* - - Resource optimization and binary shrinking to guarantee sub-10MB release APK. - - Enhanced video player controls optimized for TV remotes. - - Faster cold-boot and warm-tab restoration times. -- [ ] **Milestone 4: Cloudless Local Sharing & Extensions Hub** *(Upcoming)* - - QR-based instant URL & file transfer between phones and TVs (no cloud required). - - Custom user-script / lightweight extension ecosystem. - - Advanced backup & restore for bookmarks, notes, and shortcuts. - ---- - -## 📱 Supported Platforms & Form Factors - -- **Android TV / Google TV:** Android 5.0 (API 21) up to Android 14+ (Certified & Non-certified boxes, smart TVs, projector boxes, streaming sticks). -- **Android Tablets:** Large-screen split-views, multi-window mode, keyboard dock & mouse support. -- **Android Phones:** Responsive vertical handheld experience with bottom/top navigation. - ---- - -## ⚖️ Proprietary Notice & Usage Terms - -``` -PROPRIETARY SOURCE-AVAILABLE NOTICE -================================== - -1. OWNERSHIP & COPYRIGHT: - All source code, designs, assets, and branding contained in this repository - are the proprietary intellectual property of Bansify. - Copyright (c) Bansify. All rights reserved. - -2. ALLOWED USAGE: - - This repository is made public exclusively for code inspection, educational - review, and architectural study. - -3. STRICT PROHIBITIONS: - - NO LICENSE is granted to compile, repackage, distribute, or publish APKs or - derivatives of this application on Google Play, Amazon Appstore, F-Droid, - or any third-party app store or website. - - NO commercial or non-commercial reproduction, cloning, white-labeling, or - forking for public deployment is permitted. - - Any violation of these terms will be met with immediate legal action and DMCA - takedowns. - -Inquiries and permissions: Contact Bansify. -``` - ---- - -## ❤️ Author & Credits - -- **Creator & Lead Developer:** **Bansify** (Pawan Gothwad) -- **Origin:** Proudly conceived, engineered, and built in **India 🇮🇳** -- **Contact:** [pawangothwad@gmail.com](mailto:pawangothwad@gmail.com) - -
- Built with relentless passion for speed, privacy, and big-screen productivity. -
- diff --git a/app/.gitignore b/app/.gitignore index 22a93f20..796b96d1 100644 --- a/app/.gitignore +++ b/app/.gitignore @@ -1,8 +1 @@ /build -/app-release.apk -/google-services.json -/crashlytics/ -/local.properties -/crashlyticsGoogle/ -/schemas/ -/google/ diff --git a/app/build.gradle.kts b/app/build.gradle.kts index f0b95456..f4b41316 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -1,125 +1,140 @@ +import com.google.gms.googleservices.GoogleServicesPlugin.MissingGoogleServicesStrategy + plugins { - id("tvbrowser.android.application") - alias(libs.plugins.ksp) + alias(libs.plugins.android.application) + alias(libs.plugins.kotlin.compose) + alias(libs.plugins.google.devtools.ksp) + alias(libs.plugins.secrets) + alias(libs.plugins.google.services) } android { - namespace = "com.bansify.internet" - - defaultConfig { - applicationId = "com.bansify.internet" - val vCode = (project.findProperty("versionCode") as? String)?.toIntOrNull() ?: 2 - val vName = (project.findProperty("versionName") as? String) ?: "1.0.$vCode" - versionCode = vCode - versionName = vName - - ndk { - abiFilters.addAll(listOf("armeabi-v7a", "arm64-v8a")) - } - - buildConfigField("String", "FLAVOR_appstore", "\"generic\"") - buildConfigField("String", "FLAVOR_webengine", "\"standard\"") - buildConfigField("Boolean", "BUILT_IN_AUTO_UPDATE", "true") - - javaCompileOptions { - annotationProcessorOptions { - arguments += mapOf( - "room.incremental" to "true", - //used when AppDatabase @Database annotation exportSchema = true. Useful for migrations - "room.schemaLocation" to "$projectDir/schemas" - ) - } - } - } - - signingConfigs { - create("debugConfig") { - storeFile = file("${rootDir}/debug.keystore") - storePassword = "android" - keyAlias = "androiddebugkey" - keyPassword = "android" - } - create("release") { - val keystorePath = System.getenv("KEYSTORE_PATH") - if (keystorePath != null) { - storeFile = file(keystorePath) - storePassword = System.getenv("KEYSTORE_PASSWORD") - keyAlias = System.getenv("KEY_ALIAS") - keyPassword = System.getenv("KEY_PASSWORD") - } - } - } - - buildTypes { - getByName("debug") { - isDebuggable = true - signingConfig = signingConfigs.getByName("debugConfig") - } - getByName("release") { - isDebuggable = false - isMinifyEnabled = true - isShrinkResources = true - proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") - signingConfig = if (System.getenv("KEYSTORE_PATH") != null) - signingConfigs.getByName("release") else null - } - } - - splits { - abi { - isEnable = project.hasProperty("enableAbiSplits") - reset() - include("armeabi-v7a", "arm64-v8a", "x86_64") - isUniversalApk = false - } - } - - buildFeatures { - viewBinding = true - buildConfig = true - } - - packaging { - resources { - excludes += "/META-INF/{AL2.0,LGPL2.1}" - } + namespace = "com.bansify.browser" + compileSdk { version = release(36) { minorApiLevel = 1 } } + + defaultConfig { + applicationId = "com.bansify.browser" + minSdk = 24 + targetSdk = 36 + versionCode = 1 + versionName = "1.0" + + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + + // Release signing comes from the environment (CI secrets); a missing keystore only + // affects assembleRelease, never assembleDebug. Debug builds use the standard + // ~/.android/debug.keystore that the Android Gradle Plugin creates on first use. + signingConfigs { + create("release") { + val keystorePath = System.getenv("KEYSTORE_PATH") + if (!keystorePath.isNullOrBlank() && file(keystorePath).exists()) { + storeFile = file(keystorePath) + storePassword = System.getenv("KEYSTORE_PASSWORD") ?: System.getenv("STORE_PASSWORD") + keyAlias = System.getenv("KEY_ALIAS") ?: "upload" + keyPassword = System.getenv("KEY_PASSWORD") + } } - - testOptions { - unitTests { - isIncludeAndroidResources = true - } + } + + buildTypes { + release { + isCrunchPngs = false + isMinifyEnabled = false + proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") + // Signed only when KEYSTORE_PATH points at a real keystore (CI release builds). + if (signingConfigs.getByName("release").storeFile != null) { + signingConfig = signingConfigs.getByName("release") + } } - - lint { - abortOnError = false - checkReleaseBuilds = false + debug { + // Default debug signing: no committed keystore required. } + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + } + buildFeatures { + compose = true + buildConfig = true + } + testOptions { unitTests { isIncludeAndroidResources = true } } + dependenciesInfo { + includeInApk = false + includeInBundle = true + } } -dependencies { - implementation(project(":app:common")) - - implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar")))) - - implementation(libs.androidx.appcompat) - implementation(libs.androidx.webkit) - implementation(libs.androidx.constraintlayout) - implementation(libs.androidx.recyclerview) - implementation(libs.kotlin.stdlib) - implementation(libs.kotlinx.coroutines.android) - implementation(libs.androidx.lifecycle.runtime.ktx) - implementation(libs.androidx.lifecycle.process) - - implementation(libs.androidx.room.runtime) - annotationProcessor(libs.androidx.room.compiler) - ksp(libs.androidx.room.compiler) - implementation(libs.androidx.room.ktx) +// Configure the Secrets Gradle Plugin to use .env and .env.example files +// to match the convention used in Web projects. +secrets { + propertiesFileName = ".env" + defaultPropertiesFileName = ".env.example" + ignoreList.add("FIREBASE_APPCHECK_DEBUG_TOKEN") +} - implementation(libs.segmented.button) - implementation(libs.ad.block) - implementation(libs.pinned.section.listview) +googleServices { missingGoogleServicesStrategy = MissingGoogleServicesStrategy.WARN } - testImplementation(libs.junit) - testImplementation(libs.robolectric) -} \ No newline at end of file +// Some unused dependencies are commented out below instead of being removed. +// This makes it easy to add them back in the future if needed. +dependencies { + implementation(platform(libs.androidx.compose.bom)) + // implementation(platform(libs.firebase.bom)) + // implementation(libs.accompanist.permissions) + implementation(libs.androidx.activity.compose) + // implementation(libs.androidx.camera.camera2) + // implementation(libs.androidx.camera.core) + // implementation(libs.androidx.camera.lifecycle) + // implementation(libs.androidx.camera.view) + implementation(libs.androidx.compose.material.icons.core) + implementation(libs.androidx.compose.material.icons.extended) + implementation(libs.androidx.compose.material3) + implementation(libs.androidx.compose.ui) + implementation(libs.androidx.compose.ui.graphics) + implementation(libs.androidx.compose.ui.tooling.preview) + implementation(libs.androidx.core.ktx) + implementation(libs.androidx.datastore.preferences) + implementation(libs.androidx.lifecycle.runtime.compose) + implementation(libs.androidx.lifecycle.runtime.ktx) + implementation(libs.androidx.lifecycle.viewmodel.compose) + // implementation(libs.androidx.navigation.compose) + implementation(libs.androidx.room.ktx) + implementation(libs.androidx.room.runtime) + // implementation(libs.coil.compose) + // implementation(libs.converter.moshi) + // implementation(libs.firebase.ai) + // Uncomment to use Firestore: + // implementation(libs.firebase.firestore) + + // Uncomment ALL FOUR of the following dependencies together to use Firebase Auth and Google + // Sign-In via Credential Manager: + // implementation(libs.firebase.auth) + // implementation(libs.androidx.credentials) + // implementation(libs.androidx.credentials.play.services) + // implementation(libs.googleid) + // implementation(libs.firebase.appcheck.recaptcha) + // implementation(libs.firebase.appcheck.debug) + implementation(libs.kotlinx.coroutines.android) + implementation(libs.kotlinx.coroutines.core) + // implementation(libs.logging.interceptor) + // implementation(libs.moshi.kotlin) + // implementation(libs.okhttp) + // implementation(libs.play.services.location) + // implementation(libs.retrofit) + testImplementation(libs.androidx.compose.ui.test.junit4) + testImplementation(libs.androidx.core) + testImplementation(libs.androidx.junit) + testImplementation(libs.junit) + testImplementation(libs.kotlinx.coroutines.test) + testImplementation(libs.robolectric) + androidTestImplementation(platform(libs.androidx.compose.bom)) + androidTestImplementation(libs.androidx.compose.ui.test.junit4) + androidTestImplementation(libs.androidx.espresso.core) + androidTestImplementation(libs.androidx.junit) + androidTestImplementation(libs.androidx.runner) + debugImplementation(libs.androidx.compose.ui.test.manifest) + debugImplementation(libs.androidx.compose.ui.tooling) + "ksp"(libs.androidx.room.compiler) + // "ksp"(libs.moshi.kotlin.codegen) +} diff --git a/app/common/.gitignore b/app/common/.gitignore deleted file mode 100644 index 42afabfd..00000000 --- a/app/common/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/build \ No newline at end of file diff --git a/app/common/build.gradle.kts b/app/common/build.gradle.kts deleted file mode 100644 index 405705e3..00000000 --- a/app/common/build.gradle.kts +++ /dev/null @@ -1,18 +0,0 @@ -plugins { - id("tvbrowser.android.library") - alias(libs.plugins.ksp) -} - -android { - namespace = "com.bansify.internet.common" -} - -dependencies { - implementation(libs.androidx.appcompat) - implementation(libs.androidx.room.runtime) - annotationProcessor(libs.androidx.room.compiler) - ksp(libs.androidx.room.compiler) - implementation(libs.androidx.room.ktx) - - testImplementation(libs.junit) -} diff --git a/app/common/consumer-rules.pro b/app/common/consumer-rules.pro deleted file mode 100644 index 421be2c6..00000000 --- a/app/common/consumer-rules.pro +++ /dev/null @@ -1,3 +0,0 @@ --keepclassmembers class * extends com.bansify.internet.utils.activemodel.ActiveModel { - (...); -} \ No newline at end of file diff --git a/app/common/proguard-rules.pro b/app/common/proguard-rules.pro deleted file mode 100644 index 34621f27..00000000 --- a/app/common/proguard-rules.pro +++ /dev/null @@ -1,25 +0,0 @@ -# Add project specific ProGuard rules here. -# You can control the set of applied configuration files using the -# proguardFiles setting in build.gradle. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} - -# Uncomment this to preserve the line number information for -# debugging stack traces. -#-keepattributes SourceFile,LineNumberTable - -# If you keep the line number information, uncomment this to -# hide the original source file name. -#-renamesourcefileattribute SourceFile - --keepclassmembers class * extends com.bansify.internet.utils.activemodel.ActiveModel { - (...); -} \ No newline at end of file diff --git a/app/common/src/main/AndroidManifest.xml b/app/common/src/main/AndroidManifest.xml deleted file mode 100644 index c60fb37d..00000000 --- a/app/common/src/main/AndroidManifest.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/app/common/src/main/java/com/bansify/internet/AppContext.kt b/app/common/src/main/java/com/bansify/internet/AppContext.kt deleted file mode 100644 index 2f1d7f42..00000000 --- a/app/common/src/main/java/com/bansify/internet/AppContext.kt +++ /dev/null @@ -1,24 +0,0 @@ -package com.bansify.internet - -import android.app.Application -import android.content.Context - -class AppContext { - companion object { - private var instance: Application? = null - private var config: Config? = null - - fun init(app: Application, config: Config) { - this.instance = app - this.config = config - } - - fun get(): Context { - return instance ?: throw IllegalStateException("AppContext is not initialized") - } - - fun provideConfig(): Config { - return config ?: throw IllegalStateException("AppContext is not initialized") - } - } -} \ No newline at end of file diff --git a/app/common/src/main/java/com/bansify/internet/Config.kt b/app/common/src/main/java/com/bansify/internet/Config.kt deleted file mode 100644 index e36f83d5..00000000 --- a/app/common/src/main/java/com/bansify/internet/Config.kt +++ /dev/null @@ -1,620 +0,0 @@ -package com.bansify.internet - -import android.annotation.SuppressLint -import android.content.SharedPreferences -import android.os.Build -import com.bansify.internet.utils.Utils -import com.bansify.internet.utils.observable.ObservableValue - -class Config(val prefs: SharedPreferences) { - companion object { - const val SEARCH_ENGINE_URL_PREF_KEY = "search_engine_url" - const val SEARCH_ENGINE_AS_HOME_PAGE_KEY = "search_engine_as_home_page" - const val HOME_PAGE_KEY = "home_page" - const val USER_AGENT_PREF_KEY = "user_agent" - const val THEME_KEY = "theme" - const val LAST_UPDATE_USER_NOTIFICATION_TIME_KEY = "last_update_notif" - const val AUTO_CHECK_UPDATES_KEY = "auto_check_updates" - const val UPDATE_CHANNEL_KEY = "update_channel" - const val TV_BRO_UA_PREFIX = "Browser/1.0 " - const val HOME_URL_ALIAS = "about:home" - const val KEEP_SCREEN_ON_KEY = "keep_screen_on" - const val SCREEN_ORIENTATION_KEY = "screen_orientation" - const val ORIENTATION_LANDSCAPE = 0 - const val ORIENTATION_PORTRAIT = 1 - const val ORIENTATION_AUTO = 2 - const val DISABLE_VIRTUAL_KEYBOARD_KEY = "disable_virtual_keyboard" - const val ENABLE_VIRTUAL_CURSOR_KEY = "enable_virtual_cursor" - const val CURSOR_SIZE_PERCENT_KEY = "cursor_size_percent" - const val CURSOR_STYLE_KEY = "cursor_style" - const val BLOCKED_INPUT_DEVICES_KEY = "blocked_input_devices" - - const val ENABLE_HARDWARE_MOUSE_CUSTOMIZATION_KEY = "enable_hardware_mouse_customization" - const val HARDWARE_MOUSE_SIZE_PERCENT_KEY = "hardware_mouse_size_percent" - const val HARDWARE_MOUSE_STYLE_KEY = "hardware_mouse_style" - const val HARDWARE_MOUSE_SIZE_PERCENT_MIN = 30 - const val HARDWARE_MOUSE_SIZE_PERCENT_MAX = 300 - const val HARDWARE_MOUSE_SIZE_PERCENT_DEFAULT = 100 - - const val CURSOR_SIZE_PERCENT_MIN = 50 - const val CURSOR_SIZE_PERCENT_MAX = 200 - /** When true, analog stick / hat axes from generic motion events are not translated to DPAD keys. */ - const val DISABLE_MOTION_AXES_DPAD_NAVIGATION_KEY = "disable_motion_axes_dpad_navigation" - /** Percent of built-in default (100 = default). Range [CURSOR_PHYSICS_PERCENT_MIN], [CURSOR_PHYSICS_PERCENT_MAX]. */ - const val CURSOR_MAX_SPEED_PERCENT_KEY = "cursor_max_speed_percent" - const val CURSOR_ACCELERATION_PERCENT_KEY = "cursor_acceleration_percent" - const val CURSOR_PHYSICS_PERCENT_MIN = 25 - const val CURSOR_PHYSICS_PERCENT_MAX = 200 - const val UI_SCALE_PERCENT_KEY = "ui_scale_percent" - const val UI_SCALE_PERCENT_MIN = 1 - const val UI_SCALE_PERCENT_MAX = 100 - const val UI_SCALE_PERCENT_DEFAULT = 50 - val STANDARD_ZOOM_LEVELS = intArrayOf(25, 33, 50, 67, 75, 80, 90, 100, 110, 125, 150, 175, 200, 250, 300) - const val WEB_PAGE_ZOOM_PERCENT_KEY = "web_page_zoom_percent" - const val MOBILE_WEB_PAGE_ZOOM_PERCENT_KEY = "mobile_web_page_zoom_percent" - const val DESKTOP_WEB_PAGE_ZOOM_PERCENT_KEY = "desktop_web_page_zoom_percent" - const val WEB_PAGE_ZOOM_PERCENT_MIN = 25 - const val WEB_PAGE_ZOOM_PERCENT_MAX = 300 - const val WEB_PAGE_ZOOM_PERCENT_DEFAULT = 100 - const val INCOGNITO_MODE_KEY = "incognito_mode" - const val INCOGNITO_MODE_HINT_SUPPRESS_KEY = "incognito_mode_hint_suppress" - const val DIRECT_NAVIGATION_MODE_HINT_SUPPRESS_KEY = "direct_navigation_mode_hint_suppress" - const val HOME_PAGE_MODE = "home_page_mode" - const val HOME_PAGE_SUGGESTIONS_MODE = "home_page_suggestions_mode" - const val WEB_ENGINE = "web_engine" - const val ALLOW_AUTOPLAY_MEDIA = "allow_autoplay_media" - const val WEB_ENGINE_DEBUG_KEY = "web_engine_debug" - //const val HOME_PAGE_VERSION_EXTRACTED = "home_page_version_extracted" - const val INITIAL_BOOKMARKS_SUGGESTIONS_LOADED = "initial_bookmarks_suggestions_loaded" - const val ADBLOCK_ENABLED_PREF_KEY = "adblock_enabled" - const val ADBLOCK_LAST_UPDATE_LIST_KEY = "adblock_last_update" - const val ADBLOCK_LIST_URL_KEY = "adblock_list_url" - const val APP_WEB_EXTENSION_VERSION_KEY = "app_web_extension_version" - const val NOTIFICATION_ABOUT_ENGINE_CHANGE_SHOWN_KEY = "notification_about_engine_change_shown" - const val APP_VERSION_CODE_MARK_KEY = "app_version_code_mark" - const val SHOW_TOP_TAB_BAR_KEY = "show_top_tab_bar" - const val KEEP_ALIVE_IN_BACKGROUND_KEY = "keep_alive_in_background" - const val MAX_LIVE_TABS_KEY = "max_live_tabs" - const val SAVE_HISTORY_KEY = "save_history" - const val TRANSLATE_TARGET_LANGUAGE_KEY = "translate_target_language" - const val SAFE_BROWSING_KEY = "safe_browsing_enabled" - /** - * Maximum number of tab WebViews kept fully live in memory simultaneously. - * Default is 6: balanced for typical Android TV boxes (1.5GB - 3GB RAM) to allow - * fast tab switching without exhausting system memory. - */ - const val DEFAULT_MAX_LIVE_TABS = 6 - /** Cap for the tab-switcher snapshot width; the grid cards are far smaller than a screen. */ - const val THUMBNAIL_MAX_WIDTH_PX = 480 - const val DESKTOP_MODE_KEY = "desktop_mode" - /** Which input device the user drives the browser with - see [InputMode]. */ - const val INPUT_MODE_KEY = "input_mode" - const val DESKTOP_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36" - - const val ENGINE_WEB_VIEW = "WebView" - - const val DEFAULT_ADBLOCK_LIST_URL = "https://easylist.to/easylist/easylist.txt" - val SearchEnginesTitles = arrayOf("Google", "Bing", "DuckDuckGo", "Yahoo!", "Yandex", "Startpage", "Custom") - val SearchEnginesNames = arrayOf("google", "bing", "ddg", "yahoo", "yandex", "startpage", "custom") - val SearchEnginesURLs = listOf( - "https://www.google.com/search?q=[query]", - "https://www.bing.com/search?q=[query]", - "https://duckduckgo.com/?q=[query]", - "https://search.yahoo.com/search?p=[query]", - "https://yandex.com/search/?text=[query]", - "https://www.startpage.com/sp/search?query=[query]", - "" - ) - val SupportedWebEngines = arrayOf(ENGINE_WEB_VIEW) - const val HOME_PAGE_URL = "https://tvbrowser.phlox.dev/appcontent/home/" - - fun canRecommendGeckoView(): Boolean { - return false - } - } - - enum class Theme { - SYSTEM, - WHITE_PURE, - WHITE_WARM, - WHITE_COOL, - BLACK_AMOLED, - BLACK_CHARCOAL, - BLACK_MIDNIGHT; - } - - /** - * How the user drives the browser. This is the one setting that decides pointer handling and - * the default page layout, so that TV users do not have to dig through four different - * sub-screens (virtual cursor, joystick axes, user agent) to get a working remote or a working - * mouse. - * - * - [AUTO] - resolve from the device: touch screen -> [TOUCH], TV with a mouse plugged in -> - * [KEYBOARD_MOUSE], anything else -> [TV_REMOTE]. - * - [TV_REMOTE] - D-pad only: the DPAD-driven virtual cursor and axis navigation are on. - * - [KEYBOARD_MOUSE] - a real pointer drives the page, so the drawn virtual cursor is turned - * off (two pointers on screen at once was the classic "double cursor" complaint). - * - [TOUCH] - phone / tablet: no virtual cursor, no axis-to-DPAD translation. - */ - enum class InputMode { - AUTO, TV_REMOTE, KEYBOARD_MOUSE, TOUCH - } - - enum class HomePageMode { - HOME_PAGE, SEARCH_ENGINE, CUSTOM, BLANK - } - - enum class HomePageLinksMode { - BOOKMARKS, LATEST_HISTORY, MOST_VISITED - } - - var incognitoMode: Boolean - get() = prefs.getBoolean(INCOGNITO_MODE_KEY, false) - @SuppressLint("ApplySharedPref") - set(value) { - // The incognito process reads this flag, so it has to hit disk before the other - // process is started - apply() would race with it. - prefs.edit().putBoolean(INCOGNITO_MODE_KEY, value).commit() // quality-gate: allow - } - - var incognitoModeHintSuppress: Boolean - get() = prefs.getBoolean(INCOGNITO_MODE_HINT_SUPPRESS_KEY, false) - set(value) { - prefs.edit().putBoolean(INCOGNITO_MODE_HINT_SUPPRESS_KEY, value).apply() - } - - var directNavigationModeHintSuppress: Boolean - get() = prefs.getBoolean(DIRECT_NAVIGATION_MODE_HINT_SUPPRESS_KEY, false) - set(value) { - prefs.edit().putBoolean(DIRECT_NAVIGATION_MODE_HINT_SUPPRESS_KEY, value).apply() - } - - var keepScreenOn: Boolean - get() = prefs.getBoolean(KEEP_SCREEN_ON_KEY, false) - set(value) { - prefs.edit().putBoolean(KEEP_SCREEN_ON_KEY, value).apply() - } - - val screenOrientationObservable = object : ObservableValue(ORIENTATION_AUTO) { - override var value: Int = prefs.getInt(SCREEN_ORIENTATION_KEY, ORIENTATION_AUTO) - set(value) { - prefs.edit().putInt(SCREEN_ORIENTATION_KEY, value).apply() - field = value - notifyObservers() - } - } - - var screenOrientation: Int - get() = screenOrientationObservable.value - set(value) { - screenOrientationObservable.value = value - } - - var disableVirtualKeyboard: Boolean - get() = prefs.getBoolean(DISABLE_VIRTUAL_KEYBOARD_KEY, false) - set(value) { - prefs.edit().putBoolean(DISABLE_VIRTUAL_KEYBOARD_KEY, value).apply() - } - - var blockedInputDeviceIds: Set - get() = prefs.getStringSet(BLOCKED_INPUT_DEVICES_KEY, emptySet()) ?: emptySet() - set(value) { - prefs.edit().putStringSet(BLOCKED_INPUT_DEVICES_KEY, value).apply() - } - - fun isInputDeviceBlocked(deviceIdentifier: String): Boolean { - return blockedInputDeviceIds.contains(deviceIdentifier) - } - - fun setInputDeviceBlocked(deviceIdentifier: String, blocked: Boolean) { - val current = blockedInputDeviceIds.toMutableSet() - if (blocked) { - current.add(deviceIdentifier) - } else { - current.remove(deviceIdentifier) - } - blockedInputDeviceIds = current - } - - var enableVirtualCursor: Boolean - get() = prefs.getBoolean(ENABLE_VIRTUAL_CURSOR_KEY, true) - set(value) { - prefs.edit().putBoolean(ENABLE_VIRTUAL_CURSOR_KEY, value).apply() - } - - /** Stored input-mode choice (`AUTO` by default, i.e. "follow the device"). */ - var inputMode: InputMode - get() = prefs.getString(INPUT_MODE_KEY, null)?.let { saved -> - InputMode.entries.firstOrNull { it.name == saved } - } ?: InputMode.AUTO - set(value) { - prefs.edit().putString(INPUT_MODE_KEY, value.name).apply() - } - - /** [InputMode.AUTO] resolved against the actual device / connected hardware. */ - fun resolveInputMode(isTvDevice: Boolean, physicalMouseConnected: Boolean): InputMode = - when (inputMode) { - InputMode.AUTO -> when { - !isTvDevice -> InputMode.TOUCH - physicalMouseConnected -> InputMode.KEYBOARD_MOUSE - else -> InputMode.TV_REMOTE - } - else -> inputMode - } - - var cursorSizePercent: Int - get() = prefs.getInt(CURSOR_SIZE_PERCENT_KEY, 100) - .coerceIn(CURSOR_SIZE_PERCENT_MIN, CURSOR_SIZE_PERCENT_MAX) - set(value) { - prefs.edit().putInt( - CURSOR_SIZE_PERCENT_KEY, - value.coerceIn(CURSOR_SIZE_PERCENT_MIN, CURSOR_SIZE_PERCENT_MAX) - ).apply() - } - - var cursorStyle: Int - get() = prefs.getInt(CURSOR_STYLE_KEY, 0) - set(value) { - prefs.edit().putInt(CURSOR_STYLE_KEY, value).apply() - } - - var enableHardwareMouseCustomization: Boolean - get() = prefs.getBoolean(ENABLE_HARDWARE_MOUSE_CUSTOMIZATION_KEY, true) - set(value) { - prefs.edit().putBoolean(ENABLE_HARDWARE_MOUSE_CUSTOMIZATION_KEY, value).apply() - } - - var hardwareMouseSizePercent: Int - get() = prefs.getInt(HARDWARE_MOUSE_SIZE_PERCENT_KEY, HARDWARE_MOUSE_SIZE_PERCENT_DEFAULT) - .coerceIn(HARDWARE_MOUSE_SIZE_PERCENT_MIN, HARDWARE_MOUSE_SIZE_PERCENT_MAX) - set(value) { - prefs.edit().putInt( - HARDWARE_MOUSE_SIZE_PERCENT_KEY, - value.coerceIn(HARDWARE_MOUSE_SIZE_PERCENT_MIN, HARDWARE_MOUSE_SIZE_PERCENT_MAX) - ).apply() - } - - var hardwareMouseStyle: Int - get() = prefs.getInt(HARDWARE_MOUSE_STYLE_KEY, 0) - set(value) { - prefs.edit().putInt(HARDWARE_MOUSE_STYLE_KEY, value).apply() - } - - var disableMotionAxesDpadNavigation: Boolean - get() = prefs.getBoolean(DISABLE_MOTION_AXES_DPAD_NAVIGATION_KEY, false) - set(value) { - prefs.edit().putBoolean(DISABLE_MOTION_AXES_DPAD_NAVIGATION_KEY, value).apply() - } - - /** Virtual cursor max speed as a percent of the default (screen-width–based) cap. */ - var cursorMaxSpeedPercent: Int - get() = prefs.getInt(CURSOR_MAX_SPEED_PERCENT_KEY, 100) - .coerceIn(CURSOR_PHYSICS_PERCENT_MIN, CURSOR_PHYSICS_PERCENT_MAX) - set(value) { - prefs.edit().putInt( - CURSOR_MAX_SPEED_PERCENT_KEY, - value.coerceIn(CURSOR_PHYSICS_PERCENT_MIN, CURSOR_PHYSICS_PERCENT_MAX) - ).apply() - } - - /** Virtual cursor acceleration as a percent of the default ramp-up per frame. */ - var cursorAccelerationPercent: Int - get() = prefs.getInt(CURSOR_ACCELERATION_PERCENT_KEY, 100) - .coerceIn(CURSOR_PHYSICS_PERCENT_MIN, CURSOR_PHYSICS_PERCENT_MAX) - set(value) { - prefs.edit().putInt( - CURSOR_ACCELERATION_PERCENT_KEY, - value.coerceIn(CURSOR_PHYSICS_PERCENT_MIN, CURSOR_PHYSICS_PERCENT_MAX) - ).apply() - } - - /** UI scaling percent for Android TV interface (50 = default/100% density, 1 = 25% density, 100 = 125% density). */ - var uiScalePercent: Int - get() = prefs.getInt(UI_SCALE_PERCENT_KEY, UI_SCALE_PERCENT_DEFAULT) - .coerceIn(UI_SCALE_PERCENT_MIN, UI_SCALE_PERCENT_MAX) - set(value) { - prefs.edit().putInt( - UI_SCALE_PERCENT_KEY, - value.coerceIn(UI_SCALE_PERCENT_MIN, UI_SCALE_PERCENT_MAX) - ).apply() - } - - fun getUiScaleDensityMultiplier(): Float { - val p = uiScalePercent.coerceIn(UI_SCALE_PERCENT_MIN, UI_SCALE_PERCENT_MAX) - return if (p <= 50) { - // 1% -> 0.25f (25%), 50% -> 1.00f (100%) - 0.25f + (p - 1).toFloat() * (0.75f / 49f) - } else { - // 50% -> 1.00f (100%), 100% -> 1.25f (125%) - 1.00f + (p - 50).toFloat() * (0.25f / 50f) - } - } - - /** Web page zoom percent for mobile view (100 = default, 25 to 300). */ - var mobileWebPageZoomPercent: Int - get() = prefs.getInt(MOBILE_WEB_PAGE_ZOOM_PERCENT_KEY, prefs.getInt(WEB_PAGE_ZOOM_PERCENT_KEY, WEB_PAGE_ZOOM_PERCENT_DEFAULT)) - .coerceIn(WEB_PAGE_ZOOM_PERCENT_MIN, WEB_PAGE_ZOOM_PERCENT_MAX) - set(value) { - val clamped = value.coerceIn(WEB_PAGE_ZOOM_PERCENT_MIN, WEB_PAGE_ZOOM_PERCENT_MAX) - prefs.edit().putInt(MOBILE_WEB_PAGE_ZOOM_PERCENT_KEY, clamped).apply() - } - - /** Web page zoom percent for desktop view (100 = default, 25 to 300). */ - var desktopWebPageZoomPercent: Int - get() = prefs.getInt(DESKTOP_WEB_PAGE_ZOOM_PERCENT_KEY, prefs.getInt(WEB_PAGE_ZOOM_PERCENT_KEY, WEB_PAGE_ZOOM_PERCENT_DEFAULT)) - .coerceIn(WEB_PAGE_ZOOM_PERCENT_MIN, WEB_PAGE_ZOOM_PERCENT_MAX) - set(value) { - val clamped = value.coerceIn(WEB_PAGE_ZOOM_PERCENT_MIN, WEB_PAGE_ZOOM_PERCENT_MAX) - prefs.edit().putInt(DESKTOP_WEB_PAGE_ZOOM_PERCENT_KEY, clamped).apply() - } - - fun getEffectiveZoom(isDesktop: Boolean): Int { - return if (isDesktop) desktopWebPageZoomPercent else mobileWebPageZoomPercent - } - - fun setEffectiveZoom(isDesktop: Boolean, percent: Int) { - val clamped = percent.coerceIn(WEB_PAGE_ZOOM_PERCENT_MIN, WEB_PAGE_ZOOM_PERCENT_MAX) - if (isDesktop) { - desktopWebPageZoomPercent = clamped - } else { - mobileWebPageZoomPercent = clamped - } - } - - fun isDesktopUa(ua: String?): Boolean { - if (ua == null) return false - return ua.contains("Windows") || ua.contains("X11; Linux x86_64") || ua.contains("Macintosh") - } - - fun isDesktopMode(customUa: String? = userAgentString.value): Boolean { - return desktopMode.value || isDesktopUa(customUa) - } - - /** Current effective web page zoom percent based on active desktop/mobile mode (100 = default, 25 to 300). */ - var webPageZoomPercent: Int - get() = getEffectiveZoom(isDesktopMode()) - set(value) { - setEffectiveZoom(isDesktopMode(), value) - } - - /** Target language code for "Translate this page" ("" = device language). */ - var translateTargetLanguage: String - get() = prefs.getString(TRANSLATE_TARGET_LANGUAGE_KEY, "") ?: "" - set(value) { - prefs.edit().putString(TRANSLATE_TARGET_LANGUAGE_KEY, value).apply() - } - - /** - * Chrome-like Safe Browsing checks for navigations and downloads. Enabled by default; it can - * be turned off for debugging or on very constrained devices where the extra lookups hurt. - */ - var safeBrowsingEnabled: Boolean - get() = prefs.getBoolean(SAFE_BROWSING_KEY, true) - set(value) { - prefs.edit().putBoolean(SAFE_BROWSING_KEY, value).apply() - } - - /** Whether to record visited URLs and searches into local history. */ - var saveHistory: Boolean - get() = prefs.getBoolean(SAVE_HISTORY_KEY, true) - set(value) { - prefs.edit().putBoolean(SAVE_HISTORY_KEY, value).apply() - } - - var theme = object : ObservableValue(Theme.SYSTEM) { - override var value: Theme = - try { - val index = prefs.getInt(THEME_KEY, 0) - if (index in Theme.values().indices) Theme.values()[index] else Theme.SYSTEM - } catch (e: Exception) { - Theme.SYSTEM - } - set(value) { - prefs.edit().putInt(THEME_KEY, value.ordinal).apply() - field = value - notifyObservers() - } - } - - var homePageMode: HomePageMode - get() = prefs.getInt(HOME_PAGE_MODE, 0) - .let { - //ignore value if search engine as home page is set - if (prefs.getBoolean(SEARCH_ENGINE_AS_HOME_PAGE_KEY, false)) { - prefs.edit().remove(SEARCH_ENGINE_AS_HOME_PAGE_KEY).apply() - HomePageMode.SEARCH_ENGINE.ordinal - } else it - } - .let { if (it < 0 || it >= HomePageMode.values().size) 0 else it } - .let { HomePageMode.values()[it] } - set(value) { - prefs.edit().putInt(HOME_PAGE_MODE, value.ordinal).apply() - } - - var homePageLinksMode: HomePageLinksMode - get() = prefs.getInt(HOME_PAGE_SUGGESTIONS_MODE, 0) - .let { if (it < 0 || it >= HomePageLinksMode.values().size) 0 else it } - .let { HomePageLinksMode.values()[it] } - set(value) { - prefs.edit().putInt(HOME_PAGE_SUGGESTIONS_MODE, value.ordinal).apply() - } - - var homePage: String - get() = prefs.getString(HOME_PAGE_KEY, HOME_URL_ALIAS)!! - set(value) { - prefs.edit().putString(HOME_PAGE_KEY, value).apply() - } - - var searchEngineURL = ObservableStringPreference(SearchEnginesURLs[0], SEARCH_ENGINE_URL_PREF_KEY) - - var webEngine: String - get() = ENGINE_WEB_VIEW - set(value) { - prefs.edit().putString(WEB_ENGINE, value).apply() - } - - var allowAutoplayMedia: Boolean - get() = prefs.getBoolean(ALLOW_AUTOPLAY_MEDIA, false) - set(value) { - prefs.edit().putBoolean(ALLOW_AUTOPLAY_MEDIA, value).apply() - } - - var webEngineDebug: Boolean - get() = prefs.getBoolean(WEB_ENGINE_DEBUG_KEY, false) - set(value) { - prefs.edit().putBoolean(WEB_ENGINE_DEBUG_KEY, value).apply() - } - - /*var homePageVersionExtracted: Int - get() = prefs.getInt(HOME_PAGE_VERSION_EXTRACTED, 0) - set(value) { - prefs.edit().putInt(HOME_PAGE_VERSION_EXTRACTED, value).apply() - }*/ - - var initialBookmarksSuggestionsLoaded: Boolean - get() = prefs.getBoolean(INITIAL_BOOKMARKS_SUGGESTIONS_LOADED, false) - set(value) { - prefs.edit().putBoolean(INITIAL_BOOKMARKS_SUGGESTIONS_LOADED, value).apply() - } - - var userAgentString = ObservableOptStringPreference(null, USER_AGENT_PREF_KEY) - var desktopMode = ObservableBooleanPreference(false, DESKTOP_MODE_KEY) - var showTopTabBar = ObservableBooleanPreference(false, SHOW_TOP_TAB_BAR_KEY) - var keepAliveInBackground = ObservableBooleanPreference(true, KEEP_ALIVE_IN_BACKGROUND_KEY) - - /** - * Cap used when the user never set one. Lowered once at startup by [applyMemoryAwareDefaults]: - * a 1 GB Android TV box cannot keep six renderers alive, since every extra live WebView is a - * full native process plus a painted buffer. - */ - @Volatile - var maxLiveTabsDefault: Int = DEFAULT_MAX_LIVE_TABS - - var maxLiveTabs: Int - get() = prefs.getInt(MAX_LIVE_TABS_KEY, maxLiveTabsDefault).coerceIn(2, 20) - set(value) { - prefs.edit().putInt(MAX_LIVE_TABS_KEY, value.coerceIn(2, 20)).apply() - } - - /** - * Device-aware defaults, called from `BrowserApp.onCreate` before the first tab is restored. - * Only lowers limits on small-memory hardware; it never raises above the shipped defaults. - */ - fun applyMemoryAwareDefaults(context: android.content.Context) { - try { - val am = context.getSystemService(android.content.Context.ACTIVITY_SERVICE) - as? android.app.ActivityManager ?: return - val info = android.app.ActivityManager.MemoryInfo() - am.getMemoryInfo(info) - val totalMb = if (info.totalMem > 0) info.totalMem / (1024L * 1024L) else 0L - maxLiveTabsDefault = when { - // isLowRamDevice() is a method on ActivityManager (API 19), not on MemoryInfo. - am.isLowRamDevice || totalMb in 1..1536 -> 3 - totalMb in 1537..2816 -> 4 - totalMb > 2816 -> DEFAULT_MAX_LIVE_TABS - else -> DEFAULT_MAX_LIVE_TABS - } - } catch (e: Throwable) { - // Keep the shipped default when the memory query is unavailable. - } - } - - var adBlockEnabled: Boolean = prefs.getBoolean(ADBLOCK_ENABLED_PREF_KEY, true) - set(value) { - field = value - prefs.edit().putBoolean(ADBLOCK_ENABLED_PREF_KEY, field).apply() - } - - var adBlockListURL = ObservableStringPreference(DEFAULT_ADBLOCK_LIST_URL, ADBLOCK_LIST_URL_KEY) - - var adBlockListLastUpdate: Long - get() = prefs.getLong(ADBLOCK_LAST_UPDATE_LIST_KEY, 0) - set(value) { - prefs.edit().putLong(ADBLOCK_LAST_UPDATE_LIST_KEY, value).apply() - } - - var appWebExtensionVersion: Int - get() = prefs.getInt(APP_WEB_EXTENSION_VERSION_KEY, 0) - set(value) { - prefs.edit().putInt(APP_WEB_EXTENSION_VERSION_KEY, value).apply() - } - - //0 - not shown, any other value - app version code where notification already shown (to show only once after update) - var notificationAboutEngineChangeShown: Int - get() = prefs.getInt(NOTIFICATION_ABOUT_ENGINE_CHANGE_SHOWN_KEY, 0) - set(value) { - prefs.edit().putInt(NOTIFICATION_ABOUT_ENGINE_CHANGE_SHOWN_KEY, value).apply() - } - - var autoCheckUpdates: Boolean - get() = prefs.getBoolean(AUTO_CHECK_UPDATES_KEY, Utils.isInstalledByAPK(AppContext.get())) - set(value) { - prefs.edit().putBoolean(AUTO_CHECK_UPDATES_KEY, value).apply() - } - - var updateChannel: String - get() = prefs.getString(UPDATE_CHANNEL_KEY, "release")!! - set(value) { - prefs.edit().putString(UPDATE_CHANNEL_KEY, value).apply() - } - - var appVersionCodeMark: Int - get() = prefs.getInt(APP_VERSION_CODE_MARK_KEY, 0) - set(value) { - prefs.edit().putInt(APP_VERSION_CODE_MARK_KEY, value).apply() - } - - fun isWebEngineGecko(): Boolean { - return false - } - - fun isWebEngineNotSet(): Boolean { - return !prefs.contains(WEB_ENGINE) - } - - fun guessSearchEngineName(): String { - val url = searchEngineURL.value - val index = SearchEnginesURLs.indexOf(url) - if (index != -1 && index < SearchEnginesNames.size) { - return SearchEnginesNames[index] - } - val lower = url.lowercase() - return when { - lower.contains("google.") -> "google" - lower.contains("bing.") -> "bing" - lower.contains("duckduckgo.") -> "ddg" - lower.contains("yahoo.") -> "yahoo" - lower.contains("yandex.") -> "yandex" - lower.contains("startpage.") -> "startpage" - else -> SearchEnginesNames[SearchEnginesNames.size - 1] - } - } - - inner class ObservableStringPreference(default: String, private val prefsKey: String) : ObservableValue(default) { - override var value: String = prefs.getString(prefsKey, default)!! - set(value) { - prefs.edit().putString(prefsKey, value).apply() - field = value - notifyObservers() - } - } - - inner class ObservableOptStringPreference(default: String?, private val prefsKey: String) : ObservableValue(default) { - override var value: String? = prefs.getString(prefsKey, default) - set(value) { - if (value == null) prefs.edit().remove(prefsKey).apply() - else prefs.edit().putString(prefsKey, value).apply() - field = value - notifyObservers() - } - } - - inner class ObservableBooleanPreference(default: Boolean, private val prefsKey: String) : ObservableValue(default) { - override var value: Boolean = prefs.getBoolean(prefsKey, default) - set(value) { - prefs.edit().putBoolean(prefsKey, value).apply() - field = value - notifyObservers() - } - } -} diff --git a/app/common/src/main/java/com/bansify/internet/model/Download.kt b/app/common/src/main/java/com/bansify/internet/model/Download.kt deleted file mode 100644 index 618c5022..00000000 --- a/app/common/src/main/java/com/bansify/internet/model/Download.kt +++ /dev/null @@ -1,74 +0,0 @@ -package com.bansify.internet.model - -import androidx.room.* -import java.io.InputStream - -/** - * Created by PDT on 23.01.2017. - */ - -@Entity(tableName = "downloads", indices = arrayOf(Index(value = ["time"], name = "downloads_time_idx"), - Index(value = ["filename"], name = "downloads_filename_idx"))) -class Download() { - @PrimaryKey(autoGenerate = true) - var id: Long = 0 - var time: Long = 0 - var filename: String = "" - var filepath: String = "" - var url: String = "" - - @Volatile - var size: Long = 0 - @Volatile @ColumnInfo(name = "bytes_received") - var bytesReceived: Long = 0 - @Ignore - var operationAfterDownload = OperationAfterDownload.NOP - - //non-db fields - @Ignore - @Volatile - var cancelled: Boolean = false - @Ignore - var isDateHeader = false//user for displaying date headers inside list view - @Ignore - var mimeType: String? = null - @Ignore - var referer: String? = null - @Ignore - var userAgentString: String? = null - @Ignore - var base64BlobData: String? = null - @Ignore - var stream: InputStream? = null - - enum class OperationAfterDownload { - NOP, INSTALL - } - - constructor(url: String, filename: String, filepath: String?, operationAfterDownload: OperationAfterDownload, - mimeType: String?, referer: String?, userAgentString: String?, base64BlobData: String?, - stream: InputStream?, size: Long = 0L) : this() { - this.url = url - this.filename = filename - this.filepath = filepath ?: "" - this.operationAfterDownload = operationAfterDownload - this.mimeType = mimeType - this.referer = referer - this.userAgentString = userAgentString - this.base64BlobData = base64BlobData - this.stream = stream - this.size = size - } - - companion object { - val BROKEN_MARK: Long = -2 - val CANCELLED_MARK: Long = -3 - - fun createDateHeaderInfo(time: Long): Download { - val download = Download() - download.time = time - download.isDateHeader = true - return download - } - } -} diff --git a/app/common/src/main/java/com/bansify/internet/model/FavoriteItem.kt b/app/common/src/main/java/com/bansify/internet/model/FavoriteItem.kt deleted file mode 100644 index db804ba6..00000000 --- a/app/common/src/main/java/com/bansify/internet/model/FavoriteItem.kt +++ /dev/null @@ -1,31 +0,0 @@ -package com.bansify.internet.model - -import androidx.room.ColumnInfo -import androidx.room.Entity -import androidx.room.Index -import androidx.room.PrimaryKey -import java.util.* - -/** - * Created by PDT on 09.09.2016. - */ -@Entity(tableName = "favorites", indices = arrayOf( - Index(value = ["PARENT"], name = "favorites_parent_idx"), - Index(value = ["HOME_PAGE_BOOKMARK"], name = "favorites_home_page_bookmark_idx") - )) -class FavoriteItem { - @PrimaryKey(autoGenerate = true) - @ColumnInfo(name = "ID") var id: Long = 0 - @ColumnInfo(name = "TITLE") var title: String? = null - @ColumnInfo(name = "URL") var url: String? = null - @ColumnInfo(name = "PARENT") var parent: Long? = 0 - var favicon: String? = null - @ColumnInfo(name = "HOME_PAGE_BOOKMARK") var homePageBookmark: Boolean = false - @ColumnInfo(name = "I_ORDER") var order: Int = 0//used currently only for home page bookmarks because they can have blank cells in the grid - @ColumnInfo(name = "DEST_URL") var destUrl: String? = null//used for initial recommendations for home page bookmarks to store referral url - @ColumnInfo(name = "DESCRIPTION") var description: String? = null//used for initial recommendations for home page bookmarks if they have description - @ColumnInfo(name = "VALID_UNTIL") var validUntil: Date? = null//used for initial recommendations for home page bookmarks if they have DEST_URL - @ColumnInfo(name = "USEFUL") var useful: Boolean = false//used for initial recommendations for home page bookmarks if they have VALID_UNTIL - val isFolder: Boolean - get() = url == null -} diff --git a/app/common/src/main/java/com/bansify/internet/model/HistoryItem.kt b/app/common/src/main/java/com/bansify/internet/model/HistoryItem.kt deleted file mode 100644 index 9d70371f..00000000 --- a/app/common/src/main/java/com/bansify/internet/model/HistoryItem.kt +++ /dev/null @@ -1,40 +0,0 @@ -package com.bansify.internet.model - -import androidx.room.Entity -import androidx.room.Ignore -import androidx.room.Index -import androidx.room.PrimaryKey - -/** - * Created by fedex on 28.12.16. - */ - -@Entity(tableName = "history", indices = arrayOf(Index(value = ["time"], name = "history_time_idx"), - Index(value = ["title"], name = "history_title_idx"), Index(value = ["url"], name = "history_url_idx"))) -class HistoryItem { - @PrimaryKey(autoGenerate = true) - var id: Long = 0 - var time: Long = 0 - var title: String = "" - var url: String = "" - var favicon: String? = null - @Deprecated("Not used anymore") - var incognito: Boolean? = null - - @Ignore - var isDateHeader = false//used for displaying date headers inside list view - @Ignore - var selected = false - @Ignore - var saved = false - - companion object { - - fun createDateHeaderInfo(time: Long): HistoryItem { - val hi = HistoryItem() - hi.time = time - hi.isDateHeader = true - return hi - } - } -} diff --git a/app/common/src/main/java/com/bansify/internet/model/HomePageLink.kt b/app/common/src/main/java/com/bansify/internet/model/HomePageLink.kt deleted file mode 100644 index 1898ad67..00000000 --- a/app/common/src/main/java/com/bansify/internet/model/HomePageLink.kt +++ /dev/null @@ -1,40 +0,0 @@ -package com.bansify.internet.model - -import org.json.JSONObject -import java.text.SimpleDateFormat -import java.util.* - -class HomePageLink( - val title: String, - val url: String, - val favicon: String? = null, - val favoriteId: Long? = null, - val order: Int? = null, - val dest_url: String? = null, - val description: String? = null, - var validUntil: Date? = null -) { - fun toJsonObj(): JSONObject { - val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.US) - return JSONObject().apply { - put("title", title) - put("url", url) - put("favicon", favicon) - put("favoriteId", favoriteId) - put("order", order) - put("dest_url", dest_url) - put("description", description) - put("validUntil", dateFormat.format(validUntil?: Date())) - } - } - - companion object { - fun fromHistoryItem(item: HistoryItem): HomePageLink { - return HomePageLink(item.title, item.url) - } - - fun fromBookmarkItem(item: FavoriteItem): HomePageLink { - return HomePageLink(item.title?: "", item.url?: "", item.favicon, item.id, item.order, item.destUrl, item.description, item.validUntil) - } - } -} \ No newline at end of file diff --git a/app/common/src/main/java/com/bansify/internet/model/HostConfig.kt b/app/common/src/main/java/com/bansify/internet/model/HostConfig.kt deleted file mode 100644 index b4cfa99c..00000000 --- a/app/common/src/main/java/com/bansify/internet/model/HostConfig.kt +++ /dev/null @@ -1,30 +0,0 @@ -package com.bansify.internet.model - -import androidx.room.ColumnInfo -import androidx.room.Entity -import androidx.room.Index -import androidx.room.PrimaryKey - - -@Entity(tableName = "hosts", indices = arrayOf( - Index(value = ["host_name"], name = "hosts_name_idx", unique = true) -)) -class HostConfig( - @ColumnInfo(name = "host_name") - val hostName: String -) { - @PrimaryKey(autoGenerate = true) - var id: Long = 0 - @ColumnInfo(name = "popup_block_level") - var popupBlockLevel: Int? = null - var favicon: String? = null - - companion object { - const val POPUP_BLOCK_NONE = 0 - const val POPUP_BLOCK_DIALOGS = 1 - const val POPUP_BLOCK_NEW_AUTO_OPENED_TABS = 2 - const val POPUP_BLOCK_NEW_TABS_EVEN_BY_USER_GESTURE = 3 - - const val DEFAULT_BLOCK_POPUPS_VALUE = POPUP_BLOCK_NEW_AUTO_OPENED_TABS - } -} \ No newline at end of file diff --git a/app/common/src/main/java/com/bansify/internet/model/WebTabState.kt b/app/common/src/main/java/com/bansify/internet/model/WebTabState.kt deleted file mode 100644 index 7325acc5..00000000 --- a/app/common/src/main/java/com/bansify/internet/model/WebTabState.kt +++ /dev/null @@ -1,284 +0,0 @@ -package com.bansify.internet.model - -import android.content.Context -import android.graphics.Bitmap -import android.graphics.BitmapFactory -import android.os.Bundle -import androidx.room.ColumnInfo -import androidx.room.Entity -import androidx.room.Ignore -import androidx.room.PrimaryKey -import com.bansify.internet.AppContext -import com.bansify.internet.utils.Utils -import com.bansify.internet.webengine.WebEngineFactory -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.withContext -import org.json.JSONException -import org.json.JSONObject -import java.io.File -import java.io.FileOutputStream -import java.nio.charset.Charset - - -/** - * Created by PDT on 24.08.2016. - * - * Class to store state of tab with webView - */ -@Entity(tableName = "tabs") -data class WebTabState(@PrimaryKey(autoGenerate = true) - var id: Long = 0, - var url: String = "", - var title: String = "", - var selected: Boolean = false, - var thumbnailHash: String? = null, - var faviconHash: String? = null, - var incognito: Boolean = false, - var position: Int = 0, - @Deprecated("This field is not used anymore") - @ColumnInfo(name = "wv_state", typeAffinity = ColumnInfo.BLOB) - var wvState: ByteArray? = null, - @ColumnInfo(name = "wv_state_file") - var wvStateFileName: String? = null, - var adblock: Boolean? = null, - var scale: Float? = null, - /** - * Per-tab "Desktop site" override. `null` means "follow the global default" - * (Config.desktopMode), which keeps existing installs behaving as before until - * the user actually toggles the menu entry for one tab. - */ - @ColumnInfo(name = "desktop_mode") - var desktopMode: Boolean? = null) { - companion object { - val TAG: String = WebTabState::class.java.simpleName - - const val TAB_THUMBNAILS_DIR = "tabthumbs" - const val TAB_WVSTATES_DIR = "wvstates" - const val GECKO_SESSION_STATE_HASH_PREFIX = "gecko:" - } - - @Ignore - var thumbnail: Bitmap? = null - @Ignore - var savedState: Any? = null - @Ignore - var lastActiveTimestamp: Long = System.currentTimeMillis() - @Ignore - var isPageLoading: Boolean = false - @delegate:Ignore - val webEngine by lazy { WebEngineFactory.createWebEngine(this) } - @Ignore - var lastLoadingUrl: String? = null //this is last url appeared in WebViewClient.shouldOverrideUrlLoading callback - @Ignore - var lastUrlBeforeHome: String? = null - /** Title of the page currently covered by the native home screen (in-memory only). */ - @Ignore - var lastTitleBeforeHome: String? = null - @Ignore - var blockedAds = 0 - @Ignore - var blockedPopups = 0 - @Ignore - var cachedHostConfig: HostConfig? = null - - constructor(context: Context, json: JSONObject) : this() { - try { - url = json.getString("url") - title = json.getString("title") - selected = json.getBoolean("selected") - if (json.has("thumbnail")) { - thumbnailHash = json.getString("thumbnail") - } - if (json.has("wv_state")) { - val state = Utils.convertJsonToBundle(json.getJSONObject("wv_state")) - if (state != null && !state.isEmpty) { - savedState = state - } - } - } catch (e: JSONException) { - e.printStackTrace() - } - - } - - private suspend fun saveThumbnail(context: Context) { - val originalThumb = this.thumbnail ?: return - val thumbnailHash = this.thumbnailHash - val url = url - withContext(Dispatchers.IO) { - synchronized(this@WebTabState) { - val tabsThumbsDir = File(context.cacheDir.absolutePath + File.separator + TAB_THUMBNAILS_DIR) - if (tabsThumbsDir.exists() || tabsThumbsDir.mkdir()) { - try { - val hash = Utils.MD5_Hash(url.toByteArray(Charset.defaultCharset())) - if (hash != null && hash != thumbnailHash) { - if (thumbnailHash != null) { - removeThumbnailFile() - } - val file = File(getThumbnailPath(hash)) - var fos: FileOutputStream? = null - try { - fos = FileOutputStream(file) - // TV Optimization: Scale down thumbnail to max 360px width to save 85% RAM & storage - val maxDimension = 360 - val scaledBitmap = if (originalThumb.width > maxDimension || originalThumb.height > maxDimension) { - val scale = maxDimension.toFloat() / Math.max(originalThumb.width, originalThumb.height) - val targetW = (originalThumb.width * scale).toInt().coerceAtLeast(1) - val targetH = (originalThumb.height * scale).toInt().coerceAtLeast(1) - Bitmap.createScaledBitmap(originalThumb, targetW, targetH, true) - } else { - originalThumb - } - scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 75, fos) - if (scaledBitmap != originalThumb) { - scaledBitmap.recycle() - } - } catch (e: Exception) { - e.printStackTrace() - } finally { - fos?.close() - } - - this@WebTabState.thumbnailHash = hash - } - } catch (e: Exception) { - e.printStackTrace() - } - } - } - } - } - - private fun getThumbnailPath(hash: String) = - AppContext.get().cacheDir.absolutePath + File.separator + TAB_THUMBNAILS_DIR + File.separator + hash + ".png" - - private fun getWVStatePath(hash: String): String { - return if (hash.startsWith(GECKO_SESSION_STATE_HASH_PREFIX)) { - AppContext.get().filesDir.absolutePath + File.separator + TAB_WVSTATES_DIR + File.separator + hash.substring( - GECKO_SESSION_STATE_HASH_PREFIX.length) - } else { - AppContext.get().filesDir.absolutePath + File.separator + TAB_WVSTATES_DIR + File.separator + hash - } - } - - fun removeFiles() { - if (thumbnailHash != null) { - removeThumbnailFile() - } - wvStateFileName?.apply { - File(getWVStatePath(this)).delete() - wvStateFileName = null - } - } - - private fun removeThumbnailFile() { - if (thumbnailHash == null) return - val thumbnailFile = File(getThumbnailPath(thumbnailHash!!)) - thumbnailFile.delete() - thumbnailHash = null - } - - fun restoreWebView(): Boolean { - var state = savedState - val stateFileName = wvStateFileName - if (state != null) { - webEngine.restoreState(state) - return true - } else if (stateFileName != null) { - if (stateFileName.startsWith(GECKO_SESSION_STATE_HASH_PREFIX)) { - return false - } - try { - val stateBytes = File(getWVStatePath(stateFileName)).readBytes() - state = webEngine.stateFromBytes(stateBytes) - if (state == null) return false - this.savedState = state - webEngine.restoreState(state) - return true - } catch (e: Exception) { - e.printStackTrace() - return false - } - } - return false - } - - fun saveWebViewStateToFile() { - val state = savedState - var stateFileName = wvStateFileName - if (stateFileName != null && stateFileName.startsWith(GECKO_SESSION_STATE_HASH_PREFIX)) { - File(getWVStatePath(stateFileName)).delete() - stateFileName = null - } - if (state == null) return - val stateBytes = when (state) { - is Bundle -> { - Utils.bundleToBytes(state) ?: return - } - else -> { - state.toString().toByteArray(Charsets.UTF_8) - } - } - if (stateFileName == null) { - stateFileName = Utils.MD5_Hash(stateBytes) ?: return - } - try { - val statesDir = File(AppContext.get().filesDir.absolutePath + File.separator + TAB_WVSTATES_DIR) - if (statesDir.exists() || statesDir.mkdir()) { - File(getWVStatePath(stateFileName)).writeBytes(stateBytes) - wvStateFileName = stateFileName - } - } catch (e: Exception) { - e.printStackTrace() - } - } - - fun trimMemory() { - if (savedState == null) { - try { - savedState = webEngine.saveState() - } catch (e: Throwable) { - // ignore - } - } - webEngine.trimMemory() - thumbnail?.recycle() - thumbnail = null - } - - fun onPause() { - webEngine.let { - savedState = it.saveState() - } - } - - suspend fun updateThumbnail(context: Context, thumbnail: Bitmap) { - this.thumbnail = thumbnail - val url = url - var hash = Utils.MD5_Hash(url.toByteArray(Charset.defaultCharset())) - if (hash != null) { - hash += hashCode()//to make thumbnails from different tabs unique even with same url - if (hash != thumbnailHash) { - saveThumbnail(context) - } - } - } - - fun loadThumbnail(): Bitmap? { - val hash = thumbnailHash ?: return null - val thumbnailFile = File(getThumbnailPath(hash)) - if (thumbnailFile.exists()) { - thumbnail = BitmapFactory.decodeFile( - thumbnailFile.absolutePath, - BitmapFactory.Options().apply { - inPreferredConfig = Bitmap.Config.RGB_565 - inMutable = false - } - ) - return thumbnail - } else { - thumbnailHash = null - } - return null - } -} diff --git a/app/common/src/main/java/com/bansify/internet/singleton/FaviconsPool.kt b/app/common/src/main/java/com/bansify/internet/singleton/FaviconsPool.kt deleted file mode 100644 index eae1ef54..00000000 --- a/app/common/src/main/java/com/bansify/internet/singleton/FaviconsPool.kt +++ /dev/null @@ -1,279 +0,0 @@ -package com.bansify.internet.singleton - -import android.graphics.Bitmap -import android.graphics.BitmapFactory -import android.util.Log -import android.util.LruCache -import android.webkit.WebChromeClient -import android.webkit.WebView -import com.bansify.internet.AppContext -import com.bansify.internet.model.HostConfig -import com.bansify.internet.utils.FaviconExtractor -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext -import java.io.File -import java.net.URL - -object FaviconsPool { - const val FAVICONS_DIR = "favicons" - const val FAVICON_PREFERRED_SIDE_SIZE = 120 - private val TAG: String = FaviconsPool::class.java.simpleName - - val faviconExtractor = FaviconExtractor() - var databaseDelegate: DatabaseDelegate = object : DatabaseDelegate {} - - interface DatabaseDelegate { - fun findByHostName(host: String): HostConfig? = null - suspend fun update(hostConfig: HostConfig) {} - suspend fun insert(newHostConfig: HostConfig) {} - } - - private val cache: LruCache = object : LruCache(2 * 1024 * 1024) { - override fun sizeOf(key: String, value: Bitmap): Int { - return value.byteCount - } - } - - // In-memory LRU cache mapping host to favicon filename (or empty string if known to not exist) - private val hostFileCache: LruCache = LruCache(500) - - fun getFaviconFile(host: String): File? { - val cachedFileName = hostFileCache.get(host) - val favIconsDir = File(favIconsDir()) - - if (cachedFileName != null) { - if (cachedFileName.isEmpty()) { - return null - } - val file = File(favIconsDir, cachedFileName) - if (file.exists() && file.length() > 0) { - return file - } - } - - try { - val hostConfig = databaseDelegate.findByHostName(host) - val faviconFileName = hostConfig?.favicon ?: (host.hashCode().toString() + ".png") - val faviconFile = File(favIconsDir, faviconFileName) - if (faviconFile.exists() && faviconFile.length() > 0) { - hostFileCache.put(host, faviconFileName) - return faviconFile - } else { - hostFileCache.put(host, "") - } - } catch (e: Exception) { - Log.w(TAG, "Failed finding favicon file for $host: ${e.message}") - } - - // Trigger background fetch if not found - CoroutineScope(Dispatchers.IO).launch { - try { - get(host) - } catch (_: Exception) {} - } - return null - } - - fun getFaviconFileInputStream(host: String): java.io.InputStream? { - val file = getFaviconFile(host) ?: return null - return try { - java.io.FileInputStream(file) - } catch (e: Exception) { - Log.w(TAG, "Failed opening favicon stream for $host: ${e.message}") - null - } - } - - fun getFromMemoryOrDisk(host: String): Bitmap? { - val cached = cache.get(host) - if (cached != null) return cached - try { - val faviconFile = getFaviconFile(host) - if (faviconFile != null && faviconFile.exists() && faviconFile.length() > 0) { - val bitmap = BitmapFactory.decodeFile(faviconFile.absolutePath) - if (bitmap != null) { - cache.put(host, bitmap) - return bitmap - } - } - } catch (e: Exception) { - Log.w(TAG, "Fast favicon disk read failed for $host: ${e.message}") - } - return null - } - - suspend fun get(urlOrHost: String): Bitmap? { - Log.d(TAG, "get: $urlOrHost") - if (!urlOrHost.startsWith("http://", true) && !urlOrHost.startsWith("https://", true)) { - //host passed? - if (urlOrHost.contains("://")) { - //not http or https - return null - } - //try https first - val httpsResult = get("https://$urlOrHost") - if (httpsResult != null) { - return httpsResult - } - return get("http://$urlOrHost") - } - try { - val urlObj = URL(urlOrHost) - val host = urlObj.host - if (host != null) { - val hostBitmap = cache.get(host) - if (hostBitmap != null) { - return hostBitmap - } - val hostConfig = databaseDelegate.findByHostName(host) - if (hostConfig != null) { - val faviconFileName = hostConfig.favicon - if (faviconFileName != null) { - Log.d(TAG, "get: favicon found in db for $host") - val bitmap = withContext(Dispatchers.IO) { - val favIconsDir = - File(favIconsDir()) - if (!favIconsDir.exists() && !favIconsDir.mkdir()) return@withContext null - val faviconFile = File(favIconsDir, faviconFileName) - if (faviconFile.exists()) { - BitmapFactory.decodeFile(faviconFile.absolutePath) - } else { - null - } - } - if (bitmap != null) { - Log.d(TAG, "get: favicon loaded from file for $host") - cache.put(host, bitmap) - return bitmap - } - } - } else { - Log.d(TAG, "get: favicon not found in db for $host") - } - - val favicons = try { - withContext(Dispatchers.IO) { faviconExtractor.extractFavIconsFromURL(urlObj) } - } catch (e: Exception) { - e.printStackTrace() - ArrayList() - } - Log.d(TAG, "get: favicons found: ${favicons.size}") - while (favicons.isNotEmpty()) { - val icon = chooseNearestSizeIcon(favicons, FAVICON_PREFERRED_SIDE_SIZE, FAVICON_PREFERRED_SIDE_SIZE)!! - val bitmap = try { - downloadIcon(icon) - } catch (e: Exception) { - e.printStackTrace() - null - } - if (bitmap != null) { - Log.d(TAG, "get: favicon downloaded for $host") - cache.put(host, bitmap) - saveFavicon(host, bitmap, hostConfig) - return bitmap - } else { - Log.d(TAG, "get: favicon download failed for ${icon.src}") - } - favicons.remove(icon) - } - //try to get favicon from webview - withContext(Dispatchers.Main) { - WebView(AppContext.get()).apply { - webChromeClient = object : WebChromeClient() { - override fun onReceivedIcon(view: WebView?, icon: Bitmap?) { - super.onReceivedIcon(view, icon) - if (icon != null) { - Log.d(TAG, "get: favicon received from webview for $host") - cache.put(host, icon) - CoroutineScope(Dispatchers.IO).launch { - saveFavicon(host, icon, hostConfig) - } - } - } - } - loadUrl(urlOrHost) - } - } - } - } catch (e: Exception) { - e.printStackTrace() - } - return null - } - - fun clear() { - cache.evictAll() - hostFileCache.evictAll() - } - - fun favIconsDir(): String { - return AppContext.get().cacheDir.absolutePath + File.separator + FAVICONS_DIR - } - - private suspend fun saveFavicon(host: String, bitmap: Bitmap, hostConfig: HostConfig?) = withContext(Dispatchers.IO) { - val favIconsDir = File(favIconsDir()) - if (!favIconsDir.exists() && !favIconsDir.mkdir()) return@withContext - val faviconFileName = host.hashCode().toString() + ".png" - val faviconFile = File(favIconsDir, faviconFileName) - if (faviconFile.exists()) { - faviconFile.delete() - } - faviconFile.createNewFile() - faviconFile.outputStream().use { - bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) - } - hostFileCache.put(host, faviconFileName) - if (hostConfig != null) { - hostConfig.favicon = faviconFileName - databaseDelegate.update(hostConfig) - } else { - val newHostConfig = HostConfig(host) - newHostConfig.favicon = faviconFileName - databaseDelegate.insert(newHostConfig) - } - } - - private suspend fun downloadIcon(iconInfo: FaviconExtractor.IconInfo): Bitmap? = withContext(Dispatchers.IO) { - if (iconInfo.type?.contains("svg", ignoreCase = true) == true || iconInfo.src.endsWith(".svg", ignoreCase = true)) { - return@withContext null - } - try { - val url = URL(iconInfo.src) - val connection = url.openConnection() - connection.connectTimeout = 4000 - connection.readTimeout = 4000 - connection.connect() - val bytes = connection.getInputStream().use { it.readBytes() } - if (bytes.isEmpty()) return@withContext null - val options = BitmapFactory.Options().apply { - inJustDecodeBounds = true - } - BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options) - val width = options.outWidth - val height = options.outHeight - if (width <= 0 || height <= 0) return@withContext null - val scale = Math.max(1, Math.max(width / 512, height / 512)) - val decodeOptions = BitmapFactory.Options().apply { - inSampleSize = scale - } - return@withContext BitmapFactory.decodeByteArray(bytes, 0, bytes.size, decodeOptions) - } catch (e: Throwable) { - return@withContext null - } - } - - private fun chooseNearestSizeIcon(icons: List, w: Int, h: Int): FaviconExtractor.IconInfo? { - var nearestIcon: FaviconExtractor.IconInfo? = null - var nearestDiff = Int.MAX_VALUE - for (icon in icons) { - val diff = Math.abs(icon.width - w) + Math.abs(icon.height - h) - if (diff < nearestDiff) { - nearestDiff = diff - nearestIcon = icon - } - } - return nearestIcon - } -} \ No newline at end of file diff --git a/app/common/src/main/java/com/bansify/internet/utils/BackNavigationEventsAdapter.kt b/app/common/src/main/java/com/bansify/internet/utils/BackNavigationEventsAdapter.kt deleted file mode 100644 index fb47c840..00000000 --- a/app/common/src/main/java/com/bansify/internet/utils/BackNavigationEventsAdapter.kt +++ /dev/null @@ -1,316 +0,0 @@ -package com.bansify.internet.utils - -import android.os.SystemClock -import android.util.Log -import android.view.InputDevice -import android.view.KeyEvent -import android.view.MotionEvent -import kotlin.math.max - -/** - * Detects "back navigation" intent from multiple input channels: - * - [dispatchSystemBackNavigationEvent] (system back callback) - * - [dispatchKeyEvent] (framework key events) - * - [dispatchGenericMotionEvent] (controller button state as motion) - * - * This adapter does **not** emit/forward [KeyEvent]s. Instead it invokes [onEmulatedBackEvent] - * when it decides a "back navigation" should happen. - * - * Duplicate delivery is handled via a small cross-channel suppression window: if one channel - * recently generated BACK, other channels are ignored for a short time. - */ -class BackNavigationEventsAdapter( - /** - * Callback invoked when a back navigation intent is detected. - * - * By default, the callback is invoked only after a BACK key press and key release are - * both detected. - * - * If [gameControllersLongPressBForBackNavigation] is true, then controller sources - * ([android.view.InputDevice.SOURCE_JOYSTICK] or [android.view.InputDevice.SOURCE_GAMEPAD]) - * invoke the callback only when a long-press back is detected, not on release. - */ - private val onEmulatedBackEvent: () -> Unit, - - /** - * Milliseconds after which a held BACK/B button emits a long-press BACK [KeyEvent]. - */ - private val longPressTimeoutMs: Int = DEFAULT_LONG_PRESS_TIMEOUT_MS, - - /** - * When true, controller "B/back" short press does not trigger back navigation; long-press does. - */ - var gameControllersLongPressBForBackNavigation: Boolean = false, -) { - init { - require(longPressTimeoutMs > 0) { "longPressTimeoutMs must be > 0" } - } - - private val debugLogs: Boolean = false - private fun d(msg: String) { - if (debugLogs) { - Log.d(TAG, msg) - } - } - - private val allowedKeyCodes: Set = NavigationReservedShortcutKeyCodes.backNavigationKeys - - private fun isKeyAllowed(keyCode: Int): Boolean = allowedKeyCodes.contains(keyCode) - - private var lastBackDown: Boolean = false - - /** [KeyEvent.downTime] of the first emulated BACK [KeyEvent.ACTION_DOWN] while held. */ - private var backKeyDownTime: Long = 0L - - /** True after we emitted the synthetic long-press [KeyEvent]. */ - private var backLongPressEmitted: Boolean = false - - private enum class BackChannel { SYSTEM, KEY, MOTION } - - private fun isControllerSource(source: Int): Boolean { - return (source and android.view.InputDevice.SOURCE_JOYSTICK) != 0 || - (source and android.view.InputDevice.SOURCE_GAMEPAD) != 0 - } - - /** - * For non-controller sources, callback is fired only after ACTION_DOWN followed by - * ACTION_UP. - */ - private var pendingBackDown: Boolean = false - - /** - * When controller-long-press mode triggers, we should not fire again on release. - */ - private var controllerLongPressTriggeredSinceDown: Boolean = false - - /** - * For KeyEvent channel: latch controllerLongPressOnly for the whole press sequence. - * Some devices change flags/source across repeats; we must stay consistent until ACTION_UP. - */ - private var keyPressActive: Boolean = false - private var keyPressControllerLongPressOnly: Boolean = false - - // Timestamp of last BACK ACTION_DOWN emulated/forwarded by each channel (ms, based on uptime). - private val lastBackDownEventTimeByChannel = LongArray(BackChannel.entries.size) { -1L } - - /** - * If one channel emits BACK recently, we suppress BACK from other channels within this window. - * This replaces eventTime+action+keyCode dedupe because those can differ between channels. - */ - private val suppressOtherChannelsTimeoutMs: Long = 1000L - - private fun shouldSuppress(from: BackChannel, eventTime: Long): Boolean { - fun recent(other: BackChannel): Boolean { - val t = lastBackDownEventTimeByChannel[other.ordinal] - if (t < 0L) return false - val dt = eventTime - t - return dt in 0L..suppressOtherChannelsTimeoutMs - } - - return when (from) { - BackChannel.SYSTEM -> recent(BackChannel.KEY) || recent(BackChannel.MOTION) - BackChannel.KEY -> recent(BackChannel.SYSTEM) || recent(BackChannel.MOTION) - BackChannel.MOTION -> recent(BackChannel.SYSTEM) || recent(BackChannel.KEY) - } - } - - private fun markBackDownGenerated(from: BackChannel, eventTime: Long) { - lastBackDownEventTimeByChannel[from.ordinal] = eventTime - d("markBackDownGenerated from=$from eventTime=$eventTime") - } - - fun dispatchSystemBackNavigationEvent(): Boolean { - val now = SystemClock.uptimeMillis() - val suppressed = shouldSuppress(BackChannel.SYSTEM, now) - d("dispatchSystemBackNavigationEvent now=$now suppressed=$suppressed") - if (!suppressed) { - // Treat this as: BACK down then BACK up. - pendingBackDown = true - markBackDownGenerated(BackChannel.SYSTEM, now) - - // Callback only after both press+release have been detected. - if (pendingBackDown) { - pendingBackDown = false - try { - d("dispatchSystemBackNavigationEvent firing onEmulatedBackEvent()") - onEmulatedBackEvent() - } catch (t: Throwable) { - Log.e(TAG, "dispatchSystemBackNavigationEvent: onEmulatedBackEvent failed", t) - } - } - return true - } - return false - } - - fun dispatchKeyEvent(event: KeyEvent): Boolean { - if (!isKeyAllowed(event.keyCode)) return false - val suppressed = shouldSuppress(BackChannel.KEY, event.eventTime) - d("dispatchKeyEvent keyCode=${event.keyCode} action=${event.action} source=${event.source} " + - "eventTime=${event.eventTime} downTime=${event.downTime} repeatCount=${event.repeatCount} " + - "isLongPress=${event.isLongPress} flags=${event.flags} suppressed=$suppressed") - if (suppressed) return false - - return try { - when (event.action) { - KeyEvent.ACTION_DOWN -> { - // Latch mode on the first DOWN of a press. - if (!keyPressActive && event.repeatCount == 0) { - keyPressActive = true - keyPressControllerLongPressOnly = - gameControllersLongPressBForBackNavigation && isControllerSource(event.source) - controllerLongPressTriggeredSinceDown = false - pendingBackDown = false - d("dispatchKeyEvent latch press: controllerLongPressOnly=$keyPressControllerLongPressOnly") - } - - markBackDownGenerated(BackChannel.KEY, event.eventTime) - if (keyPressControllerLongPressOnly) { - val isLongPressNow = - event.isLongPress || event.repeatCount > 0 || (event.flags and KeyEvent.FLAG_LONG_PRESS) != 0 - if (isLongPressNow && !controllerLongPressTriggeredSinceDown) { - controllerLongPressTriggeredSinceDown = true - d("dispatchKeyEvent ACTION_DOWN controllerLongPressOnly: long-press detected -> callback") - onEmulatedBackEvent() - } - // Consume the event even when it's not long-press. - } else if (event.repeatCount == 0) { - // Non-controller: only treat the first DOWN as "press start". - d("dispatchKeyEvent ACTION_DOWN non-controller: pendingBackDown=true") - pendingBackDown = true - } - } - KeyEvent.ACTION_UP -> { - if (keyPressControllerLongPressOnly) { - // Don't call callback on release; end long-press tracking. - d("dispatchKeyEvent ACTION_UP controllerLongPressOnly: release -> no callback") - controllerLongPressTriggeredSinceDown = false - } else { - if (pendingBackDown) { - d("dispatchKeyEvent ACTION_UP non-controller: pendingBackDown -> callback") - pendingBackDown = false - onEmulatedBackEvent() - } else { - pendingBackDown = false - } - } - - keyPressActive = false - keyPressControllerLongPressOnly = false - } - } - true - } catch (t: Throwable) { - Log.e(TAG, "dispatchKeyEvent failed keyCode=${event.keyCode} action=${event.action}", t) - false - } - } - - fun dispatchGenericMotionEvent(event: MotionEvent): Boolean { - val buttonState = event.buttonState - val isMouse = (event.source and InputDevice.SOURCE_MOUSE) != 0 || - (event.source and InputDevice.SOURCE_TOUCHPAD) != 0 || - event.getToolType(0) == MotionEvent.TOOL_TYPE_MOUSE - val backPressedNow = if (isMouse) { - (buttonState and MotionEvent.BUTTON_BACK) != 0 - } else { - (buttonState and MotionEvent.BUTTON_SECONDARY) != 0 || - (buttonState and MotionEvent.BUTTON_BACK) != 0 - } - - var emittedAny = false - val suppressed = shouldSuppress(BackChannel.MOTION, event.eventTime) - - val controllerLongPressOnly = - gameControllersLongPressBForBackNavigation && isControllerSource(event.source) - - d("dispatchGenericMotionEvent buttonState=$buttonState source=${event.source} " + - "eventTime=${event.eventTime} downTime=${event.downTime} backPressedNow=$backPressedNow " + - "lastBackDown=$lastBackDown suppressed=$suppressed controllerLongPressOnly=$controllerLongPressOnly") - - if (backPressedNow && !lastBackDown) { - // Track the hold regardless of suppression so long-press can still be emitted later. - backKeyDownTime = event.downTime - backLongPressEmitted = false - if (!suppressed) { - markBackDownGenerated(BackChannel.MOTION, event.eventTime) - if (controllerLongPressOnly) { - controllerLongPressTriggeredSinceDown = false - // Don't fire callback yet; only on long-press. - } else { - pendingBackDown = true - } - emittedAny = true - } - } else if (!backPressedNow && lastBackDown) { - if (!suppressed) { - if (controllerLongPressOnly) { - // Don't call callback on release in controller-long-press mode. - d("dispatchGenericMotionEvent controllerLongPressOnly: release -> no callback") - controllerLongPressTriggeredSinceDown = false - } else { - if (pendingBackDown) { - d("dispatchGenericMotionEvent non-controller: release with pending -> callback") - pendingBackDown = false - try { - onEmulatedBackEvent() - } catch (t: Throwable) { - Log.e(TAG, "dispatchGenericMotionEvent: onEmulatedBackEvent failed", t) - } - } else { - pendingBackDown = false - } - } - emittedAny = true - } - backLongPressEmitted = false - } else if ( - backPressedNow && lastBackDown && - isKeyAllowed(KeyEvent.KEYCODE_BACK) && - !backLongPressEmitted - ) { - val elapsed = max(0L, event.eventTime - backKeyDownTime) - if (elapsed >= longPressTimeoutMs) { - if (!suppressed) { - markBackDownGenerated(BackChannel.MOTION, event.eventTime) - if (controllerLongPressOnly) { - if (!controllerLongPressTriggeredSinceDown) { - controllerLongPressTriggeredSinceDown = true - d("dispatchGenericMotionEvent controllerLongPressOnly: long-press elapsed=$elapsed -> callback") - try { - onEmulatedBackEvent() - } catch (t: Throwable) { - Log.e(TAG, "dispatchGenericMotionEvent: onEmulatedBackEvent failed", t) - } - } - } - emittedAny = true - } - backLongPressEmitted = true - } - } - - lastBackDown = backPressedNow - return emittedAny - } - - fun resetState() { - d("resetState()") - lastBackDown = false - backKeyDownTime = 0L - backLongPressEmitted = false - pendingBackDown = false - controllerLongPressTriggeredSinceDown = false - keyPressActive = false - keyPressControllerLongPressOnly = false - for (i in lastBackDownEventTimeByChannel.indices) { - lastBackDownEventTimeByChannel[i] = -1L - } - } - - companion object { - private const val TAG = "BackNavigationEventsAdapter" - private const val DEFAULT_LONG_PRESS_TIMEOUT_MS: Int = 500 - } -} - diff --git a/app/common/src/main/java/com/bansify/internet/utils/DPADNavigationEventsAdapter.kt b/app/common/src/main/java/com/bansify/internet/utils/DPADNavigationEventsAdapter.kt deleted file mode 100644 index 2b9e0480..00000000 --- a/app/common/src/main/java/com/bansify/internet/utils/DPADNavigationEventsAdapter.kt +++ /dev/null @@ -1,549 +0,0 @@ -package com.bansify.internet.utils - -import android.util.Log -import android.view.InputDevice -import android.view.KeyEvent -import android.view.MotionEvent -import kotlin.math.abs - -/** - * Handles input that may arrive as [KeyEvent]s, as [MotionEvent]s, or through both channels. - * - * - [dispatchKeyEvent] forwards allowed framework [KeyEvent]s to [onEmulatedKeyEvent]. - * - [dispatchGenericMotionEvent] translates selected motion axes/buttons into emulated key events - * and forwards them to [onEmulatedKeyEvent]. Events whose source is not a joystick, gamepad, or - * hardware DPAD (e.g. mouse, touchpad) are ignored so pointer motion is not mistaken for sticks. - * - * To avoid duplicate handling when the same physical action is delivered through both channels, - * the adapter keeps a small history of recently forwarded events and suppresses consecutive - * duplicates with the same (eventTime, action, keyCode) signature. - * - * Hardware often reports DPAD as both [KeyEvent]s and joystick [MotionEvent]s (hat / DPAD - * button bits). Those streams use different timestamps, so signature dedupe alone is not enough: - * we track the navigation key currently held according to the key channel and suppress - * motion-emulated DOWN/UP for that key while the framework reports it held, and we clear - * motion axis/button state when a matching framework UP arrives so a later axis "release" - * does not emit a second UP. - * - * Motion-to-key translation still uses dead-zone and discretization to avoid axis spam. - * Axis translation can be turned off via the `motionAxesTranslationEnabled` callback (e.g. user setting). - * - * When [isSoftwareKeyboardVisible] returns true, DPAD navigation input is ignored (not forwarded). - */ -class DPADNavigationEventsAdapter( - /** - * Callback invoked for every forwarded framework [KeyEvent] and every emitted emulated - * [KeyEvent] generated from motion input. - */ - private val onEmulatedKeyEvent: (KeyEvent) -> Boolean, - - /** - * Axis absolute value threshold beyond which we consider a stick/hat deflection "intentional". - */ - private val deadZone: Float = DEFAULT_DEAD_ZONE, - - /** - * Smaller threshold used to decide when to release a direction after it was previously active. - * Helps avoid jitter toggling around [deadZone]. - */ - private val releaseDeadZone: Float = DEFAULT_RELEASE_DEAD_ZONE, - - /** - * Preferred axis pair ordering: - * - hat axes ([MotionEvent.AXIS_HAT_X]/[MotionEvent.AXIS_HAT_Y]) if they look active - * - otherwise analog stick axes ([MotionEvent.AXIS_X]/[MotionEvent.AXIS_Y]) - */ - private val preferHatAxes: Boolean = true, - - /** - * When false, [handleAxes] is skipped (no stick/hat → DPAD translation from the motion channel). - * Buttons and directional DPAD button bits are unaffected. Use a live lambda so preferences - * apply without recreating the adapter. - */ - private val motionAxesTranslationEnabled: () -> Boolean = { true }, - - /** - * When true, DPAD navigation keys and motion-emulated navigation are not forwarded; use while - * the IME is shown so typing / keyboard navigation is not overridden by cursor logic. - */ - private val isSoftwareKeyboardVisible: () -> Boolean = { false }, -) { - init { - require(deadZone >= 0f) { "deadZone must be >= 0" } - require(releaseDeadZone >= 0f) { "releaseDeadZone must be >= 0" } - } - - private var lastDirX: Int = 0 // -1 left, 0 neutral, +1 right - private var lastDirY: Int = 0 // -1 up, 0 neutral, +1 down - private var lastDpadKeyCode: Int = 0 - private var lastDpadFromButtons: Boolean = false - - private var lastPrimaryDown: Boolean = false - - /** - * [KeyEvent.KEYCODE_DPAD_*] currently held according to the framework key channel - * ([dispatchKeyEvent]), or 0. Used to avoid emitting the same DOWN/UP again from motion. - */ - private var frameworkHeldNavigationKeyCode: Int = 0 - - // Some controllers report DPAD directions as "button bits" instead of (or in addition to) - // hat/axis values. Android does not guarantee consistent constants across devices/levels, - // so we detect them via reflection and only use them when present. - private val dpadButtonBits = DpadButtonBits.fromMotionEvent() - - // Keys DPADNavigationEventsAdapter is responsible for. - private val allowedKeyCodes: Set = NavigationReservedShortcutKeyCodes.dpadNavigationKeys - - private fun isKeyAllowed(keyCode: Int): Boolean = allowedKeyCodes.contains(keyCode) - - fun dispatchKeyEvent(event: KeyEvent): Boolean { - if (!isKeyAllowed(event.keyCode)) return false - - if (isSoftwareKeyboardVisible()) { - return false - } - - if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) { - frameworkHeldNavigationKeyCode = event.keyCode - } - - // If motion already synthesized DOWN for this key, the framework key DOWN is redundant. - if (event.action == KeyEvent.ACTION_DOWN && - event.repeatCount == 0 && - lastDpadKeyCode == event.keyCode - ) { - val sig = KeyDispatchSignature(event.eventTime, event.action, event.keyCode) - recordSentSignature(sig) - return true - } - - if (event.action == KeyEvent.ACTION_UP) { - // So a later motion "release" does not emit a second UP for the same press. - if (lastDpadKeyCode == event.keyCode) { - lastDpadKeyCode = 0 - lastDirX = 0 - lastDirY = 0 - lastDpadFromButtons = false - } - } - - val sig = KeyDispatchSignature(event.eventTime, event.action, event.keyCode) - if (sentEmulatedHistory.lastOrNull() == sig) { - // Avoid feeding duplicates that may arrive from both dispatch channels. - // Even if suppressed, report "handled" so callers can consistently consume it. - return true - } - - return try { - onEmulatedKeyEvent(event) - } catch (t: Throwable) { - Log.e(TAG, "dispatchKeyEvent: callback failed keyCode=${event.keyCode} action=${event.action}", t) - false - } finally { - recordSentSignature(sig) - if (event.action == KeyEvent.ACTION_UP && event.keyCode == frameworkHeldNavigationKeyCode) { - frameworkHeldNavigationKeyCode = 0 - } - } - } - - private data class KeyDispatchSignature(val eventTime: Long, val action: Int, val keyCode: Int) - - // Keeps a short history of the signatures that were actually forwarded to `onEmulatedKeyEvent`. - // This is used for duplicate filtering and also makes it easy to inspect behavior in a debugger. - private val sentEmulatedHistory = ArrayDeque() - private val sentEmulatedHistoryMaxSize = 16 - - private fun recordSentSignature(sig: KeyDispatchSignature) { - sentEmulatedHistory.addLast(sig) - while (sentEmulatedHistory.size > sentEmulatedHistoryMaxSize) { - sentEmulatedHistory.removeFirst() - } - } - - /** - * Process a MotionEvent (from View/Activity dispatch) and emit emulated KeyEvents as needed. - * - * @return true if the event matched the supported joystick/gamepad/DPAD motion sources and we - * emitted at least one KeyEvent (or axis translation was off and we released a prior axis-held - * direction). Callers should typically return this value from their - * dispatchGenericMotionEvent to prevent the WebView from consuming joystick axis motions. - */ - fun dispatchGenericMotionEvent(event: MotionEvent): Boolean { - if (isSoftwareKeyboardVisible()) { - return false - } - - if (!isNavigationGenericMotionSource(event.source)) { - // Mice/touchpads reuse generic motion, axes, and BUTTON_PRIMARY; never treat them as DPAD. - if (!motionAxesTranslationEnabled()) { - return releaseAxisHeldDirectionIfNeeded(event) - } - return false - } - - var emittedAnyKey = false - - if (!motionAxesTranslationEnabled()) { - emittedAnyKey = releaseAxisHeldDirectionIfNeeded(event) || emittedAnyKey - } - - // Prefer directional D-pad *buttons* over axes if they are actively pressed, otherwise - // the axis "center jitter" could release a direction while the button is still held. - val buttonState = event.buttonState - val dpadButtonsPressedNow = - dpadButtonBits.supported && - ( - (buttonState and dpadButtonBits.upBit) != 0 || - (buttonState and dpadButtonBits.downBit) != 0 || - (buttonState and dpadButtonBits.leftBit) != 0 || - (buttonState and dpadButtonBits.rightBit) != 0 - ) - - emittedAnyKey = handleDirectionalDpadButtons(event) || emittedAnyKey - emittedAnyKey = handleButtons(event) || emittedAnyKey - - if (!dpadButtonsPressedNow && motionAxesTranslationEnabled()) { - emittedAnyKey = handleAxes(event) || emittedAnyKey - } - - return emittedAnyKey - } - - /** - * If axis translation is off but we still hold a direction that came from axes, emit KEY_UP - * once so navigation does not stay stuck. - */ - private fun releaseAxisHeldDirectionIfNeeded(event: MotionEvent): Boolean { - if (lastDpadFromButtons || lastDpadKeyCode == 0) return false - if (!isKeyAllowed(lastDpadKeyCode)) { - lastDpadKeyCode = 0 - lastDirX = 0 - lastDirY = 0 - return false - } - val emitted = emitKeyEvent(event, action = KeyEvent.ACTION_UP, keyCode = lastDpadKeyCode) - lastDpadKeyCode = 0 - lastDirX = 0 - lastDirY = 0 - return emitted - } - - /** - * Clears internal state (useful if caller wants to drop axis/button tracking). - * This intentionally does not emit any KEY_UP events. - */ - fun resetState() { - lastDirX = 0 - lastDirY = 0 - lastDpadKeyCode = 0 - lastDpadFromButtons = false - lastPrimaryDown = false - frameworkHeldNavigationKeyCode = 0 - sentEmulatedHistory.clear() - } - - private fun handleAxes(event: MotionEvent): Boolean { - val dead = deadZone - val releaseDead = minOf(releaseDeadZone, dead) // ensure hysteresis is sane - - val (xAxis, yAxis) = if (preferHatAxes) { - val hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X) - val hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y) - val hatLooksActive = abs(hatX) >= dead || abs(hatY) >= dead - if (hatLooksActive) { - hatX to hatY - } else { - event.getAxisValue(MotionEvent.AXIS_X) to event.getAxisValue(MotionEvent.AXIS_Y) - } - } else { - event.getAxisValue(MotionEvent.AXIS_X) to event.getAxisValue(MotionEvent.AXIS_Y) - } - - fun axisToDir(axisValue: Float, lastDir: Int): Int { - return when { - axisValue >= dead -> 1 - axisValue <= -dead -> -1 - abs(axisValue) <= releaseDead -> 0 - else -> { - // Hysteresis band: keep direction only if axis is still on the same side - // (prevents "stickiness" when crossing through center with jitter). - val sameSign = (axisValue > 0f && lastDir == 1) || (axisValue < 0f && lastDir == -1) - if (sameSign) lastDir else 0 - } - } - } - - val newDirX = axisToDir(xAxis, lastDirX) - val newDirY = axisToDir(yAxis, lastDirY) - - val newDpadKeyCode = dpadKeyCodeFromDirs(newDirX, newDirY) - if (newDpadKeyCode == lastDpadKeyCode) { - return false - } - - // Key up old direction (if any) and key down new direction (if any). - var emittedAny = false - if (lastDpadKeyCode != 0) { - if (isKeyAllowed(lastDpadKeyCode)) { - emittedAny = emitKeyEvent(event, action = KeyEvent.ACTION_UP, keyCode = lastDpadKeyCode) || emittedAny - } - } - lastDirX = newDirX - lastDirY = newDirY - var newHeld = 0 - if (newDpadKeyCode != 0 && isKeyAllowed(newDpadKeyCode)) { - if (emitKeyEvent(event, action = KeyEvent.ACTION_DOWN, keyCode = newDpadKeyCode)) { - newHeld = newDpadKeyCode - } - } - lastDpadKeyCode = newHeld - lastDpadFromButtons = false - - return emittedAny - } - - private fun handleDirectionalDpadButtons(event: MotionEvent): Boolean { - if (!dpadButtonBits.supported) return false - - val buttonState = event.buttonState - val upPressed = (buttonState and dpadButtonBits.upBit) != 0 - val downPressed = (buttonState and dpadButtonBits.downBit) != 0 - val leftPressed = (buttonState and dpadButtonBits.leftBit) != 0 - val rightPressed = (buttonState and dpadButtonBits.rightBit) != 0 - - val isAnyPressed = upPressed || downPressed || leftPressed || rightPressed - if (!isAnyPressed) { - // Release old direction only if we previously emitted it from button DPAD. - if (lastDpadFromButtons && lastDpadKeyCode != 0) { - val emitted = if (isKeyAllowed(lastDpadKeyCode)) { - emitKeyEvent(event, action = KeyEvent.ACTION_UP, keyCode = lastDpadKeyCode) - } else { - false - } - lastDpadKeyCode = 0 - lastDirX = 0 - lastDirY = 0 - lastDpadFromButtons = false - return emitted - } - return false - } - - val (dirX, dirY, newKeyCode) = dpadKeyCodeFromButtons(upPressed, downPressed, leftPressed, rightPressed) - if (newKeyCode == 0) { - // Contradictory button combination: treat as neutral and release if needed. - if (lastDpadFromButtons && lastDpadKeyCode != 0) { - val emitted = if (isKeyAllowed(lastDpadKeyCode)) { - emitKeyEvent(event, action = KeyEvent.ACTION_UP, keyCode = lastDpadKeyCode) - } else { - false - } - lastDpadKeyCode = 0 - lastDirX = 0 - lastDirY = 0 - lastDpadFromButtons = false - return emitted - } - return false - } - - if (newKeyCode == lastDpadKeyCode) { - lastDpadFromButtons = true - return false - } - - // Key up old direction (if any) and key down new direction. - var emittedAny = false - if (lastDpadKeyCode != 0) { - if (isKeyAllowed(lastDpadKeyCode)) { - emittedAny = emitKeyEvent(event, action = KeyEvent.ACTION_UP, keyCode = lastDpadKeyCode) || emittedAny - } - } - lastDirX = dirX - lastDirY = dirY - var newHeld = 0 - if (newKeyCode != 0 && isKeyAllowed(newKeyCode)) { - if (emitKeyEvent(event, action = KeyEvent.ACTION_DOWN, keyCode = newKeyCode)) { - newHeld = newKeyCode - } - } - lastDpadKeyCode = newHeld - lastDpadFromButtons = newHeld != 0 - return emittedAny - } - - private fun dpadKeyCodeFromButtons( - upPressed: Boolean, - downPressed: Boolean, - leftPressed: Boolean, - rightPressed: Boolean - ): Triple { - val dirX = when { - leftPressed && !rightPressed -> -1 - rightPressed && !leftPressed -> 1 - else -> 0 - } - val dirY = when { - upPressed && !downPressed -> -1 - downPressed && !upPressed -> 1 - else -> 0 - } - val keyCode = when { - dirX == 0 && dirY == -1 -> KeyEvent.KEYCODE_DPAD_UP - dirX == 0 && dirY == 1 -> KeyEvent.KEYCODE_DPAD_DOWN - dirX == -1 && dirY == 0 -> KeyEvent.KEYCODE_DPAD_LEFT - dirX == 1 && dirY == 0 -> KeyEvent.KEYCODE_DPAD_RIGHT - dirX == -1 && dirY == -1 -> KeyEvent.KEYCODE_DPAD_UP_LEFT - dirX == 1 && dirY == -1 -> KeyEvent.KEYCODE_DPAD_UP_RIGHT - dirX == -1 && dirY == 1 -> KeyEvent.KEYCODE_DPAD_DOWN_LEFT - dirX == 1 && dirY == 1 -> KeyEvent.KEYCODE_DPAD_DOWN_RIGHT - else -> 0 - } - return Triple(dirX, dirY, keyCode) - } - - private fun handleButtons(event: MotionEvent): Boolean { - val buttonState = event.buttonState - - var emittedAny = false - - fun emitSelection(action: Int): Boolean { - // Emit multiple "selection" key codes; filtering decides what actually goes through. - var any = false - any = emitKeyEvent(event, action = action, keyCode = KeyEvent.KEYCODE_DPAD_CENTER) || any - any = emitKeyEvent(event, action = action, keyCode = KeyEvent.KEYCODE_ENTER) || any - any = emitKeyEvent(event, action = action, keyCode = KeyEvent.KEYCODE_NUMPAD_ENTER) || any - any = emitKeyEvent(event, action = action, keyCode = KeyEvent.KEYCODE_BUTTON_A) || any - return any - } - - val primaryPressed = (buttonState and MotionEvent.BUTTON_PRIMARY) != 0 - if (primaryPressed && !lastPrimaryDown) { - emittedAny = emitSelection(KeyEvent.ACTION_DOWN) || emittedAny - } else if (!primaryPressed && lastPrimaryDown) { - emittedAny = emitSelection(KeyEvent.ACTION_UP) || emittedAny - } - lastPrimaryDown = primaryPressed - - return emittedAny - } - - private fun dpadKeyCodeFromDirs(dirX: Int, dirY: Int): Int { - return when { - dirX == 0 && dirY == 0 -> 0 - dirX == -1 && dirY == -1 -> KeyEvent.KEYCODE_DPAD_UP_LEFT - dirX == 1 && dirY == -1 -> KeyEvent.KEYCODE_DPAD_UP_RIGHT - dirX == -1 && dirY == 1 -> KeyEvent.KEYCODE_DPAD_DOWN_LEFT - dirX == 1 && dirY == 1 -> KeyEvent.KEYCODE_DPAD_DOWN_RIGHT - dirX == -1 && dirY == 0 -> KeyEvent.KEYCODE_DPAD_LEFT - dirX == 1 && dirY == 0 -> KeyEvent.KEYCODE_DPAD_RIGHT - dirX == 0 && dirY == -1 -> KeyEvent.KEYCODE_DPAD_UP - dirX == 0 && dirY == 1 -> KeyEvent.KEYCODE_DPAD_DOWN - else -> 0 - } - } - - private fun emitKeyEvent( - event: MotionEvent, - action: Int, - keyCode: Int, - repeat: Int = 0, - flags: Int = 0, - downTime: Long = event.downTime, - ): Boolean { - if (keyCode == 0) return false - if (!isKeyAllowed(keyCode)) return false - - if (frameworkHeldNavigationKeyCode == keyCode && - (action == KeyEvent.ACTION_DOWN || action == KeyEvent.ACTION_UP) - ) { - // Framework key channel already (or will) deliver this; motion uses different - // eventTime so signature dedupe alone does not catch it. - return true - } - - val sig = KeyDispatchSignature(event.eventTime, action, keyCode) - if (sentEmulatedHistory.lastOrNull() == sig) { - // If the same event arrives from both dispatch channels at the same time, - // drop the duplicate to avoid double-handling. - // Even if suppressed, report "handled" so callers can consistently consume it. - return true - } - - // Preserve the originating [MotionEvent] source (e.g. joystick / gamepad). - val emulated = KeyEvent( - downTime, - event.eventTime, - action, - keyCode, - repeat, - /* metaState */ 0, - /* deviceId */ event.deviceId, - /* scanCode */ 0, - flags, - /* source */ event.source - ) - try { - onEmulatedKeyEvent(emulated) - return true - } catch (t: Throwable) { - // Input dispatch is timing-sensitive; never let an internal translation error kill the app. - Log.e(TAG, "Failed to dispatch emulated key=$keyCode action=$action", t) - return false - } finally { - recordSentSignature(sig) - } - } - - companion object { - private const val TAG = "DPADNavigationEventsAdapter" - private const val DEFAULT_DEAD_ZONE: Float = 0.4f - private const val DEFAULT_RELEASE_DEAD_ZONE: Float = 0.28f - - private fun readMotionEventStaticInt(fieldName: String): Int? { - return try { - val field = MotionEvent::class.java.getField(fieldName) - field.getInt(null) - } catch (_: Throwable) { - null - } - } - - /** - * True for sources that legitimately deliver joystick/DPAD-style generic motion. - * Pointer-class devices (mouse, touchpad, etc.) are excluded. - */ - fun isNavigationGenericMotionSource(source: Int): Boolean { - return (source and InputDevice.SOURCE_JOYSTICK) != 0 || - (source and InputDevice.SOURCE_GAMEPAD) != 0 || - (source and InputDevice.SOURCE_DPAD) != 0 - } - } - - private data class DpadButtonBits( - val supported: Boolean, - val upBit: Int, - val downBit: Int, - val leftBit: Int, - val rightBit: Int - ) { - companion object { - fun fromMotionEvent(): DpadButtonBits { - // Field names are not guaranteed. We only need them when the platform provides them. - val up = readMotionEventStaticInt("BUTTON_DPAD_UP") - val down = readMotionEventStaticInt("BUTTON_DPAD_DOWN") - val left = readMotionEventStaticInt("BUTTON_DPAD_LEFT") - val right = readMotionEventStaticInt("BUTTON_DPAD_RIGHT") - val supported = up != null || down != null || left != null || right != null - return DpadButtonBits( - supported = supported, - upBit = up ?: 0, - downBit = down ?: 0, - leftBit = left ?: 0, - rightBit = right ?: 0 - ) - } - } - } -} diff --git a/app/common/src/main/java/com/bansify/internet/utils/DownloadUtils.kt b/app/common/src/main/java/com/bansify/internet/utils/DownloadUtils.kt deleted file mode 100644 index 50306ea2..00000000 --- a/app/common/src/main/java/com/bansify/internet/utils/DownloadUtils.kt +++ /dev/null @@ -1,185 +0,0 @@ -/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*- - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - * - * This file incorporates work covered by the following copyright and - * permission notice: - * - * Copyright (C) 2006 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. */ - -package com.bansify.internet.utils - -import android.net.Uri -import android.webkit.MimeTypeMap - -import java.io.ByteArrayOutputStream -import java.io.UnsupportedEncodingException -import java.util.Locale -import java.util.regex.Pattern - -object DownloadUtils { - - /** - * Format as defined in RFC 2616 and RFC 5987 / RFC 6266. - * Both attachment and inline disposition types are supported. - */ - private val CONTENT_DISPOSITION_PATTERN = Pattern.compile("(?:attachment|inline)\\s*;\\s*filename\\s*=\\s*" + - "(\"((?:\\\\.|[^\"\\\\])*)\"|[^;]*)\\s*" + - "(?:;\\s*filename\\*\\s*=\\s*(utf-8|iso-8859-1)'[^']*'(\\S*))?", - Pattern.CASE_INSENSITIVE) - - /** - * Definition as per RFC 5987, section 3.2.1. (value-chars) - */ - private val ENCODED_SYMBOL_PATTERN = Pattern.compile("%[0-9a-f]{2}|[0-9a-z!#$&+-.^_`|~]", Pattern.CASE_INSENSITIVE) - - /** - * Guess the name of the file that should be downloaded. - * - * This method is largely identical to [android.webkit.URLUtil.guessFileName] - * which unfortunately does not implement RfC 5987. - */ - fun guessFileName(url: String, - contentDisposition: String?, - mimeType: String?): String { - var filename: String? = null - var extension: String? = null - - // Extract file name from content disposition header field - if (contentDisposition != null) { - filename = parseContentDisposition(contentDisposition) - if (filename != null) { - val index = filename.lastIndexOf('/') + 1 - if (index > 0) { - filename = filename.substring(index) - } - } - } - - // If all the other http-related approaches failed, use the plain uri - if (filename == null) { - var decodedUrl: String? = Uri.decode(url) - if (decodedUrl != null) { - val queryIndex = decodedUrl.indexOf('?') - // If there is a query string strip it, same as desktop browsers - if (queryIndex > 0) { - decodedUrl = decodedUrl.substring(0, queryIndex) - } - if (!decodedUrl.endsWith("/")) { - val index = decodedUrl.lastIndexOf('/') + 1 - if (index > 0) { - filename = decodedUrl.substring(index) - } - } - } - } - - // Finally, if couldn't get filename from URI, get a generic filename - if (filename == null) { - filename = "downloadfile" - } - - // Split filename between base and extension - // Add an extension if filename does not have one - val dotIndex = filename.indexOf('.') - if (dotIndex < 0) { - if (mimeType != null) { - extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType) - if (extension != null) { - extension = ".$extension" - } - } - if (extension == null) { - if (mimeType != null && mimeType.lowercase().startsWith("text/")) { - if (mimeType.equals("text/html", ignoreCase = true)) { - extension = ".html" - } else { - extension = ".txt" - } - } else { - extension = ".bin" - } - } - } else { - if (mimeType != null && "application/octet-stream" != mimeType) { - // Compare the last segment of the extension against the mime type. - // If there's a mismatch, discard the entire extension. - val lastDotIndex = filename.lastIndexOf('.') - val typeFromExt = MimeTypeMap.getSingleton().getMimeTypeFromExtension( - filename.substring(lastDotIndex + 1)) - if (typeFromExt != null && !typeFromExt.equals(mimeType, ignoreCase = true)) { - extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType) - if (extension != null) { - extension = ".$extension" - } - } - } - if (extension == null) { - extension = filename.substring(dotIndex) - } - filename = filename.substring(0, dotIndex) - } - - return filename + extension - } - - private fun parseContentDisposition(contentDisposition: String): String? { - try { - val m = CONTENT_DISPOSITION_PATTERN.matcher(contentDisposition) - - if (m.find()) { - // If escaped string is found, decode it using the given encoding. - val encodedFileName = m.group(4) - val encoding = m.group(3) - - if (encodedFileName != null) { - return decodeHeaderField(encodedFileName, encoding) - } - - // Return quoted string if available and replace escaped characters. - val quotedFileName = m.group(2) - - return quotedFileName?.replace("\\\\(.)".toRegex(), "$1") ?: m.group(1) - - // Otherwise try to extract the unquoted file name - } - } catch (ex: IllegalStateException) { - // This function is defined as returning null when it can't parse the header - } catch (ex: UnsupportedEncodingException) { - } - - return null - } - - @Throws(UnsupportedEncodingException::class) - private fun decodeHeaderField(field: String, encoding: String): String { - val m = ENCODED_SYMBOL_PATTERN.matcher(field) - val stream = ByteArrayOutputStream() - - while (m.find()) { - val symbol = m.group() - - if (symbol.startsWith("%")) { - stream.write(Integer.parseInt(symbol.substring(1), 16)) - } else { - stream.write(symbol[0].toInt()) - } - } - - return stream.toString(encoding) - } - -} diff --git a/app/common/src/main/java/com/bansify/internet/utils/Extensions.kt b/app/common/src/main/java/com/bansify/internet/utils/Extensions.kt deleted file mode 100644 index 3d56788e..00000000 --- a/app/common/src/main/java/com/bansify/internet/utils/Extensions.kt +++ /dev/null @@ -1,42 +0,0 @@ -package com.bansify.internet.utils - -import android.app.Activity -import android.content.Context -import android.content.ContextWrapper -import android.view.View -import android.view.ViewGroup -import java.util.* -import kotlin.collections.ArrayList - -val View.activity: Activity? - get() { - var ctx = context - while (true) { - if (!ContextWrapper::class.java.isInstance(ctx)) { - return null - } - if (Activity::class.java.isInstance(ctx)) { - return ctx as Activity - } - ctx = (ctx as ContextWrapper).baseContext - } - } - -fun Calendar.sameDay(other: Calendar): Boolean { - return this.get(Calendar.YEAR) == other.get(Calendar.YEAR) && - this.get(Calendar.MONTH) == other.get(Calendar.MONTH) && - this.get(Calendar.DAY_OF_MONTH) == other.get(Calendar.DAY_OF_MONTH) -} - -val ViewGroup.childs: ArrayList - get() { - val result = ArrayList() - for (i in 0 until this.childCount) { - result.add(this.getChildAt(i)) - } - return result - } - -fun Int.dip2px(context: Context): Float { - return (this * context.resources.displayMetrics.density) -} \ No newline at end of file diff --git a/app/common/src/main/java/com/bansify/internet/utils/FaviconExtractor.kt b/app/common/src/main/java/com/bansify/internet/utils/FaviconExtractor.kt deleted file mode 100644 index e3b0ae06..00000000 --- a/app/common/src/main/java/com/bansify/internet/utils/FaviconExtractor.kt +++ /dev/null @@ -1,220 +0,0 @@ -package com.bansify.internet.utils - -import android.util.JsonReader -import android.webkit.MimeTypeMap -import java.io.BufferedReader -import java.io.Reader -import java.net.URL -import java.util.regex.Pattern - - -class FaviconExtractor { - companion object { - const val DEFAULT_ICON_SRC = "/favicon.ico" - const val DEFAULT_ICON_TYPE = "image/x-icon" - const val DEFAULT_ICON_SIZE = 16 - const val DEFAULT_ICON_SIZE_STRING = "${DEFAULT_ICON_SIZE}x$DEFAULT_ICON_SIZE" - } - - private val headerClosingTagsPattern: Pattern = Pattern.compile("<\\s*(?:body|/\\s*head)(?:\\s+|>)") - private val tagsPattern: Pattern = Pattern.compile("<(?!!)(?!/)\\s*([a-zA-Z\\d]+)((?s:.)*?)>") - private val attributePattern: Pattern = Pattern.compile("(\\S+)=\\s*['\"]?([^>\"'\\s]+)['\"]?") - - class IconInfo ( - var src: String, - var type: String? = null, - var rel: String? = null, - sizes: String? = null, - baseURL: URL? = null - ) { - var width: Int = 0 - var height: Int = 0 - init { - if (sizes != null) { - try { - val sizesArr = sizes.split("x") - width = Integer.parseUnsignedInt(sizesArr[0]) - height = Integer.parseUnsignedInt(sizesArr[1]) - } catch (e: Exception) { - //it is ok, just leave default values of w and h - } - } - if (baseURL != null) { - src = URL(baseURL, src).toString() - } - if (type == null) { - val extension = MimeTypeMap.getFileExtensionFromUrl(src) - if (extension != null) { - type = guessIconType(extension) - } - } - } - - private fun guessIconType(iconExtension: String): String? { - return if (iconExtension.equals("png", true)) { - "image/png" - } else if (iconExtension.equals("jpg", true)) { - "image/jpeg" - } else if (iconExtension.equals("ico", true)) { - DEFAULT_ICON_TYPE - } else if (iconExtension.equals("gif", true)) { - "image/gif" - } else if (iconExtension.equals("svg", true)) { - "image/svg+xml" - } else null - } - } - - /** - * Downloads HTML by provided @param url, traverses all tags and collects all found - * icon as @return List - * Will also collect icons from web manifest - * - * @throws java.io.IOException - */ - fun extractFavIconsFromURL(url: URL): ArrayList { - val (result, manifestHref) = url.openConnection().inputStream.bufferedReader().use { extractFavIconsFromHTML(url, it) } - if (manifestHref != null) { - val manifestURL = URL(url, manifestHref) - try { - val manifestIcons = manifestURL.openConnection().inputStream.bufferedReader() - .use { extractFavIconsFromWebManifest(manifestURL, it) } - result.addAll(manifestIcons) - } catch (e: Exception) { - //shit happens, but I don't think it's too important here - e.printStackTrace() - } - } - if (result.isEmpty()) { - result.add( - IconInfo( - "/favicon.ico", - DEFAULT_ICON_TYPE, - null, - DEFAULT_ICON_SIZE_STRING, - url - ) - ) - } - return result - } - - fun extractFavIconsFromWebManifest(manifestURL: URL?, manifest: Reader): ArrayList { - val iconInfos = ArrayList() - val jsonReader = JsonReader(manifest) - jsonReader.isLenient = true - jsonReader.use { - jsonReader.beginObject() - while (jsonReader.hasNext()) { - val name = jsonReader.nextName() - if (name == "icons") { - jsonReader.beginArray() - while (jsonReader.hasNext()) { - jsonReader.beginObject() - var src: String? = null - var type: String? = null - var sizes: String? = null - while (jsonReader.hasNext()) { - when (jsonReader.nextName()) { - "src" -> { - src = jsonReader.nextString() - } - "sizes" -> { - sizes = jsonReader.nextString() - } - "type" -> { - type = jsonReader.nextString() - } - } - } - jsonReader.endObject() - if (src != null) { - iconInfos.add(IconInfo(src, type, null, sizes, manifestURL)) - } - } - jsonReader.endArray() - return@use - } else { - jsonReader.skipValue() - } - } - jsonReader.endObject() - } - return iconInfos - } - - /** - * @return @kotlin.Pair of list of IconInfo and href of web manifest (if found any) - * - * @throws java.io.IOException - */ - fun extractFavIconsFromHTML(baseURL: URL?, html: BufferedReader): Pair, String?> { - val iconInfos = ArrayList() - var manifestHref: String? = null - - val headerPartOfHTML = StringBuilder() - var line = html.readLine() - try { - while (line != null) { - headerPartOfHTML.appendLine(line) - val matcher = headerClosingTagsPattern.matcher(line) - if (matcher.find()) { - break - } - line = html.readLine() - } - } catch (e: Exception) { - e.printStackTrace() - return Pair(iconInfos, null) - } - - val matcher = tagsPattern.matcher(headerPartOfHTML.toString()) - while (matcher.find()) { - val tagName = matcher.group(1) ?: continue - //println("tag name: $tagName") - when (tagName) { - "link" -> { - val attributes = matcher.group(2) ?: continue - //println(" rest of the tag: $attributes") - val attributeMatcher = attributePattern.matcher(attributes) - var rel: String? = null - var href: String? = null - var sizes: String? = null - var type: String? = null - while (attributeMatcher.find()) { - val attributeName = attributeMatcher.group(1) ?: continue - val attributeValue = attributeMatcher.group(2) ?: continue - //println(" attribute name: $attributeName value: $attributeValue") - when (attributeName) { - "rel" -> rel = attributeValue - "href" -> href = attributeValue - "sizes" -> sizes = attributeValue - "type" -> type = attributeValue - } - } - if (href == null || rel == null) { - continue - } - if (rel.equals("icon", true) || - rel.equals("apple-touch-icon", true) || - rel.equals("shortcut icon", true) || - rel.equals("shortcut", true) || - rel.equals("fluid-icon", true)) { - if (sizes == null && rel.equals("apple-touch-icon", true)) { - sizes = "180x180" - } - iconInfos.add(IconInfo(href, type, rel, sizes, baseURL)) - } else if (rel.equals("manifest", true)) { - manifestHref = href - } - } - "body" -> { - break - } - } - } - - - return Pair(iconInfos, manifestHref) - } -} \ No newline at end of file diff --git a/app/common/src/main/java/com/bansify/internet/utils/HardwareInputManager.kt b/app/common/src/main/java/com/bansify/internet/utils/HardwareInputManager.kt deleted file mode 100644 index ae14a731..00000000 --- a/app/common/src/main/java/com/bansify/internet/utils/HardwareInputManager.kt +++ /dev/null @@ -1,177 +0,0 @@ -package com.bansify.internet.utils - -import android.content.Context -import android.hardware.input.InputManager -import android.os.Handler -import android.os.Looper -import android.os.SystemClock -import android.view.InputDevice -import android.view.InputEvent -import android.view.KeyEvent -import android.view.MotionEvent -import android.view.View -import com.bansify.internet.AppContext - -/** - * Inventory of the physical input devices attached to this box, plus the user's per-device block list. - * - * Deliberately narrow: it answers "what is plugged in" ([getConnectedDevices], [isPhysicalMouseConnected], - * [isPhysicalKeyboardConnected]) and "has the user ignored this device" ([isDeviceBlocked], [setDeviceBlocked]), - * and reports changes through [InputDevicesListener]. Everything that *acts* on those answers — the overlay - * cursor, joystick-axis D-pad translation, which [com.bansify.internet.Config.InputMode] the app is in — lives in - * the activity/overlay code and is driven by the platform's own flags. - * - * This class must never rewrite, inject or synthesize an input event: a real event reaches the WebView exactly as - * the OS reported it (AGENTS.md §3, rules 2 and 3). The "precision mouse click" synthetic mouse→touch pipeline that - * used to be advertised here is gone for good — it broke Chromium's native drag-to-select and only ever papered - * over one box's input driver. If clicks are dropped on a device, that is a platform/OEM bug, not something to - * compensate for in app code. - */ -class HardwareInputManager private constructor(private val context: Context) : InputManager.InputDeviceListener { - - companion object { - @Volatile - private var instance: HardwareInputManager? = null - - fun getInstance(context: Context): HardwareInputManager { - return instance ?: synchronized(this) { - instance ?: HardwareInputManager(context.applicationContext).also { instance = it } - } - } - } - - data class DeviceInfo( - val id: Int, - val name: String, - val descriptor: String, - val isMouse: Boolean, - val isKeyboard: Boolean, - val isGamepad: Boolean, - val isVirtual: Boolean, - val isBlocked: Boolean - ) - - interface InputDevicesListener { - fun onInputDevicesChanged(devices: List) - } - - private val inputManager = context.getSystemService(Context.INPUT_SERVICE) as InputManager - private val listeners = mutableListOf() - private val mainHandler = Handler(Looper.getMainLooper()) - - init { - try { - inputManager.registerInputDeviceListener(this, mainHandler) - } catch (e: Exception) { - e.printStackTrace() - } - } - - fun addListener(listener: InputDevicesListener) { - if (!listeners.contains(listener)) { - listeners.add(listener) - listener.onInputDevicesChanged(getConnectedDevices()) - } - } - - fun removeListener(listener: InputDevicesListener) { - listeners.remove(listener) - } - - override fun onInputDeviceAdded(deviceId: Int) { - notifyChanged() - } - - override fun onInputDeviceRemoved(deviceId: Int) { - notifyChanged() - } - - override fun onInputDeviceChanged(deviceId: Int) { - notifyChanged() - } - - fun notifyChanged() { - val currentDevices = getConnectedDevices() - for (l in listeners) { - l.onInputDevicesChanged(currentDevices) - } - } - - fun getConnectedDevices(): List { - val config = AppContext.provideConfig() - val list = mutableListOf() - val deviceIds = inputManager.inputDeviceIds - for (id in deviceIds) { - val device = inputManager.getInputDevice(id) ?: continue - val descriptor = device.descriptor.ifEmpty { "device_id_$id" } - val sources = device.sources - val isMouse = (sources and InputDevice.SOURCE_MOUSE) == InputDevice.SOURCE_MOUSE || - (sources and InputDevice.SOURCE_MOUSE_RELATIVE) == InputDevice.SOURCE_MOUSE_RELATIVE || - (sources and InputDevice.SOURCE_TRACKBALL) == InputDevice.SOURCE_TRACKBALL || - (sources and InputDevice.SOURCE_TOUCHPAD) == InputDevice.SOURCE_TOUCHPAD - - val isKeyboard = (sources and InputDevice.SOURCE_KEYBOARD) == InputDevice.SOURCE_KEYBOARD && - device.keyboardType == InputDevice.KEYBOARD_TYPE_ALPHABETIC - - val isGamepad = (sources and InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD || - (sources and InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK - - val isVirtual = device.isVirtual - val isBlocked = config.isInputDeviceBlocked(descriptor) || config.isInputDeviceBlocked(device.name) - - list.add( - DeviceInfo( - id = device.id, - name = device.name, - descriptor = descriptor, - isMouse = isMouse, - isKeyboard = isKeyboard, - isGamepad = isGamepad, - isVirtual = isVirtual, - isBlocked = isBlocked - ) - ) - } - return list - } - - fun setDeviceBlocked(deviceIdentifier: String, blocked: Boolean) { - val config = AppContext.provideConfig() - config.setInputDeviceBlocked(deviceIdentifier, blocked) - notifyChanged() - } - - fun unblockAllDevices() { - val config = AppContext.provideConfig() - config.blockedInputDeviceIds = emptySet() - notifyChanged() - } - - /** - * Checks if the device sending this InputEvent is marked as blocked by the user. - */ - fun isDeviceBlocked(event: InputEvent?): Boolean { - if (event == null) return false - val device = event.device ?: inputManager.getInputDevice(event.deviceId) ?: return false - if (device.isVirtual) return false // Never block virtual system device - val descriptor = device.descriptor.ifEmpty { "device_id_${device.id}" } - val config = AppContext.provideConfig() - return config.isInputDeviceBlocked(descriptor) || config.isInputDeviceBlocked(device.name) - } - - fun isDeviceBlocked(deviceId: Int): Boolean { - val device = inputManager.getInputDevice(deviceId) ?: return false - if (device.isVirtual) return false - val descriptor = device.descriptor.ifEmpty { "device_id_${device.id}" } - val config = AppContext.provideConfig() - return config.isInputDeviceBlocked(descriptor) || config.isInputDeviceBlocked(device.name) - } - - fun isPhysicalMouseConnected(): Boolean { - return getConnectedDevices().any { it.isMouse && !it.isVirtual } - } - - fun isPhysicalKeyboardConnected(): Boolean { - return getConnectedDevices().any { it.isKeyboard && !it.isVirtual } - } -} diff --git a/app/common/src/main/java/com/bansify/internet/utils/HardwareMousePointerManager.kt b/app/common/src/main/java/com/bansify/internet/utils/HardwareMousePointerManager.kt deleted file mode 100644 index 6b53bb83..00000000 --- a/app/common/src/main/java/com/bansify/internet/utils/HardwareMousePointerManager.kt +++ /dev/null @@ -1,369 +0,0 @@ -package com.bansify.internet.utils - -import android.content.Context -import android.graphics.Bitmap -import android.graphics.Canvas -import android.graphics.Color -import android.graphics.Paint -import android.graphics.Path -import android.os.Build -import android.view.PointerIcon -import android.view.View -import android.view.Window -import androidx.annotation.RequiresApi -import com.bansify.internet.AppContext -import com.bansify.internet.Config -import java.util.concurrent.ConcurrentHashMap - -object HardwareMousePointerManager { - - // Style constants - const val STYLE_CLASSIC_WHITE = 0 - const val STYLE_DARK_ONYX = 1 - const val STYLE_NEON_YELLOW = 2 - const val STYLE_CYAN_GLOW = 3 - const val STYLE_RED_ACCENT = 4 - - private val pointerCache = ConcurrentHashMap() - - fun invalidateCache() { - pointerCache.clear() - } - - /** - * Resolves the hardware pointer icon for a given view/hover request. - * Takes the system's requested type (e.g. arrow, hand, text) and provides - * the custom scaled and styled pointer icon if customization is enabled. - */ - fun resolvePointerIcon(context: Context, requestedIcon: PointerIcon?): PointerIcon? { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) return requestedIcon - val config = AppContext.provideConfig() - if (!config.enableHardwareMouseCustomization) return requestedIcon - - val type = extractPointerIconType(requestedIcon) - return getCustomPointerIcon(context, type, config.hardwareMouseSizePercent, config.hardwareMouseStyle) - ?: requestedIcon - } - - private fun extractPointerIconType(icon: PointerIcon?): Int { - if (icon == null) return PointerIcon.TYPE_ARROW - return try { - val method = icon.javaClass.getMethod("getType") - (method.invoke(icon) as? Int) ?: PointerIcon.TYPE_ARROW - } catch (e: Throwable) { - try { - val field = icon.javaClass.getDeclaredField("mType") - field.isAccessible = true - field.getInt(icon) - } catch (e2: Throwable) { - PointerIcon.TYPE_ARROW - } - } - } - - /** - * Gets the default arrow pointer icon with current user preferences. - */ - fun getArrowPointerIcon(context: Context): PointerIcon? { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) return null - val config = AppContext.provideConfig() - if (!config.enableHardwareMouseCustomization) return null - - return getCustomPointerIcon(context, PointerIcon.TYPE_ARROW, config.hardwareMouseSizePercent, config.hardwareMouseStyle) - } - - /** - * Applies the custom hardware mouse pointer icon to the specified View. - */ - fun applyToView(view: View) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - val icon = getArrowPointerIcon(view.context) - view.pointerIcon = icon - } - } - - /** - * Applies the custom hardware mouse pointer icon to an entire Activity Window. - */ - fun applyToWindow(window: Window) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - val decorView = window.decorView - val icon = getArrowPointerIcon(decorView.context) - decorView.pointerIcon = icon - } - } - - @RequiresApi(Build.VERSION_CODES.N) - private fun getCustomPointerIcon( - context: Context, - pointerType: Int, - sizePercent: Int, - style: Int - ): PointerIcon? { - val cacheKey = "$sizePercent-$style-$pointerType" - pointerCache[cacheKey]?.let { return it } - - val (bitmap, hotSpotX, hotSpotY) = createPointerBitmapAndHotspot( - context, - pointerType, - sizePercent, - style - ) ?: return null - - val pointerIcon = try { - PointerIcon.create(bitmap, hotSpotX, hotSpotY) - } catch (e: Exception) { - e.printStackTrace() - null - } - - if (pointerIcon != null) { - pointerCache[cacheKey] = pointerIcon - } - return pointerIcon - } - - /** - * Generates a preview bitmap suitable for display in the Settings UI. - */ - fun createPreviewBitmap( - context: Context, - sizePercent: Int, - style: Int - ): Bitmap? { - val triple = createPointerBitmapAndHotspot( - context, - PointerIcon.TYPE_ARROW, - sizePercent, - style - ) - return triple?.first - } - - private fun createPointerBitmapAndHotspot( - context: Context, - pointerType: Int, - sizePercent: Int, - style: Int - ): Triple? { - return try { - val density = context.resources.displayMetrics.density - val scale = (sizePercent.toFloat() / 100f).coerceIn(0.30f, 3.0f) - - when (pointerType) { - PointerIcon.TYPE_HAND -> createHandPointerBitmap(density, scale, style) - PointerIcon.TYPE_TEXT -> createTextPointerBitmap(density, scale, style) - else -> createArrowPointerBitmap(density, scale, style) - } - } catch (e: Exception) { - e.printStackTrace() - null - } - } - - private data class StyleColors(val fillColor: Int, val strokeColor: Int, val shadowColor: Int) - - private fun getColorsForStyle(style: Int): StyleColors { - return when (style) { - STYLE_DARK_ONYX -> StyleColors( - fillColor = Color.parseColor("#1E293B"), - strokeColor = Color.parseColor("#FFFFFF"), - shadowColor = Color.parseColor("#80000000") - ) - STYLE_NEON_YELLOW -> StyleColors( - fillColor = Color.parseColor("#FACC15"), - strokeColor = Color.parseColor("#000000"), - shadowColor = Color.parseColor("#90000000") - ) - STYLE_CYAN_GLOW -> StyleColors( - fillColor = Color.parseColor("#38BDF8"), - strokeColor = Color.parseColor("#0F172A"), - shadowColor = Color.parseColor("#90000000") - ) - STYLE_RED_ACCENT -> StyleColors( - fillColor = Color.parseColor("#EF4444"), - strokeColor = Color.parseColor("#FFFFFF"), - shadowColor = Color.parseColor("#90000000") - ) - else -> StyleColors( // Classic White - fillColor = Color.parseColor("#FFFFFF"), - strokeColor = Color.parseColor("#000000"), - shadowColor = Color.parseColor("#70000000") - ) - } - } - - private fun createArrowPointerBitmap( - density: Float, - scale: Float, - style: Int - ): Triple { - val baseW = 24f * density - val baseH = 34f * density - val width = (baseW * scale).toInt().coerceIn(16, 256) - val height = (baseH * scale).toInt().coerceIn(22, 360) - - val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) - val canvas = Canvas(bitmap) - - val strokeWidth = (2.2f * density * (scale.coerceIn(0.7f, 2.0f))).coerceIn(2.0f, 6.0f) - val strokeOffset = strokeWidth / 2f + 1f - - val colors = getColorsForStyle(style) - - val fillPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { - color = colors.fillColor - this.style = Paint.Style.FILL - } - - val strokePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { - color = colors.strokeColor - this.style = Paint.Style.STROKE - this.strokeWidth = strokeWidth - strokeJoin = Paint.Join.ROUND - strokeCap = Paint.Cap.ROUND - } - - val shadowPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { - color = colors.shadowColor - this.style = Paint.Style.STROKE - this.strokeWidth = strokeWidth + 2f - strokeJoin = Paint.Join.ROUND - strokeCap = Paint.Cap.ROUND - } - - val path = Path() - val availW = width - strokeOffset * 2 - 2f - val availH = height - strokeOffset * 2 - 2f - - path.moveTo(strokeOffset, strokeOffset) - path.lineTo(strokeOffset, strokeOffset + availH * 0.82f) - path.lineTo(strokeOffset + availW * 0.28f, strokeOffset + availH * 0.62f) - path.lineTo(strokeOffset + availW * 0.54f, strokeOffset + availH * 0.98f) - path.lineTo(strokeOffset + availW * 0.74f, strokeOffset + availH * 0.84f) - path.lineTo(strokeOffset + availW * 0.48f, strokeOffset + availH * 0.48f) - path.lineTo(strokeOffset + availW * 0.88f, strokeOffset + availH * 0.48f) - path.close() - - // Draw shadow slightly offset - canvas.save() - canvas.translate(1.5f, 1.5f) - canvas.drawPath(path, shadowPaint) - canvas.restore() - - // Draw fill and outline - canvas.drawPath(path, fillPaint) - canvas.drawPath(path, strokePaint) - - val hotSpotX = strokeOffset - val hotSpotY = strokeOffset - return Triple(bitmap, hotSpotX, hotSpotY) - } - - private fun createHandPointerBitmap( - density: Float, - scale: Float, - style: Int - ): Triple { - val baseW = 24f * density - val baseH = 32f * density - val width = (baseW * scale).toInt().coerceIn(16, 256) - val height = (baseH * scale).toInt().coerceIn(22, 360) - - val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) - val canvas = Canvas(bitmap) - - val strokeWidth = (2.0f * density * (scale.coerceIn(0.7f, 2.0f))).coerceIn(2.0f, 5.5f) - val strokeOffset = strokeWidth / 2f + 1f - - val colors = getColorsForStyle(style) - - val fillPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { - color = colors.fillColor - this.style = Paint.Style.FILL - } - - val strokePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { - color = colors.strokeColor - this.style = Paint.Style.STROKE - this.strokeWidth = strokeWidth - strokeJoin = Paint.Join.ROUND - strokeCap = Paint.Cap.ROUND - } - - val path = Path() - val availW = width - strokeOffset * 2 - 2f - val availH = height - strokeOffset * 2 - 2f - - // Pointing hand: index finger pointing up-left - path.moveTo(strokeOffset + availW * 0.32f, strokeOffset) - path.lineTo(strokeOffset + availW * 0.48f, strokeOffset) - path.lineTo(strokeOffset + availW * 0.48f, strokeOffset + availH * 0.42f) - path.lineTo(strokeOffset + availW * 0.62f, strokeOffset + availH * 0.42f) - path.lineTo(strokeOffset + availW * 0.62f, strokeOffset + availH * 0.52f) - path.lineTo(strokeOffset + availW * 0.76f, strokeOffset + availH * 0.52f) - path.lineTo(strokeOffset + availW * 0.76f, strokeOffset + availH * 0.64f) - path.lineTo(strokeOffset + availW * 0.88f, strokeOffset + availH * 0.64f) - path.lineTo(strokeOffset + availW * 0.88f, strokeOffset + availH * 0.90f) - path.lineTo(strokeOffset + availW * 0.20f, strokeOffset + availH * 0.90f) - path.lineTo(strokeOffset, strokeOffset + availH * 0.62f) - path.lineTo(strokeOffset + availW * 0.16f, strokeOffset + availH * 0.46f) - path.lineTo(strokeOffset + availW * 0.32f, strokeOffset + availH * 0.56f) - path.close() - - canvas.drawPath(path, fillPaint) - canvas.drawPath(path, strokePaint) - - val hotSpotX = strokeOffset + availW * 0.40f - val hotSpotY = strokeOffset - return Triple(bitmap, hotSpotX, hotSpotY) - } - - private fun createTextPointerBitmap( - density: Float, - scale: Float, - style: Int - ): Triple { - val baseW = 16f * density - val baseH = 28f * density - val width = (baseW * scale).toInt().coerceIn(14, 200) - val height = (baseH * scale).toInt().coerceIn(20, 320) - - val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) - val canvas = Canvas(bitmap) - - val strokeWidth = (2.2f * density * (scale.coerceIn(0.7f, 2.0f))).coerceIn(2.0f, 5.0f) - val colors = getColorsForStyle(style) - - val strokePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { - color = colors.fillColor - this.style = Paint.Style.STROKE - this.strokeWidth = strokeWidth - strokeCap = Paint.Cap.ROUND - } - - val outlinePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { - color = colors.strokeColor - this.style = Paint.Style.STROKE - this.strokeWidth = strokeWidth + 2f - strokeCap = Paint.Cap.ROUND - } - - val centerX = width / 2f - val pad = strokeWidth + 2f - - // I-beam shape - fun drawIBeam(p: Paint) { - canvas.drawLine(pad, pad, width - pad, pad, p) // top bar - canvas.drawLine(centerX, pad, centerX, height - pad, p) // vertical center - canvas.drawLine(pad, height - pad, width - pad, height - pad, p) // bottom bar - } - - drawIBeam(outlinePaint) - drawIBeam(strokePaint) - - val hotSpotX = centerX - val hotSpotY = height / 2f - return Triple(bitmap, hotSpotX, hotSpotY) - } -} diff --git a/app/common/src/main/java/com/bansify/internet/utils/NavigationReservedShortcutKeyCodes.kt b/app/common/src/main/java/com/bansify/internet/utils/NavigationReservedShortcutKeyCodes.kt deleted file mode 100644 index 299f3286..00000000 --- a/app/common/src/main/java/com/bansify/internet/utils/NavigationReservedShortcutKeyCodes.kt +++ /dev/null @@ -1,32 +0,0 @@ -package com.bansify.internet.utils - -import android.view.KeyEvent - -/** - * Keys consumed by [DPADNavigationEventsAdapter] and [BackNavigationEventsAdapter]. - * User-configurable shortcuts must not use these codes. - */ -object NavigationReservedShortcutKeyCodes { - val dpadNavigationKeys: Set = intArrayOf( - KeyEvent.KEYCODE_DPAD_LEFT, - KeyEvent.KEYCODE_DPAD_RIGHT, - KeyEvent.KEYCODE_DPAD_UP, - KeyEvent.KEYCODE_DPAD_DOWN, - KeyEvent.KEYCODE_DPAD_UP_LEFT, - KeyEvent.KEYCODE_DPAD_UP_RIGHT, - KeyEvent.KEYCODE_DPAD_DOWN_LEFT, - KeyEvent.KEYCODE_DPAD_DOWN_RIGHT, - KeyEvent.KEYCODE_DPAD_CENTER, - KeyEvent.KEYCODE_ENTER, - KeyEvent.KEYCODE_NUMPAD_ENTER, - KeyEvent.KEYCODE_BUTTON_A - ).toHashSet() - - val backNavigationKeys: Set = intArrayOf( - KeyEvent.KEYCODE_BACK, - KeyEvent.KEYCODE_BUTTON_B, - KeyEvent.KEYCODE_ESCAPE - ).toHashSet() - - val reservedForUserShortcuts: Set = dpadNavigationKeys + backNavigationKeys -} diff --git a/app/common/src/main/java/com/bansify/internet/utils/Utils.kt b/app/common/src/main/java/com/bansify/internet/utils/Utils.kt deleted file mode 100644 index 5ea22758..00000000 --- a/app/common/src/main/java/com/bansify/internet/utils/Utils.kt +++ /dev/null @@ -1,356 +0,0 @@ -package com.bansify.internet.utils - -import android.annotation.SuppressLint -import android.app.ActivityManager -import android.app.ActivityManager.RunningAppProcessInfo -import android.app.UiModeManager -import android.content.Context -import android.content.res.Configuration -import android.graphics.Point -import android.net.ConnectivityManager -import android.net.NetworkCapabilities -import android.os.Build -import android.os.Bundle -import android.os.Parcel -import android.view.WindowManager -import android.webkit.WebResourceResponse -import android.widget.Toast -import org.json.JSONArray -import org.json.JSONException -import org.json.JSONObject -import java.io.BufferedInputStream -import java.io.File -import java.io.FileInputStream -import java.io.FileOutputStream -import java.io.IOException -import java.math.BigInteger -import java.net.URLConnection -import java.security.MessageDigest -import java.security.NoSuchAlgorithmException -import java.util.* -import java.util.zip.ZipEntry -import java.util.zip.ZipInputStream - - -object Utils { - - /** - * Returns the screen/display size - */ - fun getDisplaySize(context: Context): Point { - val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager - val display = wm.defaultDisplay - val size = Point() - display.getSize(size) - return size - } - - /** - * Shows a (long) toast - */ - fun showToast(context: Context, msg: String) { - Toast.makeText(context, msg, Toast.LENGTH_LONG).show() - } - - /** - * Shows a (long) toast. - */ - fun showToast(context: Context, resourceId: Int) { - Toast.makeText(context, context.getString(resourceId), Toast.LENGTH_LONG).show() - } - - fun D2P(ctx: Context, dp: Float): Float { - val density = ctx.resources.displayMetrics.density - return dp * density - } - - /** - * Formats time in milliseconds to hh:mm:ss string format. - */ - fun formatMillis(millis: Int): String { - var millis = millis - var result = "" - val hr = millis / 3600000 - millis %= 3600000 - val min = millis / 60000 - millis %= 60000 - val sec = millis / 1000 - if (hr > 0) { - result += hr.toString() + ":" - } - if (min >= 0) { - if (min > 9) { - result += min.toString() + ":" - } else { - result += "0$min:" - } - } - if (sec > 9) { - result += sec - } else { - result += "0$sec" - } - return result - } - - fun MD5_Hash(bytes: ByteArray): String? { - try { - val m = MessageDigest.getInstance("MD5") - m.update(bytes, 0, bytes.size) - return BigInteger(1, m.digest()).toString(16) - } catch (e: NoSuchAlgorithmException) { - e.printStackTrace() - } - - return null - } - - @SuppressLint("MissingPermission") - fun isNetworkConnected(context: Context): Boolean { - return try { - val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager ?: return true - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - val network = cm.activeNetwork ?: return false - val capabilities = cm.getNetworkCapabilities(network) ?: return false - capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) - } else { - @Suppress("DEPRECATION") - val activeNetwork = cm.activeNetworkInfo - activeNetwork != null && activeNetwork.isConnectedOrConnecting - } - } catch (e: Exception) { - true - } - } - - fun isSameDate(date: Long, other: Long): Boolean { - if (other == -1L) return false - val c1 = Calendar.getInstance() - c1.timeInMillis = date - val c2 = Calendar.getInstance() - c2.timeInMillis = other - return c1.get(Calendar.DAY_OF_YEAR) == c2.get(Calendar.DAY_OF_YEAR) && c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) - } - - fun createTempFile(context: Context, fileName: String): File { - val externalCacheDir = context.externalCacheDir - val internalCacheDir = context.cacheDir - val cacheDir: File - if (externalCacheDir == null && internalCacheDir == null) { - throw Exception("No cache directory available") - } - if (externalCacheDir == null) { - cacheDir = internalCacheDir - } else if (internalCacheDir == null) { - cacheDir = externalCacheDir - } else { - cacheDir = if (externalCacheDir.freeSpace > internalCacheDir.freeSpace) - externalCacheDir - else - internalCacheDir - } - return File(cacheDir, fileName) - } - - fun isTV(context: Context): Boolean { - val uiModeManager = context.getSystemService(Context.UI_MODE_SERVICE) as UiModeManager - return uiModeManager.currentModeType == Configuration.UI_MODE_TYPE_TELEVISION - } - - fun isFireTV(context: Context): Boolean { - return context.packageManager.hasSystemFeature("amazon.hardware.fire_tv") - } - - fun isInstalledByGooglePlay(context: Context): Boolean { - // A list with valid installers package name - val validInstallers = ArrayList(Arrays.asList("com.android.vending", "com.google.android.feedback")) - val installer = context.packageManager.getInstallerPackageName(context.packageName) - return installer != null && validInstallers.contains(installer) - } - - fun isInstalledByAPK(context: Context): Boolean { - val installer = context.packageManager.getInstallerPackageName(context.packageName) - return installer == null || "com.google.android.packageinstaller".equals(installer) - } - - fun convertJsonToBundle(json: JSONObject): Bundle? { - val bundle = Bundle() - try { - val iterator = json.keys() - loop@ while (iterator.hasNext()) { - val key = iterator.next() as String - val value = json[key] - when (value.javaClass.simpleName) { - "String" -> bundle.putString(key, value as String) - "Integer" -> bundle.putInt(key, (value as Int)) - "Long" -> bundle.putLong(key, (value as Long)) - "Boolean" -> bundle.putBoolean(key, (value as Boolean)) - "JSONObject" -> bundle.putBundle(key, convertJsonToBundle(value as JSONObject)) - "Float" -> bundle.putFloat(key, (value as Float)) - "Double" -> bundle.putDouble(key, (value as Double)) - "JSONArray" -> { - val jsArr = value as JSONArray - if (jsArr.length() == 0) continue@loop - val first = jsArr.get(0) - when (first.javaClass.simpleName) { - "String" -> bundle.putStringArray(key, Array(jsArr.length()) { - jsArr.getString(it) - }) - //IntArray is more suitable but in our case (storing webview state) we need bytes - "Integer" -> bundle.putByteArray(key, ByteArray(jsArr.length()) { - jsArr.getInt(it).toByte() - }) - "Long" -> bundle.putLongArray(key, LongArray(jsArr.length()) { - jsArr.getLong(it) - }) - "Boolean" -> bundle.putBooleanArray(key, BooleanArray(jsArr.length()) { - jsArr.getBoolean(it) - }) - "Float" -> bundle.putFloatArray(key, FloatArray(jsArr.length()) { - jsArr.getDouble(it).toFloat() - }) - "Double" -> bundle.putDoubleArray(key, DoubleArray(jsArr.length()) { - jsArr.getDouble(it) - }) - } - } - else -> bundle.putString(key, value.javaClass.simpleName) - } - } - return bundle - } catch (e: JSONException) { - e.printStackTrace() - return null - } - } - - fun bundleToBytes(bundle: Bundle): ByteArray? { - val parcel = Parcel.obtain() - parcel.writeBundle(bundle) - val bytes = parcel.marshall() - parcel.recycle() - return bytes - } - - fun bytesToBundle(bytes: ByteArray): Bundle? { - return try { - val parcel = Parcel.obtain() - parcel.unmarshall(bytes, 0, bytes.size) - parcel.setDataPosition(0) - val bundle = parcel.readBundle(Utils::class.java.classLoader) - parcel.recycle() - bundle!! - } catch (e: Exception) { - null - } - } - - fun unzipFile(zipFile: File, targetDirectory: File, progress: (progress: Int, fileName: String) -> Unit) { - val totalLen = zipFile.length() - var alreadyUncompressed: Long = 0 - val zis = ZipInputStream(BufferedInputStream(FileInputStream(zipFile))) - try { - var ze: ZipEntry? - var count: Int - val buffer = ByteArray(1024) - while (true) { - ze = zis.nextEntry - if (ze == null) break - val file = File(targetDirectory, ze.name) - val canonicalPath = file.canonicalPath - if (!canonicalPath.startsWith(targetDirectory.canonicalPath)) { - throw SecurityException("Zip Path Traversal attack!") - } - val dir = if (ze.isDirectory) file else file.parentFile - if (!dir.isDirectory && !dir.mkdirs()) throw FileSystemException(dir, null, "Failed to ensure directory: " + dir.absolutePath) - if (ze.isDirectory) continue - var readen = 0 - FileOutputStream(file).use { - while (zis.read(buffer).also { count = it } != -1) { - it.write(buffer, 0, count) - if (ze.size > 0) { - readen += count - val entryPercents = readen * ze.compressedSize * 100 / (ze.size * totalLen) - val percent = (alreadyUncompressed * 100 / totalLen + entryPercents).toInt() - progress(percent, ze.name) - } - } - } - - alreadyUncompressed += ze.compressedSize - val percent = (alreadyUncompressed * 100 / totalLen).toInt() - progress(percent, ze.name) - - // if time should be restored as well - val time: Long = ze.time - if (time > 0) file.setLastModified(time) - } - } finally { - zis.close() - } - } - - fun isForeground(): Boolean { - val appProcessInfo = RunningAppProcessInfo() - ActivityManager.getMyMemoryState(appProcessInfo) - return (appProcessInfo.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND - || appProcessInfo.importance == RunningAppProcessInfo.IMPORTANCE_VISIBLE) - } - - fun memInfo(ctx: Context): ActivityManager.MemoryInfo { - val actManager = ctx.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager - val memInfo = ActivityManager.MemoryInfo() - actManager.getMemoryInfo(memInfo) - return memInfo - } - - fun jsonToMap(json: String): Map { - val map: MutableMap = HashMap() - try { - val jsonObject = JSONObject(json) - val keysItr = jsonObject.keys() - while (keysItr.hasNext()) { - val key = keysItr.next() - var value = jsonObject[key] - if (value is JSONArray) { - value = jsonToList(value.toString()) - } else if (value is JSONObject) { - value = jsonToMap(value.toString()) - } - map[key] = value - } - } catch (e: JSONException) { - e.printStackTrace() - } - return map - } - - private fun jsonToList(string: String): List { - val list: MutableList = ArrayList() - try { - val jsonArray = JSONArray(string) - for (i in 0 until jsonArray.length()) { - var value = jsonArray[i] - if (value is JSONArray) { - value = jsonToList(value.toString()) - } else if (value is JSONObject) { - value = jsonToMap(value.toString()) - } - list.add(value) - } - } catch (e: JSONException) { - e.printStackTrace() - } - return list - } - - fun getWebResourceResponseFromAssets(context: Context, path: String): WebResourceResponse? { - return try { - val inputStream = context.assets.open(path) - val mimeType = URLConnection.guessContentTypeFromName(path) ?: "application/octet-stream" - WebResourceResponse(mimeType, "UTF-8", inputStream) - } catch (e: IOException) { - null - } - } -} diff --git a/app/common/src/main/java/com/bansify/internet/utils/activemodel/ActiveModel.kt b/app/common/src/main/java/com/bansify/internet/utils/activemodel/ActiveModel.kt deleted file mode 100644 index a7bc8978..00000000 --- a/app/common/src/main/java/com/bansify/internet/utils/activemodel/ActiveModel.kt +++ /dev/null @@ -1,42 +0,0 @@ -package com.bansify.internet.utils.activemodel - -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.cancel - -/** - * This class is like ViewModel from Jetpack but better =) - * It can be used not only with activities and Fragments, but also for example - * with Services or other Active models (but with manual marking as Needless - - * @see com.bansify.internet.utils.statemodel.ActiveModelsRepository#markAsNeedless()). - * This also will survive not only configuration changes but also Activity switching - - * If you go from one Activity to another and they both accessing the same ActiveModel - * class then actually they will access the same object what can be good for performance. - * - * This named Active Model because I believe that making entire View data models - * (a.k.a. ViewModels) is not a really good pattern. This lead to data duplication if - * different views accessing the same data states and this lead to look at View as main - * logic part of application. Instead I propose to make an new kind of models what will - * incorporate smaller models, their states and domain actions on them. I see this - * more memory/performance effective and also more natural because in this case main - * logic block of application becomes domain data and actions on it. - */ -abstract class ActiveModel { - private var _modelScope: CoroutineScope? = null - val modelScope: CoroutineScope - get() { - return _modelScope ?: kotlin.run { - val newScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) - _modelScope = newScope - return newScope - } - } - - final fun clear() { - _modelScope?.cancel() - onClear() - } - - open fun onClear() {} -} \ No newline at end of file diff --git a/app/common/src/main/java/com/bansify/internet/utils/activemodel/ActiveModelsRepository.kt b/app/common/src/main/java/com/bansify/internet/utils/activemodel/ActiveModelsRepository.kt deleted file mode 100644 index aed791bf..00000000 --- a/app/common/src/main/java/com/bansify/internet/utils/activemodel/ActiveModelsRepository.kt +++ /dev/null @@ -1,92 +0,0 @@ -package com.bansify.internet.utils.activemodel - -import android.app.Activity -import android.app.Application -import android.os.Bundle -import androidx.annotation.MainThread -import kotlin.reflect.KClass - -object ActiveModelsRepository { - private val holdersMap = HashMap() - - private class StateModelHolder(val activeModel: ActiveModel) { - val users = ArrayList() - } - - private val activityLifecycleCallbacks = object: Application.ActivityLifecycleCallbacks { - override fun onActivityCreated(p0: Activity, p1: Bundle?) { - } - - override fun onActivityStarted(p0: Activity) { - } - - override fun onActivityResumed(p0: Activity) { - } - - override fun onActivityPaused(p0: Activity) { - } - - override fun onActivityStopped(p0: Activity) { - } - - override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) { - } - - override fun onActivityDestroyed(activity: Activity) { - if (activity.isFinishing) { - markAsNeedlessAllModelsUsedBy(activity) - } - } - } - - fun init(app: Application){ - app.registerActivityLifecycleCallbacks(activityLifecycleCallbacks) - } - - /** - * Get active model from repository. If your user is not Activity then make sure that you manually marked as needless - * (@see com.bansify.internet.utils.statemodel.ActiveModelsRepository#markAsNeedless()) - * all your "active models" when they are not needed (on your component onDestroy(), clear(), finalize() or similar) - */ - @Suppress("UNCHECKED_CAST") - @MainThread - fun get(clazz: KClass, user: Any): T { - val className = clazz.qualifiedName ?: throw IllegalStateException("clazz should have name!") - var modelHolder: StateModelHolder? = holdersMap[className] - if (modelHolder == null) { - modelHolder = StateModelHolder(clazz.java.constructors.first().newInstance() as ActiveModel) - holdersMap[className] = modelHolder - } - if (!modelHolder.users.contains(user)) { - modelHolder.users.add(user) - } - return modelHolder.activeModel as T - } - - @MainThread - fun markAsNeedless(activeModelUsed: ActiveModel, byUser: Any) { - val key = activeModelUsed::class.qualifiedName - holdersMap[key]?.let { - if (it.users.remove(byUser)) { - if (it.users.isEmpty()) { - holdersMap.remove(key) - it.activeModel.clear() - } - } - } - } - - @MainThread - fun markAsNeedlessAllModelsUsedBy(user: Any) { - val iterator = holdersMap.iterator() - while (iterator.hasNext()) { - val kv = iterator.next() - if (kv.value.users.remove(user)) { - if (kv.value.users.isEmpty()) { - iterator.remove() - kv.value.activeModel.clear() - } - } - } - } -} \ No newline at end of file diff --git a/app/common/src/main/java/com/bansify/internet/utils/observable/ObservableList.kt b/app/common/src/main/java/com/bansify/internet/utils/observable/ObservableList.kt deleted file mode 100644 index 1d58d1c9..00000000 --- a/app/common/src/main/java/com/bansify/internet/utils/observable/ObservableList.kt +++ /dev/null @@ -1,116 +0,0 @@ -package com.bansify.internet.utils.observable - -import android.os.Build.VERSION_CODES -import androidx.annotation.RequiresApi -import java.util.* -import java.util.function.Predicate -import java.util.function.UnaryOperator -import kotlin.collections.ArrayList - -typealias ListChangeObserver = (ObservableList) -> Unit - -class ObservableList(): ArrayList(), Subscribable> { - override val observers = ArrayList>() - - private fun notifyChanged() { - notifyObservers() - } - - override fun notifyObservers() { - for (observer in observers) { - observer(this) - } - } - - override fun notifyObserver(observer: ListChangeObserver) { - observer(this) - } - - override fun add(element: T): Boolean { - val result = super.add(element) - notifyChanged() - return result - } - - override fun add(index: Int, element: T) { - super.add(index, element) - notifyChanged() - } - - override fun addAll(elements: Collection): Boolean { - val result = super.addAll(elements) - notifyChanged() - return result - } - - override fun addAll(index: Int, elements: Collection): Boolean { - val result = super.addAll(index, elements) - notifyChanged() - return result - } - - override fun clear() { - super.clear() - notifyChanged() - } - - override fun remove(element: T): Boolean { - val result = super.remove(element) - notifyChanged() - return result - } - - override fun removeAll(elements: Collection): Boolean { - val result = super.removeAll(elements) - notifyChanged() - return result - } - - override fun retainAll(elements: Collection): Boolean { - val result = super.retainAll(elements) - notifyChanged() - return result - } - - @RequiresApi(VERSION_CODES.N) - override fun removeIf(filter: Predicate): Boolean { - val result = super.removeIf(filter) - notifyChanged() - return result - } - - override fun removeAt(index: Int): T { - val result = super.removeAt(index) - notifyChanged() - return result - } - - override fun set(index: Int, element: T): T { - val result = super.set(index, element) - notifyChanged() - return result - } - - @RequiresApi(VERSION_CODES.N) - override fun replaceAll(operator: UnaryOperator) { - super.replaceAll(operator) - notifyChanged() - } - - override fun removeRange(fromIndex: Int, toIndex: Int) { - super.removeRange(fromIndex, toIndex) - notifyChanged() - } - - fun swap(i: Int, j: Int) { - super.set(i, super.set(j, super.get(i))) - notifyChanged() - } - - fun replaceAll(elements: Collection): Boolean { - super.clear() - val result = super.addAll(elements) - notifyChanged() - return result - } -} \ No newline at end of file diff --git a/app/common/src/main/java/com/bansify/internet/utils/observable/SimpleObservable.kt b/app/common/src/main/java/com/bansify/internet/utils/observable/SimpleObservable.kt deleted file mode 100644 index bcd06d8e..00000000 --- a/app/common/src/main/java/com/bansify/internet/utils/observable/SimpleObservable.kt +++ /dev/null @@ -1,160 +0,0 @@ -package com.bansify.internet.utils.observable - -import androidx.lifecycle.Lifecycle -import androidx.lifecycle.LifecycleEventObserver -import androidx.lifecycle.LifecycleOwner -import kotlin.reflect.KProperty - -/** - * Just simple and more convenient replacement of java.util.Observable/Observer - * to implement observer pattern - */ - -interface Subscribable { - val observers: ArrayList - fun subscribe(observer: O, notifyOnSubscribe: Boolean = true) { - if (!observers.contains(observer)) { - observers.add(observer) - if (notifyOnSubscribe) { - notifyObserver(observer) - } - } - } - - fun subscribe(lifecycleOwner: LifecycleOwner, observer: O) { - subscribe(lifecycleOwner.lifecycle, true, observer) - } - - fun subscribe(lifecycleOwner: LifecycleOwner, notifyOnSubscribe: Boolean = true, observer: O) { - subscribe(lifecycleOwner.lifecycle, notifyOnSubscribe, observer) - } - - fun subscribe(lifecycle: Lifecycle, observer: O) { - subscribe(lifecycle, true, observer) - } - - fun subscribe(lifecycle: Lifecycle, notifyOnSubscribe: Boolean = true, observer: O) { - /*if (lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) { - subscribe(observer, notifyOnSubscribe) - }*/ - - lifecycle.addObserver(object : LifecycleEventObserver { - override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) { - when (source.lifecycle.currentState) { - Lifecycle.State.INITIALIZED, Lifecycle.State.CREATED -> { - unsubscribe(observer) - } - Lifecycle.State.RESUMED -> { - subscribe(observer, notifyOnSubscribe) - } - Lifecycle.State.STARTED -> { - unsubscribe(observer) - } - Lifecycle.State.DESTROYED -> { - lifecycle.removeObserver(this) - unsubscribe(observer) - } - } - } - }) - } - - fun unsubscribe(observer: O) { - observers.remove(observer) - } - - fun notifyObservers() { - for (observer in observers) { - notifyObserver(observer) - } - } - - fun notifyObserver(observer: O) -} - -typealias ValueObserver = (value: T) -> Unit - -open class ObservableValue(default: T) : Subscribable> { - open var value: T = default - set(value) { - field = value - notifyObservers() - } - - override val observers = ArrayList>() - - override fun notifyObservers() { - //observers can be removed during iteration - for (i in observers.size - 1 downTo 0) { - observers[i](value) - } - } - - override fun notifyObserver(observer: ValueObserver) { - observer(value) - } - - operator fun getValue(thisRef: Any, prop: KProperty<*>): T = this.value - operator fun setValue(thisRef: Any, prop: KProperty<*>, value: T) {this.value = value} -} - -/*fun makeObservable(property: KMutableProperty): ObservableValue { - return object : ObservableValue(property.getter.call()) { - override var value: T = property.getter.call() - set(value) { - property.setter.call(value) - field = value - notifyObservers() - } - get() = property.getter.call() - } -}*/ - -typealias EventObserver = () -> Unit - -class EventSource: Subscribable { - override val observers = ArrayList() - - var wasEmitted: Boolean = false - - fun emit() { - wasEmitted = true - notifyObservers() - } - - override fun notifyObservers() { - if (!wasEmitted) return - for (i in observers.size - 1 downTo 0) { - observers[i]() - } - } - - override fun notifyObserver(observer: EventObserver) { - if (!wasEmitted) return - observer() - } -} - -typealias ParameterizedEventObserver = (T) -> Unit - -class ParameterizedEventSource: Subscribable> { - override val observers = ArrayList>() - var lastEvent: T? = null - - fun emit(event: T) { - lastEvent = event - notifyObservers() - } - - override fun notifyObservers() { - val event = lastEvent ?: return - for (i in observers.size - 1 downTo 0) { - observers[i](event) - } - } - - override fun notifyObserver(observer: ParameterizedEventObserver) { - val event = lastEvent ?: return - observer(event) - } -} \ No newline at end of file diff --git a/app/common/src/main/java/com/bansify/internet/webengine/WebEngine.kt b/app/common/src/main/java/com/bansify/internet/webengine/WebEngine.kt deleted file mode 100644 index bb4273f2..00000000 --- a/app/common/src/main/java/com/bansify/internet/webengine/WebEngine.kt +++ /dev/null @@ -1,63 +0,0 @@ -package com.bansify.internet.webengine - -import android.content.Context -import android.content.Intent -import android.graphics.Bitmap -import android.view.View -import android.view.ViewGroup -import com.bansify.internet.widgets.cursor.CursorDrawerDelegate - -interface WebEngine { - val url: String? - var userAgentString: String? - - /** - * Resolved per-tab desktop-mode state (see `activity.main.DesktopMode`). Engines that cannot - * change their UA at runtime keep the default no-op and simply reload the page instead. - */ - fun setDesktopModeOverride(enabled: Boolean?) {} - - fun getWebEngineName(): String - fun saveState(): Any?//Bundle or any Object convertible to string - fun restoreState(savedInstanceState: Any) - fun stateFromBytes(bytes: ByteArray): Any? - fun loadUrl(url: String) - fun canGoForward(): Boolean - fun goForward() - fun canZoomIn(): Boolean - fun zoomIn() - fun canZoomOut(): Boolean - fun zoomOut() - fun zoomBy(zoomBy: Float) - fun setPageZoom(percent: Int) - fun evaluateJavascript(script: String) - fun setNetworkAvailable(connected: Boolean) - fun getView(): View? - @Throws(Exception::class) - fun getOrCreateView(activityContext: Context): View - fun canGoBack(): Boolean - fun goBack() - fun clearHistory() - fun reload() - fun onFilePicked(resultCode: Int, data: Intent?) - fun onResume() - fun onPause() - fun onUpdateAdblockSetting(newState: Boolean) - fun hideFullscreenView() - fun togglePlayback() - suspend fun renderThumbnail(bitmap: Bitmap?): Bitmap? - /** - * At this point of time web view should be already created but not attached to window - */ - fun onAttachToWindow(callback: WebEngineWindowProviderCallback, parent: ViewGroup) - fun onDetachFromWindow(completely: Boolean, destroyTab: Boolean) - fun trimMemory() - fun onPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray): Boolean - fun isSameSession(internalRepresentation: Any): Boolean - fun stopPlayback() - fun rewind() - fun fastForward() - fun setVirtualCursorMode(enabled: Boolean) - fun isVirtualCursorMode(): Boolean - fun getCursorDrawerDelegate(): CursorDrawerDelegate? -} \ No newline at end of file diff --git a/app/common/src/main/java/com/bansify/internet/webengine/WebEngineFactory.kt b/app/common/src/main/java/com/bansify/internet/webengine/WebEngineFactory.kt deleted file mode 100644 index 9ea39229..00000000 --- a/app/common/src/main/java/com/bansify/internet/webengine/WebEngineFactory.kt +++ /dev/null @@ -1,75 +0,0 @@ -package com.bansify.internet.webengine - -import android.content.Context -import android.util.Log -import androidx.annotation.UiThread -import com.bansify.internet.AppContext -import com.bansify.internet.Config -import com.bansify.internet.model.WebTabState -import com.bansify.internet.widgets.cursor.CursorLayout - -interface WebEngineProviderCallback { - suspend fun initialize(context: Context, webViewContainer: CursorLayout) - fun createWebEngine(tab: WebTabState): WebEngine - suspend fun clearCache(ctx: Context) - fun onThemeSettingUpdated(value: Config.Theme) - fun getWebEngineVersionString(): String -} - -data class WebEngineProvider( - val name: String, - val callback: WebEngineProviderCallback -) - - - -object WebEngineFactory { - const val TAG = "WebEngineFactory" - private val engineProviders = mutableListOf() - private lateinit var initializedProvider: WebEngineProvider - - fun registerProvider(provider: WebEngineProvider) { - engineProviders.add(provider) - } - - fun getProviders(): List { - return engineProviders - } - - @UiThread - suspend fun initialize(context: Context, webViewContainer: CursorLayout) { - val config = AppContext.provideConfig() - var webEngineProvider = engineProviders.find { it.name == config.webEngine } - if (webEngineProvider == null && engineProviders.isNotEmpty()) { - webEngineProvider = engineProviders[0] - Log.w(TAG, "WebEngineProvider with name ${config.webEngine} not found, using ${webEngineProvider.name}") - config.webEngine = webEngineProvider.name - } - if (webEngineProvider != null) { - webEngineProvider.callback.initialize(context, webViewContainer) - initializedProvider = webEngineProvider - } else { - throw IllegalArgumentException("WebEngineProvider with name ${config.webEngine} not found") - } - } - - fun createWebEngine(tab: WebTabState): WebEngine { - return initializedProvider.callback.createWebEngine(tab) - } - - suspend fun clearCache(ctx: Context) { - initializedProvider.callback.clearCache(ctx) - } - - fun onThemeSettingUpdated(value: Config.Theme) { - initializedProvider.callback.onThemeSettingUpdated(value) - } - - fun getWebEngineVersionString(): String { - return initializedProvider.callback.getWebEngineVersionString() - } -} - -fun WebEngine.isGecko(): Boolean { - return false -} \ No newline at end of file diff --git a/app/common/src/main/java/com/bansify/internet/webengine/WebEngineWindowProviderCallback.kt b/app/common/src/main/java/com/bansify/internet/webengine/WebEngineWindowProviderCallback.kt deleted file mode 100644 index aadde2ce..00000000 --- a/app/common/src/main/java/com/bansify/internet/webengine/WebEngineWindowProviderCallback.kt +++ /dev/null @@ -1,58 +0,0 @@ -package com.bansify.internet.webengine - -import android.app.Activity -import android.content.Intent -import android.graphics.Bitmap -import android.net.Uri -import android.view.View -import com.bansify.internet.model.Download -import com.bansify.internet.model.HomePageLink -import com.bansify.internet.widgets.cursor.CursorDrawerDelegate -import java.io.InputStream - -interface WebEngineWindowProviderCallback { - fun getActivity(): Activity - fun onOpenInNewTabRequested(url: String, navigateImmediately: Boolean): WebEngine? - fun onDownloadRequested(url: String) - fun onDownloadRequested(url: String, referer: String, originalDownloadFileName: String?, userAgent: String?, mimeType: String?, - operationAfterDownload: Download.OperationAfterDownload = Download.OperationAfterDownload.NOP, - base64BlobData: String? = null, stream: InputStream? = null, size: Long = 0L, contentDisposition: String? = null) - fun onDownloadRequested(url: String, userAgent: String?, contentDisposition: String, mimetype: String?, contentLength: Long) - fun onProgressChanged(newProgress: Int) - fun onReceivedTitle(title: String) - fun requestPermissions(array: Array): Int - fun onShowFileChooser(intent: Intent): Boolean - fun onReceivedIcon(icon: Bitmap) - fun shouldOverrideUrlLoading(url: String): Boolean - fun onPageStarted(url: String?) - fun onPageFinished(url: String?) - fun onPageCertificateError(url: String?) - fun isAd(url: Uri, acceptHeader: String?, baseUri: Uri): Boolean? - fun isAdBlockingEnabled(): Boolean - fun isDialogsBlockingEnabled(): Boolean - fun shouldBlockNewWindow(dialog: Boolean, userGesture: Boolean): Boolean - fun onBlockedAd(uri: String) - fun onBlockedDialog(newTab: Boolean) - fun onCreateWindow(dialog: Boolean, userGesture: Boolean): View? - fun closeWindow(internalRepresentation: Any) - fun onScaleChanged(oldScale: Float, newScale: Float) - fun onCopyTextToClipboardRequested(url: String) - fun onShareUrlRequested(url: String) - fun onOpenInExternalAppRequested(url: String) - fun initiateVoiceSearch() - fun onEditHomePageBookmarkSelected(index: Int) - fun getHomePageLinks(): List - fun onPrepareForFullscreen() - fun onExitFullscreen() - fun onVisited(url: String) - fun suggestActionsForLink(baseUri: String?, linkUri: String?, srcUri: String?, - title: String?, altText: String?, textContent: String?, - x: Int, y: Int) - fun markBookmarkRecommendationAsUseful(bookmarkOrder: Int) - fun onContextMenu( - cursorDrawer: CursorDrawerDelegate, baseUri: String?, linkUri: String?, srcUri: String?, - title: String?, altText: String?, - textContent: String?, x: Int, y: Int - ) - fun onScrollChange(scrollY: Int, oldScrollY: Int, dy: Int) {} -} \ No newline at end of file diff --git a/app/common/src/main/java/com/bansify/internet/widgets/cursor/CursorDrawerDelegate.kt b/app/common/src/main/java/com/bansify/internet/widgets/cursor/CursorDrawerDelegate.kt deleted file mode 100644 index 978706eb..00000000 --- a/app/common/src/main/java/com/bansify/internet/widgets/cursor/CursorDrawerDelegate.kt +++ /dev/null @@ -1,767 +0,0 @@ -package com.bansify.internet.widgets.cursor - -import android.animation.ValueAnimator -import android.content.Context -import android.graphics.Canvas -import android.graphics.Color -import android.graphics.Paint -import android.graphics.Point -import android.graphics.PointF -import android.graphics.Rect -import android.os.Handler -import android.os.Looper -import android.os.SystemClock -import android.util.Log -import android.view.KeyEvent -import android.view.MotionEvent -import android.view.View -import android.view.ViewConfiguration -import android.view.WindowManager -import com.bansify.internet.AppContext -import com.bansify.internet.Config -import com.bansify.internet.utils.Utils - -class CursorDrawerDelegate(val context: Context, val surface: View) { - private var cursorRadius: Int = 0 - private var cursorRadiusPressed: Int = 0 - private var cursorRadiusAnimationMultiplier: Float = 1f - /** Pixels/sec cap baseline from display width (see [init]); scaled by [Config.cursorMaxSpeedPercent]. */ - private var maxSpeedBaselinePx: Float = 0f - private var scrollStartPadding = 100 - private var cursorStrokeWidth: Float = 0f - private val cursorDirection = Point(0, 0) - val cursorPosition = PointF(0f, 0f) - var isDispatchingSyntheticEvent: Boolean = false - private set - private val cursorSpeed = PointF(0f, 0f) - private val paint = Paint() - private var lastCursorUpdate = System.currentTimeMillis() - CURSOR_DISAPPEAR_TIMEOUT - private var dpadCenterPressed = false - internal var tmpPointF = PointF() - var callback: Callback? = null - var customScrollCallback: CustomScrollCallback? = null - private val cursorHideRunnable = Runnable { surface.invalidate() } - private val mainHandler = Handler(Looper.getMainLooper()) - private var scrollHackStarted = false - private val scrollHackCoords = PointF() - private val scrollHackActiveRect = Rect() - private var grabMode = false - private var downTime: Long = 0L - - //handle long press - private val longPressRunnable = Runnable { - // End the synthetic finger stream before clearing state. Otherwise WebView still has an - // active pointer while dpadCenterPressed is false — scroll-hack or the next frame can inject - // another ACTION_DOWN, which yields ACTION_CANCEL + ACTION_DOWN and a spurious tap. - if (dpadCenterPressed) { - dpadCenterPressed = false - dispatchMotionEvent(cursorPosition.x, cursorPosition.y, MotionEvent.ACTION_CANCEL) - } - surface.keyDispatcherState.reset(this@CursorDrawerDelegate) - grabMode = false - callback?.onLongPress(cursorPosition.x.toInt(), cursorPosition.y.toInt()) - } - - private val isCursorDisappear: Boolean - get() { - val newTime = System.currentTimeMillis() - return newTime - lastCursorUpdate > CURSOR_DISAPPEAR_TIMEOUT - } - - private fun scheduleCursorHide() { - mainHandler.removeCallbacks(cursorHideRunnable) - mainHandler.postDelayed(cursorHideRunnable, CURSOR_DISAPPEAR_TIMEOUT.toLong()) - } - - interface Callback { - fun onLongPress(x: Int, y: Int) - fun onCursorNearTop() {} - fun onScrollDirection(dy: Int) {} - } - - interface CustomScrollCallback { - fun onScroll(scrollX: Int, scrollY: Int): Boolean - } - - fun init() { - paint.isAntiAlias = true - val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager - val display = wm.defaultDisplay - val displaySize = Point() - display.getSize(displaySize) - cursorStrokeWidth = (displaySize.x / 400).toFloat() - cursorRadius = displaySize.x / 100 - cursorRadiusPressed = cursorRadius - Utils.D2P(context, 5f).toInt() - maxSpeedBaselinePx = (displaySize.x / 25).toFloat() - scrollStartPadding = displaySize.x / 15 - } - - fun onSizeChanged(w: Int, h: Int, ow: Int, oh: Int) { - cursorPosition.set(w / 2.0f, h / 2.0f) - scrollHackActiveRect.set(0, 0, surface.width, surface.height) - scrollHackActiveRect.inset(SCROLL_HACK_PADDING, SCROLL_HACK_PADDING) - scheduleCursorHide() - } - - fun isCursorNearTop(): Boolean { - return cursorPosition.y < Utils.D2P(context, 45f) - } - - fun canHandleBackNavigation(): Boolean { - return grabMode - } - - fun handleBackNavigation() { - if (grabMode) { - exitGrabMode() - } - } - - fun dispatchKeyEvent(event: KeyEvent): Boolean { - //Log.d(TAG, "dispatchKeyEvent: $event") - when (event.keyCode) { - KeyEvent.KEYCODE_DPAD_LEFT -> { - if (event.action == KeyEvent.ACTION_DOWN) { - handleDirectionKeyEvent(event, -1, UNCHANGED, true) - } else if (event.action == KeyEvent.ACTION_UP) { - handleDirectionKeyEvent(event, 0, UNCHANGED, false) - } - return true - } - KeyEvent.KEYCODE_DPAD_RIGHT -> { - if (event.action == KeyEvent.ACTION_DOWN) { - handleDirectionKeyEvent(event, 1, UNCHANGED, true) - } else if (event.action == KeyEvent.ACTION_UP) { - handleDirectionKeyEvent(event, 0, UNCHANGED, false) - } - return true - } - KeyEvent.KEYCODE_DPAD_UP -> { - if (event.action == KeyEvent.ACTION_DOWN) { - handleDirectionKeyEvent(event, UNCHANGED, -1, true) - } else if (event.action == KeyEvent.ACTION_UP) { - handleDirectionKeyEvent(event, UNCHANGED, 0, false) - } - return true - } - KeyEvent.KEYCODE_DPAD_DOWN -> { - if (event.action == KeyEvent.ACTION_DOWN) { - handleDirectionKeyEvent(event, UNCHANGED, 1, true) - } else if (event.action == KeyEvent.ACTION_UP) { - handleDirectionKeyEvent(event, UNCHANGED, 0, false) - } - return true - } - - KeyEvent.KEYCODE_DPAD_UP_LEFT -> { - if (event.action == KeyEvent.ACTION_DOWN) { - handleDirectionKeyEvent(event, -1, -1, true) - } else if (event.action == KeyEvent.ACTION_UP) { - handleDirectionKeyEvent(event, 0, 0, false) - } - return true - } - - KeyEvent.KEYCODE_DPAD_UP_RIGHT -> { - if (event.action == KeyEvent.ACTION_DOWN) { - handleDirectionKeyEvent(event, 1, -1, true) - } else if (event.action == KeyEvent.ACTION_UP) { - handleDirectionKeyEvent(event, 0, 0, false) - } - return true - } - - KeyEvent.KEYCODE_DPAD_DOWN_LEFT -> { - if (event.action == KeyEvent.ACTION_DOWN) { - handleDirectionKeyEvent(event, -1, 1, true) - } else if (event.action == KeyEvent.ACTION_UP) { - handleDirectionKeyEvent(event, 0, 0, false) - } - return true - } - - KeyEvent.KEYCODE_DPAD_DOWN_RIGHT -> { - if (event.action == KeyEvent.ACTION_DOWN) { - handleDirectionKeyEvent(event, 1, 1, true) - } else if (event.action == KeyEvent.ACTION_UP) { - handleDirectionKeyEvent(event, 0, 0, false) - } - return true - } - KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_BUTTON_A -> { - // [DPADNavigationEventsAdapter] may emit several selection key codes for one physical - // click; each is a distinct KeyEvent so keyDispatcherState.isTracking is per-key. - // Map them to a single touch DOWN/UP stream. - if (event.action == KeyEvent.ACTION_DOWN && - event.repeatCount == 0 && - !surface.keyDispatcherState.isTracking(event) - ) { - if (grabMode) { - exitGrabMode() - return false - } else { - surface.keyDispatcherState.startTracking(event, this) - if (!isCursorDisappear && !dpadCenterPressed) { - dpadCenterPressed = true - dispatchMotionEvent(cursorPosition.x, cursorPosition.y, MotionEvent.ACTION_DOWN) - surface.postInvalidate() - surface.postDelayed(longPressRunnable, LONG_PRESS_TIMEOUT) - } - } - } else if (event.action == KeyEvent.ACTION_UP) { - surface.keyDispatcherState.handleUpEvent(event) - surface.removeCallbacks(longPressRunnable) - if (grabMode) { - //nop - } else if (isCursorDisappear) { - lastCursorUpdate = System.currentTimeMillis() - surface.postInvalidate() - scheduleCursorHide() - } else { - if (dpadCenterPressed) { - dpadCenterPressed = false - dispatchMotionEvent(cursorPosition.x, cursorPosition.y, MotionEvent.ACTION_UP) - } - surface.postInvalidate() - } - } - - return true - } - } - return false - } - - private fun dispatchMotionEvent(x: Float, y: Float, action: Int, pointerId: Int = 0) { - if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_POINTER_DOWN) { - downTime = SystemClock.uptimeMillis() - } - val eventTime = SystemClock.uptimeMillis() - val properties = arrayOfNulls(1) - val pp1 = MotionEvent.PointerProperties() - pp1.id = pointerId - pp1.toolType = MotionEvent.TOOL_TYPE_FINGER - properties[0] = pp1 - val pointerCoords = arrayOfNulls(1) - val pc1 = MotionEvent.PointerCoords() - pc1.x = x - pc1.y = y - pc1.pressure = 1f - pc1.size = 1f - pointerCoords[0] = pc1 - val motionEvent = MotionEvent.obtain(downTime, eventTime, - action, 1, properties, - pointerCoords, 0, 0, 1f, 1f, 0, 0, 0, 0) - try { - dispatchSyntheticTouchEvent(motionEvent) - } finally { - motionEvent.recycle() - } - } - - private fun dispatchSyntheticTouchEvent(event: MotionEvent) { - isDispatchingSyntheticEvent = true - try { - surface.dispatchTouchEvent(event) - } finally { - isDispatchingSyntheticEvent = false - } - } - - private fun handleDirectionKeyEvent(event: KeyEvent, x: Int, y: Int, keyDown: Boolean) { - lastCursorUpdate = System.currentTimeMillis() - if (keyDown) { - if (surface.keyDispatcherState.isTracking(event)) { - return - } - surface.removeCallbacks(cursorUpdateRunnable) - surface.post(cursorUpdateRunnable) - surface.keyDispatcherState.startTracking(event, this) - } else { - surface.keyDispatcherState.handleUpEvent(event) - cursorSpeed.set(0f, 0f) - if (scrollHackStarted) { - dispatchMotionEvent(scrollHackCoords.x, scrollHackCoords.y, MotionEvent.ACTION_CANCEL) - scrollHackStarted = false - } - } - - cursorDirection.set(if (x == UNCHANGED) cursorDirection.x else x, if (y == UNCHANGED) cursorDirection.y else y) - } - - private fun scrollWebViewBy(scrollX: Int, scrollY: Int) { - if (scrollX == 0 && scrollY == 0) { - return - } - if (scrollY != 0) { - callback?.onScrollDirection(scrollY) - } - - if ((scrollX != 0 && surface.canScrollHorizontally(scrollX)) || (scrollY != 0 && surface.canScrollVertically(scrollY))) { - surface.scrollTo(surface.scrollX + scrollX, surface.scrollY + scrollY) - } else if (customScrollCallback != null && customScrollCallback?.onScroll(scrollX, scrollY) == true) { - return - } else if (USE_SCROLL_HACK && !dpadCenterPressed) { - var justStarted = false - if (!scrollHackStarted) { - scrollHackCoords.set( - bound(cursorPosition.x, scrollHackActiveRect.left.toFloat(), scrollHackActiveRect.right.toFloat()), - bound(cursorPosition.y, scrollHackActiveRect.top.toFloat(), scrollHackActiveRect.bottom.toFloat())) - dispatchMotionEvent(scrollHackCoords.x, scrollHackCoords.y, MotionEvent.ACTION_DOWN) - scrollHackStarted = true - justStarted = true - } - scrollHackCoords.x -= scrollX - scrollHackCoords.y -= scrollY - if (scrollHackCoords.x < scrollHackActiveRect.left || scrollHackCoords.x >= scrollHackActiveRect.right || - scrollHackCoords.y < scrollHackActiveRect.top || scrollHackCoords.y >= scrollHackActiveRect.bottom) { - scrollHackCoords.x += scrollX - scrollHackCoords.y += scrollY - dispatchMotionEvent(scrollHackCoords.x, scrollHackCoords.y, MotionEvent.ACTION_CANCEL) - scrollHackStarted = false - if (!justStarted) { - scrollWebViewBy(scrollX, scrollY) - } - return - } - dispatchMotionEvent(scrollHackCoords.x, scrollHackCoords.y, MotionEvent.ACTION_MOVE) - } - } - - - private fun bound(value: Float, max: Float): Float { - return if (value > max) { - max - } else if (value < -max) { - -max - } else { - value - } - } - - private fun bound(value: Float, min: Float, max: Float): Float { - return if (value > max) { - max - } else if (value < min) { - min - } else { - value - } - } - - fun dispatchDraw(canvas: Canvas) { - val cfg = AppContext.provideConfig() - if (!cfg.enableVirtualCursor) return - - if (grabMode || !isCursorDisappear) { - val cx = cursorPosition.x - val cy = cursorPosition.y - val baseRadius = if (dpadCenterPressed) cursorRadiusPressed.toFloat() else - (cursorRadius * cursorRadiusAnimationMultiplier) - - val sizeScale = cfg.cursorSizePercent / 100f - val radius = baseRadius * sizeScale - - when (cfg.cursorStyle) { - 0 -> { // Classic Circle / Ring - paint.color = when { - grabMode -> Color.argb(128, 200, 200, 255) - else -> Color.argb(128, 255, 255, 255) - } - paint.style = Paint.Style.FILL - canvas.drawCircle(cx, cy, radius, paint) - - paint.color = Color.GRAY - paint.strokeWidth = cursorStrokeWidth * sizeScale - paint.style = Paint.Style.STROKE - canvas.drawCircle(cx, cy, radius, paint) - - if (grabMode) { - val halfRadius = radius / 2f - canvas.drawLine(cx - halfRadius, cy, cx + halfRadius, cy, paint) - canvas.drawLine(cx, cy - halfRadius, cx, cy + halfRadius, paint) - } - } - 1 -> { // Arrow Pointer - val path = android.graphics.Path() - val arrowSize = (cursorRadius * 2.5f) * sizeScale - path.moveTo(cx, cy) - path.lineTo(cx, cy + arrowSize) - path.lineTo(cx + arrowSize * 0.45f, cy + arrowSize * 0.75f) - path.lineTo(cx + arrowSize * 0.75f, cy + arrowSize * 1.1f) - path.lineTo(cx + arrowSize * 0.95f, cy + arrowSize * 0.95f) - path.lineTo(cx + arrowSize * 0.65f, cy + arrowSize * 0.6f) - path.lineTo(cx + arrowSize * 0.9f, cy + arrowSize * 0.6f) - path.close() - - paint.color = if (dpadCenterPressed) Color.rgb(200, 200, 200) else Color.WHITE - paint.style = Paint.Style.FILL - canvas.drawPath(path, paint) - - paint.color = Color.BLACK - paint.style = Paint.Style.STROKE - paint.strokeWidth = (cursorStrokeWidth * 0.8f * sizeScale).coerceAtLeast(2f) - canvas.drawPath(path, paint) - } - 2 -> { // Crosshair Target - val crossSize = (cursorRadius * 1.8f) * sizeScale - paint.color = if (dpadCenterPressed) Color.RED else Color.GREEN - paint.style = Paint.Style.STROKE - paint.strokeWidth = (cursorStrokeWidth * sizeScale).coerceAtLeast(3f) - - canvas.drawCircle(cx, cy, crossSize * 0.5f, paint) - canvas.drawLine(cx - crossSize, cy, cx + crossSize, cy, paint) - canvas.drawLine(cx, cy - crossSize, cx, cy + crossSize, paint) - } - 3 -> { // Glowing Red Laser - paint.style = Paint.Style.FILL - paint.color = Color.argb(80, 255, 0, 0) - canvas.drawCircle(cx, cy, radius * 1.8f, paint) - - paint.color = if (dpadCenterPressed) Color.YELLOW else Color.RED - canvas.drawCircle(cx, cy, radius * 0.8f, paint) - } - 4 -> { // Neon Blue Pointer - val path = android.graphics.Path() - val arrowSize = (cursorRadius * 2.5f) * sizeScale - path.moveTo(cx, cy) - path.lineTo(cx, cy + arrowSize) - path.lineTo(cx + arrowSize * 0.35f, cy + arrowSize * 0.7f) - path.lineTo(cx + arrowSize * 0.7f, cy + arrowSize * 0.7f) - path.close() - - paint.style = Paint.Style.FILL - paint.color = if (dpadCenterPressed) Color.rgb(255, 64, 129) else Color.rgb(0, 229, 255) - canvas.drawPath(path, paint) - - paint.style = Paint.Style.STROKE - paint.color = Color.WHITE - paint.strokeWidth = (cursorStrokeWidth * sizeScale).coerceAtLeast(2f) - canvas.drawPath(path, paint) - } - } - } - } - - fun goToGrabMode() { - grabMode = true - surface.postInvalidate() - } - - fun exitGrabMode() { - dispatchMotionEvent(cursorPosition.x, cursorPosition.y, MotionEvent.ACTION_UP) - dpadCenterPressed = false - grabMode = false - surface.postInvalidate() - } - - private val cursorUpdateRunnable = object : Runnable { - override fun run() { - mainHandler.removeCallbacks(cursorHideRunnable) - - val newTime = System.currentTimeMillis() - val dTime = newTime - lastCursorUpdate - lastCursorUpdate = newTime - - val cfg = AppContext.provideConfig() - val speedCap = maxSpeedBaselinePx * (cfg.cursorMaxSpeedPercent / 100f) - val accelerationFactor = 0.05f * (cfg.cursorAccelerationPercent / 100f) * dTime - //float decelerationFactor = 1 - Math.min(0.5f, 0.005f * dTime); - cursorSpeed.set(bound(cursorSpeed.x/* * decelerationFactor*/ + bound(cursorDirection.x.toFloat(), 1f) * accelerationFactor, speedCap), - bound(cursorSpeed.y/* * decelerationFactor*/ + bound(cursorDirection.y.toFloat(), 1f) * accelerationFactor, speedCap)) - if (Math.abs(cursorSpeed.x) < 0.1f) cursorSpeed.x = 0f - if (Math.abs(cursorSpeed.y) < 0.1f) cursorSpeed.y = 0f - if (cursorDirection.x == 0 && cursorDirection.y == 0 && cursorSpeed.x == 0f && cursorSpeed.y == 0f) { - if (scrollHackStarted) { - dispatchMotionEvent(scrollHackCoords.x, scrollHackCoords.y, MotionEvent.ACTION_CANCEL) - scrollHackStarted = false - } - scheduleCursorHide() - return - } - tmpPointF.set(cursorPosition) - cursorPosition.offset(cursorSpeed.x, cursorSpeed.y) - surface.removeCallbacks(longPressRunnable) - if (cursorPosition.x < 0) { - cursorPosition.x = 0f - } else if (cursorPosition.x > surface.width - 1) { - cursorPosition.x = (surface.width - 1).toFloat() - } - if (cursorPosition.y < 0) { - cursorPosition.y = 0f - } else if (cursorPosition.y > surface.height - 1) { - cursorPosition.y = (surface.height - 1).toFloat() - } - if (cursorPosition.y < Utils.D2P(context, 45f)) { - callback?.onCursorNearTop() - } - var dx = 0 - var dy = 0 - if (cursorPosition.y > surface.height - scrollStartPadding) { - if (cursorSpeed.y > 0) { - dy = cursorSpeed.y.toInt() - } - } else if (cursorPosition.y < scrollStartPadding) { - if (cursorSpeed.y < 0) { - dy = cursorSpeed.y.toInt() - } - } - if (cursorPosition.x > surface.width - scrollStartPadding) { - if (cursorSpeed.x > 0) { - dx = cursorSpeed.x.toInt() - } - } else if (cursorPosition.x < scrollStartPadding) { - if (cursorSpeed.x < 0) { - dx = cursorSpeed.x.toInt() - } - } - if (dx != 0 || dy != 0) { - scrollWebViewBy(dx, dy) - } - // Touch MOVE only while "click" is held (scroll-hack uses its own touch at scrollHackCoords). - if (dpadCenterPressed && - (tmpPointF.x != cursorPosition.x || tmpPointF.y != cursorPosition.y) - ) { - dispatchMotionEvent(cursorPosition.x, cursorPosition.y, MotionEvent.ACTION_MOVE) - } - - surface.invalidate() - surface.post(this) - } - } - - fun tryZoomIn() { - generateZoomGesture(true) - } - - fun tryZoomOut() { - generateZoomGesture(false) - } - - fun animateAppearing() { - lastCursorUpdate = System.currentTimeMillis() - scheduleCursorHide() - cursorRadiusAnimationMultiplier = 2f - val animator = ValueAnimator.ofFloat(2f, 1f) - animator.duration = 300 - animator.addUpdateListener { valueAnimator -> - cursorRadiusAnimationMultiplier = valueAnimator.animatedValue as Float - surface.postInvalidate() - } - animator.start() - } - - //https://stackoverflow.com/questions/11523423/how-to-generate-zoom-pinch-gesture-for-testing-for-android - var pinchZoomStartTime = 0L - val pinchZoomDuration = 1000 - var pinchZoomIn = true - val zoomFactor = 0.1f - private fun generateZoomGesture(pinchZoomIn: Boolean) { - if (pinchZoomStartTime != 0L) { - return - } - this.pinchZoomIn = pinchZoomIn - this.pinchZoomStartTime = System.currentTimeMillis() - val deltaX = zoomFactor / 2f * surface.height - val deltaY = zoomFactor / 2f * surface.height - val deltaX2 = deltaX / 2f - val deltaY2 = deltaY / 2f - val startPoint1: PointF = if (pinchZoomIn) { - PointF(surface.width / 2f - deltaX2, surface.height / 2f - deltaY2) - } else { - PointF(surface.width / 2f - deltaX, surface.height / 2f - deltaY) - } - val startPoint2: PointF = if (pinchZoomIn) { - PointF(surface.width / 2f + deltaX2, surface.height / 2f + deltaY2) - } else { - PointF(surface.width / 2f + deltaX, surface.height / 2f + deltaY) - } - var event: MotionEvent? - val eventX1: Float = startPoint1.x - val eventY1: Float = startPoint1.y - val eventX2: Float = startPoint2.x - val eventY2: Float = startPoint2.y - - // specify the property for the two touch points - val properties = arrayOfNulls(2) - val pp1 = MotionEvent.PointerProperties() - pp1.id = 0 - pp1.toolType = MotionEvent.TOOL_TYPE_FINGER - val pp2 = MotionEvent.PointerProperties() - pp2.id = 1 - pp2.toolType = MotionEvent.TOOL_TYPE_FINGER - properties[0] = pp1 - properties[1] = pp2 - - //specify the coordinations of the two touch points - //NOTE: you MUST set the pressure and size value, or it doesn't work - val pointerCoords = arrayOfNulls(2) - val pc1 = MotionEvent.PointerCoords() - pc1.x = eventX1 - pc1.y = eventY1 - pc1.pressure = 1f - pc1.size = 1f - val pc2 = MotionEvent.PointerCoords() - pc2.x = eventX2 - pc2.y = eventY2 - pc2.pressure = 1f - pc2.size = 1f - pointerCoords[0] = pc1 - pointerCoords[1] = pc2 - - ////////////////////////////////////////////////////////////// - // events sequence of zoom gesture - // 1. send ACTION_DOWN event of one start point - // 2. send ACTION_POINTER_2_DOWN of two start points - // 3. send ACTION_MOVE of two middle points - // 4. repeat step 3 with updated middle points (x,y), - // until reach the end points - // 5. send ACTION_POINTER_2_UP of two end points - // 6. send ACTION_UP of one end point - ////////////////////////////////////////////////////////////// - - // step 1 - event = MotionEvent.obtain( - pinchZoomStartTime, pinchZoomStartTime, - MotionEvent.ACTION_DOWN, 1, properties, - pointerCoords, 0, 0, 1f, 1f, 0, 0, 0, 0 - ) - dispatchSyntheticTouchEvent(event) - - //step 2 - event = MotionEvent.obtain( - pinchZoomStartTime, pinchZoomStartTime, - MotionEvent.ACTION_POINTER_2_DOWN, 2, - properties, pointerCoords, 0, 0, 1f, 1f, 0, 0, 0, 0 - ) - dispatchSyntheticTouchEvent(event) - - surface.post(pinchZoomRunnable) - } - - fun hideCursor() { - if (dpadCenterPressed) { - dpadCenterPressed = false - dispatchMotionEvent(cursorPosition.x, cursorPosition.y, MotionEvent.ACTION_UP) - } - if (scrollHackStarted) { - scrollHackStarted = false - dispatchMotionEvent(scrollHackCoords.x, scrollHackCoords.y, MotionEvent.ACTION_CANCEL) - } - surface.removeCallbacks(cursorUpdateRunnable) - cursorSpeed.set(0f, 0f) - cursorDirection.set(0, 0) - surface.keyDispatcherState.reset(this) - grabMode = false - mainHandler.removeCallbacks(cursorHideRunnable) - lastCursorUpdate = System.currentTimeMillis() - CURSOR_DISAPPEAR_TIMEOUT - surface.postInvalidate() - } - - fun showCursor() { - lastCursorUpdate = System.currentTimeMillis() - scheduleCursorHide() - surface.postInvalidate() - } - - private val pinchZoomRunnable: Runnable by lazy { - object : Runnable { - override fun run() { - if (pinchZoomStartTime == 0L) { - return - } - val deltaX = zoomFactor / 2 * surface.height - val deltaY = zoomFactor / 2 * surface.height - val deltaX2 = deltaX / 2 - val deltaY2 = deltaY / 2 - val startPoint1: PointF = if (pinchZoomIn) { - PointF(surface.width / 2f - deltaX2, surface.height / 2f - deltaY2) - } else { - PointF(surface.width / 2f - deltaX, surface.height / 2f - deltaY) - } - val startPoint2: PointF = if (pinchZoomIn) { - PointF(surface.width / 2f + deltaX2, surface.height / 2f + deltaY2) - } else { - PointF(surface.width / 2f + deltaX, surface.height / 2f + deltaY) - } - val endPoint1: PointF = if (pinchZoomIn) { - PointF(surface.width / 2f - deltaX, surface.height / 2f - deltaY) - } else { - PointF(surface.width / 2f - deltaX2, surface.height / 2f - deltaY2) - } - val endPoint2: PointF = if (pinchZoomIn) { - PointF(surface.width / 2f + deltaX, surface.height / 2f + deltaY) - } else { - PointF(surface.width / 2f + deltaX2, surface.height / 2f + deltaY2) - } - - val properties = arrayOfNulls(2) - val pp1 = MotionEvent.PointerProperties() - pp1.id = 0 - pp1.toolType = MotionEvent.TOOL_TYPE_FINGER - val pp2 = MotionEvent.PointerProperties() - pp2.id = 1 - pp2.toolType = MotionEvent.TOOL_TYPE_FINGER - properties[0] = pp1 - properties[1] = pp2 - val pointerCoords = arrayOfNulls(2) - val pc1 = MotionEvent.PointerCoords() - val pc2 = MotionEvent.PointerCoords() - val now = System.currentTimeMillis() - if (now - pinchZoomStartTime < pinchZoomDuration) { - val progress = (now - pinchZoomStartTime).toFloat() / pinchZoomDuration - //step 3, 4 - // update the move events - pc1.x = startPoint1.x + (endPoint1.x - startPoint1.x) * progress - pc1.y = startPoint1.y + (endPoint1.y - startPoint1.y) * progress - pc2.x = startPoint2.x + (endPoint2.x - startPoint2.x) * progress - pc2.y = startPoint2.y + (endPoint2.y - startPoint2.y) * progress - pointerCoords[0] = pc1 - pointerCoords[1] = pc2 - val event = MotionEvent.obtain( - pinchZoomStartTime, now, - MotionEvent.ACTION_MOVE, 2, properties, - pointerCoords, 0, 0, 1f, 1f, 0, 0, 0, 0 - ) - dispatchSyntheticTouchEvent(event) - surface.post(pinchZoomRunnable) - } else { - //step 5 - pc1.x = endPoint1.x - pc1.y = endPoint1.y - pc2.x = endPoint2.x - pc2.y = endPoint2.y - pointerCoords[0] = pc1 - pointerCoords[1] = pc2 - var event = MotionEvent.obtain( - pinchZoomStartTime, now, - MotionEvent.ACTION_POINTER_2_UP, 2, properties, - pointerCoords, 0, 0, 1f, 1f, 0, 0, 0, 0 - ) - dispatchSyntheticTouchEvent(event) - - // step 6 - event = MotionEvent.obtain( - pinchZoomStartTime, now, - MotionEvent.ACTION_UP, 1, properties, - pointerCoords, 0, 0, 1f, 1f, 0, 0, 0, 0 - ) - dispatchSyntheticTouchEvent(event) - pinchZoomStartTime = 0 - } - } - } - } - - companion object { - private val TAG = CursorDrawerDelegate::class.java.simpleName - private const val UNCHANGED = Integer.MIN_VALUE - private const val CURSOR_DISAPPEAR_TIMEOUT = 5000 - private const val USE_SCROLL_HACK = true - private const val SCROLL_HACK_PADDING = 300 - //100ms more to let underlying view handle long press first - //idea to let geckoview handle long press first (and receive ContentDelegate.onContextMenu callback) - //and if it doesn't handle it, then we handle it as long press - private val LONG_PRESS_TIMEOUT = ViewConfiguration.getLongPressTimeout() + 100L - } -} \ No newline at end of file diff --git a/app/common/src/main/java/com/bansify/internet/widgets/cursor/CursorLayout.kt b/app/common/src/main/java/com/bansify/internet/widgets/cursor/CursorLayout.kt deleted file mode 100644 index 70ec253e..00000000 --- a/app/common/src/main/java/com/bansify/internet/widgets/cursor/CursorLayout.kt +++ /dev/null @@ -1,125 +0,0 @@ -package com.bansify.internet.widgets.cursor - -import android.content.Context -import android.graphics.Canvas -import android.util.AttributeSet -import android.util.Log -import android.view.InputDevice -import android.view.KeyEvent -import android.view.MotionEvent -import android.widget.FrameLayout -import androidx.core.view.ViewCompat -import androidx.core.view.WindowInsetsCompat -import com.bansify.internet.AppContext -import com.bansify.internet.utils.DPADNavigationEventsAdapter - - -/** - * Created by PDT on 25.08.2016. - */ -class CursorLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null): - FrameLayout(context, attrs) { - var cursorEnabled: Boolean - get() = !willNotDraw() - set(value) { - setWillNotDraw(!value) - } - lateinit var cursorDrawerDelegate: CursorDrawerDelegate - private val inputEventsAdapter = DPADNavigationEventsAdapter( - onEmulatedKeyEvent = { keyEvent -> - cursorDrawerDelegate.dispatchKeyEvent(keyEvent) - }, - motionAxesTranslationEnabled = { !AppContext.provideConfig().disableMotionAxesDpadNavigation }, - isSoftwareKeyboardVisible = { - ViewCompat.getRootWindowInsets(rootView)?.isVisible(WindowInsetsCompat.Type.ime()) == true - }, - ) - - init { - init() - } - - private fun init() { - if (isInEditMode) { - return - } - setWillNotDraw(false) - cursorDrawerDelegate = CursorDrawerDelegate(context, this) - cursorDrawerDelegate.init() - } - - override fun onSizeChanged(w: Int, h: Int, ow: Int, oh: Int) { - super.onSizeChanged(w, h, ow, oh) - if (isInEditMode || willNotDraw()) { - return - } - cursorDrawerDelegate.onSizeChanged(w, h, ow, oh) - } - - override fun setWillNotDraw(willNotDraw: Boolean) { - inputEventsAdapter.resetState() - super.setWillNotDraw(willNotDraw) - } - - override fun dispatchKeyEvent(event: KeyEvent): Boolean { - Log.d("CursorLayout", "dispatchKeyEvent: $event") - - if (willNotDraw() || !AppContext.provideConfig().enableVirtualCursor) return super.dispatchKeyEvent(event) - - if (inputEventsAdapter.dispatchKeyEvent(event)) { - return true - } - - return super.dispatchKeyEvent(event) - } - - override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean { - Log.d("CursorLayout", "dispatchGenericMotionEvent: $event") - val hwInput = com.bansify.internet.utils.HardwareInputManager.getInstance(context) - if (hwInput.isDeviceBlocked(event)) return true - - val isMouseOrTouch = (event.source and InputDevice.SOURCE_MOUSE) != 0 || - (event.source and InputDevice.SOURCE_TOUCHPAD) != 0 || - (event.source and InputDevice.SOURCE_TOUCHSCREEN) != 0 || - event.getToolType(0) == MotionEvent.TOOL_TYPE_MOUSE - - if (isMouseOrTouch) { - cursorDrawerDelegate.hideCursor() - return super.dispatchGenericMotionEvent(event) - } - - if (willNotDraw() || !AppContext.provideConfig().enableVirtualCursor) return super.dispatchGenericMotionEvent(event) - - if (inputEventsAdapter.dispatchGenericMotionEvent(event)) { - return true - } - - return super.dispatchGenericMotionEvent(event) - } - - override fun dispatchTouchEvent(ev: MotionEvent): Boolean { - val hwInput = com.bansify.internet.utils.HardwareInputManager.getInstance(context) - if (hwInput.isDeviceBlocked(ev)) return true - if (!cursorDrawerDelegate.isDispatchingSyntheticEvent) { - cursorDrawerDelegate.hideCursor() - } - return super.dispatchTouchEvent(ev) - } - - override fun onResolvePointerIcon(event: MotionEvent, pointerIndex: Int): android.view.PointerIcon? { - if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) { - val systemIcon = super.onResolvePointerIcon(event, pointerIndex) - return com.bansify.internet.utils.HardwareMousePointerManager.resolvePointerIcon(context, systemIcon) - } - return super.onResolvePointerIcon(event, pointerIndex) - } - - override fun dispatchDraw(canvas: Canvas) { - super.dispatchDraw(canvas) - if (isInEditMode || willNotDraw()) { - return - } - - cursorDrawerDelegate.dispatchDraw(canvas) - } -} diff --git a/app/common/src/main/res/values-de/strings.xml b/app/common/src/main/res/values-de/strings.xml deleted file mode 100644 index e216f7cf..00000000 --- a/app/common/src/main/res/values-de/strings.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - Nutzername - Passwort - \ No newline at end of file diff --git a/app/common/src/main/res/values-fa/strings.xml b/app/common/src/main/res/values-fa/strings.xml deleted file mode 100644 index c9b2363a..00000000 --- a/app/common/src/main/res/values-fa/strings.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - نام کاربری - کلمه عبور - diff --git a/app/common/src/main/res/values-it/strings.xml b/app/common/src/main/res/values-it/strings.xml deleted file mode 100644 index 8a6cea88..00000000 --- a/app/common/src/main/res/values-it/strings.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - Nome utente - Parola d&#39;ordine - diff --git a/app/common/src/main/res/values-iw/strings.xml b/app/common/src/main/res/values-iw/strings.xml deleted file mode 100644 index adb6937c..00000000 --- a/app/common/src/main/res/values-iw/strings.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - שם משתמש - סיסמה - diff --git a/app/common/src/main/res/values-pl/strings.xml b/app/common/src/main/res/values-pl/strings.xml deleted file mode 100644 index 722d0f7e..00000000 --- a/app/common/src/main/res/values-pl/strings.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - Nazwa użytkownika - Hasło - diff --git a/app/common/src/main/res/values-ru/strings.xml b/app/common/src/main/res/values-ru/strings.xml deleted file mode 100644 index 4d46604e..00000000 --- a/app/common/src/main/res/values-ru/strings.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - Имя пользователя - Пароль - diff --git a/app/common/src/main/res/values-uk/strings.xml b/app/common/src/main/res/values-uk/strings.xml deleted file mode 100644 index 58107328..00000000 --- a/app/common/src/main/res/values-uk/strings.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - Ім\'я користувача - Пароль - diff --git a/app/common/src/main/res/values-vi/strings.xml b/app/common/src/main/res/values-vi/strings.xml deleted file mode 100644 index 5bec80f1..00000000 --- a/app/common/src/main/res/values-vi/strings.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - Tên tài khoản - Mật khẩu - diff --git a/app/common/src/main/res/values-zh-rTW/strings.xml b/app/common/src/main/res/values-zh-rTW/strings.xml deleted file mode 100644 index a2dc0bae..00000000 --- a/app/common/src/main/res/values-zh-rTW/strings.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - 使用者名稱 - 密碼 - \ No newline at end of file diff --git a/app/common/src/main/res/values-zh/strings.xml b/app/common/src/main/res/values-zh/strings.xml deleted file mode 100644 index c6d7d823..00000000 --- a/app/common/src/main/res/values-zh/strings.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - 用户名 - 密码 - diff --git a/app/common/src/main/res/values/strings.xml b/app/common/src/main/res/values/strings.xml deleted file mode 100644 index 5ccf8e81..00000000 --- a/app/common/src/main/res/values/strings.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - Username - Password - \ No newline at end of file diff --git a/app/common/src/test/java/com/bansify/internet/ConfigRulesTest.kt b/app/common/src/test/java/com/bansify/internet/ConfigRulesTest.kt deleted file mode 100644 index d40e4e46..00000000 --- a/app/common/src/test/java/com/bansify/internet/ConfigRulesTest.kt +++ /dev/null @@ -1,212 +0,0 @@ -package com.bansify.internet - -import android.content.SharedPreferences -import org.junit.Assert.assertEquals -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue -import org.junit.Test - -/** - * Pure-JVM tests for the rules in [Config] that the app's behaviour depends on. - * - * These are the decisions that were silently wrong more than once during development (the live-tab - * cap ignoring its own bounds, the desktop/mobile zoom buckets overwriting each other, an unknown - * stored input mode crashing instead of falling back), so they are pinned down here without needing - * Robolectric or a device. - */ -class ConfigRulesTest { - - private class FakePrefs : SharedPreferences { - val map = mutableMapOf() - - override fun getAll(): MutableMap = map - - override fun getString(key: String, defValue: String?): String? = - if (map.containsKey(key)) map[key] as String? else defValue - - @Suppress("UNCHECKED_CAST") - override fun getStringSet(key: String, defValues: MutableSet?): MutableSet? = - if (map.containsKey(key)) map[key] as MutableSet else defValues - - override fun getInt(key: String, defValue: Int): Int = - if (map.containsKey(key)) (map[key] as Number).toInt() else defValue - - override fun getLong(key: String, defValue: Long): Long = - if (map.containsKey(key)) (map[key] as Number).toLong() else defValue - - override fun getFloat(key: String, defValue: Float): Float = - if (map.containsKey(key)) (map[key] as Number).toFloat() else defValue - - override fun getBoolean(key: String, defValue: Boolean): Boolean = - if (map.containsKey(key)) map[key] as Boolean else defValue - - override fun contains(key: String): Boolean = map.containsKey(key) - - override fun edit(): SharedPreferences.Editor = object : SharedPreferences.Editor { - override fun putString(key: String, value: String?): SharedPreferences.Editor = - apply { map[key] = value } - - override fun putStringSet( - key: String, - values: MutableSet? - ): SharedPreferences.Editor = apply { map[key] = values } - - override fun putInt(key: String, value: Int): SharedPreferences.Editor = - apply { map[key] = value } - - override fun putLong(key: String, value: Long): SharedPreferences.Editor = - apply { map[key] = value } - - override fun putFloat(key: String, value: Float): SharedPreferences.Editor = - apply { map[key] = value } - - override fun putBoolean(key: String, value: Boolean): SharedPreferences.Editor = - apply { map[key] = value } - - override fun remove(key: String): SharedPreferences.Editor = apply { map.remove(key) } - - override fun clear(): SharedPreferences.Editor = apply { map.clear() } - - override fun commit(): Boolean = true - - override fun apply() {} - } - - override fun registerOnSharedPreferenceChangeListener( - listener: SharedPreferences.OnSharedPreferenceChangeListener? - ) { - } - - override fun unregisterOnSharedPreferenceChangeListener( - listener: SharedPreferences.OnSharedPreferenceChangeListener? - ) { - } - } - - private fun configWith(vararg seed: Pair): Config { - val prefs = FakePrefs() - seed.forEach { (k, v) -> prefs.map[k] = v } - return Config(prefs) - } - - // ------------------------------------------------------------------ live tab cap - - @Test - fun maxLiveTabs_usesTheAdaptiveDefault_whenTheUserNeverSetOne() { - val config = configWith() - assertEquals(Config.DEFAULT_MAX_LIVE_TABS, config.maxLiveTabs) - config.maxLiveTabsDefault = 3 - assertEquals(3, config.maxLiveTabs) - } - - @Test - fun maxLiveTabs_isClampedToTheSaneRange_andRemembered() { - val config = configWith() - config.maxLiveTabs = 1 - assertEquals(2, config.maxLiveTabs) - config.maxLiveTabs = 99 - assertEquals(20, config.maxLiveTabs) - config.maxLiveTabs = 5 - assertEquals(5, config.maxLiveTabs) - // An explicit value must win over the adaptive default. - config.maxLiveTabsDefault = 3 - assertEquals(5, config.maxLiveTabs) - } - - @Test - fun maxLiveTabs_reparsesPersistedValueInAFreshInstance() { - val prefs = FakePrefs() - Config(prefs).maxLiveTabs = 4 - assertEquals(4, Config(prefs).maxLiveTabs) - } - - // ------------------------------------------------------------------ input mode - - @Test - fun inputMode_fallsBackToAuto_onAnUnreadableStoredValue() { - val config = configWith(Config.INPUT_MODE_KEY to "TOUCHSCREEN_OF_THE_FUTURE") - assertEquals(Config.InputMode.AUTO, config.inputMode) - } - - @Test - fun inputMode_autoResolvesPerDevice() { - val config = configWith() - assertEquals(Config.InputMode.AUTO, config.inputMode) - assertEquals(Config.InputMode.TOUCH, config.resolveInputMode(isTvDevice = false, physicalMouseConnected = false)) - assertEquals(Config.InputMode.TV_REMOTE, config.resolveInputMode(isTvDevice = true, physicalMouseConnected = false)) - assertEquals(Config.InputMode.KEYBOARD_MOUSE, config.resolveInputMode(isTvDevice = true, physicalMouseConnected = true)) - // A phone with a mouse stays a touch device: AUTO only upgrades TV hardware. - assertEquals(Config.InputMode.TOUCH, config.resolveInputMode(isTvDevice = false, physicalMouseConnected = true)) - } - - @Test - fun inputMode_explicitChoiceIsNeverOverriddenByTheDevice() { - val config = configWith() - config.inputMode = Config.InputMode.TOUCH - assertEquals(Config.InputMode.TOUCH, config.resolveInputMode(isTvDevice = true, physicalMouseConnected = true)) - config.inputMode = Config.InputMode.TV_REMOTE - assertEquals(Config.InputMode.TV_REMOTE, config.resolveInputMode(isTvDevice = false, physicalMouseConnected = false)) - } - - // ------------------------------------------------------------------ per-mode zoom - - @Test - fun zoom_keepsMobileAndDesktopBucketsSeparate() { - val config = configWith() - assertEquals(Config.WEB_PAGE_ZOOM_PERCENT_DEFAULT, config.getEffectiveZoom(false)) - assertEquals(Config.WEB_PAGE_ZOOM_PERCENT_DEFAULT, config.getEffectiveZoom(true)) - - config.setEffectiveZoom(true, 150) - assertEquals(150, config.getEffectiveZoom(true)) - assertEquals(Config.WEB_PAGE_ZOOM_PERCENT_DEFAULT, config.getEffectiveZoom(false)) - } - - @Test - fun zoom_clampsToTheSupportedRange() { - val config = configWith() - config.setEffectiveZoom(false, 10) - assertEquals(Config.WEB_PAGE_ZOOM_PERCENT_MIN, config.getEffectiveZoom(false)) - config.setEffectiveZoom(false, 5000) - assertEquals(Config.WEB_PAGE_ZOOM_PERCENT_MAX, config.getEffectiveZoom(false)) - } - - // ------------------------------------------------------------------ desktop identity - - @Test - fun desktopUa_isRecognisedFromTheUaString() { - val config = configWith() - assertTrue(config.isDesktopUa(Config.DESKTOP_UA)) - assertFalse(config.isDesktopUa("Mozilla/5.0 (Linux; Android 13; SM-A135F) Mobile Safari/537.36")) - assertFalse(config.isDesktopUa(null)) - } - - @Test - fun desktopMode_globalFlagOrCustomUaBothTurnItOn() { - val config = configWith() - assertFalse(config.isDesktopMode()) - config.desktopMode.value = true - assertTrue(config.isDesktopMode()) - - val custom = configWith(Config.USER_AGENT_PREF_KEY to "Firefox/128.0 on X11; Linux x86_64") - assertFalse(custom.desktopMode.value) - assertTrue(custom.isDesktopMode()) - } - - @Test - fun privacyAndSafetyFlags_defaultOnAndPersistWhenDisabled() { - // The shipped app once advertised "securest browser" while Safe Browsing was pinned to - // false; these defaults are the product promise, so they are asserted, not assumed. - val config = configWith() - assertTrue("safe browsing must default to on", config.safeBrowsingEnabled) - assertTrue("history must default to on", config.saveHistory) - assertFalse("autoplay must default to off", config.allowAutoplayMedia) - - config.safeBrowsingEnabled = false - config.saveHistory = false - assertFalse(config.safeBrowsingEnabled) - assertFalse(config.saveHistory) - - val persisted = FakePrefs().apply { map[Config.SAFE_BROWSING_KEY] = false } - assertFalse(Config(persisted).safeBrowsingEnabled) - } -} diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro index fbe1b8cc..f1b42451 100644 --- a/app/proguard-rules.pro +++ b/app/proguard-rules.pro @@ -1,35 +1,21 @@ -# TV Browser ProGuard / R8 Performance & Size Rules +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html -# Strip excessive Android debug logging in release builds to eliminate string allocations & logging overhead on TV D-Pad navigation --assumenosideeffects class android.util.Log { - public static boolean isLoggable(java.lang.String, int); - public static int v(...); - public static int d(...); - public static int i(...); - public static int w(...); -} +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} -# Optimize Room & SQLite Database --keepclassmembers class * extends androidx.room.RoomDatabase { - (); -} +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable -# WebKit & JavaScript Interfaces --keepclassmembers class * { - @android.webkit.JavascriptInterface ; -} - -# WebEngine and Models --keep class com.bansify.internet.webengine.webview.WebViewWebEngine { *; } - --keepclassmembers class com.bansify.internet.model.** { - public *; -} --keepclassmembers class com.brave.adblock.AdBlockClient { - public *; - private *; -} --keepclassmembers class com.bansify.internet.webengine.webview.AndroidJSInterface { - public *; - private *; -} +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/app/src/androidTest/java/com/bansify/browser/ExampleInstrumentedTest.kt b/app/src/androidTest/java/com/bansify/browser/ExampleInstrumentedTest.kt new file mode 100644 index 00000000..60dbbd95 --- /dev/null +++ b/app/src/androidTest/java/com/bansify/browser/ExampleInstrumentedTest.kt @@ -0,0 +1,22 @@ +package com.bansify.browser + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith + +/** + * Instrumented test, which will execute on an Android device. + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +@RunWith(AndroidJUnit4::class) +class ExampleInstrumentedTest { + @Test + fun useAppContext() { + // Context of the app under test. + val appContext = InstrumentationRegistry.getInstrumentation().targetContext + assertEquals(BuildConfig.APPLICATION_ID, appContext.packageName) + } +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 759cb3bc..97a9b68e 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -4,185 +4,38 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + android:hardwareAccelerated="true" + android:theme="@style/Theme.MyApplication"> + android:label="@string/app_name" + android:launchMode="singleTask" + android:configChanges="orientation|screenSize|screenLayout|keyboardHidden|smallestScreenSize" + android:windowSoftInputMode="adjustResize" + android:theme="@style/Theme.MyApplication"> - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file + + diff --git a/app/src/main/assets/generic_injects.js b/app/src/main/assets/generic_injects.js deleted file mode 100644 index cad4fe10..00000000 --- a/app/src/main/assets/generic_injects.js +++ /dev/null @@ -1,125 +0,0 @@ -// download blobs support -if (!window.tvBroClicksListener) { - window.tvBroClicksListener = function(e) { - if (e.target && e.target.tagName && e.target.tagName.toUpperCase() == "A" && e.target.attributes && e.target.attributes.href && e.target.attributes.href.value && e.target.attributes.href.value.toLowerCase().startsWith("blob:")) { - var fileName = e.target.download; - var url = e.target.attributes.href.value; - var xhr = new XMLHttpRequest(); - xhr.open('GET', url, true); - xhr.responseType = 'blob'; - xhr.onload = function(e) { - if (this.status == 200) { - var blob = this.response; - var reader = new FileReader(); - reader.readAsDataURL(blob); - reader.onloadend = function() { - var base64data = reader.result; - BrowserApp.takeBlobDownloadData(base64data, fileName, url, blob.type); - } - } - }; - xhr.send(); - e.stopPropagation(); - e.preventDefault(); - } - }; - document.addEventListener("click", window.tvBroClicksListener); -} - -// media playback control support (driven by the media / DPAD keys handled in MainActivity) -// NOTE: deliberately NOT a HTMLMediaElement.prototype patch - injecting a getter into a platform -// prototype changes every page script on the site and can be detected / re-defined by the host page. -function tvBroMediaIsPlaying(m) { - return !!(m && m.currentTime > 0 && !m.paused && !m.ended && m.readyState > 2); -} - -// The element the media keys should drive: whatever is actually playing, else the first one. -function tvBroActiveMedia() { - var list = document.querySelectorAll('video, audio'); - for (var i = 0; i < list.length; i++) { - if (tvBroMediaIsPlaying(list[i])) { - return list[i]; - } - } - return list.length > 0 ? list[0] : null; -} - -window.tvBroTogglePlayback = function() { - var media = tvBroActiveMedia(); - if (!media) { - return; - } - if (tvBroMediaIsPlaying(media)) { - media.pause(); - } else { - var p = media.play(); - // Autoplay policies reject the promise; swallow it instead of logging an uncaught error. - if (p && typeof p.catch === 'function') { - p.catch(function() {}); - } - } -} - -window.tvBroStopPlayback = function() { - var media = tvBroActiveMedia(); - if (media) { - media.pause(); - media.currentTime = 0; - } -} - -window.tvBroRewind = function() { - var media = tvBroActiveMedia(); - if (media) { - media.currentTime -= 10; - } -} - -window.tvBroFastForward = function() { - var media = tvBroActiveMedia(); - if (media) { - media.currentTime += 10; - } -} - -// context menu support -window.addEventListener("touchstart", function(e) { - if (e.touches && e.touches.length > 0) { - window.TVBRO_activeElement = e.target; - window.TVBRO_touchStartX = e.touches[0].clientX; - window.TVBRO_touchStartY = e.touches[0].clientY; - } -}); - -// Real Desktop Mode fitting for TV Browser -(function() { - var ua = navigator.userAgent || ""; - var isDesktop = ua.indexOf("Windows NT") !== -1 || ua.indexOf("X11; Linux x86_64") !== -1 || ua.indexOf("Macintosh") !== -1; - if (isDesktop) { - var metas = document.querySelectorAll('meta[name="viewport"]'); - for (var i = 0; i < metas.length; i++) { - metas[i].parentNode.removeChild(metas[i]); - } - } -})(); - -// Force Enable Zoom: Ensure pages can never disable pinch or user scaling -(function() { - function ensureZoomable() { - var metas = document.querySelectorAll('meta[name="viewport"]'); - for (var i = 0; i < metas.length; i++) { - var content = metas[i].getAttribute('content') || ''; - if (/user-scalable\s*=\s*no/i.test(content) || /maximum-scale\s*=\s*1(\.0)?/i.test(content)) { - var updated = content - .replace(/user-scalable\s*=\s*no/gi, 'user-scalable=yes') - .replace(/maximum-scale\s*=\s*1(\.0)?/gi, 'maximum-scale=5.0'); - metas[i].setAttribute('content', updated); - } - } - } - ensureZoomable(); - if (document.readyState === 'loading') { - document.addEventListener('DOMContentLoaded', ensureZoomable); - } -})(); - diff --git a/app/src/main/assets/pages/ic_warning.svg b/app/src/main/assets/pages/ic_warning.svg deleted file mode 100644 index add4f5f1..00000000 --- a/app/src/main/assets/pages/ic_warning.svg +++ /dev/null @@ -1,59 +0,0 @@ - - - - - - image/svg+xml - - - - - - - - - diff --git a/app/src/main/assets/pages/warning-certificate.html b/app/src/main/assets/pages/warning-certificate.html deleted file mode 100644 index 9c043147..00000000 --- a/app/src/main/assets/pages/warning-certificate.html +++ /dev/null @@ -1,97 +0,0 @@ - - - - Security warning - - - - -
-
- - -

-

-

-


- -
- - -
-
-
- - - \ No newline at end of file diff --git a/app/src/main/java/com/bansify/browser/MainActivity.kt b/app/src/main/java/com/bansify/browser/MainActivity.kt new file mode 100644 index 00000000..00127e34 --- /dev/null +++ b/app/src/main/java/com/bansify/browser/MainActivity.kt @@ -0,0 +1,44 @@ +package com.bansify.browser + +import android.content.Intent +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import androidx.activity.viewModels +import com.bansify.browser.ui.BrowserApp +import com.bansify.browser.viewmodel.BrowserViewModel + +class MainActivity : ComponentActivity() { + + private val viewModel: BrowserViewModel by viewModels() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enableEdgeToEdge() + handleIncomingIntent(intent) + + setContent { + BrowserApp(viewModel = viewModel) + } + } + + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + setIntent(intent) + handleIncomingIntent(intent) + } + + private fun handleIncomingIntent(intent: Intent?) { + if (intent?.action == Intent.ACTION_VIEW) { + val url = intent.dataString + if (!url.isNullOrBlank()) { + if (viewModel.settings.value.openExternalLinksInNewTab) { + viewModel.createNewTab(url = url, isIncognito = false) + } else { + viewModel.openUrlInActiveTab(url) + } + } + } + } +} diff --git a/app/src/main/java/com/bansify/browser/browser/UrlUtils.kt b/app/src/main/java/com/bansify/browser/browser/UrlUtils.kt new file mode 100644 index 00000000..3b606073 --- /dev/null +++ b/app/src/main/java/com/bansify/browser/browser/UrlUtils.kt @@ -0,0 +1,162 @@ +package com.bansify.browser.browser + +import android.net.Uri +import android.util.Patterns +import com.bansify.browser.data.BrowserTab +import com.bansify.browser.data.SearchEngine +import java.net.URLEncoder +import java.text.SimpleDateFormat +import java.util.Calendar +import java.util.Date +import java.util.Locale + +object UrlUtils { + + fun resolveInputToUrl( + rawInput: String, + searchEngine: SearchEngine, + httpsFirst: Boolean + ): String { + val trimmed = rawInput.trim() + if (trimmed.isEmpty()) return BrowserTab.NEW_TAB_URL + + // Disallow javascript: injection from Omnibox for safety + if (trimmed.startsWith("javascript:", ignoreCase = true)) { + return buildSearchUrl(trimmed, searchEngine) + } + + if (trimmed.equals("about:blank", ignoreCase = true) || + trimmed.equals(BrowserTab.NEW_TAB_URL, ignoreCase = true) + ) { + return BrowserTab.NEW_TAB_URL + } + + // Explicit scheme + if (trimmed.startsWith("http://", ignoreCase = true)) { + return if (httpsFirst) { + "https://" + trimmed.removePrefix("http://").removePrefix("HTTP://") + } else { + trimmed + } + } + if (trimmed.startsWith("https://", ignoreCase = true)) { + return trimmed + } + + // No whitespace and looks like a domain/host or localhost/IP + val hasSpaces = trimmed.any { it.isWhitespace() } + if (!hasSpaces) { + val isLocalhost = trimmed.startsWith("localhost", ignoreCase = true) || + trimmed.matches(Regex("^\\d{1,3}(\\.\\d{1,3}){3}(:\\d+)?(/.*)?$")) + if (isLocalhost) { + return "http://$trimmed" + } + + if (Patterns.WEB_URL.matcher(trimmed).matches() && trimmed.contains('.')) { + return "https://$trimmed" + } + } + + return buildSearchUrl(trimmed, searchEngine) + } + + fun buildSearchUrl(query: String, searchEngine: SearchEngine): String { + val encoded = URLEncoder.encode(query.trim(), "UTF-8") + return searchEngine.queryUrlTemplate.replace("%s", encoded) + } + + fun extractDisplayHost(url: String): String { + if (url.isBlank() || url == BrowserTab.NEW_TAB_URL) return "" + return try { + val uri = Uri.parse(url) + val host = uri.host ?: return url + host.removePrefix("www.").removePrefix("m.") + } catch (_: Exception) { + url + } + } + + fun extractShortDomain(url: String): String { + val host = extractDisplayHost(url) + return host.ifBlank { url } + } + + fun extractFirstLetter(title: String, url: String): String { + val host = extractDisplayHost(url) + val candidate = host.firstOrNull { it.isLetterOrDigit() } + ?: title.firstOrNull { it.isLetterOrDigit() } + ?: 'B' + return candidate.uppercaseChar().toString() + } + + fun inferDownloadCategory(fileName: String, mimeType: String): String { + val lowerName = fileName.lowercase(Locale.US) + val lowerMime = mimeType.lowercase(Locale.US) + return when { + lowerMime.startsWith("image/") || + lowerName.endsWith(".png") || lowerName.endsWith(".jpg") || + lowerName.endsWith(".jpeg") || lowerName.endsWith(".webp") || + lowerName.endsWith(".gif") -> "Images" + + lowerMime.contains("html") || lowerMime.contains("mht") || + lowerName.endsWith(".mht") || lowerName.endsWith(".html") -> "Pages" + + lowerMime.contains("pdf") || lowerMime.contains("document") || + lowerMime.contains("text/") || lowerName.endsWith(".pdf") || + lowerName.endsWith(".doc") || lowerName.endsWith(".docx") || + lowerName.endsWith(".txt") || lowerName.endsWith(".csv") -> "Documents" + + else -> "Other" + } + } + + fun formatFileSize(bytes: Long): String { + if (bytes <= 0L) return "Unknown size" + val kb = bytes / 1024.0 + val mb = kb / 1024.0 + val gb = mb / 1024.0 + return when { + gb >= 1.0 -> String.format(Locale.US, "%.2f GB", gb) + mb >= 1.0 -> String.format(Locale.US, "%.1f MB", mb) + kb >= 1.0 -> String.format(Locale.US, "%.0f KB", kb) + else -> "$bytes B" + } + } + + fun formatHistorySectionHeader(timestamp: Long): String { + val now = Calendar.getInstance() + val target = Calendar.getInstance().apply { timeInMillis = timestamp } + val sameYear = now.get(Calendar.YEAR) == target.get(Calendar.YEAR) + val dayDiff = now.get(Calendar.DAY_OF_YEAR) - target.get(Calendar.DAY_OF_YEAR) + + return when { + sameYear && dayDiff == 0 -> "Today" + sameYear && dayDiff == 1 -> "Yesterday" + else -> SimpleDateFormat("EEEE, MMM d, yyyy", Locale.getDefault()).format(Date(timestamp)) + } + } + + fun formatShortTime(timestamp: Long): String { + return SimpleDateFormat("h:mm a", Locale.getDefault()).format(Date(timestamp)) + } + + fun formatShortDate(timestamp: Long): String { + return SimpleDateFormat("MMM d, yyyy", Locale.getDefault()).format(Date(timestamp)) + } + + fun colorForDomain(url: String): Long { + val palette = listOf( + 0xFF1A73E8L, + 0xFF188038L, + 0xFFD93025L, + 0xFFE37400L, + 0xFF8430CEL, + 0xFF007B83L, + 0xFFC5221FL, + 0xFF3F51B5L + ) + val host = extractDisplayHost(url) + val index = kotlin.math.abs(host.hashCode()) % palette.size + return palette[index] + } +} diff --git a/app/src/main/java/com/bansify/browser/browser/WebViewPool.kt b/app/src/main/java/com/bansify/browser/browser/WebViewPool.kt new file mode 100644 index 00000000..6c4f0f42 --- /dev/null +++ b/app/src/main/java/com/bansify/browser/browser/WebViewPool.kt @@ -0,0 +1,541 @@ +package com.bansify.browser.browser + +import android.annotation.SuppressLint +import android.app.DownloadManager +import android.content.ActivityNotFoundException +import android.content.Context +import android.content.Intent +import android.graphics.Bitmap +import android.graphics.Canvas +import android.net.Uri +import android.os.Build +import android.os.Environment +import android.view.View +import android.view.ViewGroup +import android.webkit.CookieManager +import android.webkit.JsPromptResult +import android.webkit.JsResult +import android.webkit.URLUtil +import android.webkit.ValueCallback +import android.webkit.WebChromeClient +import android.webkit.WebResourceRequest +import android.webkit.WebSettings +import android.webkit.WebView +import android.webkit.WebViewClient +import com.bansify.browser.data.BrowserSettings +import com.bansify.browser.data.BrowserTab +import com.bansify.browser.data.JsDialogState +import com.bansify.browser.data.SafeBrowsingLevel +import com.bansify.browser.data.ThirdPartyCookiePolicy +import java.io.File + +/** + * Keeps live Android WebView instances alive per tab ID so switching tabs, opening Settings, + * or toggling the Tab Switcher preserves exact scroll position, DOM state, and back/forward history. + */ +class WebViewPool( + private val context: Context, + private val callbacks: Callbacks +) { + interface Callbacks { + fun onPageStarted(tabId: String, url: String) + fun onPageFinished(tabId: String, url: String, title: String, canGoBack: Boolean, canGoForward: Boolean) + fun onProgressChanged(tabId: String, progress: Int) + fun onTitleReceived(tabId: String, title: String) + fun onFaviconReceived(tabId: String, icon: Bitmap?) + fun onThumbnailCaptured(tabId: String, bitmap: Bitmap) + fun onDownloadStarted(fileName: String, url: String, mimeType: String, sizeBytes: Long, localPath: String) + fun onJsDialog(dialog: JsDialogState) + fun onShowCustomView(view: View, callback: WebChromeClient.CustomViewCallback) + fun onHideCustomView() + fun onFileChooserRequested(filePathCallback: ValueCallback>, acceptTypes: Array) + fun onFindResults(activeMatchOrdinal: Int, numberOfMatches: Int) + fun onOpenNewTabRequest(url: String, isIncognito: Boolean) + fun onExternalUrlError(message: String) + } + + private val webViews = mutableMapOf() + private val defaultUserAgents = mutableMapOf() + private var currentSettings: BrowserSettings = BrowserSettings() + + companion object { + private const val DESKTOP_USER_AGENT = + "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36" + } + + fun getOrCreateWebView(tab: BrowserTab, settings: BrowserSettings): WebView { + currentSettings = settings + val existing = webViews[tab.id] + if (existing != null) { + applySettingsToWebView(existing, tab, settings) + return existing + } + + val webView = createWebView(tab, settings) + webViews[tab.id] = webView + if (!tab.isNewTab) { + loadUrl(tab.id, tab.url, settings) + } + return webView + } + + fun getWebViewIfExists(tabId: String): WebView? = webViews[tabId] + + fun updateSettingsForAll(tabs: List, settings: BrowserSettings) { + currentSettings = settings + val tabMap = tabs.associateBy { it.id } + webViews.forEach { (id, wv) -> + val tab = tabMap[id] + if (tab != null) { + applySettingsToWebView(wv, tab, settings) + } + } + } + + fun loadUrl(tabId: String, url: String, settings: BrowserSettings = currentSettings) { + val webView = webViews[tabId] ?: return + if (url == BrowserTab.NEW_TAB_URL || url.isBlank()) { + webView.stopLoading() + return + } + val headers = mutableMapOf() + if (settings.doNotTrackEnabled) { + headers["DNT"] = "1" + } + val langTag = when { + settings.preferredLanguage.startsWith("Hindi") -> "hi-IN,hi;q=0.9,en;q=0.8" + settings.preferredLanguage.startsWith("Spanish") -> "es-ES,es;q=0.9,en;q=0.8" + settings.preferredLanguage.startsWith("French") -> "fr-FR,fr;q=0.9,en;q=0.8" + settings.preferredLanguage.startsWith("German") -> "de-DE,de;q=0.9,en;q=0.8" + settings.preferredLanguage.startsWith("Japanese") -> "ja-JP,ja;q=0.9,en;q=0.8" + else -> "en-US,en;q=0.9" + } + headers["Accept-Language"] = langTag + webView.loadUrl(url, headers) + } + + fun extractReadableArticle(tabId: String, onResult: (title: String, paragraphs: List) -> Unit) { + val wv = webViews[tabId] + if (wv == null) { + onResult("", emptyList()) + return + } + val js = """ + (function() { + var title = document.title || ''; + var root = document.querySelector('article') || document.querySelector('main') || document.body; + var nodes = root ? root.querySelectorAll('h1, h2, h3, p, li') : []; + var out = []; + for (var i = 0; i < nodes.length && out.length < 80; i++) { + var t = (nodes[i].innerText || '').trim().replace(/\s+/g, ' '); + if (t.length >= 25) out.push(t); + } + if (out.length === 0 && root && root.innerText) { + var lines = root.innerText.split('\n'); + for (var j = 0; j < lines.length && out.length < 60; j++) { + var l = lines[j].trim(); + if (l.length >= 20) out.push(l); + } + } + return JSON.stringify({ title: title, paragraphs: out }); + })(); + """.trimIndent() + wv.evaluateJavascript(js) { raw -> + try { + if (raw == null || raw == "null") { + onResult(wv.title.orEmpty(), emptyList()) + return@evaluateJavascript + } + // Unquote JSON string returned by evaluateJavascript + val jsonText = org.json.JSONTokener(raw).nextValue() as? String ?: raw + val obj = org.json.JSONObject(jsonText) + val title = obj.optString("title", wv.title.orEmpty()) + val arr = obj.optJSONArray("paragraphs") + val list = mutableListOf() + if (arr != null) { + for (i in 0 until arr.length()) { + val p = arr.optString(i).trim() + if (p.isNotEmpty()) list.add(p) + } + } + onResult(title, list) + } catch (_: Exception) { + onResult(wv.title.orEmpty(), emptyList()) + } + } + } + + fun reload(tabId: String) { + webViews[tabId]?.reload() + } + + fun stopLoading(tabId: String) { + webViews[tabId]?.stopLoading() + } + + fun goBack(tabId: String): Boolean { + val wv = webViews[tabId] ?: return false + return if (wv.canGoBack()) { + wv.goBack() + true + } else { + false + } + } + + fun goForward(tabId: String): Boolean { + val wv = webViews[tabId] ?: return false + return if (wv.canGoForward()) { + wv.goForward() + true + } else { + false + } + } + + fun setDesktopSite(tab: BrowserTab, enabled: Boolean) { + val wv = webViews[tab.id] ?: return + val defaultUa = defaultUserAgents[tab.id] ?: wv.settings.userAgentString + wv.settings.userAgentString = if (enabled) DESKTOP_USER_AGENT else defaultUa + wv.settings.useWideViewPort = true + wv.settings.loadWithOverviewMode = true + if (!tab.isNewTab) { + wv.reload() + } + } + + fun findInPage(tabId: String, query: String) { + val wv = webViews[tabId] ?: return + if (query.isBlank()) { + wv.clearMatches() + callbacks.onFindResults(0, 0) + } else { + wv.findAllAsync(query) + } + } + + fun findNext(tabId: String, forward: Boolean) { + webViews[tabId]?.findNext(forward) + } + + fun clearFindMatches(tabId: String) { + webViews[tabId]?.clearMatches() + } + + fun saveCurrentPageArchive(tabId: String, title: String, url: String) { + val wv = webViews[tabId] ?: return + val safeName = (title.ifBlank { UrlUtils.extractDisplayHost(url).ifBlank { "page" } }) + .replace(Regex("[^a-zA-Z0-9._-]"), "_") + .take(40) + ".mht" + val dir = File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) ?: context.filesDir, "saved_pages") + if (!dir.exists()) dir.mkdirs() + val destFile = File(dir, safeName) + wv.saveWebArchive(destFile.absolutePath, false) { savedPath -> + val actualPath = savedPath ?: destFile.absolutePath + val size = runCatching { File(actualPath).length() }.getOrDefault(0L) + callbacks.onDownloadStarted( + fileName = safeName, + url = url, + mimeType = "multipart/related", + sizeBytes = size, + localPath = actualPath + ) + } + } + + fun captureThumbnail(tabId: String) { + val wv = webViews[tabId] ?: return + if (wv.width <= 0 || wv.height <= 0) return + try { + val scale = 0.25f + val targetW = (wv.width * scale).toInt().coerceIn(120, 360) + val targetH = (wv.height * scale).toInt().coerceIn(160, 480) + val bitmap = Bitmap.createBitmap(targetW, targetH, Bitmap.Config.RGB_565) + val canvas = Canvas(bitmap) + canvas.scale(targetW.toFloat() / wv.width.toFloat(), targetH.toFloat() / wv.height.toFloat()) + wv.draw(canvas) + callbacks.onThumbnailCaptured(tabId, bitmap) + } catch (_: Exception) { + // Skip thumbnail if WebView is not currently laid out + } + } + + fun clearAllCaches() { + webViews.values.forEach { it.clearCache(true) } + } + + fun destroyTab(tabId: String) { + val wv = webViews.remove(tabId) ?: return + defaultUserAgents.remove(tabId) + (wv.parent as? ViewGroup)?.removeView(wv) + wv.stopLoading() + wv.loadUrl("about:blank") + wv.clearHistory() + wv.removeAllViews() + wv.destroy() + } + + fun destroyAll() { + webViews.keys.toList().forEach { destroyTab(it) } + } + + @SuppressLint("SetJavaScriptEnabled") + private fun createWebView(tab: BrowserTab, settings: BrowserSettings): WebView { + val webView = WebView(context).apply { + layoutParams = ViewGroup.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.MATCH_PARENT + ) + isFocusable = true + isFocusableInTouchMode = true + } + + defaultUserAgents[tab.id] = webView.settings.userAgentString + applySettingsToWebView(webView, tab, settings) + + webView.setFindListener { activeMatchOrdinal, numberOfMatches, _ -> + callbacks.onFindResults( + activeMatchOrdinal = if (numberOfMatches > 0) activeMatchOrdinal + 1 else 0, + numberOfMatches = numberOfMatches + ) + } + + webView.webViewClient = object : WebViewClient() { + override fun shouldOverrideUrlLoading( + view: WebView?, + request: WebResourceRequest? + ): Boolean { + val uri = request?.url ?: return false + val scheme = uri.scheme?.lowercase() ?: return false + if (scheme == "http" || scheme == "https") { + if (scheme == "http" && currentSettings.httpsFirstEnabled && request.isForMainFrame) { + val upgraded = uri.buildUpon().scheme("https").build().toString() + loadUrl(tab.id, upgraded, currentSettings) + return true + } + return false + } + if (scheme == "about" || scheme == "data" || scheme == "blob") { + return false + } + return handleExternalScheme(uri) + } + + override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) { + val actualUrl = url ?: return + if (actualUrl == "about:blank") return + callbacks.onPageStarted(tab.id, actualUrl) + } + + override fun onPageFinished(view: WebView?, url: String?) { + val actualUrl = url ?: return + if (actualUrl == "about:blank") return + val wv = view ?: return + if (currentSettings.forceEnableZoom) { + injectForceZoom(wv) + } + callbacks.onPageFinished( + tabId = tab.id, + url = actualUrl, + title = wv.title?.takeIf { it.isNotBlank() } ?: UrlUtils.extractDisplayHost(actualUrl), + canGoBack = wv.canGoBack(), + canGoForward = wv.canGoForward() + ) + wv.postDelayed({ captureThumbnail(tab.id) }, 250L) + } + } + + webView.webChromeClient = object : WebChromeClient() { + override fun onProgressChanged(view: WebView?, newProgress: Int) { + callbacks.onProgressChanged(tab.id, newProgress) + } + + override fun onReceivedTitle(view: WebView?, title: String?) { + if (!title.isNullOrBlank()) { + callbacks.onTitleReceived(tab.id, title) + } + } + + override fun onReceivedIcon(view: WebView?, icon: Bitmap?) { + callbacks.onFaviconReceived(tab.id, icon) + } + + override fun onJsAlert( + view: WebView?, + url: String?, + message: String?, + result: JsResult? + ): Boolean { + if (result == null) return false + callbacks.onJsDialog(JsDialogState.Alert(url.orEmpty(), message.orEmpty(), result)) + return true + } + + override fun onJsConfirm( + view: WebView?, + url: String?, + message: String?, + result: JsResult? + ): Boolean { + if (result == null) return false + callbacks.onJsDialog(JsDialogState.Confirm(url.orEmpty(), message.orEmpty(), result)) + return true + } + + override fun onJsPrompt( + view: WebView?, + url: String?, + message: String?, + defaultValue: String?, + result: JsPromptResult? + ): Boolean { + if (result == null) return false + callbacks.onJsDialog( + JsDialogState.Prompt( + url.orEmpty(), + message.orEmpty(), + defaultValue.orEmpty(), + result + ) + ) + return true + } + + override fun onShowCustomView(view: View?, callback: CustomViewCallback?) { + if (view != null && callback != null) { + callbacks.onShowCustomView(view, callback) + } + } + + override fun onHideCustomView() { + callbacks.onHideCustomView() + } + + override fun onShowFileChooser( + webView: WebView?, + filePathCallback: ValueCallback>?, + fileChooserParams: FileChooserParams? + ): Boolean { + if (filePathCallback == null) return false + val acceptTypes = fileChooserParams?.acceptTypes ?: arrayOf("*/*") + callbacks.onFileChooserRequested(filePathCallback, acceptTypes) + return true + } + } + + webView.setDownloadListener { url, userAgent, contentDisposition, mimeType, contentLength -> + val fileName = URLUtil.guessFileName(url, contentDisposition, mimeType) + val resolvedMime = mimeType.ifBlank { "application/octet-stream" } + var localPath = "" + if (url.startsWith("http://", ignoreCase = true) || + url.startsWith("https://", ignoreCase = true) + ) { + runCatching { + val request = DownloadManager.Request(Uri.parse(url)).apply { + setMimeType(resolvedMime) + val cookies = CookieManager.getInstance().getCookie(url) + if (!cookies.isNullOrBlank()) addRequestHeader("cookie", cookies) + addRequestHeader("User-Agent", userAgent) + setTitle(fileName) + setDescription("Downloading with Bansify Browser") + setNotificationVisibility( + DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED + ) + setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName) + } + val dm = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager + dm.enqueue(request) + localPath = File( + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), + fileName + ).absolutePath + } + } + callbacks.onDownloadStarted( + fileName = fileName, + url = url, + mimeType = resolvedMime, + sizeBytes = contentLength.coerceAtLeast(0L), + localPath = localPath + ) + } + + return webView + } + + @SuppressLint("SetJavaScriptEnabled") + private fun applySettingsToWebView( + webView: WebView, + tab: BrowserTab, + settings: BrowserSettings + ) { + val ws = webView.settings + ws.javaScriptEnabled = settings.javascriptEnabled + ws.domStorageEnabled = !tab.isIncognito + ws.databaseEnabled = !tab.isIncognito + ws.loadsImagesAutomatically = settings.loadImagesEnabled + ws.javaScriptCanOpenWindowsAutomatically = settings.popupsAllowed + ws.mediaPlaybackRequiresUserGesture = !settings.mediaAutoplayEnabled + ws.textZoom = settings.textZoomPercent.coerceIn(50, 200) + ws.useWideViewPort = true + ws.loadWithOverviewMode = true + ws.builtInZoomControls = true + ws.displayZoomControls = false + ws.setSupportZoom(true) + ws.allowFileAccess = false + ws.allowContentAccess = true + ws.mixedContentMode = WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE + ws.cacheMode = if (tab.isIncognito) WebSettings.LOAD_NO_CACHE else WebSettings.LOAD_DEFAULT + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + ws.safeBrowsingEnabled = settings.safeBrowsingLevel != SafeBrowsingLevel.NONE + } + + val defaultUa = defaultUserAgents[tab.id] ?: ws.userAgentString + val wantDesktop = tab.isDesktopSite || settings.defaultDesktopSite + val desiredUa = if (wantDesktop) DESKTOP_USER_AGENT else defaultUa + if (ws.userAgentString != desiredUa) { + ws.userAgentString = desiredUa + } + + val cookieManager = CookieManager.getInstance() + cookieManager.setAcceptCookie(settings.cookiesEnabled && !tab.isIncognito) + val allowThirdParty = when { + !settings.cookiesEnabled -> false + settings.thirdPartyCookiePolicy == ThirdPartyCookiePolicy.BLOCK_ALL -> false + settings.thirdPartyCookiePolicy == ThirdPartyCookiePolicy.BLOCK_INCOGNITO && tab.isIncognito -> false + else -> true + } + cookieManager.setAcceptThirdPartyCookies(webView, allowThirdParty) + } + + private fun injectForceZoom(webView: WebView) { + val script = """ + (function() { + var meta = document.querySelector('meta[name=viewport]'); + if (meta) { + meta.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=5.0, user-scalable=yes'); + } + })(); + """.trimIndent() + webView.evaluateJavascript(script, null) + } + + private fun handleExternalScheme(uri: Uri): Boolean { + return try { + val intent = if (uri.scheme.equals("intent", ignoreCase = true)) { + Intent.parseUri(uri.toString(), Intent.URI_INTENT_SCHEME) + } else { + Intent(Intent.ACTION_VIEW, uri) + } + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + context.startActivity(intent) + true + } catch (_: ActivityNotFoundException) { + callbacks.onExternalUrlError("No app found to open ${uri.scheme} link") + true + } catch (_: Exception) { + true + } + } +} diff --git a/app/src/main/java/com/bansify/browser/data/BansifyAccount.kt b/app/src/main/java/com/bansify/browser/data/BansifyAccount.kt new file mode 100644 index 00000000..f85c391a --- /dev/null +++ b/app/src/main/java/com/bansify/browser/data/BansifyAccount.kt @@ -0,0 +1,180 @@ +package com.bansify.browser.data + +import android.content.Context +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.booleanPreferencesKey +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.longPreferencesKey +import androidx.datastore.preferences.core.stringPreferencesKey +import androidx.datastore.preferences.preferencesDataStore +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.map +import java.util.UUID + +private val Context.bansifyAccountDataStore: DataStore by preferencesDataStore( + name = "bansify_account_store" +) + +data class BansifyAccountState( + val isSignedIn: Boolean = false, + val userId: String = "", + val displayName: String = "", + val email: String = "", + val avatarColorHex: Long = 0xFF1A73E8L, + val syncEverything: Boolean = true, + val syncBookmarks: Boolean = true, + val syncHistory: Boolean = true, + val syncOpenTabs: Boolean = true, + val syncShortcuts: Boolean = true, + val syncSettings: Boolean = true, + val syncDownloadsList: Boolean = false, + val autocompleteSearches: Boolean = true, + val improveSearchSuggestions: Boolean = true, + val usageReportsEnabled: Boolean = false, + val lastSyncedAt: Long = 0L, + val isSyncing: Boolean = false +) { + val effectiveBookmarksSync: Boolean get() = isSignedIn && (syncEverything || syncBookmarks) + val effectiveHistorySync: Boolean get() = isSignedIn && (syncEverything || syncHistory) + val effectiveTabsSync: Boolean get() = isSignedIn && (syncEverything || syncOpenTabs) + val effectiveShortcutsSync: Boolean get() = isSignedIn && (syncEverything || syncShortcuts) + val effectiveSettingsSync: Boolean get() = isSignedIn && (syncEverything || syncSettings) + val effectiveDownloadsSync: Boolean get() = isSignedIn && (syncEverything || syncDownloadsList) + + val activeSyncCategoriesCount: Int + get() = listOf( + effectiveBookmarksSync, + effectiveHistorySync, + effectiveTabsSync, + effectiveShortcutsSync, + effectiveSettingsSync, + effectiveDownloadsSync + ).count { it } + + val initialLetter: String + get() = displayName.firstOrNull { it.isLetterOrDigit() }?.uppercaseChar()?.toString() + ?: email.firstOrNull { it.isLetterOrDigit() }?.uppercaseChar()?.toString() + ?: "B" +} + +/** + * Clean contract for Bansify Account authentication & cloud sync. + * Replace DemoBansifyAccountProvider with your real Bansify API client later + * without changing any UI or ViewModel code. + */ +interface BansifyAccountProvider { + val accountState: Flow + suspend fun signIn(displayName: String, email: String, avatarColorHex: Long = 0xFF1A73E8L) + suspend fun updateProfile(displayName: String, email: String, avatarColorHex: Long) + suspend fun signOut() + suspend fun updateSyncPreferences(transform: (BansifyAccountState) -> BansifyAccountState) + suspend fun performSync(): Long +} + +/** + * Local demo implementation backed by Jetpack DataStore. + * Preserves sign-in state, profile, granular sync preferences, and last sync timestamp. + */ +class DemoBansifyAccountProvider( + private val context: Context +) : BansifyAccountProvider { + + private object Keys { + val IS_SIGNED_IN = booleanPreferencesKey("is_signed_in") + val USER_ID = stringPreferencesKey("user_id") + val DISPLAY_NAME = stringPreferencesKey("display_name") + val EMAIL = stringPreferencesKey("email") + val AVATAR_COLOR = longPreferencesKey("avatar_color") + val SYNC_EVERYTHING = booleanPreferencesKey("sync_everything") + val SYNC_BOOKMARKS = booleanPreferencesKey("sync_bookmarks") + val SYNC_HISTORY = booleanPreferencesKey("sync_history") + val SYNC_OPEN_TABS = booleanPreferencesKey("sync_open_tabs") + val SYNC_SHORTCUTS = booleanPreferencesKey("sync_shortcuts") + val SYNC_SETTINGS = booleanPreferencesKey("sync_settings") + val SYNC_DOWNLOADS = booleanPreferencesKey("sync_downloads") + val AUTOCOMPLETE_SEARCHES = booleanPreferencesKey("autocomplete_searches") + val IMPROVE_SUGGESTIONS = booleanPreferencesKey("improve_suggestions") + val USAGE_REPORTS = booleanPreferencesKey("usage_reports") + val LAST_SYNCED_AT = longPreferencesKey("last_synced_at") + } + + private fun readState(prefs: Preferences): BansifyAccountState = BansifyAccountState( + isSignedIn = prefs[Keys.IS_SIGNED_IN] ?: false, + userId = prefs[Keys.USER_ID] ?: "", + displayName = prefs[Keys.DISPLAY_NAME] ?: "", + email = prefs[Keys.EMAIL] ?: "", + avatarColorHex = prefs[Keys.AVATAR_COLOR] ?: 0xFF1A73E8L, + syncEverything = prefs[Keys.SYNC_EVERYTHING] ?: true, + syncBookmarks = prefs[Keys.SYNC_BOOKMARKS] ?: true, + syncHistory = prefs[Keys.SYNC_HISTORY] ?: true, + syncOpenTabs = prefs[Keys.SYNC_OPEN_TABS] ?: true, + syncShortcuts = prefs[Keys.SYNC_SHORTCUTS] ?: true, + syncSettings = prefs[Keys.SYNC_SETTINGS] ?: true, + syncDownloadsList = prefs[Keys.SYNC_DOWNLOADS] ?: false, + autocompleteSearches = prefs[Keys.AUTOCOMPLETE_SEARCHES] ?: true, + improveSearchSuggestions = prefs[Keys.IMPROVE_SUGGESTIONS] ?: true, + usageReportsEnabled = prefs[Keys.USAGE_REPORTS] ?: false, + lastSyncedAt = prefs[Keys.LAST_SYNCED_AT] ?: 0L + ) + + override val accountState: Flow = + context.bansifyAccountDataStore.data.map(::readState) + + override suspend fun signIn(displayName: String, email: String, avatarColorHex: Long) { + val now = System.currentTimeMillis() + context.bansifyAccountDataStore.edit { prefs -> + prefs[Keys.IS_SIGNED_IN] = true + prefs[Keys.USER_ID] = "bansify_${UUID.randomUUID().toString().take(8)}" + prefs[Keys.DISPLAY_NAME] = displayName.trim().ifBlank { "Bansify User" } + prefs[Keys.EMAIL] = email.trim().ifBlank { "user@bansify.com" } + prefs[Keys.AVATAR_COLOR] = avatarColorHex + prefs[Keys.LAST_SYNCED_AT] = now + } + } + + override suspend fun updateProfile(displayName: String, email: String, avatarColorHex: Long) { + context.bansifyAccountDataStore.edit { prefs -> + prefs[Keys.DISPLAY_NAME] = displayName.trim().ifBlank { "Bansify User" } + prefs[Keys.EMAIL] = email.trim().ifBlank { "user@bansify.com" } + prefs[Keys.AVATAR_COLOR] = avatarColorHex + } + } + + override suspend fun signOut() { + context.bansifyAccountDataStore.edit { prefs -> + prefs[Keys.IS_SIGNED_IN] = false + prefs[Keys.USER_ID] = "" + prefs[Keys.DISPLAY_NAME] = "" + prefs[Keys.EMAIL] = "" + prefs[Keys.LAST_SYNCED_AT] = 0L + } + } + + override suspend fun updateSyncPreferences(transform: (BansifyAccountState) -> BansifyAccountState) { + context.bansifyAccountDataStore.edit { prefs -> + val updated = transform(readState(prefs)) + prefs[Keys.SYNC_EVERYTHING] = updated.syncEverything + prefs[Keys.SYNC_BOOKMARKS] = updated.syncBookmarks + prefs[Keys.SYNC_HISTORY] = updated.syncHistory + prefs[Keys.SYNC_OPEN_TABS] = updated.syncOpenTabs + prefs[Keys.SYNC_SHORTCUTS] = updated.syncShortcuts + prefs[Keys.SYNC_SETTINGS] = updated.syncSettings + prefs[Keys.SYNC_DOWNLOADS] = updated.syncDownloadsList + prefs[Keys.AUTOCOMPLETE_SEARCHES] = updated.autocompleteSearches + prefs[Keys.IMPROVE_SUGGESTIONS] = updated.improveSearchSuggestions + prefs[Keys.USAGE_REPORTS] = updated.usageReportsEnabled + } + } + + override suspend fun performSync(): Long { + // Simulated network round-trip — replace with real Bansify Sync REST call later + delay(550L) + val now = System.currentTimeMillis() + context.bansifyAccountDataStore.edit { prefs -> + prefs[Keys.LAST_SYNCED_AT] = now + } + return now + } +} diff --git a/app/src/main/java/com/bansify/browser/data/BrowserDao.kt b/app/src/main/java/com/bansify/browser/data/BrowserDao.kt new file mode 100644 index 00000000..31cf5958 --- /dev/null +++ b/app/src/main/java/com/bansify/browser/data/BrowserDao.kt @@ -0,0 +1,91 @@ +package com.bansify.browser.data + +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.OnConflictStrategy +import androidx.room.Query +import androidx.room.Update +import kotlinx.coroutines.flow.Flow + +@Dao +interface BrowserDao { + // --- Bookmarks --- + @Query("SELECT * FROM bookmarks ORDER BY createdAt DESC") + fun getAllBookmarks(): Flow> + + @Query("SELECT * FROM bookmarks WHERE url = :url LIMIT 1") + suspend fun getBookmarkByUrl(url: String): BookmarkEntity? + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun insertBookmark(bookmark: BookmarkEntity): Long + + @Update + suspend fun updateBookmark(bookmark: BookmarkEntity) + + @Query("DELETE FROM bookmarks WHERE id = :id") + suspend fun deleteBookmarkById(id: Long) + + @Query("DELETE FROM bookmarks WHERE url = :url") + suspend fun deleteBookmarkByUrl(url: String) + + // --- History --- + @Query("SELECT * FROM history ORDER BY visitedAt DESC LIMIT 500") + fun getAllHistory(): Flow> + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun insertHistory(entry: HistoryEntity) + + @Query("DELETE FROM history WHERE id = :id") + suspend fun deleteHistoryById(id: Long) + + @Query("DELETE FROM history WHERE visitedAt >= :sinceTimestamp") + suspend fun deleteHistorySince(sinceTimestamp: Long) + + @Query("DELETE FROM history") + suspend fun clearAllHistory() + + // --- Downloads --- + @Query("SELECT * FROM downloads ORDER BY downloadedAt DESC") + fun getAllDownloads(): Flow> + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun insertDownload(download: DownloadEntity): Long + + @Query("UPDATE downloads SET status = :status, sizeBytes = :sizeBytes, localPath = :localPath WHERE id = :id") + suspend fun updateDownloadStatus(id: Long, status: String, sizeBytes: Long, localPath: String) + + @Query("DELETE FROM downloads WHERE id = :id") + suspend fun deleteDownloadById(id: Long) + + @Query("DELETE FROM downloads") + suspend fun clearAllDownloads() + + // --- Quick Shortcuts --- + @Query("SELECT * FROM shortcuts ORDER BY sortOrder ASC, id ASC") + fun getAllShortcuts(): Flow> + + @Query("SELECT COUNT(*) FROM shortcuts") + suspend fun getShortcutCount(): Int + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun insertShortcuts(shortcuts: List) + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun insertShortcut(shortcut: ShortcutEntity) + + @Update + suspend fun updateShortcut(shortcut: ShortcutEntity) + + @Query("DELETE FROM shortcuts WHERE id = :id") + suspend fun deleteShortcutById(id: Long) + + // --- Saved Tabs --- + @Query("SELECT * FROM saved_tabs ORDER BY lastAccessedAt ASC") + suspend fun getSavedTabsOnce(): List + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun saveTabs(tabs: List) + + @Query("DELETE FROM saved_tabs") + suspend fun clearSavedTabs() +} diff --git a/app/src/main/java/com/bansify/browser/data/BrowserDatabase.kt b/app/src/main/java/com/bansify/browser/data/BrowserDatabase.kt new file mode 100644 index 00000000..905cb376 --- /dev/null +++ b/app/src/main/java/com/bansify/browser/data/BrowserDatabase.kt @@ -0,0 +1,38 @@ +package com.bansify.browser.data + +import android.content.Context +import androidx.room.Database +import androidx.room.Room +import androidx.room.RoomDatabase + +@Database( + entities = [ + BookmarkEntity::class, + HistoryEntity::class, + DownloadEntity::class, + ShortcutEntity::class, + SavedTabEntity::class + ], + version = 1, + exportSchema = false +) +abstract class BrowserDatabase : RoomDatabase() { + abstract fun browserDao(): BrowserDao + + companion object { + @Volatile + private var INSTANCE: BrowserDatabase? = null + + fun getInstance(context: Context): BrowserDatabase { + return INSTANCE ?: synchronized(this) { + INSTANCE ?: Room.databaseBuilder( + context.applicationContext, + BrowserDatabase::class.java, + "bansify_browser.db" + ).fallbackToDestructiveMigration(dropAllTables = true) + .build() + .also { INSTANCE = it } + } + } + } +} diff --git a/app/src/main/java/com/bansify/browser/data/BrowserEntities.kt b/app/src/main/java/com/bansify/browser/data/BrowserEntities.kt new file mode 100644 index 00000000..c323bcd9 --- /dev/null +++ b/app/src/main/java/com/bansify/browser/data/BrowserEntities.kt @@ -0,0 +1,52 @@ +package com.bansify.browser.data + +import androidx.room.Entity +import androidx.room.PrimaryKey + +@Entity(tableName = "bookmarks") +data class BookmarkEntity( + @PrimaryKey(autoGenerate = true) val id: Long = 0, + val title: String, + val url: String, + val folder: String = "Mobile bookmarks", + val createdAt: Long = System.currentTimeMillis() +) + +@Entity(tableName = "history") +data class HistoryEntity( + @PrimaryKey(autoGenerate = true) val id: Long = 0, + val title: String, + val url: String, + val visitedAt: Long = System.currentTimeMillis() +) + +@Entity(tableName = "downloads") +data class DownloadEntity( + @PrimaryKey(autoGenerate = true) val id: Long = 0, + val fileName: String, + val url: String, + val mimeType: String = "application/octet-stream", + val sizeBytes: Long = 0L, + val category: String = "Other", // Pages, Images, Documents, Other + val status: String = "Completed", // Downloading, Completed, Failed + val downloadedAt: Long = System.currentTimeMillis(), + val localPath: String = "" +) + +@Entity(tableName = "shortcuts") +data class ShortcutEntity( + @PrimaryKey(autoGenerate = true) val id: Long = 0, + val title: String, + val url: String, + val accentColor: Long = 0xFF1A73E8, + val sortOrder: Int = 0 +) + +@Entity(tableName = "saved_tabs") +data class SavedTabEntity( + @PrimaryKey val tabId: String, + val url: String, + val title: String, + val isDesktopSite: Boolean = false, + val lastAccessedAt: Long = System.currentTimeMillis() +) diff --git a/app/src/main/java/com/bansify/browser/data/BrowserModels.kt b/app/src/main/java/com/bansify/browser/data/BrowserModels.kt new file mode 100644 index 00000000..db1d7ca9 --- /dev/null +++ b/app/src/main/java/com/bansify/browser/data/BrowserModels.kt @@ -0,0 +1,207 @@ +package com.bansify.browser.data + +import android.graphics.Bitmap +import android.webkit.JsPromptResult +import android.webkit.JsResult +import java.util.UUID + +enum class SearchEngine( + val displayName: String, + val domain: String, + val queryUrlTemplate: String +) { + GOOGLE("Google", "google.com", "https://www.google.com/search?q=%s"), + DUCKDUCKGO("DuckDuckGo", "duckduckgo.com", "https://duckduckgo.com/?q=%s"), + BING("Bing", "bing.com", "https://www.bing.com/search?q=%s"), + YAHOO("Yahoo!", "search.yahoo.com", "https://search.yahoo.com/search?p=%s"), + BRAVE("Brave Search", "search.brave.com", "https://search.brave.com/search?q=%s"), + ECOSIA("Ecosia", "ecosia.org", "https://www.ecosia.org/search?q=%s") +} + +enum class ThemeMode(val label: String) { + SYSTEM("System default"), + LIGHT("Light"), + DARK("Dark") +} + +enum class AddressBarPosition(val label: String, val description: String) { + TOP("Top", "Show address bar at the top of the screen"), + BOTTOM("Bottom", "Move address bar to the bottom for easier one-handed reach") +} + +enum class SafeBrowsingLevel(val label: String, val summary: String) { + ENHANCED( + "Enhanced protection", + "Faster, proactive protection against dangerous websites, downloads, and extensions" + ), + STANDARD( + "Standard protection", + "Standard protection against websites, downloads, and extensions known to be dangerous" + ), + NONE( + "No protection (not recommended)", + "Does not protect you against dangerous websites, downloads, and extensions" + ) +} + +enum class ThirdPartyCookiePolicy(val label: String, val summary: String) { + ALLOW("Allow third-party cookies", "Sites can use cookies to improve your browsing experience"), + BLOCK_INCOGNITO( + "Block third-party cookies in Incognito", + "Features on some sites may break in Incognito mode" + ), + BLOCK_ALL( + "Block third-party cookies", + "Sites can't use cookies that track you across the web" + ) +} + +enum class ToolbarShortcut(val label: String) { + NEW_TAB("New tab"), + SHARE("Share"), + BOOKMARK("Bookmark"), + NONE("None") +} + +enum class TimeRange(val label: String, val durationMillis: Long) { + LAST_15_MIN("Last 15 minutes", 15L * 60L * 1000L), + LAST_HOUR("Last hour", 60L * 60L * 1000L), + LAST_24_HOURS("Last 24 hours", 24L * 60L * 60L * 1000L), + LAST_7_DAYS("Last 7 days", 7L * 24L * 60L * 60L * 1000L), + LAST_4_WEEKS("Last 4 weeks", 28L * 24L * 60L * 60L * 1000L), + ALL_TIME("All time", Long.MAX_VALUE) +} + +data class BrowserSettings( + val searchEngine: SearchEngine = SearchEngine.GOOGLE, + val addressBarPosition: AddressBarPosition = AddressBarPosition.TOP, + val themeMode: ThemeMode = ThemeMode.SYSTEM, + val homepageEnabled: Boolean = true, + val useCustomHomepage: Boolean = false, + val customHomepageUrl: String = "https://www.google.com", + val toolbarShortcut: ToolbarShortcut = ToolbarShortcut.NEW_TAB, + val openExternalLinksInNewTab: Boolean = true, + val autoCloseTabsDays: Int = 0, + val safeBrowsingLevel: SafeBrowsingLevel = SafeBrowsingLevel.STANDARD, + val httpsFirstEnabled: Boolean = true, + val doNotTrackEnabled: Boolean = false, + val thirdPartyCookiePolicy: ThirdPartyCookiePolicy = ThirdPartyCookiePolicy.BLOCK_INCOGNITO, + val lockIncognitoOnLeave: Boolean = false, + val saveFormDataEnabled: Boolean = true, + val autofillAddressesEnabled: Boolean = true, + val notificationsEnabled: Boolean = true, + val downloadNotificationsEnabled: Boolean = true, + val preferredLanguage: String = "English (United States)", + val offerTranslatePages: Boolean = true, + val javascriptEnabled: Boolean = true, + val cookiesEnabled: Boolean = true, + val popupsAllowed: Boolean = false, + val loadImagesEnabled: Boolean = true, + val defaultDesktopSite: Boolean = false, + val mediaAutoplayEnabled: Boolean = true, + val textZoomPercent: Int = 100, + val forceEnableZoom: Boolean = false, + val simplifiedViewEnabled: Boolean = false, + val askWhereToSaveDownloads: Boolean = false, + val showRecentCardsOnNtp: Boolean = true +) + +data class BrowserTab( + val id: String = UUID.randomUUID().toString(), + val url: String = NEW_TAB_URL, + val title: String = "New tab", + val isIncognito: Boolean = false, + val isDesktopSite: Boolean = false, + val groupName: String? = null, + val groupColor: Long? = null, + val progress: Int = 0, + val isLoading: Boolean = false, + val canGoBack: Boolean = false, + val canGoForward: Boolean = false, + val isSecure: Boolean = false, + val favicon: Bitmap? = null, + val thumbnail: Bitmap? = null, + val createdAt: Long = System.currentTimeMillis(), + val lastAccessedAt: Long = System.currentTimeMillis() +) { + val isNewTab: Boolean + get() = url.isBlank() || url == NEW_TAB_URL + + companion object { + const val NEW_TAB_URL = "bansify://newtab" + } +} + +data class ClosedTab( + val title: String, + val url: String, + val closedAt: Long = System.currentTimeMillis() +) + +data class ReadingModeContent( + val title: String, + val domain: String, + val url: String, + val paragraphs: List +) + +enum class SettingsSubScreen(val title: String) { + MAIN("Settings"), + BANSIFY_ACCOUNT("Bansify Account & sync"), + BANSIFY_SERVICES("Bansify services"), + SEARCH_ENGINE("Search engine"), + ADDRESS_BAR("Address bar"), + PRIVACY_SECURITY("Privacy and security"), + SAFE_BROWSING("Safe Browsing"), + THIRD_PARTY_COOKIES("Third-party cookies"), + SAFETY_CHECK("Safety check"), + DEFAULT_BROWSER("Default browser"), + AUTOFILL("Autofill and passwords"), + TABS("Tabs and tab groups"), + HOMEPAGE("Homepage"), + NOTIFICATIONS("Notifications"), + APPEARANCE("Appearance"), + TOOLBAR_SHORTCUT("Toolbar shortcut"), + THEME("Theme"), + ACCESSIBILITY("Accessibility"), + SITE_SETTINGS("Site settings"), + LANGUAGES("Languages"), + DOWNLOADS_SETTINGS("Downloads"), + ABOUT("About Bansify") +} + +sealed interface BrowserOverlay { + data object None : BrowserOverlay + data class TabSwitcher(val showIncognito: Boolean = false) : BrowserOverlay + data class Omnibox(val initialQuery: String = "") : BrowserOverlay + data object Bookmarks : BrowserOverlay + data object History : BrowserOverlay + data object Downloads : BrowserOverlay + data object RecentTabs : BrowserOverlay + data object DeleteBrowsingData : BrowserOverlay + data class Settings(val subScreen: SettingsSubScreen = SettingsSubScreen.MAIN) : BrowserOverlay +} + +sealed interface JsDialogState { + data class Alert(val url: String, val message: String, val result: JsResult) : JsDialogState + data class Confirm(val url: String, val message: String, val result: JsResult) : JsDialogState + data class Prompt( + val url: String, + val message: String, + val defaultValue: String, + val result: JsPromptResult + ) : JsDialogState +} + +data class FindInPageState( + val isActive: Boolean = false, + val query: String = "", + val activeMatchOrdinal: Int = 0, + val numberOfMatches: Int = 0 +) + +data class SnackbarEvent( + val message: String, + val actionLabel: String? = null, + val onAction: (() -> Unit)? = null +) diff --git a/app/src/main/java/com/bansify/browser/data/BrowserPreferences.kt b/app/src/main/java/com/bansify/browser/data/BrowserPreferences.kt new file mode 100644 index 00000000..98c98682 --- /dev/null +++ b/app/src/main/java/com/bansify/browser/data/BrowserPreferences.kt @@ -0,0 +1,147 @@ +package com.bansify.browser.data + +import android.content.Context +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.booleanPreferencesKey +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.intPreferencesKey +import androidx.datastore.preferences.core.stringPreferencesKey +import androidx.datastore.preferences.preferencesDataStore +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.map + +private val Context.browserDataStore: DataStore by preferencesDataStore( + name = "bansify_browser_settings" +) + +class BrowserPreferences(private val context: Context) { + + private object Keys { + val SEARCH_ENGINE = stringPreferencesKey("search_engine") + val ADDRESS_BAR_POSITION = stringPreferencesKey("address_bar_position") + val THEME_MODE = stringPreferencesKey("theme_mode") + val HOMEPAGE_ENABLED = booleanPreferencesKey("homepage_enabled") + val USE_CUSTOM_HOMEPAGE = booleanPreferencesKey("use_custom_homepage") + val CUSTOM_HOMEPAGE_URL = stringPreferencesKey("custom_homepage_url") + val TOOLBAR_SHORTCUT = stringPreferencesKey("toolbar_shortcut") + val OPEN_EXTERNAL_NEW_TAB = booleanPreferencesKey("open_external_new_tab") + val AUTO_CLOSE_TABS_DAYS = intPreferencesKey("auto_close_tabs_days") + val SAFE_BROWSING = stringPreferencesKey("safe_browsing") + val HTTPS_FIRST = booleanPreferencesKey("https_first") + val DO_NOT_TRACK = booleanPreferencesKey("do_not_track") + val THIRD_PARTY_COOKIES = stringPreferencesKey("third_party_cookies") + val LOCK_INCOGNITO_ON_LEAVE = booleanPreferencesKey("lock_incognito_on_leave") + val SAVE_FORM_DATA = booleanPreferencesKey("save_form_data") + val AUTOFILL_ADDRESSES = booleanPreferencesKey("autofill_addresses") + val NOTIFICATIONS_ENABLED = booleanPreferencesKey("notifications_enabled") + val DOWNLOAD_NOTIFICATIONS = booleanPreferencesKey("download_notifications") + val PREFERRED_LANGUAGE = stringPreferencesKey("preferred_language") + val OFFER_TRANSLATE = booleanPreferencesKey("offer_translate") + val JAVASCRIPT_ENABLED = booleanPreferencesKey("javascript_enabled") + val COOKIES_ENABLED = booleanPreferencesKey("cookies_enabled") + val POPUPS_ALLOWED = booleanPreferencesKey("popups_allowed") + val LOAD_IMAGES = booleanPreferencesKey("load_images") + val DEFAULT_DESKTOP_SITE = booleanPreferencesKey("default_desktop_site") + val MEDIA_AUTOPLAY = booleanPreferencesKey("media_autoplay") + val TEXT_ZOOM_PERCENT = intPreferencesKey("text_zoom_percent") + val FORCE_ENABLE_ZOOM = booleanPreferencesKey("force_enable_zoom") + val SIMPLIFIED_VIEW = booleanPreferencesKey("simplified_view") + val ASK_WHERE_TO_SAVE = booleanPreferencesKey("ask_where_to_save") + val SHOW_RECENT_CARDS = booleanPreferencesKey("show_recent_cards") + val SHORTCUTS_SEEDED = booleanPreferencesKey("shortcuts_seeded") + } + + private fun readSettings(prefs: Preferences): BrowserSettings = BrowserSettings( + searchEngine = prefs[Keys.SEARCH_ENGINE] + ?.let { runCatching { SearchEngine.valueOf(it) }.getOrNull() } + ?: SearchEngine.GOOGLE, + addressBarPosition = prefs[Keys.ADDRESS_BAR_POSITION] + ?.let { runCatching { AddressBarPosition.valueOf(it) }.getOrNull() } + ?: AddressBarPosition.TOP, + themeMode = prefs[Keys.THEME_MODE] + ?.let { runCatching { ThemeMode.valueOf(it) }.getOrNull() } + ?: ThemeMode.SYSTEM, + homepageEnabled = prefs[Keys.HOMEPAGE_ENABLED] ?: true, + useCustomHomepage = prefs[Keys.USE_CUSTOM_HOMEPAGE] ?: false, + customHomepageUrl = prefs[Keys.CUSTOM_HOMEPAGE_URL] ?: "https://www.google.com", + toolbarShortcut = prefs[Keys.TOOLBAR_SHORTCUT] + ?.let { runCatching { ToolbarShortcut.valueOf(it) }.getOrNull() } + ?: ToolbarShortcut.NEW_TAB, + openExternalLinksInNewTab = prefs[Keys.OPEN_EXTERNAL_NEW_TAB] ?: true, + autoCloseTabsDays = prefs[Keys.AUTO_CLOSE_TABS_DAYS] ?: 0, + safeBrowsingLevel = prefs[Keys.SAFE_BROWSING] + ?.let { runCatching { SafeBrowsingLevel.valueOf(it) }.getOrNull() } + ?: SafeBrowsingLevel.STANDARD, + httpsFirstEnabled = prefs[Keys.HTTPS_FIRST] ?: true, + doNotTrackEnabled = prefs[Keys.DO_NOT_TRACK] ?: false, + thirdPartyCookiePolicy = prefs[Keys.THIRD_PARTY_COOKIES] + ?.let { runCatching { ThirdPartyCookiePolicy.valueOf(it) }.getOrNull() } + ?: ThirdPartyCookiePolicy.BLOCK_INCOGNITO, + lockIncognitoOnLeave = prefs[Keys.LOCK_INCOGNITO_ON_LEAVE] ?: false, + saveFormDataEnabled = prefs[Keys.SAVE_FORM_DATA] ?: true, + autofillAddressesEnabled = prefs[Keys.AUTOFILL_ADDRESSES] ?: true, + notificationsEnabled = prefs[Keys.NOTIFICATIONS_ENABLED] ?: true, + downloadNotificationsEnabled = prefs[Keys.DOWNLOAD_NOTIFICATIONS] ?: true, + preferredLanguage = prefs[Keys.PREFERRED_LANGUAGE] ?: "English (United States)", + offerTranslatePages = prefs[Keys.OFFER_TRANSLATE] ?: true, + javascriptEnabled = prefs[Keys.JAVASCRIPT_ENABLED] ?: true, + cookiesEnabled = prefs[Keys.COOKIES_ENABLED] ?: true, + popupsAllowed = prefs[Keys.POPUPS_ALLOWED] ?: false, + loadImagesEnabled = prefs[Keys.LOAD_IMAGES] ?: true, + defaultDesktopSite = prefs[Keys.DEFAULT_DESKTOP_SITE] ?: false, + mediaAutoplayEnabled = prefs[Keys.MEDIA_AUTOPLAY] ?: true, + textZoomPercent = prefs[Keys.TEXT_ZOOM_PERCENT] ?: 100, + forceEnableZoom = prefs[Keys.FORCE_ENABLE_ZOOM] ?: false, + simplifiedViewEnabled = prefs[Keys.SIMPLIFIED_VIEW] ?: false, + askWhereToSaveDownloads = prefs[Keys.ASK_WHERE_TO_SAVE] ?: false, + showRecentCardsOnNtp = prefs[Keys.SHOW_RECENT_CARDS] ?: true + ) + + val settingsFlow: Flow = context.browserDataStore.data.map(::readSettings) + + val shortcutsSeededFlow: Flow = context.browserDataStore.data.map { prefs -> + prefs[Keys.SHORTCUTS_SEEDED] ?: false + } + + suspend fun markShortcutsSeeded() { + context.browserDataStore.edit { it[Keys.SHORTCUTS_SEEDED] = true } + } + + suspend fun updateSettings(transform: (BrowserSettings) -> BrowserSettings) { + context.browserDataStore.edit { prefs -> + val updated = transform(readSettings(prefs)) + prefs[Keys.SEARCH_ENGINE] = updated.searchEngine.name + prefs[Keys.ADDRESS_BAR_POSITION] = updated.addressBarPosition.name + prefs[Keys.THEME_MODE] = updated.themeMode.name + prefs[Keys.HOMEPAGE_ENABLED] = updated.homepageEnabled + prefs[Keys.USE_CUSTOM_HOMEPAGE] = updated.useCustomHomepage + prefs[Keys.CUSTOM_HOMEPAGE_URL] = updated.customHomepageUrl + prefs[Keys.TOOLBAR_SHORTCUT] = updated.toolbarShortcut.name + prefs[Keys.OPEN_EXTERNAL_NEW_TAB] = updated.openExternalLinksInNewTab + prefs[Keys.AUTO_CLOSE_TABS_DAYS] = updated.autoCloseTabsDays + prefs[Keys.SAFE_BROWSING] = updated.safeBrowsingLevel.name + prefs[Keys.HTTPS_FIRST] = updated.httpsFirstEnabled + prefs[Keys.DO_NOT_TRACK] = updated.doNotTrackEnabled + prefs[Keys.THIRD_PARTY_COOKIES] = updated.thirdPartyCookiePolicy.name + prefs[Keys.LOCK_INCOGNITO_ON_LEAVE] = updated.lockIncognitoOnLeave + prefs[Keys.SAVE_FORM_DATA] = updated.saveFormDataEnabled + prefs[Keys.AUTOFILL_ADDRESSES] = updated.autofillAddressesEnabled + prefs[Keys.NOTIFICATIONS_ENABLED] = updated.notificationsEnabled + prefs[Keys.DOWNLOAD_NOTIFICATIONS] = updated.downloadNotificationsEnabled + prefs[Keys.PREFERRED_LANGUAGE] = updated.preferredLanguage + prefs[Keys.OFFER_TRANSLATE] = updated.offerTranslatePages + prefs[Keys.JAVASCRIPT_ENABLED] = updated.javascriptEnabled + prefs[Keys.COOKIES_ENABLED] = updated.cookiesEnabled + prefs[Keys.POPUPS_ALLOWED] = updated.popupsAllowed + prefs[Keys.LOAD_IMAGES] = updated.loadImagesEnabled + prefs[Keys.DEFAULT_DESKTOP_SITE] = updated.defaultDesktopSite + prefs[Keys.MEDIA_AUTOPLAY] = updated.mediaAutoplayEnabled + prefs[Keys.TEXT_ZOOM_PERCENT] = updated.textZoomPercent + prefs[Keys.FORCE_ENABLE_ZOOM] = updated.forceEnableZoom + prefs[Keys.SIMPLIFIED_VIEW] = updated.simplifiedViewEnabled + prefs[Keys.ASK_WHERE_TO_SAVE] = updated.askWhereToSaveDownloads + prefs[Keys.SHOW_RECENT_CARDS] = updated.showRecentCardsOnNtp + } + } +} diff --git a/app/src/main/java/com/bansify/browser/data/BrowserRepository.kt b/app/src/main/java/com/bansify/browser/data/BrowserRepository.kt new file mode 100644 index 00000000..a347488f --- /dev/null +++ b/app/src/main/java/com/bansify/browser/data/BrowserRepository.kt @@ -0,0 +1,157 @@ +package com.bansify.browser.data + +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.first + +class BrowserRepository( + private val dao: BrowserDao, + private val preferences: BrowserPreferences +) { + val settings: Flow = preferences.settingsFlow + val bookmarks: Flow> = dao.getAllBookmarks() + val history: Flow> = dao.getAllHistory() + val downloads: Flow> = dao.getAllDownloads() + val shortcuts: Flow> = dao.getAllShortcuts() + + suspend fun ensureDefaultShortcuts() { + val alreadySeeded = preferences.shortcutsSeededFlow.first() + if (!alreadySeeded && dao.getShortcutCount() == 0) { + dao.insertShortcuts( + listOf( + ShortcutEntity( + title = "Wikipedia", + url = "https://www.wikipedia.org", + accentColor = 0xFF3366CC, + sortOrder = 0 + ), + ShortcutEntity( + title = "YouTube", + url = "https://m.youtube.com", + accentColor = 0xFFEA4335, + sortOrder = 1 + ), + ShortcutEntity( + title = "GitHub", + url = "https://github.com", + accentColor = 0xFF24292F, + sortOrder = 2 + ), + ShortcutEntity( + title = "Reddit", + url = "https://www.reddit.com", + accentColor = 0xFFFF4500, + sortOrder = 3 + ), + ShortcutEntity( + title = "News", + url = "https://news.google.com", + accentColor = 0xFF1A73E8, + sortOrder = 4 + ), + ShortcutEntity( + title = "MDN Docs", + url = "https://developer.mozilla.org", + accentColor = 0xFF0060DF, + sortOrder = 5 + ), + ShortcutEntity( + title = "Weather", + url = "https://www.weather.com", + accentColor = 0xFF0B8043, + sortOrder = 6 + ) + ) + ) + preferences.markShortcutsSeeded() + } + } + + suspend fun updateSettings(transform: (BrowserSettings) -> BrowserSettings) { + preferences.updateSettings(transform) + } + + // Bookmarks + suspend fun getBookmarkByUrl(url: String): BookmarkEntity? = dao.getBookmarkByUrl(url) + + suspend fun addBookmark(title: String, url: String, folder: String = "Mobile bookmarks"): Long { + return dao.insertBookmark( + BookmarkEntity(title = title.ifBlank { url }, url = url, folder = folder) + ) + } + + suspend fun updateBookmark(bookmark: BookmarkEntity) = dao.updateBookmark(bookmark) + + suspend fun deleteBookmark(id: Long) = dao.deleteBookmarkById(id) + + suspend fun deleteBookmarkByUrl(url: String) = dao.deleteBookmarkByUrl(url) + + // History + suspend fun recordHistory(title: String, url: String) { + if (url.isBlank() || url == BrowserTab.NEW_TAB_URL || url == "about:blank") return + dao.insertHistory( + HistoryEntity( + title = title.ifBlank { url }, + url = url, + visitedAt = System.currentTimeMillis() + ) + ) + } + + suspend fun deleteHistoryItem(id: Long) = dao.deleteHistoryById(id) + + suspend fun clearHistory(timeRange: TimeRange) { + if (timeRange == TimeRange.ALL_TIME) { + dao.clearAllHistory() + } else { + val cutoff = System.currentTimeMillis() - timeRange.durationMillis + dao.deleteHistorySince(cutoff) + } + } + + // Downloads + suspend fun insertDownload(download: DownloadEntity): Long = dao.insertDownload(download) + + suspend fun updateDownloadStatus(id: Long, status: String, sizeBytes: Long, localPath: String) { + dao.updateDownloadStatus(id, status, sizeBytes, localPath) + } + + suspend fun deleteDownload(id: Long) = dao.deleteDownloadById(id) + + suspend fun clearAllDownloads() = dao.clearAllDownloads() + + // Shortcuts + suspend fun addShortcut(title: String, url: String, accentColor: Long) { + val nextOrder = dao.getShortcutCount() + dao.insertShortcut( + ShortcutEntity( + title = title, + url = url, + accentColor = accentColor, + sortOrder = nextOrder + ) + ) + } + + suspend fun updateShortcut(shortcut: ShortcutEntity) = dao.updateShortcut(shortcut) + + suspend fun deleteShortcut(id: Long) = dao.deleteShortcutById(id) + + // Saved Tabs + suspend fun loadSavedTabs(): List = dao.getSavedTabsOnce() + + suspend fun persistOpenTabs(tabs: List) { + val normalTabs = tabs.filter { !it.isIncognito }.map { + SavedTabEntity( + tabId = it.id, + url = it.url, + title = it.title, + isDesktopSite = it.isDesktopSite, + lastAccessedAt = it.lastAccessedAt + ) + } + dao.clearSavedTabs() + if (normalTabs.isNotEmpty()) { + dao.saveTabs(normalTabs) + } + } +} diff --git a/app/src/main/java/com/bansify/browser/ui/BrowserApp.kt b/app/src/main/java/com/bansify/browser/ui/BrowserApp.kt new file mode 100644 index 00000000..ab11065f --- /dev/null +++ b/app/src/main/java/com/bansify/browser/ui/BrowserApp.kt @@ -0,0 +1,738 @@ +package com.bansify.browser.ui + +import android.app.Activity +import android.content.ActivityNotFoundException +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Context +import android.content.Intent +import android.graphics.Bitmap +import android.net.Uri +import android.speech.RecognizerIntent +import android.view.View +import android.view.ViewGroup +import android.webkit.ValueCallback +import android.webkit.WebChromeClient +import android.widget.FrameLayout +import androidx.activity.compose.BackHandler +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.statusBarsPadding +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarDuration +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.SnackbarResult +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.viewinterop.AndroidView +import androidx.core.content.pm.ShortcutInfoCompat +import androidx.core.content.pm.ShortcutManagerCompat +import androidx.core.graphics.drawable.IconCompat +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.bansify.browser.MainActivity +import com.bansify.browser.R +import com.bansify.browser.browser.UrlUtils +import com.bansify.browser.browser.WebViewPool +import com.bansify.browser.data.AddressBarPosition +import com.bansify.browser.data.BookmarkEntity +import com.bansify.browser.data.BrowserOverlay +import com.bansify.browser.data.BrowserTab +import com.bansify.browser.data.JsDialogState +import com.bansify.browser.data.ReadingModeContent +import com.bansify.browser.data.SettingsSubScreen +import com.bansify.browser.ui.components.BookmarkEditDialog +import com.bansify.browser.ui.components.ChromeOverflowMenu +import com.bansify.browser.ui.components.ChromeToolbar +import com.bansify.browser.ui.components.PageInfoBottomSheet +import com.bansify.browser.ui.components.ReadingModeOverlay +import com.bansify.browser.ui.components.TranslatePageBottomSheet +import com.bansify.browser.ui.components.WebViewJsDialog +import com.bansify.browser.ui.screens.BookmarksScreen +import com.bansify.browser.ui.screens.DeleteBrowsingDataScreen +import com.bansify.browser.ui.screens.DownloadsScreen +import com.bansify.browser.ui.screens.HistoryScreen +import com.bansify.browser.ui.screens.NewTabScreen +import com.bansify.browser.ui.screens.OmniboxOverlay +import com.bansify.browser.ui.screens.RecentTabsScreen +import com.bansify.browser.ui.screens.SettingsScreen +import com.bansify.browser.ui.screens.TabSwitcherScreen +import com.bansify.browser.ui.theme.BansifyBrowserTheme +import com.bansify.browser.ui.theme.LocalIsDarkBrowserTheme +import com.bansify.browser.viewmodel.BrowserViewModel +import java.util.Locale + +@Composable +fun BrowserApp(viewModel: BrowserViewModel) { + val context = LocalContext.current + val settings by viewModel.settings.collectAsStateWithLifecycle() + val accountState by viewModel.accountState.collectAsStateWithLifecycle() + val tabs by viewModel.tabs.collectAsStateWithLifecycle() + val activeTab by viewModel.activeTab.collectAsStateWithLifecycle() + val bookmarks by viewModel.bookmarks.collectAsStateWithLifecycle() + val history by viewModel.history.collectAsStateWithLifecycle() + val downloads by viewModel.downloads.collectAsStateWithLifecycle() + val shortcuts by viewModel.shortcuts.collectAsStateWithLifecycle() + val recentlyClosed by viewModel.recentlyClosedTabs.collectAsStateWithLifecycle() + val recentSearches by viewModel.recentSearches.collectAsStateWithLifecycle() + val overlay by viewModel.overlay.collectAsStateWithLifecycle() + val findInPage by viewModel.findInPage.collectAsStateWithLifecycle() + val jsDialog by viewModel.jsDialog.collectAsStateWithLifecycle() + val showPageInfo by viewModel.showPageInfoSheet.collectAsStateWithLifecycle() + val showTranslate by viewModel.showTranslateSheet.collectAsStateWithLifecycle() + val readingMode by viewModel.readingModeContent.collectAsStateWithLifecycle() + val editingBookmark by viewModel.editingBookmark.collectAsStateWithLifecycle() + + var overflowMenuExpanded by remember { mutableStateOf(false) } + var customFullscreenView by remember { mutableStateOf(null) } + var customFullscreenCallback by remember { mutableStateOf(null) } + var pendingFileChooserCallback by remember { mutableStateOf>?>(null) } + + val fileChooserLauncher = rememberLauncherForActivityResult( + contract = ActivityResultContracts.GetMultipleContents() + ) { uris -> + pendingFileChooserCallback?.onReceiveValue(uris.toTypedArray()) + pendingFileChooserCallback = null + } + + val voiceSearchLauncher = rememberLauncherForActivityResult( + contract = ActivityResultContracts.StartActivityForResult() + ) { result -> + if (result.resultCode == Activity.RESULT_OK) { + val spoken = result.data + ?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS) + ?.firstOrNull() + if (!spoken.isNullOrBlank()) { + viewModel.openUrlInActiveTab(spoken) + } + } + } + + fun launchVoiceSearch() { + val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply { + putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH) + putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault()) + putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak to search with ${settings.searchEngine.displayName}") + } + try { + voiceSearchLauncher.launch(intent) + } catch (_: ActivityNotFoundException) { + viewModel.showSnackbar("Voice search is not available on this device") + } + } + + val webViewPool = remember { + WebViewPool( + context = context, + callbacks = object : WebViewPool.Callbacks { + override fun onPageStarted(tabId: String, url: String) { + viewModel.onWebPageStarted(tabId, url) + } + + override fun onPageFinished( + tabId: String, + url: String, + title: String, + canGoBack: Boolean, + canGoForward: Boolean + ) { + viewModel.onWebPageFinished(tabId, url, title, canGoBack, canGoForward) + } + + override fun onProgressChanged(tabId: String, progress: Int) { + viewModel.onWebProgressChanged(tabId, progress) + } + + override fun onTitleReceived(tabId: String, title: String) { + viewModel.onWebTitleReceived(tabId, title) + } + + override fun onFaviconReceived(tabId: String, icon: Bitmap?) { + viewModel.onWebFaviconReceived(tabId, icon) + } + + override fun onThumbnailCaptured(tabId: String, bitmap: Bitmap) { + viewModel.onThumbnailCaptured(tabId, bitmap) + } + + override fun onDownloadStarted( + fileName: String, + url: String, + mimeType: String, + sizeBytes: Long, + localPath: String + ) { + viewModel.onDownloadRecorded(fileName, url, mimeType, sizeBytes, localPath) + } + + override fun onJsDialog(dialog: JsDialogState) { + viewModel.showJsDialog(dialog) + } + + override fun onShowCustomView(view: View, callback: WebChromeClient.CustomViewCallback) { + customFullscreenView = view + customFullscreenCallback = callback + } + + override fun onHideCustomView() { + customFullscreenView = null + customFullscreenCallback?.onCustomViewHidden() + customFullscreenCallback = null + } + + override fun onFileChooserRequested( + filePathCallback: ValueCallback>, + acceptTypes: Array + ) { + pendingFileChooserCallback?.onReceiveValue(null) + pendingFileChooserCallback = filePathCallback + val mime = acceptTypes.firstOrNull { it.isNotBlank() } ?: "*/*" + fileChooserLauncher.launch(mime) + } + + override fun onFindResults(activeMatchOrdinal: Int, numberOfMatches: Int) { + viewModel.updateFindResults(activeMatchOrdinal, numberOfMatches) + } + + override fun onOpenNewTabRequest(url: String, isIncognito: Boolean) { + viewModel.createNewTab(url = url, isIncognito = isIncognito) + } + + override fun onExternalUrlError(message: String) { + viewModel.showSnackbar(message) + } + } + ) + } + + DisposableEffect(Unit) { + onDispose { webViewPool.destroyAll() } + } + + LaunchedEffect(settings) { + webViewPool.updateSettingsForAll(tabs, settings) + } + + LaunchedEffect(Unit) { + viewModel.destroyedTabIds.collect { tabId -> + webViewPool.destroyTab(tabId) + } + } + + LaunchedEffect(Unit) { + viewModel.loadUrlCommands.collect { (tabId, url) -> + val tab = viewModel.tabs.value.firstOrNull { it.id == tabId } + if (tab != null) { + webViewPool.getOrCreateWebView(tab, viewModel.settings.value) + webViewPool.loadUrl(tabId, url, viewModel.settings.value) + } + } + } + + val snackbarHostState = remember { SnackbarHostState() } + LaunchedEffect(Unit) { + viewModel.snackbarEvents.collect { event -> + snackbarHostState.currentSnackbarData?.dismiss() + val result = snackbarHostState.showSnackbar( + message = event.message, + actionLabel = event.actionLabel, + duration = SnackbarDuration.Short + ) + if (result == SnackbarResult.ActionPerformed) { + event.onAction?.invoke() + } + } + } + + val isBookmarked = remember(bookmarks, activeTab.url) { + !activeTab.isNewTab && bookmarks.any { it.url == activeTab.url } + } + + val tabCountForCurrentMode = remember(tabs, activeTab.isIncognito) { + tabs.count { it.isIncognito == activeTab.isIncognito } + } + + fun shareText(title: String, text: String) { + val sendIntent = Intent(Intent.ACTION_SEND).apply { + type = "text/plain" + putExtra(Intent.EXTRA_SUBJECT, title) + putExtra(Intent.EXTRA_TEXT, text) + } + context.startActivity(Intent.createChooser(sendIntent, "Share via")) + } + + fun copyToClipboard(text: String) { + val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager + clipboard.setPrimaryClip(ClipData.newPlainText("URL", text)) + viewModel.showSnackbar("Link copied") + } + + fun pinCurrentPageToHomeScreen() { + if (activeTab.isNewTab) return + if (ShortcutManagerCompat.isRequestPinShortcutSupported(context)) { + val shortcutIntent = Intent(context, MainActivity::class.java).apply { + action = Intent.ACTION_VIEW + data = Uri.parse(activeTab.url) + } + val icon = activeTab.favicon?.let { IconCompat.createWithBitmap(it) } + ?: IconCompat.createWithResource(context, R.mipmap.ic_launcher) + val shortcutInfo = ShortcutInfoCompat.Builder(context, "bansify_${activeTab.url.hashCode()}") + .setShortLabel(activeTab.title.ifBlank { UrlUtils.extractDisplayHost(activeTab.url) }.take(24)) + .setIcon(icon) + .setIntent(shortcutIntent) + .build() + ShortcutManagerCompat.requestPinShortcut(context, shortcutInfo, null) + viewModel.showSnackbar("Shortcut requested for Home screen") + } else { + viewModel.showSnackbar("Home screen shortcuts are not supported by this launcher") + } + } + + fun navigateBackInCurrentTab() { + if (!webViewPool.goBack(activeTab.id)) { + viewModel.openUrlInActiveTab(BrowserTab.NEW_TAB_URL) + } + } + + fun openReadingModeForCurrentTab() { + if (activeTab.isNewTab) return + webViewPool.extractReadableArticle(activeTab.id) { title, paragraphs -> + viewModel.showReadingMode( + ReadingModeContent( + title = title.ifBlank { activeTab.title }, + domain = UrlUtils.extractDisplayHost(activeTab.url), + url = activeTab.url, + paragraphs = paragraphs + ) + ) + } + } + + BackHandler(enabled = customFullscreenView != null) { + customFullscreenCallback?.onCustomViewHidden() + customFullscreenView = null + customFullscreenCallback = null + } + + BackHandler(enabled = customFullscreenView == null && readingMode == null && findInPage.isActive && overlay == BrowserOverlay.None) { + webViewPool.clearFindMatches(activeTab.id) + viewModel.setFindInPageActive(false) + } + + BackHandler(enabled = customFullscreenView == null && readingMode == null && !findInPage.isActive && overlay == BrowserOverlay.None && !activeTab.isNewTab) { + navigateBackInCurrentTab() + } + + val useIncognitoTheme = activeTab.isIncognito && + (overlay == BrowserOverlay.None || overlay is BrowserOverlay.Omnibox) + + val isBottomAddressBar = settings.addressBarPosition == AddressBarPosition.BOTTOM && !activeTab.isNewTab + + BansifyBrowserTheme( + themeMode = settings.themeMode, + isIncognito = useIncognitoTheme + ) { + val isDarkNow = LocalIsDarkBrowserTheme.current + + val toolbarComposable: @Composable () -> Unit = { + ChromeToolbar( + activeTab = activeTab, + tabCount = tabCountForCurrentMode, + settings = settings, + accountState = accountState, + isBookmarked = isBookmarked, + findInPage = findInPage, + isBottomPlacement = isBottomAddressBar, + overflowMenuExpanded = overflowMenuExpanded, + onOverflowMenuChange = { overflowMenuExpanded = it }, + onHomeClick = { viewModel.navigateHome() }, + onAccountClick = { + viewModel.openOverlay(BrowserOverlay.Settings(SettingsSubScreen.BANSIFY_ACCOUNT)) + }, + onOmniboxClick = { viewModel.openOverlay(BrowserOverlay.Omnibox()) }, + onPageInfoClick = { viewModel.setPageInfoVisible(true) }, + onTabSwitcherClick = { + if (!activeTab.isNewTab) { + webViewPool.captureThumbnail(activeTab.id) + } + viewModel.openOverlay(BrowserOverlay.TabSwitcher(showIncognito = activeTab.isIncognito)) + }, + onNewTabClick = { viewModel.createNewTab(isIncognito = false) }, + onNewIncognitoTabClick = { viewModel.createNewTab(isIncognito = true) }, + onCloseActiveTabClick = { viewModel.closeTab(activeTab.id) }, + onShareClick = { + if (!activeTab.isNewTab) shareText(activeTab.title, activeTab.url) + }, + onToggleBookmarkClick = { viewModel.toggleBookmarkForActiveTab() }, + onFindQueryChange = { query -> + viewModel.updateFindQuery(query) + webViewPool.findInPage(activeTab.id, query) + }, + onFindNext = { forward -> webViewPool.findNext(activeTab.id, forward) }, + onCloseFindInPage = { + webViewPool.clearFindMatches(activeTab.id) + viewModel.setFindInPageActive(false) + }, + overflowMenuContent = {} + ) + } + + Box(modifier = Modifier.fillMaxSize()) { + Scaffold( + snackbarHost = { + SnackbarHost( + hostState = snackbarHostState, + modifier = Modifier.navigationBarsPadding() + ) + }, + topBar = { + if (!isBottomAddressBar) toolbarComposable() + }, + bottomBar = { + if (isBottomAddressBar) toolbarComposable() + } + ) { innerPadding -> + Box( + modifier = Modifier + .fillMaxSize() + .padding(innerPadding) + .then(if (isBottomAddressBar) Modifier.statusBarsPadding() else Modifier) + .imePadding() + ) { + if (activeTab.isNewTab) { + NewTabScreen( + isIncognito = activeTab.isIncognito, + settings = settings, + shortcuts = shortcuts, + recentBookmarks = bookmarks, + recentHistory = history, + onSearchClick = { viewModel.openOverlay(BrowserOverlay.Omnibox()) }, + onVoiceSearchClick = { launchVoiceSearch() }, + onNewTabClick = { viewModel.createNewTab(isIncognito = false) }, + onNewIncognitoTabClick = { viewModel.createNewTab(isIncognito = true) }, + onOpenUrl = { url -> viewModel.openUrlInActiveTab(url) }, + onAddShortcut = { title, url -> viewModel.addShortcut(title, url) }, + onUpdateShortcut = { shortcut -> viewModel.updateShortcut(shortcut) }, + onDeleteShortcut = { id -> viewModel.deleteShortcut(id) }, + onToggleIncognitoBlockThirdParty = { block -> + viewModel.toggleIncognitoBlockThirdPartyCookies(block) + }, + onOpenBookmarks = { viewModel.openOverlay(BrowserOverlay.Bookmarks) }, + onOpenHistory = { viewModel.openOverlay(BrowserOverlay.History) } + ) + } else { + AndroidView( + factory = { ctx -> + FrameLayout(ctx).apply { + layoutParams = ViewGroup.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.MATCH_PARENT + ) + } + }, + update = { container -> + val targetWebView = webViewPool.getOrCreateWebView(activeTab, settings) + if (container.childCount != 1 || container.getChildAt(0) !== targetWebView) { + container.removeAllViews() + (targetWebView.parent as? ViewGroup)?.removeView(targetWebView) + container.addView(targetWebView) + } + }, + modifier = Modifier + .fillMaxSize() + .then(if (!isBottomAddressBar) Modifier.navigationBarsPadding() else Modifier) + ) + } + } + } + + // Root-aligned Chrome 3-Dot Overflow Menu (flush right edge + full vertical scrolling) + ChromeOverflowMenu( + expanded = overflowMenuExpanded, + activeTab = activeTab, + isBookmarked = isBookmarked, + isBottomPlacement = isBottomAddressBar, + onDismiss = { overflowMenuExpanded = false }, + onBack = { navigateBackInCurrentTab() }, + onForward = { webViewPool.goForward(activeTab.id) }, + onToggleBookmark = { viewModel.toggleBookmarkForActiveTab() }, + onDownloadPage = { + webViewPool.saveCurrentPageArchive( + tabId = activeTab.id, + title = activeTab.title, + url = activeTab.url + ) + }, + onReloadOrStop = { + if (activeTab.isLoading) { + webViewPool.stopLoading(activeTab.id) + } else { + webViewPool.reload(activeTab.id) + } + }, + onNewTab = { viewModel.createNewTab(isIncognito = false) }, + onNewIncognitoTab = { viewModel.createNewTab(isIncognito = true) }, + onAddTabToNewGroup = { viewModel.addActiveTabToNewGroup() }, + onHistory = { viewModel.openOverlay(BrowserOverlay.History) }, + onDeleteBrowsingData = { viewModel.openOverlay(BrowserOverlay.DeleteBrowsingData) }, + onSiteControls = { viewModel.setPageInfoVisible(true) }, + onDownloads = { viewModel.openOverlay(BrowserOverlay.Downloads) }, + onBookmarks = { viewModel.openOverlay(BrowserOverlay.Bookmarks) }, + onRecentTabs = { viewModel.openOverlay(BrowserOverlay.RecentTabs) }, + onShare = { + if (!activeTab.isNewTab) shareText(activeTab.title, activeTab.url) + }, + onFindInPage = { viewModel.setFindInPageActive(true) }, + onTranslate = { viewModel.setTranslateSheetVisible(true) }, + onReadingMode = { openReadingModeForCurrentTab() }, + onAddToHomeScreen = { pinCurrentPageToHomeScreen() }, + onToggleDesktopSite = { + val enabled = viewModel.toggleDesktopSiteForActiveTab() + webViewPool.setDesktopSite(activeTab, enabled) + viewModel.showSnackbar(if (enabled) "Desktop site enabled" else "Mobile site enabled") + }, + onSettings = { + viewModel.openOverlay(BrowserOverlay.Settings(SettingsSubScreen.MAIN)) + }, + onHelpAndFeedback = { + viewModel.openOverlay(BrowserOverlay.Settings(SettingsSubScreen.ABOUT)) + } + ) + + // Fullscreen Chrome Overlays + when (val currentOverlay = overlay) { + BrowserOverlay.None -> Unit + + is BrowserOverlay.Omnibox -> { + OmniboxOverlay( + activeTab = activeTab, + openTabs = tabs, + bookmarks = bookmarks, + history = history, + shortcuts = shortcuts, + recentSearches = recentSearches, + settings = settings, + onDismiss = { viewModel.closeOverlay() }, + onSubmitUrl = { input -> viewModel.openUrlInActiveTab(input) }, + onVoiceSearchClick = { launchVoiceSearch() }, + onNewTabClick = { viewModel.createNewTab(isIncognito = false) }, + onSwitchToTab = { tabId -> viewModel.selectTab(tabId) }, + onShareCurrentUrl = { + if (!activeTab.isNewTab) shareText(activeTab.title, activeTab.url) + }, + onCopyCurrentUrl = { + if (!activeTab.isNewTab) copyToClipboard(activeTab.url) + } + ) + } + + is BrowserOverlay.TabSwitcher -> { + TabSwitcherScreen( + tabs = tabs, + activeTabId = activeTab.id, + initialShowIncognito = currentOverlay.showIncognito, + onDismiss = { viewModel.closeOverlay() }, + onSelectTab = { tabId -> viewModel.selectTab(tabId) }, + onCloseTab = { tabId -> viewModel.closeTab(tabId) }, + onCreateNewTab = { incognito -> viewModel.createNewTab(isIncognito = incognito) }, + onCloseAllTabs = { incognitoOnly -> viewModel.closeAllTabs(incognitoOnly) }, + onOpenSettings = { + viewModel.openOverlay(BrowserOverlay.Settings(SettingsSubScreen.MAIN)) + } + ) + } + + BrowserOverlay.Bookmarks -> { + BookmarksScreen( + bookmarks = bookmarks, + accountState = accountState, + onClose = { viewModel.closeOverlay() }, + onOpenUrl = { url -> viewModel.openUrlInActiveTab(url) }, + onOpenInNewTab = { url, incog -> viewModel.createNewTab(url = url, isIncognito = incog) }, + onAddBookmark = { + viewModel.startEditingBookmark( + BookmarkEntity( + id = 0L, + title = if (activeTab.isNewTab) "" else activeTab.title, + url = if (activeTab.isNewTab) "https://" else activeTab.url + ) + ) + }, + onEditBookmark = { bm -> viewModel.startEditingBookmark(bm) }, + onDeleteBookmark = { id -> viewModel.deleteBookmark(id) }, + onCopyUrl = { url -> copyToClipboard(url) }, + onOpenSyncSettings = { + viewModel.openOverlay(BrowserOverlay.Settings(SettingsSubScreen.BANSIFY_ACCOUNT)) + } + ) + } + + BrowserOverlay.History -> { + HistoryScreen( + history = history, + onClose = { viewModel.closeOverlay() }, + onOpenUrl = { url -> viewModel.openUrlInActiveTab(url) }, + onDeleteItem = { id -> viewModel.deleteHistoryItem(id) }, + onOpenDeleteBrowsingData = { viewModel.openOverlay(BrowserOverlay.DeleteBrowsingData) } + ) + } + + BrowserOverlay.Downloads -> { + DownloadsScreen( + downloads = downloads, + onClose = { viewModel.closeOverlay() }, + onOpenDownloadUrl = { url -> viewModel.openUrlInActiveTab(url) }, + onShareDownload = { dl -> shareText(dl.fileName, dl.url) }, + onDeleteDownload = { id -> viewModel.deleteDownload(id) }, + onOpenDownloadsSettings = { + viewModel.openOverlay(BrowserOverlay.Settings(SettingsSubScreen.DOWNLOADS_SETTINGS)) + } + ) + } + + BrowserOverlay.RecentTabs -> { + RecentTabsScreen( + recentlyClosedTabs = recentlyClosed, + onClose = { viewModel.closeOverlay() }, + onReopenTab = { url -> viewModel.createNewTab(url = url, isIncognito = false) }, + onOpenFullHistory = { viewModel.openOverlay(BrowserOverlay.History) } + ) + } + + BrowserOverlay.DeleteBrowsingData -> { + DeleteBrowsingDataScreen( + historyCount = history.size, + openNormalTabCount = tabs.count { !it.isIncognito }, + onBack = { viewModel.closeOverlay() }, + onConfirmClear = { range, clearHist, clearCookies, clearCache, clearSiteData, closeTabs -> + viewModel.clearBrowsingData( + timeRange = range, + clearHistory = clearHist, + clearCookies = clearCookies, + clearCache = clearCache, + clearSiteData = clearSiteData, + closeOpenTabs = closeTabs, + onClearWebViewCache = { webViewPool.clearAllCaches() } + ) + } + ) + } + + is BrowserOverlay.Settings -> { + SettingsScreen( + subScreen = currentOverlay.subScreen, + settings = settings, + accountState = accountState, + bookmarksCount = bookmarks.size, + historyCount = history.size, + openTabsCount = tabs.count { !it.isIncognito }, + shortcutsCount = shortcuts.size, + downloadsCount = downloads.size, + onBack = { viewModel.navigateSettingsBack() }, + onNavigateSubScreen = { sub -> viewModel.navigateSettingsSubScreen(sub) }, + onOpenDeleteBrowsingData = { viewModel.openOverlay(BrowserOverlay.DeleteBrowsingData) }, + onUpdateSettings = { transform -> viewModel.updateSettings(transform) }, + onSignInBansify = { name, email, color -> + viewModel.signInBansifyAccount(name, email, color) + }, + onUpdateBansifyProfile = { name, email, color -> + viewModel.updateBansifyProfile(name, email, color) + }, + onSignOutBansify = { viewModel.signOutBansifyAccount() }, + onUpdateBansifySync = { transform -> viewModel.updateBansifySync(transform) }, + onSyncNow = { viewModel.triggerManualSync() } + ) + } + } + + // Reading Mode Distraction-Free Overlay + readingMode?.let { article -> + ReadingModeOverlay( + content = article, + initialDark = isDarkNow, + onClose = { viewModel.closeReadingMode() } + ) + } + + // Fullscreen WebView Video Container + customFullscreenView?.let { fsView -> + Box( + modifier = Modifier + .fillMaxSize() + .background(Color.Black) + ) { + AndroidView( + factory = { ctx -> + FrameLayout(ctx).apply { + (fsView.parent as? ViewGroup)?.removeView(fsView) + addView(fsView) + } + }, + modifier = Modifier.fillMaxSize() + ) + } + } + + // Chrome Page Info / Site Controls Bottom Sheet + if (showPageInfo && !activeTab.isNewTab) { + PageInfoBottomSheet( + tab = activeTab, + cookiesAllowed = settings.cookiesEnabled, + onDismiss = { viewModel.setPageInfoVisible(false) }, + onClearSiteData = { + viewModel.clearSiteDataForActiveSite { webViewPool.clearAllCaches() } + }, + onOpenSiteSettings = { + viewModel.openOverlay(BrowserOverlay.Settings(SettingsSubScreen.SITE_SETTINGS)) + }, + onShareUrl = { shareText(activeTab.title, activeTab.url) } + ) + } + + // Chrome Translate Page Bottom Sheet + if (showTranslate && !activeTab.isNewTab) { + TranslatePageBottomSheet( + currentUrl = activeTab.url, + onDismiss = { viewModel.setTranslateSheetVisible(false) }, + onSelectLanguage = { code, name -> + viewModel.translateActivePage(code, name) + } + ) + } + + // Bookmark Add / Edit Dialog + editingBookmark?.let { bm -> + BookmarkEditDialog( + bookmark = bm, + onDismiss = { viewModel.startEditingBookmark(null) }, + onSave = { id, title, url, folder -> + viewModel.saveBookmark(id, title, url, folder) + }, + onDelete = { id -> viewModel.deleteBookmark(id) } + ) + } + + // WebView JavaScript Alert / Confirm / Prompt Dialogs + jsDialog?.let { dialog -> + WebViewJsDialog( + dialog = dialog, + onDismiss = { viewModel.showJsDialog(null) } + ) + } + } + } +} diff --git a/app/src/main/java/com/bansify/browser/ui/components/ChromeDialogsAndSheets.kt b/app/src/main/java/com/bansify/browser/ui/components/ChromeDialogsAndSheets.kt new file mode 100644 index 00000000..a17932e8 --- /dev/null +++ b/app/src/main/java/com/bansify/browser/ui/components/ChromeDialogsAndSheets.kt @@ -0,0 +1,458 @@ +package com.bansify.browser.ui.components + +import androidx.compose.foundation.clickable +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.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Cookie +import androidx.compose.material.icons.outlined.DeleteOutline +import androidx.compose.material.icons.outlined.Lock +import androidx.compose.material.icons.outlined.Settings +import androidx.compose.material.icons.outlined.Share +import androidx.compose.material.icons.outlined.WarningAmber +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.FilterChip +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import com.bansify.browser.browser.UrlUtils +import com.bansify.browser.data.BookmarkEntity +import com.bansify.browser.data.BrowserTab +import com.bansify.browser.data.JsDialogState +import com.bansify.browser.data.ShortcutEntity +import com.bansify.browser.ui.theme.SecureGreen + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun PageInfoBottomSheet( + tab: BrowserTab, + cookiesAllowed: Boolean, + onDismiss: () -> Unit, + onClearSiteData: () -> Unit, + onOpenSiteSettings: () -> Unit, + onShareUrl: () -> Unit +) { + ModalBottomSheet( + onDismissRequest = onDismiss, + containerColor = MaterialTheme.colorScheme.surfaceContainerLow, + shape = RoundedCornerShape(topStart = 24.dp, topEnd = 24.dp) + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .navigationBarsPadding() + .padding(bottom = 20.dp) + ) { + // URL Header + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 24.dp, vertical = 8.dp) + ) { + Text( + text = UrlUtils.extractDisplayHost(tab.url).ifBlank { tab.title }, + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + Spacer(modifier = Modifier.height(2.dp)) + Text( + text = tab.url, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 2, + overflow = TextOverflow.Ellipsis + ) + } + + HorizontalDivider( + modifier = Modifier.padding(vertical = 8.dp), + color = MaterialTheme.colorScheme.outlineVariant + ) + + // Connection security row + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 24.dp, vertical = 14.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = if (tab.isSecure) Icons.Outlined.Lock else Icons.Outlined.WarningAmber, + contentDescription = null, + tint = if (tab.isSecure) SecureGreen else MaterialTheme.colorScheme.error, + modifier = Modifier.size(22.dp) + ) + Spacer(modifier = Modifier.width(16.dp)) + Column { + Text( + text = if (tab.isSecure) "Connection is secure" else "Connection is not secure", + style = MaterialTheme.typography.bodyLarge, + fontWeight = FontWeight.Medium, + color = MaterialTheme.colorScheme.onSurface + ) + Text( + text = if (tab.isSecure) { + "Your information (for example, passwords or credit card numbers) is private when sent to this site." + } else { + "You should not enter sensitive information on this site (for example, passwords or cards)." + }, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + + // Cookies & site data + Row( + modifier = Modifier + .fillMaxWidth() + .clickable(onClick = onClearSiteData) + .testTag("page_info_clear_cookies") + .padding(horizontal = 24.dp, vertical = 14.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.Outlined.Cookie, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(22.dp) + ) + Spacer(modifier = Modifier.width(16.dp)) + Column(modifier = Modifier.weight(1f)) { + Text( + text = "Cookies and site data", + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurface + ) + Text( + text = if (cookiesAllowed && !tab.isIncognito) "Cookies allowed • Tap to clear" else "Restricted in this tab • Tap to clear", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + Icon( + imageVector = Icons.Outlined.DeleteOutline, + contentDescription = "Clear site data", + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(20.dp) + ) + } + + // Site Settings + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { + onDismiss() + onOpenSiteSettings() + } + .testTag("page_info_site_settings") + .padding(horizontal = 24.dp, vertical = 14.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.Outlined.Settings, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(22.dp) + ) + Spacer(modifier = Modifier.width(16.dp)) + Text( + text = "Site settings", + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurface + ) + } + + // Share + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { + onDismiss() + onShareUrl() + } + .padding(horizontal = 24.dp, vertical = 14.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.Outlined.Share, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(22.dp) + ) + Spacer(modifier = Modifier.width(16.dp)) + Text( + text = "Share link", + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurface + ) + } + } + } +} + +@Composable +fun BookmarkEditDialog( + bookmark: BookmarkEntity, + onDismiss: () -> Unit, + onSave: (id: Long, title: String, url: String, folder: String) -> Unit, + onDelete: ((Long) -> Unit)? = null +) { + var title by remember(bookmark) { mutableStateOf(bookmark.title) } + var url by remember(bookmark) { mutableStateOf(bookmark.url) } + var folder by remember(bookmark) { mutableStateOf(bookmark.folder) } + val folders = listOf("Mobile bookmarks", "Favorites", "Reading list") + + AlertDialog( + onDismissRequest = onDismiss, + title = { + Text(text = if (bookmark.id == 0L) "Add bookmark" else "Edit bookmark") + }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { + OutlinedTextField( + value = title, + onValueChange = { title = it }, + label = { Text("Name") }, + singleLine = true, + modifier = Modifier.fillMaxWidth() + ) + OutlinedTextField( + value = url, + onValueChange = { url = it }, + label = { Text("URL") }, + singleLine = true, + modifier = Modifier.fillMaxWidth() + ) + Text( + text = "Folder", + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { + folders.forEach { option -> + FilterChip( + selected = folder == option, + onClick = { folder = option }, + label = { + Text( + text = option.replace(" bookmarks", ""), + style = MaterialTheme.typography.labelSmall + ) + } + ) + } + } + } + }, + confirmButton = { + TextButton( + onClick = { + if (url.isNotBlank()) { + val normalized = if (url.startsWith("http://") || url.startsWith("https://")) url else "https://$url" + onSave(bookmark.id, title.ifBlank { normalized }, normalized, folder) + } + } + ) { + Text("Save") + } + }, + dismissButton = { + Row { + if (bookmark.id != 0L && onDelete != null) { + TextButton(onClick = { + onDelete(bookmark.id) + onDismiss() + }) { + Text("Delete", color = MaterialTheme.colorScheme.error) + } + } + TextButton(onClick = onDismiss) { + Text("Cancel") + } + } + } + ) +} + +@Composable +fun ShortcutDialog( + initial: ShortcutEntity? = null, + onDismiss: () -> Unit, + onSave: (title: String, url: String) -> Unit, + onDelete: (() -> Unit)? = null +) { + var title by remember(initial) { mutableStateOf(initial?.title.orEmpty()) } + var url by remember(initial) { mutableStateOf(initial?.url.orEmpty()) } + + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(if (initial == null) "Add shortcut" else "Edit shortcut") }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { + OutlinedTextField( + value = title, + onValueChange = { title = it }, + label = { Text("Name") }, + singleLine = true, + modifier = Modifier.fillMaxWidth() + ) + OutlinedTextField( + value = url, + onValueChange = { url = it }, + label = { Text("URL") }, + placeholder = { Text("https://example.com") }, + singleLine = true, + modifier = Modifier.fillMaxWidth() + ) + } + }, + confirmButton = { + TextButton( + onClick = { + if (url.isNotBlank()) { + onSave(title.trim(), url.trim()) + } + } + ) { + Text("Done") + } + }, + dismissButton = { + Row { + if (initial != null && onDelete != null) { + TextButton(onClick = { + onDelete() + onDismiss() + }) { + Text("Remove", color = MaterialTheme.colorScheme.error) + } + } + TextButton(onClick = onDismiss) { + Text("Cancel") + } + } + } + ) +} + +@Composable +fun WebViewJsDialog( + dialog: JsDialogState, + onDismiss: () -> Unit +) { + when (dialog) { + is JsDialogState.Alert -> { + AlertDialog( + onDismissRequest = { + dialog.result.cancel() + onDismiss() + }, + title = { Text("${UrlUtils.extractDisplayHost(dialog.url).ifBlank { "Page" }} says") }, + text = { Text(dialog.message) }, + confirmButton = { + TextButton(onClick = { + dialog.result.confirm() + onDismiss() + }) { + Text("OK") + } + } + ) + } + + is JsDialogState.Confirm -> { + AlertDialog( + onDismissRequest = { + dialog.result.cancel() + onDismiss() + }, + title = { Text("${UrlUtils.extractDisplayHost(dialog.url).ifBlank { "Page" }} says") }, + text = { Text(dialog.message) }, + confirmButton = { + TextButton(onClick = { + dialog.result.confirm() + onDismiss() + }) { + Text("OK") + } + }, + dismissButton = { + TextButton(onClick = { + dialog.result.cancel() + onDismiss() + }) { + Text("Cancel") + } + } + ) + } + + is JsDialogState.Prompt -> { + var input by remember(dialog) { mutableStateOf(dialog.defaultValue) } + AlertDialog( + onDismissRequest = { + dialog.result.cancel() + onDismiss() + }, + title = { Text("${UrlUtils.extractDisplayHost(dialog.url).ifBlank { "Page" }} says") }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { + Text(dialog.message) + OutlinedTextField( + value = input, + onValueChange = { input = it }, + singleLine = true, + modifier = Modifier.fillMaxWidth() + ) + } + }, + confirmButton = { + TextButton(onClick = { + dialog.result.confirm(input) + onDismiss() + }) { + Text("OK") + } + }, + dismissButton = { + TextButton(onClick = { + dialog.result.cancel() + onDismiss() + }) { + Text("Cancel") + } + } + ) + } + } +} diff --git a/app/src/main/java/com/bansify/browser/ui/components/ChromeIcons.kt b/app/src/main/java/com/bansify/browser/ui/components/ChromeIcons.kt new file mode 100644 index 00000000..43e8bc3c --- /dev/null +++ b/app/src/main/java/com/bansify/browser/ui/components/ChromeIcons.kt @@ -0,0 +1,186 @@ +package com.bansify.browser.ui.components + +import android.graphics.Bitmap +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.StrokeCap +import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.bansify.browser.browser.UrlUtils + +/** + * Authentic Chrome Android Incognito Hat & Glasses vector drawn crisp on Canvas. + */ +@Composable +fun IncognitoIcon( + modifier: Modifier = Modifier, + size: Dp = 22.dp, + tint: Color = MaterialTheme.colorScheme.onSurface +) { + Canvas(modifier = modifier.size(size)) { + val w = this.size.width + val h = this.size.height + + // Hat crown (trapezoid) + val hatPath = Path().apply { + moveTo(w * 0.27f, h * 0.44f) + lineTo(w * 0.35f, h * 0.14f) + lineTo(w * 0.65f, h * 0.14f) + lineTo(w * 0.73f, h * 0.44f) + close() + } + drawPath(path = hatPath, color = tint) + + // Hat brim + drawLine( + color = tint, + start = Offset(w * 0.10f, h * 0.48f), + end = Offset(w * 0.90f, h * 0.48f), + strokeWidth = h * 0.085f, + cap = StrokeCap.Round + ) + + // Glasses left & right lenses + val lensRadius = w * 0.145f + val lensY = h * 0.72f + val leftCenter = Offset(w * 0.31f, lensY) + val rightCenter = Offset(w * 0.69f, lensY) + val strokeW = h * 0.075f + + drawCircle( + color = tint, + radius = lensRadius, + center = leftCenter, + style = Stroke(width = strokeW) + ) + drawCircle( + color = tint, + radius = lensRadius, + center = rightCenter, + style = Stroke(width = strokeW) + ) + + // Glasses bridge + drawLine( + color = tint, + start = Offset(leftCenter.x + lensRadius, lensY - h * 0.02f), + end = Offset(rightCenter.x - lensRadius, lensY - h * 0.02f), + strokeWidth = strokeW, + cap = StrokeCap.Round + ) + } +} + +/** + * Authentic Chrome Android rounded-square tab counter badge. + * Displays ":D" when count >= 100 just like real Chrome! + */ +@Composable +fun ChromeTabCountBadge( + count: Int, + modifier: Modifier = Modifier, + color: Color = MaterialTheme.colorScheme.onSurfaceVariant, + filled: Boolean = false, + contentColor: Color = color +) { + val label = if (count > 99) ":D" else count.coerceAtLeast(0).toString() + val fontSize = when { + count > 99 -> 10.sp + count >= 10 -> 10.5.sp + else -> 12.sp + } + + Box( + modifier = modifier + .size(22.dp) + .clip(RoundedCornerShape(5.dp)) + .then( + if (filled) { + Modifier.background(color) + } else { + Modifier.border( + border = BorderStroke(1.8.dp, color), + shape = RoundedCornerShape(5.dp) + ) + } + ), + contentAlignment = Alignment.Center + ) { + Text( + text = label, + color = contentColor, + fontSize = fontSize, + fontWeight = FontWeight.Bold, + maxLines = 1 + ) + } +} + +/** + * Renders a live WebView favicon bitmap if present, or a crisp Material 3 domain monogram badge. + */ +@Composable +fun SiteAvatar( + title: String, + url: String, + favicon: Bitmap? = null, + accentColor: Long? = null, + size: Dp = 36.dp, + modifier: Modifier = Modifier +) { + val bitmap = remember(favicon) { favicon?.asImageBitmap() } + val bgColor = remember(url, accentColor) { + Color(accentColor ?: UrlUtils.colorForDomain(url)) + } + val letter = remember(title, url) { + UrlUtils.extractFirstLetter(title, url) + } + + Box( + modifier = modifier + .size(size) + .clip(CircleShape) + .background(if (bitmap != null) MaterialTheme.colorScheme.surfaceContainerHigh else bgColor.copy(alpha = 0.14f)), + contentAlignment = Alignment.Center + ) { + if (bitmap != null) { + Image( + bitmap = bitmap, + contentDescription = null, + modifier = Modifier + .size(size * 0.62f) + .clip(RoundedCornerShape(4.dp)), + contentScale = ContentScale.Fit + ) + } else { + Text( + text = letter, + color = bgColor, + fontSize = (size.value * 0.44f).sp, + fontWeight = FontWeight.SemiBold + ) + } + } +} diff --git a/app/src/main/java/com/bansify/browser/ui/components/ChromeOverflowMenu.kt b/app/src/main/java/com/bansify/browser/ui/components/ChromeOverflowMenu.kt new file mode 100644 index 00000000..71752bfe --- /dev/null +++ b/app/src/main/java/com/bansify/browser/ui/components/ChromeOverflowMenu.kt @@ -0,0 +1,547 @@ +package com.bansify.browser.ui.components + +import androidx.activity.compose.BackHandler +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.core.tween +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +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.height +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.statusBarsPadding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.automirrored.filled.ArrowForward +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Refresh +import androidx.compose.material.icons.filled.Star +import androidx.compose.material.icons.outlined.AddBox +import androidx.compose.material.icons.outlined.AddToHomeScreen +import androidx.compose.material.icons.outlined.ChromeReaderMode +import androidx.compose.material.icons.outlined.DashboardCustomize +import androidx.compose.material.icons.outlined.DeleteOutline +import androidx.compose.material.icons.outlined.DesktopWindows +import androidx.compose.material.icons.outlined.Devices +import androidx.compose.material.icons.outlined.Download +import androidx.compose.material.icons.outlined.DownloadDone +import androidx.compose.material.icons.outlined.FindInPage +import androidx.compose.material.icons.outlined.HelpOutline +import androidx.compose.material.icons.outlined.History +import androidx.compose.material.icons.outlined.Settings +import androidx.compose.material.icons.outlined.Share +import androidx.compose.material.icons.outlined.StarBorder +import androidx.compose.material.icons.outlined.Translate +import androidx.compose.material.icons.outlined.Tune +import androidx.compose.material3.Checkbox +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.bansify.browser.R +import com.bansify.browser.data.BrowserTab +import com.bansify.browser.ui.theme.ChromeDarkMenuCircle +import com.bansify.browser.ui.theme.ChromeDarkMenuSurface +import com.bansify.browser.ui.theme.LocalIsDarkBrowserTheme + +/** + * Pixel-accurate Chrome Android 3-Dot Overflow Menu: + * - Rendered in the root overlay layer aligned flush to TopEnd (or BottomEnd for bottom toolbar) + * with tight 6.dp right edge margin and sleek 256.dp width. + * - Bounded automatically by available window height (status bar to navigation bar), + * so verticalScroll() reaches every bottom item (Desktop site, Settings, Help and feedback) cleanly. + */ +@Composable +fun ChromeOverflowMenu( + expanded: Boolean, + activeTab: BrowserTab, + isBookmarked: Boolean, + isBottomPlacement: Boolean = false, + onDismiss: () -> Unit, + onBack: () -> Unit, + onForward: () -> Unit, + onToggleBookmark: () -> Unit, + onDownloadPage: () -> Unit, + onReloadOrStop: () -> Unit, + onNewTab: () -> Unit, + onNewIncognitoTab: () -> Unit, + onAddTabToNewGroup: () -> Unit, + onHistory: () -> Unit, + onDeleteBrowsingData: () -> Unit, + onSiteControls: () -> Unit, + onDownloads: () -> Unit, + onBookmarks: () -> Unit, + onRecentTabs: () -> Unit, + onShare: () -> Unit, + onFindInPage: () -> Unit, + onTranslate: () -> Unit, + onReadingMode: () -> Unit, + onAddToHomeScreen: () -> Unit, + onToggleDesktopSite: () -> Unit, + onSettings: () -> Unit, + onHelpAndFeedback: () -> Unit +) { + BackHandler(enabled = expanded) { + onDismiss() + } + + val isWebPage = !activeTab.isNewTab + val isDark = LocalIsDarkBrowserTheme.current + val menuBg = if (isDark) ChromeDarkMenuSurface else MaterialTheme.colorScheme.surfaceContainerLow + val circleBg = if (isDark) ChromeDarkMenuCircle else MaterialTheme.colorScheme.surfaceContainerHigh + val circleDisabledBg = if (isDark) Color(0xFF3E4044) else MaterialTheme.colorScheme.surfaceContainerHighest.copy(alpha = 0.65f) + val dividerColor = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.55f) + val scrollState = rememberScrollState() + + LaunchedEffect(expanded) { + if (expanded) { + scrollState.scrollTo(0) + } + } + + AnimatedVisibility( + visible = expanded, + enter = fadeIn(tween(130)), + exit = fadeOut(tween(110)) + ) { + Box( + modifier = Modifier + .fillMaxSize() + .background(Color.Black.copy(alpha = 0.16f)) + .clickable( + interactionSource = remember { MutableInteractionSource() }, + indication = null, + onClick = onDismiss + ) + .statusBarsPadding() + .navigationBarsPadding() + .padding( + top = if (isBottomPlacement) 12.dp else 6.dp, + end = 6.dp, + bottom = if (isBottomPlacement) 6.dp else 12.dp + ), + contentAlignment = if (isBottomPlacement) Alignment.BottomEnd else Alignment.TopEnd + ) { + Surface( + shape = RoundedCornerShape(22.dp), + color = menuBg, + shadowElevation = 16.dp, + tonalElevation = 4.dp, + modifier = Modifier + .width(256.dp) + .clickable( + interactionSource = remember { MutableInteractionSource() }, + indication = null, + onClick = {} + ) + .testTag("chrome_overflow_menu") + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .verticalScroll(scrollState) + .padding(top = 8.dp, bottom = 10.dp) + ) { + // Exact Chrome Top 5 Circular Buttons Strip (Back, Forward, Star, Download, Reload) + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 10.dp, vertical = 4.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + MenuCircleAction( + icon = Icons.AutoMirrored.Filled.ArrowBack, + contentDescription = stringResource(R.string.cd_back), + enabled = activeTab.canGoBack || isWebPage, + activeBg = circleBg, + disabledBg = circleDisabledBg, + testTag = "menu_back", + onClick = { + onDismiss() + onBack() + } + ) + + MenuCircleAction( + icon = Icons.AutoMirrored.Filled.ArrowForward, + contentDescription = stringResource(R.string.cd_forward), + enabled = activeTab.canGoForward, + activeBg = circleBg, + disabledBg = circleDisabledBg, + testTag = "menu_forward", + onClick = { + onDismiss() + onForward() + } + ) + + MenuCircleAction( + icon = if (isBookmarked) Icons.Default.Star else Icons.Outlined.StarBorder, + contentDescription = stringResource(R.string.cd_bookmark), + enabled = isWebPage, + activeBg = circleBg, + disabledBg = circleDisabledBg, + iconTint = if (isBookmarked && isWebPage) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface, + testTag = "menu_bookmark_star", + onClick = { + onDismiss() + onToggleBookmark() + } + ) + + MenuCircleAction( + icon = Icons.Outlined.Download, + contentDescription = stringResource(R.string.cd_download_page), + enabled = isWebPage, + activeBg = circleBg, + disabledBg = circleDisabledBg, + testTag = "menu_download_page", + onClick = { + onDismiss() + onDownloadPage() + } + ) + + MenuCircleAction( + icon = if (activeTab.isLoading) Icons.Default.Close else Icons.Default.Refresh, + contentDescription = stringResource(if (activeTab.isLoading) R.string.cd_stop else R.string.cd_reload), + enabled = isWebPage, + activeBg = circleBg, + disabledBg = circleDisabledBg, + testTag = "menu_reload", + onClick = { + onDismiss() + onReloadOrStop() + } + ) + } + + Spacer(modifier = Modifier.height(4.dp)) + + // Section 1: Tabs & Groups + ChromeMenuRow( + icon = Icons.Outlined.AddBox, + label = "New tab", + testTag = "menu_new_tab", + onClick = { + onDismiss() + onNewTab() + } + ) + + Row( + modifier = Modifier + .fillMaxWidth() + .height(46.dp) + .clickable { + onDismiss() + onNewIncognitoTab() + } + .testTag("menu_new_incognito_tab") + .padding(horizontal = 16.dp), + verticalAlignment = Alignment.CenterVertically + ) { + IncognitoIcon( + size = 20.dp, + tint = MaterialTheme.colorScheme.onSurfaceVariant + ) + Spacer(modifier = Modifier.width(15.dp)) + Text( + text = "New Incognito tab", + style = MaterialTheme.typography.bodyLarge.copy(fontSize = 15.sp), + color = MaterialTheme.colorScheme.onSurface + ) + } + + ChromeMenuRow( + icon = Icons.Outlined.DashboardCustomize, + label = "Add tab to new group", + testTag = "menu_add_tab_group", + onClick = { + onDismiss() + onAddTabToNewGroup() + } + ) + + MenuSectionDivider(dividerColor) + + // Section 2: History, Clear Data, Site Controls + ChromeMenuRow( + icon = Icons.Outlined.History, + label = "History", + testTag = "menu_history", + onClick = { + onDismiss() + onHistory() + } + ) + + ChromeMenuRow( + icon = Icons.Outlined.DeleteOutline, + label = "Delete browsing data", + testTag = "menu_delete_browsing_data", + onClick = { + onDismiss() + onDeleteBrowsingData() + } + ) + + if (isWebPage) { + ChromeMenuRow( + icon = Icons.Outlined.Tune, + label = "Site controls", + testTag = "menu_site_controls", + onClick = { + onDismiss() + onSiteControls() + } + ) + } + + MenuSectionDivider(dividerColor) + + // Section 3: Downloads, Bookmarks, Recent tabs + ChromeMenuRow( + icon = Icons.Outlined.DownloadDone, + label = "Downloads", + testTag = "menu_downloads", + onClick = { + onDismiss() + onDownloads() + } + ) + + ChromeMenuRow( + icon = Icons.Default.Star, + label = "Bookmarks", + testTag = "menu_bookmarks", + onClick = { + onDismiss() + onBookmarks() + } + ) + + ChromeMenuRow( + icon = Icons.Outlined.Devices, + label = "Recent tabs", + testTag = "menu_recent_tabs", + onClick = { + onDismiss() + onRecentTabs() + } + ) + + if (isWebPage) { + MenuSectionDivider(dividerColor) + + // Section 4: Page Actions + ChromeMenuRow( + icon = Icons.Outlined.Share, + label = "Share...", + testTag = "menu_share", + onClick = { + onDismiss() + onShare() + } + ) + + ChromeMenuRow( + icon = Icons.Outlined.FindInPage, + label = "Find in page", + testTag = "menu_find_in_page", + onClick = { + onDismiss() + onFindInPage() + } + ) + + ChromeMenuRow( + icon = Icons.Outlined.Translate, + label = "Translate...", + testTag = "menu_translate", + onClick = { + onDismiss() + onTranslate() + } + ) + + ChromeMenuRow( + icon = Icons.Outlined.ChromeReaderMode, + label = "Show Reading mode", + testTag = "menu_reading_mode", + onClick = { + onDismiss() + onReadingMode() + } + ) + + ChromeMenuRow( + icon = Icons.Outlined.AddToHomeScreen, + label = "Install and create shortcut", + testTag = "menu_add_to_home_screen", + onClick = { + onDismiss() + onAddToHomeScreen() + } + ) + + Row( + modifier = Modifier + .fillMaxWidth() + .height(46.dp) + .clickable { + onDismiss() + onToggleDesktopSite() + } + .testTag("menu_desktop_site") + .padding(start = 16.dp, end = 6.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.Outlined.DesktopWindows, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(20.dp) + ) + Spacer(modifier = Modifier.width(15.dp)) + Text( + text = "Desktop site", + style = MaterialTheme.typography.bodyLarge.copy(fontSize = 15.sp), + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.weight(1f) + ) + Checkbox( + checked = activeTab.isDesktopSite, + onCheckedChange = { + onDismiss() + onToggleDesktopSite() + } + ) + } + } + + MenuSectionDivider(dividerColor) + + // Section 5: Settings & Help + ChromeMenuRow( + icon = Icons.Outlined.Settings, + label = "Settings", + testTag = "menu_settings", + onClick = { + onDismiss() + onSettings() + } + ) + + ChromeMenuRow( + icon = Icons.Outlined.HelpOutline, + label = "Help and feedback", + testTag = "menu_help_about", + onClick = { + onDismiss() + onHelpAndFeedback() + } + ) + } + } + } + } +} + +@Composable +private fun MenuCircleAction( + icon: ImageVector, + contentDescription: String, + enabled: Boolean, + activeBg: Color, + disabledBg: Color, + iconTint: Color = MaterialTheme.colorScheme.onSurface, + testTag: String, + onClick: () -> Unit +) { + Box( + modifier = Modifier + .size(42.dp) + .clip(CircleShape) + .background(if (enabled) activeBg else disabledBg) + .clickable(enabled = enabled, onClick = onClick) + .testTag(testTag), + contentAlignment = Alignment.Center + ) { + Icon( + imageVector = icon, + contentDescription = contentDescription, + tint = if (enabled) iconTint else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.35f), + modifier = Modifier.size(20.dp) + ) + } +} + +@Composable +private fun MenuSectionDivider(color: Color) { + HorizontalDivider( + modifier = Modifier.padding(horizontal = 14.dp, vertical = 4.dp), + thickness = 0.6.dp, + color = color + ) +} + +@Composable +private fun ChromeMenuRow( + icon: ImageVector, + label: String, + testTag: String, + onClick: () -> Unit +) { + Row( + modifier = Modifier + .fillMaxWidth() + .height(46.dp) + .clickable(onClick = onClick) + .testTag(testTag) + .padding(horizontal = 16.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = icon, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(20.dp) + ) + Spacer(modifier = Modifier.width(15.dp)) + Text( + text = label, + style = MaterialTheme.typography.bodyLarge.copy(fontSize = 15.sp), + color = MaterialTheme.colorScheme.onSurface + ) + } +} diff --git a/app/src/main/java/com/bansify/browser/ui/components/ChromeToolbar.kt b/app/src/main/java/com/bansify/browser/ui/components/ChromeToolbar.kt new file mode 100644 index 00000000..9e37b986 --- /dev/null +++ b/app/src/main/java/com/bansify/browser/ui/components/ChromeToolbar.kt @@ -0,0 +1,515 @@ +package com.bansify.browser.ui.components + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.combinedClickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.statusBarsPadding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.KeyboardArrowDown +import androidx.compose.material.icons.filled.KeyboardArrowUp +import androidx.compose.material.icons.filled.MoreVert +import androidx.compose.material.icons.filled.Share +import androidx.compose.material.icons.filled.Star +import androidx.compose.material.icons.outlined.AccountCircle +import androidx.compose.material.icons.outlined.Home +import androidx.compose.material.icons.outlined.StarBorder +import androidx.compose.material.icons.outlined.WarningAmber +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.bansify.browser.R +import com.bansify.browser.data.BansifyAccountState +import com.bansify.browser.data.BrowserSettings +import com.bansify.browser.data.BrowserTab +import com.bansify.browser.data.FindInPageState +import com.bansify.browser.data.ToolbarShortcut + +/** + * Pixel-accurate modern Chrome Android toolbar: + * - On webpage: [Home] [Clean Pill URL Bar] [+ / Shortcut] [Tab Count Box] [3-dot] + * - On NTP: [Home] ... [Bansify Account Avatar] [Tab Count Box] [3-dot] + * - Supports both Top and Bottom address bar placement cleanly with system insets. + */ +@OptIn(ExperimentalFoundationApi::class) +@Composable +fun ChromeToolbar( + activeTab: BrowserTab, + tabCount: Int, + settings: BrowserSettings, + accountState: BansifyAccountState, + isBookmarked: Boolean, + findInPage: FindInPageState, + isBottomPlacement: Boolean, + overflowMenuExpanded: Boolean, + onOverflowMenuChange: (Boolean) -> Unit, + onHomeClick: () -> Unit, + onAccountClick: () -> Unit, + onOmniboxClick: () -> Unit, + onPageInfoClick: () -> Unit, + onTabSwitcherClick: () -> Unit, + onNewTabClick: () -> Unit, + onNewIncognitoTabClick: () -> Unit, + onCloseActiveTabClick: () -> Unit, + onShareClick: () -> Unit, + onToggleBookmarkClick: () -> Unit, + onFindQueryChange: (String) -> Unit, + onFindNext: (Boolean) -> Unit, + onCloseFindInPage: () -> Unit, + overflowMenuContent: @Composable () -> Unit +) { + var tabQuickMenuExpanded by remember { mutableStateOf(false) } + + val toolbarBg = if (activeTab.isNewTab) { + MaterialTheme.colorScheme.background + } else { + MaterialTheme.colorScheme.surface + } + + val insetModifier = if (isBottomPlacement) { + Modifier.navigationBarsPadding() + } else { + Modifier.statusBarsPadding() + } + + Surface( + color = toolbarBg, + tonalElevation = 0.dp, + modifier = Modifier.fillMaxWidth() + ) { + Column(modifier = insetModifier) { + if (isBottomPlacement && !activeTab.isNewTab) { + ProgressOrDivider(activeTab) + } + + if (findInPage.isActive) { + FindInPageBar( + state = findInPage, + onQueryChange = onFindQueryChange, + onFindNext = onFindNext, + onClose = onCloseFindInPage + ) + } else { + Row( + modifier = Modifier + .fillMaxWidth() + .height(56.dp) + .padding(horizontal = 4.dp), + verticalAlignment = Alignment.CenterVertically + ) { + // Home button (shown on both webpage & NTP like Screenshot 4 & 7 when enabled!) + if (settings.homepageEnabled) { + IconButton( + onClick = onHomeClick, + modifier = Modifier.testTag("toolbar_home_button") + ) { + Icon( + imageVector = Icons.Outlined.Home, + contentDescription = stringResource(R.string.cd_home), + tint = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.size(24.dp) + ) + } + } else if (activeTab.isNewTab && activeTab.isIncognito) { + Box( + modifier = Modifier.size(48.dp), + contentAlignment = Alignment.Center + ) { + IncognitoIcon( + size = 22.dp, + tint = MaterialTheme.colorScheme.onSurface + ) + } + } else { + Spacer(modifier = Modifier.width(10.dp)) + } + + // Clean Pill Omnibox (matches Screenshot 7: clean domain/path pill!) + if (!activeTab.isNewTab) { + val displayUrl = remember(activeTab.url) { + activeTab.url + .removePrefix("https://") + .removePrefix("http://") + .removePrefix("www.") + .trimEnd('/') + } + + Row( + modifier = Modifier + .weight(1f) + .height(42.dp) + .clip(RoundedCornerShape(21.dp)) + .background(MaterialTheme.colorScheme.surfaceContainer) + .combinedClickable( + onClick = onOmniboxClick, + onLongClick = onPageInfoClick + ) + .testTag("omnibox_bar") + .padding(horizontal = 14.dp), + verticalAlignment = Alignment.CenterVertically + ) { + if (activeTab.isIncognito) { + IncognitoIcon( + size = 18.dp, + tint = MaterialTheme.colorScheme.onSurface + ) + Spacer(modifier = Modifier.width(8.dp)) + } else if (!activeTab.isSecure) { + Icon( + imageVector = Icons.Outlined.WarningAmber, + contentDescription = stringResource(R.string.cd_page_info), + tint = MaterialTheme.colorScheme.error, + modifier = Modifier + .size(18.dp) + .clickable(onClick = onPageInfoClick) + ) + Spacer(modifier = Modifier.width(8.dp)) + } + + Text( + text = displayUrl, + style = MaterialTheme.typography.bodyLarge.copy(fontSize = 15.5.sp), + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f) + ) + } + } else { + // On NTP: Home on left, Bansify Account avatar + Tab counter + 3-dot on right + if (activeTab.isIncognito) { + Spacer(modifier = Modifier.width(4.dp)) + IncognitoIcon( + size = 20.dp, + tint = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + Spacer(modifier = Modifier.weight(1f)) + + if (!activeTab.isIncognito) { + Box( + modifier = Modifier + .size(44.dp) + .clip(CircleShape) + .clickable(onClick = onAccountClick) + .testTag("ntp_account_avatar"), + contentAlignment = Alignment.Center + ) { + if (accountState.isSignedIn) { + Box( + modifier = Modifier + .size(30.dp) + .clip(CircleShape) + .background(Color(accountState.avatarColorHex)), + contentAlignment = Alignment.Center + ) { + Text( + text = accountState.initialLetter, + color = Color.White, + fontSize = 14.sp, + fontWeight = FontWeight.Bold + ) + } + } else { + Icon( + imageVector = Icons.Outlined.AccountCircle, + contentDescription = "Bansify Account", + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(27.dp) + ) + } + } + } + } + + // Toolbar Shortcut icon (Default: '+' New Tab, matching Screenshot 7!) + if (!activeTab.isNewTab && settings.toolbarShortcut != ToolbarShortcut.NONE) { + when (settings.toolbarShortcut) { + ToolbarShortcut.NEW_TAB -> { + IconButton( + onClick = onNewTabClick, + modifier = Modifier.testTag("toolbar_shortcut_new_tab") + ) { + Icon( + imageVector = Icons.Default.Add, + contentDescription = stringResource(R.string.new_tab), + tint = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.size(25.dp) + ) + } + } + ToolbarShortcut.SHARE -> { + IconButton( + onClick = onShareClick, + modifier = Modifier.testTag("toolbar_shortcut_share") + ) { + Icon( + imageVector = Icons.Default.Share, + contentDescription = stringResource(R.string.share), + tint = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.size(21.dp) + ) + } + } + ToolbarShortcut.BOOKMARK -> { + IconButton( + onClick = onToggleBookmarkClick, + modifier = Modifier.testTag("toolbar_shortcut_bookmark") + ) { + Icon( + imageVector = if (isBookmarked) Icons.Default.Star else Icons.Outlined.StarBorder, + contentDescription = stringResource(R.string.cd_bookmark), + tint = if (isBookmarked) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface, + modifier = Modifier.size(22.dp) + ) + } + } + ToolbarShortcut.NONE -> Unit + } + } + + // Tab Switcher Counter Box + Box { + Box( + modifier = Modifier + .size(44.dp) + .clip(CircleShape) + .combinedClickable( + onClick = onTabSwitcherClick, + onLongClick = { tabQuickMenuExpanded = true } + ) + .testTag("tab_switcher_button"), + contentAlignment = Alignment.Center + ) { + ChromeTabCountBadge( + count = tabCount, + color = MaterialTheme.colorScheme.onSurface + ) + } + + DropdownMenu( + expanded = tabQuickMenuExpanded, + onDismissRequest = { tabQuickMenuExpanded = false }, + shape = RoundedCornerShape(16.dp), + containerColor = MaterialTheme.colorScheme.surfaceContainer + ) { + DropdownMenuItem( + text = { Text(stringResource(R.string.new_tab)) }, + onClick = { + tabQuickMenuExpanded = false + onNewTabClick() + } + ) + DropdownMenuItem( + text = { Text(stringResource(R.string.new_incognito_tab)) }, + onClick = { + tabQuickMenuExpanded = false + onNewIncognitoTabClick() + } + ) + DropdownMenuItem( + text = { Text("Close tab") }, + onClick = { + tabQuickMenuExpanded = false + onCloseActiveTabClick() + } + ) + } + } + + // 3-Dot Overflow Menu Trigger + Box { + IconButton( + onClick = { onOverflowMenuChange(true) }, + modifier = Modifier + .size(44.dp) + .testTag("overflow_menu_button") + ) { + Icon( + imageVector = Icons.Default.MoreVert, + contentDescription = stringResource(R.string.cd_more_options), + tint = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.size(23.dp) + ) + } + overflowMenuContent() + } + } + } + + if (!isBottomPlacement) { + ProgressOrDivider(activeTab) + } + } + } +} + +@Composable +private fun ProgressOrDivider(activeTab: BrowserTab) { + Box( + modifier = Modifier + .fillMaxWidth() + .height(2.dp) + ) { + if (activeTab.isLoading && activeTab.progress in 1..99 && !activeTab.isNewTab) { + LinearProgressIndicator( + progress = { activeTab.progress / 100f }, + modifier = Modifier + .fillMaxWidth() + .height(2.dp), + color = MaterialTheme.colorScheme.primary, + trackColor = MaterialTheme.colorScheme.surfaceVariant + ) + } else if (!activeTab.isNewTab) { + HorizontalDivider( + thickness = 0.5.dp, + color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.45f) + ) + } + } +} + +@Composable +private fun FindInPageBar( + state: FindInPageState, + onQueryChange: (String) -> Unit, + onFindNext: (Boolean) -> Unit, + onClose: () -> Unit +) { + val focusRequester = remember { FocusRequester() } + LaunchedEffect(Unit) { + focusRequester.requestFocus() + } + + Row( + modifier = Modifier + .fillMaxWidth() + .height(56.dp) + .padding(horizontal = 8.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(2.dp) + ) { + Box( + modifier = Modifier + .weight(1f) + .height(42.dp) + .clip(RoundedCornerShape(21.dp)) + .background(MaterialTheme.colorScheme.surfaceContainer) + .padding(horizontal = 14.dp), + contentAlignment = Alignment.CenterStart + ) { + BasicTextField( + value = state.query, + onValueChange = onQueryChange, + singleLine = true, + textStyle = MaterialTheme.typography.bodyLarge.copy( + color = MaterialTheme.colorScheme.onSurface + ), + cursorBrush = SolidColor(MaterialTheme.colorScheme.primary), + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search), + keyboardActions = KeyboardActions(onSearch = { onFindNext(true) }), + modifier = Modifier + .fillMaxWidth() + .focusRequester(focusRequester) + .testTag("find_in_page_input"), + decorationBox = { inner -> + if (state.query.isEmpty()) { + Text( + text = "Find in page", + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + inner() + } + ) + } + + AnimatedVisibility(visible = state.query.isNotEmpty()) { + Text( + text = "${state.activeMatchOrdinal}/${state.numberOfMatches}", + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 6.dp) + ) + } + + IconButton( + onClick = { onFindNext(false) }, + enabled = state.numberOfMatches > 0 + ) { + Icon( + imageVector = Icons.Default.KeyboardArrowUp, + contentDescription = "Previous match", + tint = MaterialTheme.colorScheme.onSurface + ) + } + + IconButton( + onClick = { onFindNext(true) }, + enabled = state.numberOfMatches > 0 + ) { + Icon( + imageVector = Icons.Default.KeyboardArrowDown, + contentDescription = "Next match", + tint = MaterialTheme.colorScheme.onSurface + ) + } + + IconButton( + onClick = onClose, + modifier = Modifier.testTag("find_in_page_close") + ) { + Icon( + imageVector = Icons.Default.Close, + contentDescription = stringResource(R.string.cd_close), + tint = MaterialTheme.colorScheme.onSurface + ) + } + } +} diff --git a/app/src/main/java/com/bansify/browser/ui/components/ExpressiveComponents.kt b/app/src/main/java/com/bansify/browser/ui/components/ExpressiveComponents.kt new file mode 100644 index 00000000..2bdf5a39 --- /dev/null +++ b/app/src/main/java/com/bansify/browser/ui/components/ExpressiveComponents.kt @@ -0,0 +1,56 @@ +package com.bansify.browser.ui.components + +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Shape +import androidx.compose.ui.unit.dp +import com.bansify.browser.ui.theme.LocalIsDarkBrowserTheme + +/** + * Computes Chrome Android's exact Material 3 Expressive segmented card corners: + * - Single item: 20.dp all around + * - First item in group: 20.dp top, 4.dp bottom + * - Middle item: 4.dp all around + * - Last item in group: 4.dp top, 20.dp bottom + */ +fun expressiveCardShape(index: Int, totalCount: Int): Shape { + val outer = 20.dp + val inner = 4.dp + return when { + totalCount <= 1 -> RoundedCornerShape(outer) + index == 0 -> RoundedCornerShape(topStart = outer, topEnd = outer, bottomStart = inner, bottomEnd = inner) + index == totalCount - 1 -> RoundedCornerShape(topStart = inner, topEnd = inner, bottomStart = outer, bottomEnd = outer) + else -> RoundedCornerShape(inner) + } +} + +@Composable +fun expressiveCanvasColor(): Color { + return MaterialTheme.colorScheme.surfaceContainerLowest +} + +@Composable +fun expressiveCardColor(): Color { + val isDark = LocalIsDarkBrowserTheme.current + return if (isDark) MaterialTheme.colorScheme.surfaceContainerLow else MaterialTheme.colorScheme.surface +} + +@Composable +fun ExpressiveGroupedCard( + index: Int, + totalCount: Int, + modifier: Modifier = Modifier, + containerColor: Color = expressiveCardColor(), + content: @Composable () -> Unit +) { + Surface( + shape = expressiveCardShape(index, totalCount), + color = containerColor, + modifier = modifier, + content = content + ) +} diff --git a/app/src/main/java/com/bansify/browser/ui/components/ReadingModeOverlay.kt b/app/src/main/java/com/bansify/browser/ui/components/ReadingModeOverlay.kt new file mode 100644 index 00000000..de64a95b --- /dev/null +++ b/app/src/main/java/com/bansify/browser/ui/components/ReadingModeOverlay.kt @@ -0,0 +1,279 @@ +package com.bansify.browser.ui.components + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +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.height +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.outlined.FormatSize +import androidx.compose.material.icons.outlined.Translate +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.FilterChip +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Slider +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.bansify.browser.data.ReadingModeContent + +private enum class ReaderPalette(val label: String, val bg: Color, val text: Color, val muted: Color) { + DARK("Dark", Color(0xFF161719), Color(0xFFE8EAED), Color(0xFF9AA0A6)), + SEPIA("Sepia", Color(0xFFF6EFE0), Color(0xFF33291E), Color(0xFF6B5D4D)), + LIGHT("Light", Color(0xFFFFFFFF), Color(0xFF1F1F1F), Color(0xFF5F6368)) +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun ReadingModeOverlay( + content: ReadingModeContent, + initialDark: Boolean, + onClose: () -> Unit +) { + BackHandler { onClose() } + + var palette by remember { mutableStateOf(if (initialDark) ReaderPalette.DARK else ReaderPalette.LIGHT) } + var fontSizeSp by remember { mutableFloatStateOf(17f) } + var showAppearanceBar by remember { mutableStateOf(false) } + + Scaffold( + containerColor = palette.bg, + topBar = { + TopAppBar( + title = { + Column { + Text( + text = "Reading mode", + style = MaterialTheme.typography.titleMedium, + color = palette.text + ) + Text( + text = content.domain, + style = MaterialTheme.typography.labelSmall, + color = palette.muted + ) + } + }, + actions = { + IconButton(onClick = { showAppearanceBar = !showAppearanceBar }) { + Icon( + imageVector = Icons.Outlined.FormatSize, + contentDescription = "Reading appearance", + tint = palette.text + ) + } + IconButton(onClick = onClose) { + Icon( + imageVector = Icons.Default.Close, + contentDescription = "Close reading mode", + tint = palette.text + ) + } + }, + colors = TopAppBarDefaults.topAppBarColors(containerColor = palette.bg) + ) + } + ) { innerPadding -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(innerPadding) + .background(palette.bg), + horizontalAlignment = Alignment.CenterHorizontally + ) { + if (showAppearanceBar) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 20.dp, vertical = 10.dp), + verticalArrangement = Arrangement.spacedBy(8.dp) + ) { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + ReaderPalette.entries.forEach { option -> + FilterChip( + selected = palette == option, + onClick = { palette = option }, + label = { Text(option.label) } + ) + } + } + Row(verticalAlignment = Alignment.CenterVertically) { + Text("A", fontSize = 13.sp, color = palette.muted) + Slider( + value = fontSizeSp, + onValueChange = { fontSizeSp = it }, + valueRange = 14f..26f, + modifier = Modifier + .weight(1f) + .padding(horizontal = 12.dp) + ) + Text("A", fontSize = 22.sp, fontWeight = FontWeight.Bold, color = palette.text) + } + } + HorizontalDivider(color = palette.muted.copy(alpha = 0.25f)) + } + + LazyColumn( + modifier = Modifier + .fillMaxSize() + .widthIn(max = 680.dp), + contentPadding = PaddingValues(horizontal = 24.dp, vertical = 20.dp), + verticalArrangement = Arrangement.spacedBy(16.dp) + ) { + item { + Text( + text = content.title.ifBlank { content.domain }, + style = MaterialTheme.typography.headlineMedium, + color = palette.text, + fontWeight = FontWeight.Bold + ) + Spacer(modifier = Modifier.height(6.dp)) + Text( + text = content.url, + style = MaterialTheme.typography.bodySmall, + color = palette.muted + ) + Spacer(modifier = Modifier.height(10.dp)) + HorizontalDivider(color = palette.muted.copy(alpha = 0.25f)) + } + + if (content.paragraphs.isEmpty()) { + item { + Text( + text = "This page doesn't contain long-form article text to simplify. Try Reading mode on a news article, blog post, or documentation page.", + fontSize = fontSizeSp.sp, + lineHeight = (fontSizeSp * 1.6f).sp, + color = palette.muted + ) + } + } else { + items(content.paragraphs) { paragraph -> + Text( + text = paragraph, + fontSize = fontSizeSp.sp, + lineHeight = (fontSizeSp * 1.62f).sp, + color = palette.text + ) + } + } + + item { Spacer(modifier = Modifier.height(32.dp)) } + } + } + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun TranslatePageBottomSheet( + currentUrl: String, + onDismiss: () -> Unit, + onSelectLanguage: (code: String, displayName: String) -> Unit +) { + val languages = listOf( + "en" to "English", + "hi" to "Hindi (हिन्दी)", + "es" to "Spanish (Español)", + "fr" to "French (Français)", + "de" to "German (Deutsch)", + "ar" to "Arabic (العربية)", + "ja" to "Japanese (日本語)", + "pt" to "Portuguese (Português)", + "zh-CN" to "Chinese (Simplified)" + ) + + ModalBottomSheet( + onDismissRequest = onDismiss, + containerColor = MaterialTheme.colorScheme.surfaceContainerLow, + shape = RoundedCornerShape(topStart = 24.dp, topEnd = 24.dp) + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .navigationBarsPadding() + .padding(bottom = 20.dp) + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 24.dp, vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.Outlined.Translate, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(24.dp) + ) + Spacer(modifier = Modifier.width(14.dp)) + Column { + Text( + text = "Translate page", + style = MaterialTheme.typography.titleMedium, + color = MaterialTheme.colorScheme.onSurface + ) + Text( + text = "Choose target language for this page", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + + HorizontalDivider( + modifier = Modifier.padding(vertical = 8.dp), + color = MaterialTheme.colorScheme.outlineVariant + ) + + LazyColumn(modifier = Modifier.height(340.dp)) { + items(languages) { (code, label) -> + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { onSelectLanguage(code, label) } + .padding(horizontal = 24.dp, vertical = 14.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = label, + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurface + ) + } + } + } + } + } +} diff --git a/app/src/main/java/com/bansify/browser/ui/screens/BansifyAccountScreen.kt b/app/src/main/java/com/bansify/browser/ui/screens/BansifyAccountScreen.kt new file mode 100644 index 00000000..60232044 --- /dev/null +++ b/app/src/main/java/com/bansify/browser/ui/screens/BansifyAccountScreen.kt @@ -0,0 +1,797 @@ +package com.bansify.browser.ui.screens + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +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.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.automirrored.outlined.Logout +import androidx.compose.material.icons.outlined.CloudDone +import androidx.compose.material.icons.outlined.CloudOff +import androidx.compose.material.icons.outlined.Edit +import androidx.compose.material.icons.outlined.Sync +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.FilledTonalButton +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Surface +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableLongStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.bansify.browser.R +import com.bansify.browser.browser.UrlUtils +import com.bansify.browser.data.BansifyAccountState +import com.bansify.browser.ui.components.ExpressiveGroupedCard +import com.bansify.browser.ui.components.expressiveCanvasColor +import com.bansify.browser.ui.theme.BrandBlue +import com.bansify.browser.ui.theme.LocalIsDarkBrowserTheme +import com.bansify.browser.ui.theme.SecureGreen +import com.bansify.browser.ui.theme.SecureGreenDark + +private val BansifyAvatarColors = listOf( + 0xFF1A73E8L, + 0xFF188038L, + 0xFF8430CEL, + 0xFFD93025L, + 0xFFE37400L, + 0xFF007B83L +) + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun BansifyAccountScreen( + accountState: BansifyAccountState, + bookmarksCount: Int, + historyCount: Int, + openTabsCount: Int, + shortcutsCount: Int, + downloadsCount: Int, + onBack: () -> Unit, + onSignIn: (displayName: String, email: String, avatarColorHex: Long) -> Unit, + onUpdateProfile: (displayName: String, email: String, avatarColorHex: Long) -> Unit, + onSignOut: () -> Unit, + onUpdateSync: ((BansifyAccountState) -> BansifyAccountState) -> Unit, + onSyncNow: () -> Unit +) { + BackHandler { onBack() } + + val canvasBg = expressiveCanvasColor() + var showEditProfileDialog by remember { mutableStateOf(false) } + + Scaffold( + containerColor = canvasBg, + topBar = { + TopAppBar( + title = { + Text(if (accountState.isSignedIn) "Bansify Account & sync" else "Sign in to Bansify") + }, + navigationIcon = { + IconButton(onClick = onBack, modifier = Modifier.testTag("bansify_account_back")) { + Icon( + imageVector = Icons.AutoMirrored.Filled.ArrowBack, + contentDescription = stringResource(R.string.cd_back) + ) + } + }, + colors = TopAppBarDefaults.topAppBarColors(containerColor = canvasBg) + ) + } + ) { innerPadding -> + LazyColumn( + modifier = Modifier + .fillMaxSize() + .background(canvasBg) + .padding(innerPadding), + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(2.dp) + ) { + if (!accountState.isSignedIn) { + item(key = "sign_in_card") { + BansifySignInCard(onSignIn = onSignIn) + } + } else { + // Hero Signed-In Profile + Sync Now Card + item(key = "signed_in_hero") { + val syncedColor = if (LocalIsDarkBrowserTheme.current) SecureGreenDark else SecureGreen + ExpressiveGroupedCard(index = 0, totalCount = 1) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(20.dp) + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + Box( + modifier = Modifier + .size(56.dp) + .clip(CircleShape) + .background(Color(accountState.avatarColorHex)), + contentAlignment = Alignment.Center + ) { + Text( + text = accountState.initialLetter, + color = Color.White, + fontSize = 24.sp, + fontWeight = FontWeight.Bold + ) + } + Spacer(modifier = Modifier.width(16.dp)) + Column(modifier = Modifier.weight(1f)) { + Text( + text = accountState.displayName, + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onSurface + ) + Text( + text = accountState.email, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Spacer(modifier = Modifier.height(4.dp)) + Row(verticalAlignment = Alignment.CenterVertically) { + Icon( + imageVector = if (accountState.activeSyncCategoriesCount > 0) Icons.Outlined.CloudDone else Icons.Outlined.CloudOff, + contentDescription = null, + tint = if (accountState.activeSyncCategoriesCount > 0) syncedColor else MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(15.dp) + ) + Spacer(modifier = Modifier.width(6.dp)) + val syncText = when { + accountState.isSyncing -> "Syncing with Bansify…" + accountState.activeSyncCategoriesCount == 0 -> "Sync paused (0 of 6 categories)" + accountState.lastSyncedAt > 0L -> + "Synced ${accountState.activeSyncCategoriesCount}/6 • ${UrlUtils.formatShortTime(accountState.lastSyncedAt)}" + else -> "Sync active (${accountState.activeSyncCategoriesCount}/6)" + } + Text( + text = syncText, + style = MaterialTheme.typography.labelSmall, + color = if (accountState.activeSyncCategoriesCount > 0) syncedColor else MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + IconButton(onClick = { showEditProfileDialog = true }) { + Icon( + imageVector = Icons.Outlined.Edit, + contentDescription = "Edit profile", + tint = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + + Spacer(modifier = Modifier.height(16.dp)) + + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(10.dp) + ) { + FilledTonalButton( + onClick = onSyncNow, + enabled = !accountState.isSyncing, + shape = RoundedCornerShape(22.dp), + modifier = Modifier + .weight(1f) + .testTag("bansify_sync_now_button") + ) { + if (accountState.isSyncing) { + CircularProgressIndicator( + modifier = Modifier.size(16.dp), + strokeWidth = 2.dp + ) + } else { + Icon( + imageVector = Icons.Outlined.Sync, + contentDescription = null, + modifier = Modifier.size(18.dp) + ) + } + Spacer(modifier = Modifier.width(8.dp)) + Text(if (accountState.isSyncing) "Syncing..." else "Sync now") + } + + OutlinedButton( + onClick = onSignOut, + shape = RoundedCornerShape(22.dp), + modifier = Modifier + .weight(1f) + .testTag("bansify_sign_out_button") + ) { + Icon( + imageVector = Icons.AutoMirrored.Outlined.Logout, + contentDescription = null, + modifier = Modifier.size(18.dp) + ) + Spacer(modifier = Modifier.width(8.dp)) + Text("Sign out") + } + } + } + } + } + + // Manage what syncs (kya kya sync ho raha hai, kya nahi) + item(key = "sync_header") { + Spacer(modifier = Modifier.height(14.dp)) + ExpressiveSettingsSectionTitle("Manage what you sync") + } + + item(key = "sync_master") { + SyncSwitchRow( + index = 0, + totalCount = 7, + title = "Sync everything", + subtitle = if (accountState.syncEverything) { + "All 6 Bansify categories are syncing automatically" + } else { + "Custom sync • Choose individual categories below" + }, + statusBadge = if (accountState.syncEverything) "All ON" else "${accountState.activeSyncCategoriesCount}/6 ON", + isActive = accountState.syncEverything, + checked = accountState.syncEverything, + enabled = true, + onCheckedChange = { enabled -> + onUpdateSync { it.copy(syncEverything = enabled) } + } + ) + } + + item(key = "sync_bookmarks") { + val active = accountState.effectiveBookmarksSync + SyncSwitchRow( + index = 1, + totalCount = 7, + title = "Bookmarks", + subtitle = "$bookmarksCount saved bookmark(s) & folders", + statusBadge = if (active) "Syncing" else "Not syncing", + isActive = active, + checked = active, + enabled = !accountState.syncEverything, + onCheckedChange = { enabled -> + onUpdateSync { it.copy(syncBookmarks = enabled) } + } + ) + } + + item(key = "sync_history") { + val active = accountState.effectiveHistorySync + SyncSwitchRow( + index = 2, + totalCount = 7, + title = "History", + subtitle = "$historyCount visited page(s) across normal tabs", + statusBadge = if (active) "Syncing" else "Not syncing", + isActive = active, + checked = active, + enabled = !accountState.syncEverything, + onCheckedChange = { enabled -> + onUpdateSync { it.copy(syncHistory = enabled) } + } + ) + } + + item(key = "sync_tabs") { + val active = accountState.effectiveTabsSync + SyncSwitchRow( + index = 3, + totalCount = 7, + title = "Open tabs", + subtitle = "$openTabsCount open normal tab(s) & tab groups", + statusBadge = if (active) "Syncing" else "Not syncing", + isActive = active, + checked = active, + enabled = !accountState.syncEverything, + onCheckedChange = { enabled -> + onUpdateSync { it.copy(syncOpenTabs = enabled) } + } + ) + } + + item(key = "sync_shortcuts") { + val active = accountState.effectiveShortcutsSync + SyncSwitchRow( + index = 4, + totalCount = 7, + title = "Home shortcuts", + subtitle = "$shortcutsCount quick shortcut(s) on New Tab page", + statusBadge = if (active) "Syncing" else "Not syncing", + isActive = active, + checked = active, + enabled = !accountState.syncEverything, + onCheckedChange = { enabled -> + onUpdateSync { it.copy(syncShortcuts = enabled) } + } + ) + } + + item(key = "sync_settings") { + val active = accountState.effectiveSettingsSync + SyncSwitchRow( + index = 5, + totalCount = 7, + title = "Settings & preferences", + subtitle = "Search engine, theme, address bar & site settings", + statusBadge = if (active) "Syncing" else "Not syncing", + isActive = active, + checked = active, + enabled = !accountState.syncEverything, + onCheckedChange = { enabled -> + onUpdateSync { it.copy(syncSettings = enabled) } + } + ) + } + + item(key = "sync_downloads") { + val active = accountState.effectiveDownloadsSync + SyncSwitchRow( + index = 6, + totalCount = 7, + title = "Downloads history", + subtitle = "$downloadsCount downloaded file record(s)", + statusBadge = if (active) "Syncing" else "Not syncing", + isActive = active, + checked = active, + enabled = !accountState.syncEverything, + onCheckedChange = { enabled -> + onUpdateSync { it.copy(syncDownloadsList = enabled) } + } + ) + } + + // Developer / Architecture note card + item(key = "sync_arch_note") { + Spacer(modifier = Modifier.height(14.dp)) + ExpressiveGroupedCard(index = 0, totalCount = 1) { + Column(modifier = Modifier.padding(18.dp)) { + Text( + text = "Demo Bansify Account Architecture", + style = MaterialTheme.typography.titleSmall, + color = MaterialTheme.colorScheme.primary + ) + Spacer(modifier = Modifier.height(4.dp)) + Text( + text = "Local demo account & sync state is persisted via BansifyAccountProvider. Swap DemoBansifyAccountProvider with your real Bansify API client later to enable live multi-device cloud sync.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } + } + + item { Spacer(modifier = Modifier.height(28.dp)) } + } + } + + if (showEditProfileDialog) { + EditBansifyProfileDialog( + accountState = accountState, + onDismiss = { showEditProfileDialog = false }, + onSave = { name, email, colorHex -> + onUpdateProfile(name, email, colorHex) + showEditProfileDialog = false + } + ) + } +} + +@Composable +private fun BansifySignInCard( + onSignIn: (displayName: String, email: String, avatarColorHex: Long) -> Unit +) { + var name by remember { mutableStateOf("") } + var email by remember { mutableStateOf("") } + var selectedColor by remember { mutableLongStateOf(BansifyAvatarColors.first()) } + + ExpressiveGroupedCard(index = 0, totalCount = 1) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(22.dp), + horizontalAlignment = Alignment.CenterHorizontally + ) { + Box( + modifier = Modifier + .size(64.dp) + .clip(CircleShape) + .background(Color(selectedColor)), + contentAlignment = Alignment.Center + ) { + Text( + text = name.firstOrNull { it.isLetterOrDigit() }?.uppercaseChar()?.toString() ?: "B", + color = Color.White, + fontSize = 28.sp, + fontWeight = FontWeight.Bold + ) + } + + Spacer(modifier = Modifier.height(14.dp)) + + Text( + text = "Sign in to Bansify", + style = MaterialTheme.typography.headlineSmall, + color = MaterialTheme.colorScheme.onSurface + ) + + Spacer(modifier = Modifier.height(6.dp)) + + Text( + text = "Get your bookmarks, history, open tabs, and settings synced with your Bansify Account.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + + Spacer(modifier = Modifier.height(10.dp)) + + Surface( + shape = RoundedCornerShape(12.dp), + color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.55f) + ) { + Text( + text = "Demo Account Structure • Ready for Real Bansify API", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onPrimaryContainer, + modifier = Modifier.padding(horizontal = 10.dp, vertical = 5.dp) + ) + } + + Spacer(modifier = Modifier.height(18.dp)) + + OutlinedTextField( + value = name, + onValueChange = { name = it }, + label = { Text("Full name") }, + placeholder = { Text("e.g. Alex Bansify") }, + singleLine = true, + modifier = Modifier + .fillMaxWidth() + .testTag("bansify_signin_name") + ) + + Spacer(modifier = Modifier.height(12.dp)) + + OutlinedTextField( + value = email, + onValueChange = { email = it }, + label = { Text("Bansify email") }, + placeholder = { Text("e.g. alex@bansify.com") }, + singleLine = true, + modifier = Modifier + .fillMaxWidth() + .testTag("bansify_signin_email") + ) + + Spacer(modifier = Modifier.height(14.dp)) + + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(10.dp, Alignment.CenterHorizontally) + ) { + BansifyAvatarColors.forEach { hex -> + Box( + modifier = Modifier + .size(30.dp) + .clip(CircleShape) + .background(Color(hex)) + .then( + if (selectedColor == hex) { + Modifier.border(2.5.dp, MaterialTheme.colorScheme.onSurface, CircleShape) + } else { + Modifier + } + ) + .clickable { selectedColor = hex } + ) + } + } + + Spacer(modifier = Modifier.height(20.dp)) + + Button( + onClick = { + val resolvedName = name.trim().ifBlank { "Bansify User" } + val resolvedEmail = email.trim().ifBlank { "user@bansify.com" } + onSignIn(resolvedName, resolvedEmail, selectedColor) + }, + shape = RoundedCornerShape(24.dp), + modifier = Modifier + .fillMaxWidth() + .height(48.dp) + .testTag("bansify_signin_submit") + ) { + Text("Sign in with Bansify") + } + + Spacer(modifier = Modifier.height(10.dp)) + + FilledTonalButton( + onClick = { + onSignIn("Bansify Demo", "demo@bansify.com", BrandBlue.value.toLong().let { 0xFF1A73E8L }) + }, + shape = RoundedCornerShape(24.dp), + modifier = Modifier + .fillMaxWidth() + .height(44.dp) + .testTag("bansify_quick_demo_signin") + ) { + Text("Quick Demo Login (demo@bansify.com)") + } + } + } +} + +@Composable +private fun SyncSwitchRow( + index: Int, + totalCount: Int, + title: String, + subtitle: String, + statusBadge: String, + isActive: Boolean, + checked: Boolean, + enabled: Boolean, + onCheckedChange: (Boolean) -> Unit +) { + val activeGreen = if (LocalIsDarkBrowserTheme.current) SecureGreenDark else SecureGreen + ExpressiveGroupedCard(index = index, totalCount = totalCount) { + Row( + modifier = Modifier + .fillMaxWidth() + .clickable(enabled = enabled) { onCheckedChange(!checked) } + .padding(horizontal = 20.dp, vertical = 14.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Column(modifier = Modifier.weight(1f)) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp) + ) { + Text( + text = title, + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurface + ) + Surface( + shape = RoundedCornerShape(8.dp), + color = if (isActive) { + activeGreen.copy(alpha = 0.16f) + } else { + MaterialTheme.colorScheme.surfaceContainerHighest + } + ) { + Text( + text = statusBadge, + style = MaterialTheme.typography.labelSmall, + color = if (isActive) activeGreen else MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 7.dp, vertical = 2.dp) + ) + } + } + Spacer(modifier = Modifier.height(2.dp)) + Text( + text = subtitle, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + Spacer(modifier = Modifier.width(12.dp)) + Switch( + checked = checked, + onCheckedChange = onCheckedChange, + enabled = enabled + ) + } + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun BansifyServicesScreen( + accountState: BansifyAccountState, + onBack: () -> Unit, + onUpdateSync: ((BansifyAccountState) -> BansifyAccountState) -> Unit +) { + BackHandler { onBack() } + val canvasBg = expressiveCanvasColor() + + Scaffold( + containerColor = canvasBg, + topBar = { + TopAppBar( + title = { Text("Bansify services") }, + navigationIcon = { + IconButton(onClick = onBack) { + Icon( + imageVector = Icons.AutoMirrored.Filled.ArrowBack, + contentDescription = stringResource(R.string.cd_back) + ) + } + }, + colors = TopAppBarDefaults.topAppBarColors(containerColor = canvasBg) + ) + } + ) { innerPadding -> + LazyColumn( + modifier = Modifier + .fillMaxSize() + .background(canvasBg) + .padding(innerPadding), + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(2.dp) + ) { + item { + ExpressiveSettingsSectionTitle("Bansify cloud & search services") + } + item { + BansifyServiceSwitchCard( + index = 0, + totalCount = 3, + title = "Autocomplete searches and URLs", + subtitle = "Sends typed queries in the address bar to match sites and suggestions faster", + checked = accountState.autocompleteSearches, + onCheckedChange = { v -> onUpdateSync { it.copy(autocompleteSearches = v) } } + ) + } + item { + BansifyServiceSwitchCard( + index = 1, + totalCount = 3, + title = "Improve search suggestions", + subtitle = "Prioritize your recent searches, bookmarks, and open tabs in the Omnibox", + checked = accountState.improveSearchSuggestions, + onCheckedChange = { v -> onUpdateSync { it.copy(improveSearchSuggestions = v) } } + ) + } + item { + BansifyServiceSwitchCard( + index = 2, + totalCount = 3, + title = "Help improve Bansify's features", + subtitle = "Share anonymous diagnostic info once real Bansify backend is connected", + checked = accountState.usageReportsEnabled, + onCheckedChange = { v -> onUpdateSync { it.copy(usageReportsEnabled = v) } } + ) + } + } + } +} + +@Composable +private fun BansifyServiceSwitchCard( + index: Int, + totalCount: Int, + title: String, + subtitle: String, + checked: Boolean, + onCheckedChange: (Boolean) -> Unit +) { + ExpressiveGroupedCard(index = index, totalCount = totalCount) { + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { onCheckedChange(!checked) } + .padding(horizontal = 20.dp, vertical = 15.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Column(modifier = Modifier.weight(1f)) { + Text( + text = title, + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurface + ) + Spacer(modifier = Modifier.height(2.dp)) + Text( + text = subtitle, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + Spacer(modifier = Modifier.width(12.dp)) + Switch(checked = checked, onCheckedChange = onCheckedChange) + } + } +} + +@Composable +private fun EditBansifyProfileDialog( + accountState: BansifyAccountState, + onDismiss: () -> Unit, + onSave: (displayName: String, email: String, avatarColorHex: Long) -> Unit +) { + var name by remember(accountState) { mutableStateOf(accountState.displayName) } + var email by remember(accountState) { mutableStateOf(accountState.email) } + var colorHex by remember(accountState) { mutableLongStateOf(accountState.avatarColorHex) } + + AlertDialog( + onDismissRequest = onDismiss, + title = { Text("Edit Bansify profile") }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { + OutlinedTextField( + value = name, + onValueChange = { name = it }, + label = { Text("Name") }, + singleLine = true, + modifier = Modifier.fillMaxWidth() + ) + OutlinedTextField( + value = email, + onValueChange = { email = it }, + label = { Text("Bansify email") }, + singleLine = true, + modifier = Modifier.fillMaxWidth() + ) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(10.dp) + ) { + BansifyAvatarColors.forEach { hex -> + Box( + modifier = Modifier + .size(28.dp) + .clip(CircleShape) + .background(Color(hex)) + .then( + if (colorHex == hex) { + Modifier.border(2.dp, MaterialTheme.colorScheme.onSurface, CircleShape) + } else { + Modifier + } + ) + .clickable { colorHex = hex } + ) + } + } + } + }, + confirmButton = { + TextButton(onClick = { onSave(name, email, colorHex) }) { + Text("Save") + } + }, + dismissButton = { + TextButton(onClick = onDismiss) { + Text("Cancel") + } + } + ) +} diff --git a/app/src/main/java/com/bansify/browser/ui/screens/BookmarksScreen.kt b/app/src/main/java/com/bansify/browser/ui/screens/BookmarksScreen.kt new file mode 100644 index 00000000..2ba91373 --- /dev/null +++ b/app/src/main/java/com/bansify/browser/ui/screens/BookmarksScreen.kt @@ -0,0 +1,312 @@ +package com.bansify.browser.ui.screens + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +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.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyRow +import androidx.compose.foundation.lazy.items +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.MoreVert +import androidx.compose.material.icons.filled.Search +import androidx.compose.material.icons.outlined.BookmarkBorder +import androidx.compose.material.icons.outlined.CloudDone +import androidx.compose.material.icons.outlined.CloudOff +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.FilterChip +import androidx.compose.material3.FloatingActionButton +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +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.style.TextOverflow +import androidx.compose.ui.unit.dp +import com.bansify.browser.R +import com.bansify.browser.data.BansifyAccountState +import com.bansify.browser.data.BookmarkEntity +import com.bansify.browser.ui.components.SiteAvatar +import com.bansify.browser.ui.theme.LocalIsDarkBrowserTheme +import com.bansify.browser.ui.theme.SecureGreen +import com.bansify.browser.ui.theme.SecureGreenDark + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun BookmarksScreen( + bookmarks: List, + accountState: BansifyAccountState, + onClose: () -> Unit, + onOpenUrl: (String) -> Unit, + onOpenInNewTab: (String, Boolean) -> Unit, + onAddBookmark: () -> Unit, + onEditBookmark: (BookmarkEntity) -> Unit, + onDeleteBookmark: (Long) -> Unit, + onCopyUrl: (String) -> Unit, + onOpenSyncSettings: () -> Unit +) { + BackHandler { onClose() } + + var searchActive by remember { mutableStateOf(false) } + var searchQuery by remember { mutableStateOf("") } + var selectedFolder by remember { mutableStateOf("All") } + val folders = listOf("All", "Mobile bookmarks", "Favorites", "Reading list") + + val filtered = remember(bookmarks, searchQuery, selectedFolder) { + bookmarks.filter { bm -> + val matchesFolder = selectedFolder == "All" || bm.folder == selectedFolder + val matchesQuery = searchQuery.isBlank() || + bm.title.contains(searchQuery, ignoreCase = true) || + bm.url.contains(searchQuery, ignoreCase = true) + matchesFolder && matchesQuery + } + } + + Scaffold( + topBar = { + TopAppBar( + title = { + if (searchActive) { + OutlinedTextField( + value = searchQuery, + onValueChange = { searchQuery = it }, + placeholder = { Text("Search bookmarks") }, + singleLine = true, + modifier = Modifier.fillMaxWidth() + ) + } else { + Text(stringResource(R.string.bookmarks)) + } + }, + actions = { + IconButton(onClick = { + searchActive = !searchActive + if (!searchActive) searchQuery = "" + }) { + Icon( + imageVector = if (searchActive) Icons.Default.Close else Icons.Default.Search, + contentDescription = stringResource(R.string.cd_search) + ) + } + IconButton(onClick = onClose) { + Icon( + imageVector = Icons.Default.Close, + contentDescription = stringResource(R.string.cd_close) + ) + } + }, + colors = TopAppBarDefaults.topAppBarColors( + containerColor = MaterialTheme.colorScheme.surface + ) + ) + }, + floatingActionButton = { + FloatingActionButton( + onClick = onAddBookmark, + containerColor = MaterialTheme.colorScheme.primaryContainer, + contentColor = MaterialTheme.colorScheme.onPrimaryContainer + ) { + Icon(Icons.Default.Add, contentDescription = "Add bookmark") + } + } + ) { innerPadding -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(innerPadding) + ) { + // Subtle Bansify Account Bookmarks Sync strip + val syncActive = accountState.effectiveBookmarksSync + val greenColor = if (LocalIsDarkBrowserTheme.current) SecureGreenDark else SecureGreen + Surface( + color = MaterialTheme.colorScheme.surfaceContainerLow, + modifier = Modifier + .fillMaxWidth() + .clickable(onClick = onOpenSyncSettings) + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = if (syncActive) Icons.Outlined.CloudDone else Icons.Outlined.CloudOff, + contentDescription = null, + tint = if (syncActive) greenColor else MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(18.dp) + ) + Spacer(modifier = Modifier.width(10.dp)) + Text( + text = when { + !accountState.isSignedIn -> "Sign in to Bansify to sync bookmarks" + syncActive -> "Synced with ${accountState.email}" + else -> "Bookmarks sync is off • Tap to manage" + }, + style = MaterialTheme.typography.labelMedium, + color = if (syncActive) greenColor else MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + } + + LazyRow( + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp) + ) { + items(folders) { folder -> + FilterChip( + selected = selectedFolder == folder, + onClick = { selectedFolder = folder }, + label = { Text(folder) } + ) + } + } + + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) + + if (filtered.isEmpty()) { + Box( + modifier = Modifier + .fillMaxSize() + .padding(32.dp), + contentAlignment = Alignment.Center + ) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Icon( + imageVector = Icons.Outlined.BookmarkBorder, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(48.dp) + ) + Spacer(modifier = Modifier.height(12.dp)) + Text( + text = if (searchQuery.isNotBlank()) "No matching bookmarks" else "No bookmarks yet", + style = MaterialTheme.typography.titleMedium, + color = MaterialTheme.colorScheme.onSurface + ) + Spacer(modifier = Modifier.height(4.dp)) + Text( + text = "Tap the star icon in the 3-dot menu to save pages here.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } else { + LazyColumn(modifier = Modifier.fillMaxSize()) { + items(filtered, key = { it.id }) { bm -> + var itemMenuExpanded by remember { mutableStateOf(false) } + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { onOpenUrl(bm.url) } + .padding(start = 16.dp, end = 4.dp, top = 10.dp, bottom = 10.dp), + verticalAlignment = Alignment.CenterVertically + ) { + SiteAvatar(title = bm.title, url = bm.url, size = 38.dp) + Spacer(modifier = Modifier.width(14.dp)) + Column(modifier = Modifier.weight(1f)) { + Text( + text = bm.title, + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + Text( + text = bm.url, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + Box { + IconButton(onClick = { itemMenuExpanded = true }) { + Icon( + imageVector = Icons.Default.MoreVert, + contentDescription = "Bookmark options", + tint = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + DropdownMenu( + expanded = itemMenuExpanded, + onDismissRequest = { itemMenuExpanded = false } + ) { + DropdownMenuItem( + text = { Text("Open in new tab") }, + onClick = { + itemMenuExpanded = false + onOpenInNewTab(bm.url, false) + } + ) + DropdownMenuItem( + text = { Text("Open in Incognito tab") }, + onClick = { + itemMenuExpanded = false + onOpenInNewTab(bm.url, true) + } + ) + DropdownMenuItem( + text = { Text("Edit") }, + onClick = { + itemMenuExpanded = false + onEditBookmark(bm) + } + ) + DropdownMenuItem( + text = { Text("Copy link") }, + onClick = { + itemMenuExpanded = false + onCopyUrl(bm.url) + } + ) + DropdownMenuItem( + text = { Text("Delete", color = MaterialTheme.colorScheme.error) }, + onClick = { + itemMenuExpanded = false + onDeleteBookmark(bm.id) + } + ) + } + } + } + HorizontalDivider( + modifier = Modifier.padding(start = 68.dp), + color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f) + ) + } + } + } + } + } +} diff --git a/app/src/main/java/com/bansify/browser/ui/screens/DeleteBrowsingDataScreen.kt b/app/src/main/java/com/bansify/browser/ui/screens/DeleteBrowsingDataScreen.kt new file mode 100644 index 00000000..d3c7e9a8 --- /dev/null +++ b/app/src/main/java/com/bansify/browser/ui/screens/DeleteBrowsingDataScreen.kt @@ -0,0 +1,270 @@ +package com.bansify.browser.ui.screens + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +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.height +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.ArrowDropDown +import androidx.compose.material3.Button +import androidx.compose.material3.Checkbox +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Surface +import androidx.compose.material3.Tab +import androidx.compose.material3.TabRow +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import com.bansify.browser.R +import com.bansify.browser.data.TimeRange + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun DeleteBrowsingDataScreen( + historyCount: Int, + openNormalTabCount: Int, + onBack: () -> Unit, + onConfirmClear: ( + timeRange: TimeRange, + clearHistory: Boolean, + clearCookies: Boolean, + clearCache: Boolean, + clearSiteData: Boolean, + closeOpenTabs: Boolean + ) -> Unit +) { + BackHandler { onBack() } + + var selectedTab by remember { mutableIntStateOf(0) } // 0 = Basic, 1 = Advanced + var timeRange by remember { mutableStateOf(TimeRange.LAST_24_HOURS) } + var timeMenuExpanded by remember { mutableStateOf(false) } + + var clearHistory by remember { mutableStateOf(true) } + var clearCookies by remember { mutableStateOf(true) } + var clearCache by remember { mutableStateOf(true) } + var clearSiteData by remember { mutableStateOf(false) } + var closeOpenTabs by remember { mutableStateOf(false) } + + Scaffold( + topBar = { + TopAppBar( + title = { Text(stringResource(R.string.delete_browsing_data)) }, + navigationIcon = { + IconButton(onClick = onBack) { + Icon( + imageVector = Icons.AutoMirrored.Filled.ArrowBack, + contentDescription = stringResource(R.string.cd_back) + ) + } + }, + colors = TopAppBarDefaults.topAppBarColors( + containerColor = MaterialTheme.colorScheme.surface + ) + ) + }, + bottomBar = { + Surface( + tonalElevation = 2.dp, + color = MaterialTheme.colorScheme.surface, + modifier = Modifier.fillMaxWidth() + ) { + Box( + modifier = Modifier + .fillMaxWidth() + .navigationBarsPadding() + .padding(horizontal = 20.dp, vertical = 12.dp), + contentAlignment = Alignment.CenterEnd + ) { + Button( + onClick = { + onConfirmClear( + timeRange, + clearHistory, + clearCookies, + clearCache, + clearSiteData, + closeOpenTabs + ) + }, + enabled = clearHistory || clearCookies || clearCache || clearSiteData || closeOpenTabs, + shape = RoundedCornerShape(24.dp), + modifier = Modifier.testTag("confirm_delete_browsing_data") + ) { + Text("Delete data") + } + } + } + } + ) { innerPadding -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(innerPadding) + ) { + TabRow(selectedTabIndex = selectedTab) { + Tab( + selected = selectedTab == 0, + onClick = { selectedTab = 0 }, + text = { Text("Basic") } + ) + Tab( + selected = selectedTab == 1, + onClick = { selectedTab = 1 }, + text = { Text("Advanced") } + ) + } + + LazyColumn(modifier = Modifier.fillMaxSize()) { + item { + // Time Range Picker Row (Exact Chrome Layout) + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { timeMenuExpanded = true } + .padding(horizontal = 20.dp, vertical = 16.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = "Time range", + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.weight(1f) + ) + Box { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + text = timeRange.label, + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.primary + ) + Icon( + imageVector = Icons.Default.ArrowDropDown, + contentDescription = "Select time range", + tint = MaterialTheme.colorScheme.primary + ) + } + DropdownMenu( + expanded = timeMenuExpanded, + onDismissRequest = { timeMenuExpanded = false } + ) { + TimeRange.entries.forEach { range -> + DropdownMenuItem( + text = { Text(range.label) }, + onClick = { + timeRange = range + timeMenuExpanded = false + } + ) + } + } + } + } + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) + } + + item { + ClearDataCheckRow( + title = "Browsing history", + summary = if (historyCount == 0) "No items" else "$historyCount visited items", + checked = clearHistory, + onCheckedChange = { clearHistory = it } + ) + ClearDataCheckRow( + title = "Cookies and site data", + summary = "Signs you out of most sites", + checked = clearCookies, + onCheckedChange = { clearCookies = it } + ) + ClearDataCheckRow( + title = "Cached images and files", + summary = "Frees up local WebView storage. Some sites may load more slowly on your next visit.", + checked = clearCache, + onCheckedChange = { clearCache = it } + ) + } + + if (selectedTab == 1) { + item { + ClearDataCheckRow( + title = "Web storage & local databases", + summary = "Clears HTML5 localStorage, IndexedDB, and WebSQL data", + checked = clearSiteData, + onCheckedChange = { clearSiteData = it } + ) + ClearDataCheckRow( + title = "Open tabs", + summary = "$openNormalTabCount open normal tab(s) will be closed", + checked = closeOpenTabs, + onCheckedChange = { closeOpenTabs = it } + ) + } + } + + item { Spacer(modifier = Modifier.height(24.dp)) } + } + } + } +} + +@Composable +private fun ClearDataCheckRow( + title: String, + summary: String, + checked: Boolean, + onCheckedChange: (Boolean) -> Unit +) { + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { onCheckedChange(!checked) } + .padding(horizontal = 16.dp, vertical = 14.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Checkbox( + checked = checked, + onCheckedChange = onCheckedChange + ) + Spacer(modifier = Modifier.width(10.dp)) + Column(modifier = Modifier.weight(1f)) { + Text( + text = title, + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurface + ) + Text( + text = summary, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } +} diff --git a/app/src/main/java/com/bansify/browser/ui/screens/DownloadsScreen.kt b/app/src/main/java/com/bansify/browser/ui/screens/DownloadsScreen.kt new file mode 100644 index 00000000..0420a2f3 --- /dev/null +++ b/app/src/main/java/com/bansify/browser/ui/screens/DownloadsScreen.kt @@ -0,0 +1,273 @@ +package com.bansify.browser.ui.screens + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +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.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyRow +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.MoreVert +import androidx.compose.material.icons.filled.Search +import androidx.compose.material.icons.outlined.Description +import androidx.compose.material.icons.outlined.DownloadForOffline +import androidx.compose.material.icons.outlined.Image +import androidx.compose.material.icons.outlined.InsertDriveFile +import androidx.compose.material.icons.outlined.Language +import androidx.compose.material.icons.outlined.Settings +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.FilterChip +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import com.bansify.browser.R +import com.bansify.browser.browser.UrlUtils +import com.bansify.browser.data.DownloadEntity + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun DownloadsScreen( + downloads: List, + onClose: () -> Unit, + onOpenDownloadUrl: (String) -> Unit, + onShareDownload: (DownloadEntity) -> Unit, + onDeleteDownload: (Long) -> Unit, + onOpenDownloadsSettings: () -> Unit +) { + BackHandler { onClose() } + + var searchActive by remember { mutableStateOf(false) } + var searchQuery by remember { mutableStateOf("") } + var selectedCategory by remember { mutableStateOf("All") } + val categories = listOf("All", "Pages", "Images", "Documents", "Other") + + val filtered = remember(downloads, searchQuery, selectedCategory) { + downloads.filter { dl -> + val matchesCat = selectedCategory == "All" || dl.category == selectedCategory + val matchesQuery = searchQuery.isBlank() || + dl.fileName.contains(searchQuery, ignoreCase = true) || + dl.url.contains(searchQuery, ignoreCase = true) + matchesCat && matchesQuery + } + } + + Scaffold( + topBar = { + TopAppBar( + title = { + if (searchActive) { + OutlinedTextField( + value = searchQuery, + onValueChange = { searchQuery = it }, + placeholder = { Text("Search downloads") }, + singleLine = true, + modifier = Modifier.fillMaxWidth() + ) + } else { + Text(stringResource(R.string.downloads)) + } + }, + actions = { + IconButton(onClick = { + searchActive = !searchActive + if (!searchActive) searchQuery = "" + }) { + Icon( + imageVector = if (searchActive) Icons.Default.Close else Icons.Default.Search, + contentDescription = stringResource(R.string.cd_search) + ) + } + IconButton(onClick = onOpenDownloadsSettings) { + Icon( + imageVector = Icons.Outlined.Settings, + contentDescription = "Download settings" + ) + } + IconButton(onClick = onClose) { + Icon( + imageVector = Icons.Default.Close, + contentDescription = stringResource(R.string.cd_close) + ) + } + }, + colors = TopAppBarDefaults.topAppBarColors( + containerColor = MaterialTheme.colorScheme.surface + ) + ) + } + ) { innerPadding -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(innerPadding) + ) { + LazyRow( + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp) + ) { + items(categories) { category -> + FilterChip( + selected = selectedCategory == category, + onClick = { selectedCategory = category }, + label = { Text(category) } + ) + } + } + + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) + + if (filtered.isEmpty()) { + Box( + modifier = Modifier + .fillMaxSize() + .padding(32.dp), + contentAlignment = Alignment.Center + ) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Icon( + imageVector = Icons.Outlined.DownloadForOffline, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(48.dp) + ) + Spacer(modifier = Modifier.height(12.dp)) + Text( + text = "No downloads yet", + style = MaterialTheme.typography.titleMedium, + color = MaterialTheme.colorScheme.onSurface + ) + Spacer(modifier = Modifier.height(4.dp)) + Text( + text = "Files and saved web pages you download appear here.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } else { + LazyColumn(modifier = Modifier.fillMaxSize()) { + items(filtered, key = { it.id }) { item -> + var itemMenu by remember { mutableStateOf(false) } + val icon = when (item.category) { + "Pages" -> Icons.Outlined.Language + "Images" -> Icons.Outlined.Image + "Documents" -> Icons.Outlined.Description + else -> Icons.Outlined.InsertDriveFile + } + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { onOpenDownloadUrl(item.url) } + .padding(start = 16.dp, end = 6.dp, top = 12.dp, bottom = 12.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Box( + modifier = Modifier + .size(42.dp) + .clip(RoundedCornerShape(10.dp)) + .background(MaterialTheme.colorScheme.surfaceContainerHigh), + contentAlignment = Alignment.Center + ) { + Icon( + imageVector = icon, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(22.dp) + ) + } + Spacer(modifier = Modifier.width(14.dp)) + Column(modifier = Modifier.weight(1f)) { + Text( + text = item.fileName, + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + Text( + text = "${UrlUtils.formatFileSize(item.sizeBytes)} • ${UrlUtils.extractShortDomain(item.url)} • ${UrlUtils.formatShortDate(item.downloadedAt)}", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + Box { + IconButton(onClick = { itemMenu = true }) { + Icon( + imageVector = Icons.Default.MoreVert, + contentDescription = "Download options", + tint = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + DropdownMenu( + expanded = itemMenu, + onDismissRequest = { itemMenu = false } + ) { + DropdownMenuItem( + text = { Text("Open source page") }, + onClick = { + itemMenu = false + onOpenDownloadUrl(item.url) + } + ) + DropdownMenuItem( + text = { Text("Share") }, + onClick = { + itemMenu = false + onShareDownload(item) + } + ) + DropdownMenuItem( + text = { Text("Delete", color = MaterialTheme.colorScheme.error) }, + onClick = { + itemMenu = false + onDeleteDownload(item.id) + } + ) + } + } + } + HorizontalDivider( + modifier = Modifier.padding(start = 72.dp), + color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f) + ) + } + } + } + } + } +} diff --git a/app/src/main/java/com/bansify/browser/ui/screens/HistoryScreen.kt b/app/src/main/java/com/bansify/browser/ui/screens/HistoryScreen.kt new file mode 100644 index 00000000..3c894d48 --- /dev/null +++ b/app/src/main/java/com/bansify/browser/ui/screens/HistoryScreen.kt @@ -0,0 +1,228 @@ +package com.bansify.browser.ui.screens + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +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.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Search +import androidx.compose.material.icons.outlined.DeleteOutline +import androidx.compose.material.icons.outlined.History +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import com.bansify.browser.R +import com.bansify.browser.browser.UrlUtils +import com.bansify.browser.data.HistoryEntity +import com.bansify.browser.ui.components.SiteAvatar + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun HistoryScreen( + history: List, + onClose: () -> Unit, + onOpenUrl: (String) -> Unit, + onDeleteItem: (Long) -> Unit, + onOpenDeleteBrowsingData: () -> Unit +) { + BackHandler { onClose() } + + var searchActive by remember { mutableStateOf(false) } + var searchQuery by remember { mutableStateOf("") } + + val grouped = remember(history, searchQuery) { + val filtered = if (searchQuery.isBlank()) { + history + } else { + history.filter { + it.title.contains(searchQuery, ignoreCase = true) || + it.url.contains(searchQuery, ignoreCase = true) + } + } + filtered.groupBy { UrlUtils.formatHistorySectionHeader(it.visitedAt) } + } + + Scaffold( + topBar = { + TopAppBar( + title = { + if (searchActive) { + OutlinedTextField( + value = searchQuery, + onValueChange = { searchQuery = it }, + placeholder = { Text("Search history") }, + singleLine = true, + modifier = Modifier.fillMaxWidth() + ) + } else { + Text(stringResource(R.string.history)) + } + }, + actions = { + IconButton(onClick = { + searchActive = !searchActive + if (!searchActive) searchQuery = "" + }) { + Icon( + imageVector = if (searchActive) Icons.Default.Close else Icons.Default.Search, + contentDescription = stringResource(R.string.cd_search) + ) + } + IconButton(onClick = onClose) { + Icon( + imageVector = Icons.Default.Close, + contentDescription = stringResource(R.string.cd_close) + ) + } + }, + colors = TopAppBarDefaults.topAppBarColors( + containerColor = MaterialTheme.colorScheme.surface + ) + ) + } + ) { innerPadding -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(innerPadding) + ) { + // Iconic Chrome "Delete browsing data..." banner at top of History! + Row( + modifier = Modifier + .fillMaxWidth() + .clickable(onClick = onOpenDeleteBrowsingData) + .testTag("history_delete_browsing_data_link") + .padding(horizontal = 20.dp, vertical = 14.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.Outlined.DeleteOutline, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(20.dp) + ) + Spacer(modifier = Modifier.width(12.dp)) + Text( + text = "Delete browsing data…", + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.primary + ) + } + + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) + + if (grouped.isEmpty()) { + Box( + modifier = Modifier + .fillMaxSize() + .padding(32.dp), + contentAlignment = Alignment.Center + ) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Icon( + imageVector = Icons.Outlined.History, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(48.dp) + ) + Spacer(modifier = Modifier.height(12.dp)) + Text( + text = if (searchQuery.isNotBlank()) "No matching history" else "You'll find your history here", + style = MaterialTheme.typography.titleMedium, + color = MaterialTheme.colorScheme.onSurface + ) + Spacer(modifier = Modifier.height(4.dp)) + Text( + text = "Sites you visit in normal tabs appear here.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } else { + LazyColumn(modifier = Modifier.fillMaxSize()) { + grouped.forEach { (dateHeader, entries) -> + item(key = "header_$dateHeader") { + Text( + text = dateHeader, + style = MaterialTheme.typography.labelLarge, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 12.dp) + ) + } + + items(entries, key = { it.id }) { entry -> + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { onOpenUrl(entry.url) } + .padding(start = 16.dp, end = 6.dp, top = 10.dp, bottom = 10.dp), + verticalAlignment = Alignment.CenterVertically + ) { + SiteAvatar(title = entry.title, url = entry.url, size = 36.dp) + Spacer(modifier = Modifier.width(14.dp)) + Column(modifier = Modifier.weight(1f)) { + Text( + text = entry.title, + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + Text( + text = "${UrlUtils.extractShortDomain(entry.url)} • ${UrlUtils.formatShortTime(entry.visitedAt)}", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + IconButton(onClick = { onDeleteItem(entry.id) }) { + Icon( + imageVector = Icons.Default.Close, + contentDescription = "Remove from history", + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(18.dp) + ) + } + } + } + } + } + } + } + } +} diff --git a/app/src/main/java/com/bansify/browser/ui/screens/NewTabScreen.kt b/app/src/main/java/com/bansify/browser/ui/screens/NewTabScreen.kt new file mode 100644 index 00000000..a9b0bc3b --- /dev/null +++ b/app/src/main/java/com/bansify/browser/ui/screens/NewTabScreen.kt @@ -0,0 +1,809 @@ +package com.bansify.browser.ui.screens + +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.combinedClickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +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.height +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyRow +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.outlined.Bookmarks +import androidx.compose.material.icons.outlined.History +import androidx.compose.material.icons.outlined.Mic +import androidx.compose.material.icons.outlined.Public +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.text.withStyle +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.bansify.browser.R +import com.bansify.browser.browser.UrlUtils +import com.bansify.browser.data.BookmarkEntity +import com.bansify.browser.data.BrowserSettings +import com.bansify.browser.data.HistoryEntity +import com.bansify.browser.data.ShortcutEntity +import com.bansify.browser.data.ThirdPartyCookiePolicy +import com.bansify.browser.ui.components.IncognitoIcon +import com.bansify.browser.ui.components.ShortcutDialog +import com.bansify.browser.ui.components.SiteAvatar +import com.bansify.browser.ui.theme.BrandBlue +import com.bansify.browser.ui.theme.BrandGreen +import com.bansify.browser.ui.theme.BrandRed +import com.bansify.browser.ui.theme.BrandYellow +import com.bansify.browser.ui.theme.LocalIsDarkBrowserTheme +import com.bansify.browser.ui.theme.PlusJakartaSansFontFamily + +@Composable +fun NewTabScreen( + isIncognito: Boolean, + settings: BrowserSettings, + shortcuts: List, + recentBookmarks: List, + recentHistory: List, + onSearchClick: () -> Unit, + onVoiceSearchClick: () -> Unit, + onNewTabClick: () -> Unit, + onNewIncognitoTabClick: () -> Unit, + onOpenUrl: (String) -> Unit, + onAddShortcut: (title: String, url: String) -> Unit, + onUpdateShortcut: (ShortcutEntity) -> Unit, + onDeleteShortcut: (Long) -> Unit, + onToggleIncognitoBlockThirdParty: (Boolean) -> Unit, + onOpenBookmarks: () -> Unit, + onOpenHistory: () -> Unit +) { + if (isIncognito) { + IncognitoNewTabContent( + settings = settings, + onSearchClick = onSearchClick, + onToggleBlockThirdParty = onToggleIncognitoBlockThirdParty + ) + } else { + NormalNewTabContent( + settings = settings, + shortcuts = shortcuts, + recentBookmarks = recentBookmarks, + recentHistory = recentHistory, + onSearchClick = onSearchClick, + onVoiceSearchClick = onVoiceSearchClick, + onNewTabClick = onNewTabClick, + onNewIncognitoTabClick = onNewIncognitoTabClick, + onOpenUrl = onOpenUrl, + onAddShortcut = onAddShortcut, + onUpdateShortcut = onUpdateShortcut, + onDeleteShortcut = onDeleteShortcut, + onOpenBookmarks = onOpenBookmarks, + onOpenHistory = onOpenHistory + ) + } +} + +/** + * Pixel-accurate clone of modern Chrome Android's New Tab Page: + * - Centered geometric wordmark (crisp white in Dark mode, brand colors in Light mode) + * - 60.dp rounded pill search bar: [+] Search Google or type URL [Mic] + * - Side-by-side 2 rounded pill buttons directly below: [Bookmarks] & [Incognito] + * - Single 24.dp rounded Most Visited shortcuts card with horizontal scrollable circular icons + * - Rounded 24.dp Continue Browsing & Bookmarks cards + */ +@OptIn(ExperimentalFoundationApi::class) +@Composable +private fun NormalNewTabContent( + settings: BrowserSettings, + shortcuts: List, + recentBookmarks: List, + recentHistory: List, + onSearchClick: () -> Unit, + onVoiceSearchClick: () -> Unit, + onNewTabClick: () -> Unit, + onNewIncognitoTabClick: () -> Unit, + onOpenUrl: (String) -> Unit, + onAddShortcut: (title: String, url: String) -> Unit, + onUpdateShortcut: (ShortcutEntity) -> Unit, + onDeleteShortcut: (Long) -> Unit, + onOpenBookmarks: () -> Unit, + onOpenHistory: () -> Unit +) { + var showAddShortcutDialog by remember { mutableStateOf(false) } + var editingShortcut by remember { mutableStateOf(null) } + + Box( + modifier = Modifier + .fillMaxSize() + .background(MaterialTheme.colorScheme.background), + contentAlignment = Alignment.TopCenter + ) { + LazyColumn( + modifier = Modifier + .fillMaxSize() + .widthIn(max = 600.dp) + .navigationBarsPadding(), + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 12.dp), + horizontalAlignment = Alignment.CenterHorizontally + ) { + // Centered Geometric Wordmark + item { + Spacer(modifier = Modifier.height(22.dp)) + BansifyWordmark() + Spacer(modifier = Modifier.height(28.dp)) + } + + // Exact Chrome 60.dp Rounded Pill Search Bar ([+] Search Google or type URL [Mic]) + item { + Surface( + shape = RoundedCornerShape(30.dp), + color = MaterialTheme.colorScheme.surfaceContainerHigh, + modifier = Modifier + .fillMaxWidth() + .height(60.dp) + .clip(RoundedCornerShape(30.dp)) + .clickable(onClick = onSearchClick) + .testTag("ntp_search_bar") + ) { + Row( + modifier = Modifier + .fillMaxSize() + .padding(start = 8.dp, end = 8.dp), + verticalAlignment = Alignment.CenterVertically + ) { + IconButton( + onClick = onNewTabClick, + modifier = Modifier.size(44.dp) + ) { + Icon( + imageVector = Icons.Default.Add, + contentDescription = stringResource(R.string.new_tab), + tint = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.size(24.dp) + ) + } + + Text( + text = "Search ${settings.searchEngine.displayName} or type URL", + style = MaterialTheme.typography.titleMedium.copy( + fontSize = 17.sp, + fontWeight = FontWeight.Normal + ), + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier + .weight(1f) + .padding(horizontal = 4.dp) + ) + + IconButton( + onClick = onVoiceSearchClick, + modifier = Modifier + .size(44.dp) + .testTag("ntp_voice_search") + ) { + Icon( + imageVector = Icons.Outlined.Mic, + contentDescription = "Voice search", + tint = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.size(22.dp) + ) + } + } + } + Spacer(modifier = Modifier.height(12.dp)) + } + + // Two Equal-Width Side-by-Side Pill Buttons directly below search bar (exact Chrome layout!) + item { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(10.dp) + ) { + Surface( + shape = RoundedCornerShape(24.dp), + color = MaterialTheme.colorScheme.surfaceContainerHigh, + modifier = Modifier + .weight(1f) + .height(46.dp) + .clip(RoundedCornerShape(24.dp)) + .clickable(onClick = onOpenBookmarks) + .testTag("ntp_bookmarks_pill") + ) { + Row( + modifier = Modifier.fillMaxSize(), + horizontalArrangement = Arrangement.Center, + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.Outlined.Bookmarks, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.size(19.dp) + ) + Spacer(modifier = Modifier.width(8.dp)) + Text( + text = "Bookmarks", + style = MaterialTheme.typography.labelLarge.copy( + fontSize = 14.5.sp, + fontWeight = FontWeight.Medium + ), + color = MaterialTheme.colorScheme.onSurface + ) + } + } + + Surface( + shape = RoundedCornerShape(24.dp), + color = MaterialTheme.colorScheme.surfaceContainerHigh, + modifier = Modifier + .weight(1f) + .height(46.dp) + .clip(RoundedCornerShape(24.dp)) + .clickable(onClick = onNewIncognitoTabClick) + .testTag("ntp_incognito_pill") + ) { + Row( + modifier = Modifier.fillMaxSize(), + horizontalArrangement = Arrangement.Center, + verticalAlignment = Alignment.CenterVertically + ) { + IncognitoIcon( + size = 20.dp, + tint = MaterialTheme.colorScheme.onSurface + ) + Spacer(modifier = Modifier.width(8.dp)) + Text( + text = "Incognito", + style = MaterialTheme.typography.labelLarge.copy( + fontSize = 14.5.sp, + fontWeight = FontWeight.Medium + ), + color = MaterialTheme.colorScheme.onSurface + ) + } + } + } + Spacer(modifier = Modifier.height(16.dp)) + } + + // Single 24.dp Rounded Most Visited Shortcuts Card with Horizontal Row (matches Screenshot 4!) + item { + Card( + shape = RoundedCornerShape(24.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceContainerLow + ), + modifier = Modifier.fillMaxWidth() + ) { + LazyRow( + contentPadding = PaddingValues(horizontal = 14.dp, vertical = 18.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), + modifier = Modifier.fillMaxWidth() + ) { + items(shortcuts, key = { it.id }) { shortcut -> + Column( + modifier = Modifier + .width(68.dp) + .clip(RoundedCornerShape(14.dp)) + .combinedClickable( + onClick = { onOpenUrl(shortcut.url) }, + onLongClick = { editingShortcut = shortcut } + ) + .padding(vertical = 4.dp), + horizontalAlignment = Alignment.CenterHorizontally + ) { + Box( + modifier = Modifier + .size(50.dp) + .clip(CircleShape) + .background(MaterialTheme.colorScheme.surfaceContainer), + contentAlignment = Alignment.Center + ) { + SiteAvatar( + title = shortcut.title, + url = shortcut.url, + accentColor = shortcut.accentColor, + size = 34.dp + ) + } + Spacer(modifier = Modifier.height(8.dp)) + Text( + text = shortcut.title, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + textAlign = TextAlign.Center + ) + } + } + + // "+ Add" Shortcut Tile at end of row + item(key = "add_shortcut_tile") { + Column( + modifier = Modifier + .width(68.dp) + .clip(RoundedCornerShape(14.dp)) + .clickable { showAddShortcutDialog = true } + .testTag("ntp_add_shortcut") + .padding(vertical = 4.dp), + horizontalAlignment = Alignment.CenterHorizontally + ) { + Box( + modifier = Modifier + .size(50.dp) + .clip(CircleShape) + .background(MaterialTheme.colorScheme.surfaceContainer), + contentAlignment = Alignment.Center + ) { + Icon( + imageVector = Icons.Default.Add, + contentDescription = "Add shortcut", + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(22.dp) + ) + } + Spacer(modifier = Modifier.height(8.dp)) + Text( + text = "Add", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + textAlign = TextAlign.Center + ) + } + } + } + } + } + + // Recent Bookmarks & Continue Browsing Rounded Cards + if (settings.showRecentCardsOnNtp && (recentBookmarks.isNotEmpty() || recentHistory.isNotEmpty())) { + item { Spacer(modifier = Modifier.height(16.dp)) } + + if (recentHistory.isNotEmpty()) { + item { + NtpRoundedModuleCard( + title = "Continue browsing", + icon = Icons.Outlined.History, + actionText = "History", + onActionClick = onOpenHistory + ) { + val distinctRecent = remember(recentHistory) { + recentHistory.distinctBy { it.url }.take(5) + } + Column(modifier = Modifier.fillMaxWidth()) { + distinctRecent.forEachIndexed { idx, entry -> + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { onOpenUrl(entry.url) } + .padding(horizontal = 18.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically + ) { + SiteAvatar( + title = entry.title, + url = entry.url, + size = 34.dp + ) + Spacer(modifier = Modifier.width(14.dp)) + Column(modifier = Modifier.weight(1f)) { + Text( + text = entry.title, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + Text( + text = UrlUtils.extractShortDomain(entry.url), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + } + if (idx < distinctRecent.lastIndex) { + HorizontalDivider( + modifier = Modifier.padding(start = 66.dp, end = 16.dp), + thickness = 0.5.dp, + color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.45f) + ) + } + } + } + } + Spacer(modifier = Modifier.height(14.dp)) + } + } + + if (recentBookmarks.isNotEmpty()) { + item { + NtpRoundedModuleCard( + title = "Saved bookmarks", + icon = Icons.Outlined.Bookmarks, + actionText = "See all", + onActionClick = onOpenBookmarks + ) { + LazyRow( + horizontalArrangement = Arrangement.spacedBy(10.dp), + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 12.dp) + ) { + items(recentBookmarks.take(8), key = { it.id }) { bm -> + Surface( + shape = RoundedCornerShape(16.dp), + color = MaterialTheme.colorScheme.surfaceContainer, + modifier = Modifier + .width(160.dp) + .clip(RoundedCornerShape(16.dp)) + .clickable { onOpenUrl(bm.url) } + ) { + Row( + modifier = Modifier.padding(11.dp), + verticalAlignment = Alignment.CenterVertically + ) { + SiteAvatar( + title = bm.title, + url = bm.url, + size = 30.dp + ) + Spacer(modifier = Modifier.width(10.dp)) + Column(modifier = Modifier.weight(1f)) { + Text( + text = bm.title, + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + Text( + text = UrlUtils.extractShortDomain(bm.url), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + } + } + } + } + } + } + } + } + + item { Spacer(modifier = Modifier.height(32.dp)) } + } + } + + if (showAddShortcutDialog) { + ShortcutDialog( + onDismiss = { showAddShortcutDialog = false }, + onSave = { title, url -> + onAddShortcut(title, url) + showAddShortcutDialog = false + } + ) + } + + editingShortcut?.let { shortcut -> + ShortcutDialog( + initial = shortcut, + onDismiss = { editingShortcut = null }, + onSave = { title, url -> + val normalized = if (url.startsWith("http://") || url.startsWith("https://")) url else "https://$url" + onUpdateShortcut(shortcut.copy(title = title.ifBlank { shortcut.title }, url = normalized)) + editingShortcut = null + }, + onDelete = { + onDeleteShortcut(shortcut.id) + } + ) + } +} + +@Composable +private fun BansifyWordmark() { + val isDark = LocalIsDarkBrowserTheme.current + if (isDark) { + // Matches Screenshot 4's crisp pure-white geometric wordmark in Chrome Dark mode! + Text( + text = "Bansify", + fontFamily = PlusJakartaSansFontFamily, + fontWeight = FontWeight.Bold, + fontSize = 44.sp, + letterSpacing = (-1.2).sp, + color = MaterialTheme.colorScheme.onBackground, + textAlign = TextAlign.Center + ) + } else { + val wordmark = buildAnnotatedString { + withStyle(SpanStyle(color = BrandBlue)) { append("B") } + withStyle(SpanStyle(color = BrandRed)) { append("a") } + withStyle(SpanStyle(color = BrandYellow)) { append("n") } + withStyle(SpanStyle(color = BrandBlue)) { append("s") } + withStyle(SpanStyle(color = BrandGreen)) { append("i") } + withStyle(SpanStyle(color = BrandRed)) { append("f") } + withStyle(SpanStyle(color = BrandYellow)) { append("y") } + } + Text( + text = wordmark, + fontFamily = PlusJakartaSansFontFamily, + fontWeight = FontWeight.Bold, + fontSize = 44.sp, + letterSpacing = (-1.2).sp, + textAlign = TextAlign.Center + ) + } +} + +@Composable +private fun NtpRoundedModuleCard( + title: String, + icon: androidx.compose.ui.graphics.vector.ImageVector, + actionText: String, + onActionClick: () -> Unit, + content: @Composable () -> Unit +) { + Card( + shape = RoundedCornerShape(24.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceContainerLow + ), + modifier = Modifier.fillMaxWidth() + ) { + Column(modifier = Modifier.fillMaxWidth()) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(start = 18.dp, end = 12.dp, top = 14.dp, bottom = 4.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = icon, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(18.dp) + ) + Spacer(modifier = Modifier.width(8.dp)) + Text( + text = title, + style = MaterialTheme.typography.titleSmall, + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.weight(1f) + ) + Text( + text = actionText, + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.primary, + modifier = Modifier + .clip(RoundedCornerShape(10.dp)) + .clickable(onClick = onActionClick) + .padding(horizontal = 8.dp, vertical = 4.dp) + ) + } + content() + } + } +} + +@Composable +private fun IncognitoNewTabContent( + settings: BrowserSettings, + onSearchClick: () -> Unit, + onToggleBlockThirdParty: (Boolean) -> Unit +) { + val blockThirdParty = settings.thirdPartyCookiePolicy != ThirdPartyCookiePolicy.ALLOW + + Box( + modifier = Modifier + .fillMaxSize() + .background(MaterialTheme.colorScheme.background), + contentAlignment = Alignment.TopCenter + ) { + LazyColumn( + modifier = Modifier + .fillMaxSize() + .widthIn(max = 600.dp) + .navigationBarsPadding(), + contentPadding = PaddingValues(horizontal = 24.dp, vertical = 20.dp), + horizontalAlignment = Alignment.CenterHorizontally + ) { + item { + Surface( + shape = RoundedCornerShape(28.dp), + color = MaterialTheme.colorScheme.surfaceContainer, + modifier = Modifier + .fillMaxWidth() + .height(50.dp) + .clip(RoundedCornerShape(28.dp)) + .clickable(onClick = onSearchClick) + .testTag("incognito_search_bar") + ) { + Row( + modifier = Modifier + .fillMaxSize() + .padding(horizontal = 18.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.Outlined.Public, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(20.dp) + ) + Spacer(modifier = Modifier.width(12.dp)) + Text( + text = "Search ${settings.searchEngine.displayName} or type URL", + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + Spacer(modifier = Modifier.height(28.dp)) + } + + item { + Box( + modifier = Modifier + .size(72.dp) + .clip(CircleShape) + .background(MaterialTheme.colorScheme.surfaceContainerHigh), + contentAlignment = Alignment.Center + ) { + IncognitoIcon( + size = 42.dp, + tint = MaterialTheme.colorScheme.onSurface + ) + } + Spacer(modifier = Modifier.height(18.dp)) + Text( + text = stringResource(R.string.incognito_title), + style = MaterialTheme.typography.headlineSmall, + color = MaterialTheme.colorScheme.onSurface, + textAlign = TextAlign.Center + ) + Spacer(modifier = Modifier.height(12.dp)) + Text( + text = stringResource(R.string.incognito_subtitle), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Start, + modifier = Modifier.fillMaxWidth() + ) + Spacer(modifier = Modifier.height(20.dp)) + } + + item { + Column( + modifier = Modifier.fillMaxWidth(), + verticalArrangement = Arrangement.spacedBy(16.dp) + ) { + IncognitoInfoBlock( + heading = "Bansify won't save:", + bullets = listOf( + "Your browsing history", + "Cookies and site data", + "Information entered in forms" + ) + ) + IncognitoInfoBlock( + heading = "Your activity might still be visible to:", + bullets = listOf( + "Websites you visit", + "Your employer or school", + "Your internet service provider" + ) + ) + } + Spacer(modifier = Modifier.height(22.dp)) + } + + item { + Card( + shape = RoundedCornerShape(20.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceContainerLow + ), + modifier = Modifier.fillMaxWidth() + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(18.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Column(modifier = Modifier.weight(1f)) { + Text( + text = "Block third-party cookies", + style = MaterialTheme.typography.titleSmall, + color = MaterialTheme.colorScheme.onSurface + ) + Spacer(modifier = Modifier.height(4.dp)) + Text( + text = "When on, sites can't use cookies that track you across the web. Features on some sites may break.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + Spacer(modifier = Modifier.width(12.dp)) + Switch( + checked = blockThirdParty, + onCheckedChange = onToggleBlockThirdParty, + modifier = Modifier.testTag("incognito_block_cookies_switch") + ) + } + } + } + } + } +} + +@Composable +private fun IncognitoInfoBlock(heading: String, bullets: List) { + Column(modifier = Modifier.fillMaxWidth()) { + Text( + text = heading, + style = MaterialTheme.typography.titleSmall, + color = MaterialTheme.colorScheme.onSurface + ) + Spacer(modifier = Modifier.height(6.dp)) + bullets.forEach { bullet -> + Row( + modifier = Modifier.padding(vertical = 2.dp, horizontal = 4.dp), + verticalAlignment = Alignment.Top + ) { + Text( + text = "•", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(end = 10.dp) + ) + Text( + text = bullet, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } +} diff --git a/app/src/main/java/com/bansify/browser/ui/screens/OmniboxOverlay.kt b/app/src/main/java/com/bansify/browser/ui/screens/OmniboxOverlay.kt new file mode 100644 index 00000000..ee465a2f --- /dev/null +++ b/app/src/main/java/com/bansify/browser/ui/screens/OmniboxOverlay.kt @@ -0,0 +1,645 @@ +package com.bansify.browser.ui.screens + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +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.height +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.statusBarsPadding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.NorthWest +import androidx.compose.material.icons.filled.Search +import androidx.compose.material.icons.outlined.ContentCopy +import androidx.compose.material.icons.outlined.Edit +import androidx.compose.material.icons.outlined.History +import androidx.compose.material.icons.outlined.Mic +import androidx.compose.material.icons.outlined.Share +import androidx.compose.material.icons.outlined.Tab +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.TextRange +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.input.TextFieldValue +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.text.withStyle +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.bansify.browser.R +import com.bansify.browser.browser.UrlUtils +import com.bansify.browser.data.BookmarkEntity +import com.bansify.browser.data.BrowserSettings +import com.bansify.browser.data.BrowserTab +import com.bansify.browser.data.HistoryEntity +import com.bansify.browser.data.ShortcutEntity +import com.bansify.browser.ui.components.ExpressiveGroupedCard +import com.bansify.browser.ui.components.SiteAvatar +import com.bansify.browser.ui.components.expressiveCanvasColor +import com.bansify.browser.ui.theme.ChromeLinkBlueDark +import com.bansify.browser.ui.theme.ChromeLinkBlueLight +import com.bansify.browser.ui.theme.LocalIsDarkBrowserTheme + +private sealed interface OmniboxItem { + val key: String + + data class RecentSearch(val query: String) : OmniboxItem { + override val key = "search_$query" + } + + data class SiteMatch( + val id: String, + val title: String, + val url: String, + val displayUrl: String, + val accentColor: Long? = null + ) : OmniboxItem { + override val key = "site_$id" + } + + data class OpenTabMatch(val tab: BrowserTab) : OmniboxItem { + override val key = "tab_${tab.id}" + } + + data class DirectSearch(val query: String, val isUrl: Boolean) : OmniboxItem { + override val key = "direct_$query" + } +} + +/** + * Pixel-accurate clone of modern Chrome Android Omnibox Overlay (Screenshots 5 & 6): + * - Top pill search bar with [+] / matching site favicon, inline highlighted autocomplete suffix, + * and [Mic] (when empty) or [X] (when typing) + * - Material 3 Expressive segmented card suggestion list (20dp outer / 4dp inner corners, 2dp gap) + * - Bolded query match highlights, Chrome-blue URLs, and NorthWest insert arrows + */ +@Composable +fun OmniboxOverlay( + activeTab: BrowserTab, + openTabs: List, + bookmarks: List, + history: List, + shortcuts: List, + recentSearches: List, + settings: BrowserSettings, + onDismiss: () -> Unit, + onSubmitUrl: (String) -> Unit, + onVoiceSearchClick: () -> Unit, + onNewTabClick: () -> Unit, + onSwitchToTab: (String) -> Unit, + onShareCurrentUrl: () -> Unit, + onCopyCurrentUrl: () -> Unit +) { + BackHandler { onDismiss() } + + val initialText = if (activeTab.isNewTab) "" else activeTab.url + var fieldValue by remember { + mutableStateOf( + TextFieldValue( + text = initialText, + selection = TextRange(0, initialText.length) + ) + ) + } + + val focusRequester = remember { FocusRequester() } + LaunchedEffect(Unit) { + focusRequester.requestFocus() + } + + val query = fieldValue.text.trim() + val isDark = LocalIsDarkBrowserTheme.current + val linkBlue = if (isDark) ChromeLinkBlueDark else ChromeLinkBlueLight + + // Build unified site candidates from shortcuts, bookmarks, and history for rich inline autocomplete + val allSiteCandidates = remember(shortcuts, bookmarks, history) { + buildList { + shortcuts.forEach { + add( + OmniboxItem.SiteMatch( + id = "sc_${it.id}", + title = it.title, + url = it.url, + displayUrl = it.url.removePrefix("https://").removePrefix("http://").removePrefix("www.").trimEnd('/'), + accentColor = it.accentColor + ) + ) + } + bookmarks.forEach { + add( + OmniboxItem.SiteMatch( + id = "bm_${it.id}", + title = it.title, + url = it.url, + displayUrl = it.url.removePrefix("https://").removePrefix("http://").removePrefix("www.").trimEnd('/') + ) + ) + } + history.distinctBy { it.url }.forEach { + add( + OmniboxItem.SiteMatch( + id = "hi_${it.id}", + title = it.title, + url = it.url, + displayUrl = it.url.removePrefix("https://").removePrefix("http://").removePrefix("www.").trimEnd('/') + ) + ) + } + }.distinctBy { it.displayUrl.lowercase() } + } + + // Inline Chrome-style domain autocomplete (e.g., typing "g" suggests "github.com" inline!) + val inlineAutocomplete = remember(query, allSiteCandidates) { + if (query.isBlank() || query.contains(' ') || query.startsWith("http")) { + null + } else { + allSiteCandidates.firstOrNull { + it.displayUrl.startsWith(query, ignoreCase = true) && it.displayUrl.length > query.length + } + } + } + + val suggestions = remember(query, openTabs, activeTab.id, recentSearches, allSiteCandidates, inlineAutocomplete) { + buildList { + if (query.isEmpty()) { + recentSearches.take(6).forEach { add(OmniboxItem.RecentSearch(it)) } + allSiteCandidates.take(6).forEach { add(it) } + } else { + inlineAutocomplete?.let { add(it) } + + openTabs.filter { + it.id != activeTab.id && !it.isNewTab && + (it.title.contains(query, ignoreCase = true) || it.url.contains(query, ignoreCase = true)) + }.take(2).forEach { add(OmniboxItem.OpenTabMatch(it)) } + + recentSearches.filter { it.contains(query, ignoreCase = true) } + .take(3) + .forEach { add(OmniboxItem.RecentSearch(it)) } + + allSiteCandidates.filter { + it.key != inlineAutocomplete?.key && + (it.title.contains(query, ignoreCase = true) || it.displayUrl.contains(query, ignoreCase = true)) + }.take(6).forEach { add(it) } + + val isLikelyUrl = query.contains('.') && !query.contains(' ') + add(OmniboxItem.DirectSearch(query = query, isUrl = isLikelyUrl)) + } + } + } + + Surface( + color = expressiveCanvasColor(), + modifier = Modifier + .fillMaxSize() + .statusBarsPadding() + .navigationBarsPadding() + .imePadding() + ) { + Column(modifier = Modifier.fillMaxSize()) { + // Top Rounded Pill Omnibox Bar (Matches Screenshots 5 & 6!) + Surface( + shape = RoundedCornerShape(26.dp), + color = MaterialTheme.colorScheme.surfaceContainerLow, + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 10.dp, vertical = 8.dp) + .height(50.dp) + ) { + Row( + modifier = Modifier + .fillMaxSize() + .padding(start = 6.dp, end = 6.dp), + verticalAlignment = Alignment.CenterVertically + ) { + if (inlineAutocomplete != null) { + Box( + modifier = Modifier.size(40.dp), + contentAlignment = Alignment.Center + ) { + SiteAvatar( + title = inlineAutocomplete.title, + url = inlineAutocomplete.url, + accentColor = inlineAutocomplete.accentColor, + size = 26.dp + ) + } + } else { + IconButton( + onClick = onNewTabClick, + modifier = Modifier + .size(40.dp) + .testTag("omnibox_new_tab_button") + ) { + Icon( + imageVector = Icons.Default.Add, + contentDescription = stringResource(R.string.new_tab), + tint = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.size(22.dp) + ) + } + } + + Spacer(modifier = Modifier.width(4.dp)) + + Box( + modifier = Modifier.weight(1f), + contentAlignment = Alignment.CenterStart + ) { + // Render inline highlighted autocomplete suffix behind cursor just like Screenshot 6! + if (inlineAutocomplete != null && fieldValue.selection.collapsed && fieldValue.selection.end == fieldValue.text.length) { + val suffix = inlineAutocomplete.displayUrl.substring(query.length) + Text( + text = buildAnnotatedString { + withStyle(SpanStyle(color = Color.Transparent)) { + append(fieldValue.text) + } + withStyle( + SpanStyle( + color = MaterialTheme.colorScheme.onSurface, + background = MaterialTheme.colorScheme.primary.copy(alpha = 0.28f) + ) + ) { + append(suffix) + } + }, + style = MaterialTheme.typography.bodyLarge.copy(fontSize = 16.5.sp), + maxLines = 1, + overflow = TextOverflow.Clip + ) + } + + BasicTextField( + value = fieldValue, + onValueChange = { fieldValue = it }, + singleLine = true, + textStyle = MaterialTheme.typography.bodyLarge.copy( + fontSize = 16.5.sp, + color = MaterialTheme.colorScheme.onSurface + ), + cursorBrush = SolidColor(MaterialTheme.colorScheme.primary), + keyboardOptions = KeyboardOptions( + keyboardType = KeyboardType.Uri, + imeAction = ImeAction.Go + ), + keyboardActions = KeyboardActions( + onGo = { + val target = inlineAutocomplete?.url ?: query + if (target.isNotBlank()) onSubmitUrl(target) + } + ), + modifier = Modifier + .fillMaxWidth() + .focusRequester(focusRequester) + .testTag("omnibox_text_input"), + decorationBox = { inner -> + if (fieldValue.text.isEmpty()) { + Text( + text = "Search ${settings.searchEngine.displayName} or type URL", + style = MaterialTheme.typography.bodyLarge.copy(fontSize = 16.5.sp), + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + inner() + } + ) + } + + if (fieldValue.text.isNotEmpty()) { + IconButton( + onClick = { fieldValue = TextFieldValue("") }, + modifier = Modifier + .size(40.dp) + .testTag("omnibox_clear_button") + ) { + Icon( + imageVector = Icons.Default.Close, + contentDescription = stringResource(R.string.cd_clear), + tint = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.size(21.dp) + ) + } + } else { + IconButton( + onClick = onVoiceSearchClick, + modifier = Modifier + .size(40.dp) + .testTag("omnibox_voice_button") + ) { + Icon( + imageVector = Icons.Outlined.Mic, + contentDescription = "Voice search", + tint = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.size(21.dp) + ) + } + } + } + } + + LazyColumn( + modifier = Modifier.fillMaxSize(), + contentPadding = PaddingValues(horizontal = 10.dp, vertical = 4.dp), + verticalArrangement = Arrangement.spacedBy(2.dp) + ) { + // Current Page Quick Share / Copy / Edit Card (when editing an open webpage) + if (!activeTab.isNewTab) { + item(key = "current_page_card") { + Surface( + shape = RoundedCornerShape(20.dp), + color = MaterialTheme.colorScheme.surfaceContainerLow, + modifier = Modifier + .fillMaxWidth() + .padding(bottom = 6.dp) + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 14.dp, vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically + ) { + SiteAvatar( + title = activeTab.title, + url = activeTab.url, + favicon = activeTab.favicon, + size = 30.dp + ) + Spacer(modifier = Modifier.width(12.dp)) + Column(modifier = Modifier.weight(1f)) { + Text( + text = activeTab.title, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + Text( + text = activeTab.url, + style = MaterialTheme.typography.bodySmall, + color = linkBlue, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + IconButton(onClick = onShareCurrentUrl, modifier = Modifier.size(36.dp)) { + Icon( + imageVector = Icons.Outlined.Share, + contentDescription = "Share", + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(19.dp) + ) + } + IconButton(onClick = onCopyCurrentUrl, modifier = Modifier.size(36.dp)) { + Icon( + imageVector = Icons.Outlined.ContentCopy, + contentDescription = "Copy", + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(19.dp) + ) + } + IconButton( + onClick = { + fieldValue = TextFieldValue( + text = activeTab.url, + selection = TextRange(activeTab.url.length) + ) + }, + modifier = Modifier.size(36.dp) + ) { + Icon( + imageVector = Icons.Outlined.Edit, + contentDescription = "Edit URL", + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(19.dp) + ) + } + } + } + } + } + + // Material 3 Expressive Segmented Suggestion Cards (Exact Screenshots 5 & 6!) + itemsIndexed(suggestions, key = { _, item -> item.key }) { index, item -> + ExpressiveGroupedCard( + index = index, + totalCount = suggestions.size, + modifier = Modifier.fillMaxWidth() + ) { + when (item) { + is OmniboxItem.RecentSearch -> { + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { onSubmitUrl(item.query) } + .padding(start = 16.dp, end = 8.dp, top = 12.dp, bottom = 12.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.Outlined.History, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(22.dp) + ) + Spacer(modifier = Modifier.width(16.dp)) + Text( + text = highlightMatch(item.query, query), + style = MaterialTheme.typography.bodyLarge.copy(fontSize = 15.5.sp), + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f) + ) + IconButton( + onClick = { + fieldValue = TextFieldValue(item.query, TextRange(item.query.length)) + }, + modifier = Modifier.size(38.dp) + ) { + Icon( + imageVector = Icons.Default.NorthWest, + contentDescription = "Insert query", + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(20.dp) + ) + } + } + } + + is OmniboxItem.SiteMatch -> { + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { onSubmitUrl(item.url) } + .padding(start = 14.dp, end = 8.dp, top = 11.dp, bottom = 11.dp), + verticalAlignment = Alignment.CenterVertically + ) { + SiteAvatar( + title = item.title, + url = item.url, + accentColor = item.accentColor, + size = 28.dp + ) + Spacer(modifier = Modifier.width(14.dp)) + Column(modifier = Modifier.weight(1f)) { + Text( + text = highlightMatch(item.title, query), + style = MaterialTheme.typography.bodyLarge.copy(fontSize = 15.5.sp), + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + Text( + text = highlightMatch(item.displayUrl, query), + style = MaterialTheme.typography.bodySmall.copy(fontSize = 13.5.sp), + color = linkBlue, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + IconButton( + onClick = { + fieldValue = TextFieldValue(item.displayUrl, TextRange(item.displayUrl.length)) + }, + modifier = Modifier.size(38.dp) + ) { + Icon( + imageVector = Icons.Default.NorthWest, + contentDescription = "Insert URL", + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(20.dp) + ) + } + } + } + + is OmniboxItem.OpenTabMatch -> { + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { onSwitchToTab(item.tab.id) } + .padding(start = 16.dp, end = 12.dp, top = 12.dp, bottom = 12.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.Outlined.Tab, + contentDescription = null, + tint = linkBlue, + modifier = Modifier.size(22.dp) + ) + Spacer(modifier = Modifier.width(16.dp)) + Column(modifier = Modifier.weight(1f)) { + Text( + text = item.tab.title, + style = MaterialTheme.typography.bodyLarge.copy(fontSize = 15.sp), + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + Text( + text = "Switch to this tab • ${UrlUtils.extractShortDomain(item.tab.url)}", + style = MaterialTheme.typography.bodySmall, + color = linkBlue, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + } + } + + is OmniboxItem.DirectSearch -> { + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { onSubmitUrl(item.query) } + .testTag("omnibox_submit_row") + .padding(start = 16.dp, end = 12.dp, top = 13.dp, bottom = 13.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.Default.Search, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(22.dp) + ) + Spacer(modifier = Modifier.width(16.dp)) + Column(modifier = Modifier.weight(1f)) { + Text( + text = item.query, + style = MaterialTheme.typography.bodyLarge.copy(fontSize = 15.5.sp), + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + Text( + text = if (item.isUrl) "Open website" else "${settings.searchEngine.displayName} Search", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } + } + } + } + + item { Spacer(modifier = Modifier.height(16.dp)) } + } + } + } +} + +private fun highlightMatch(text: String, query: String): AnnotatedString { + if (query.isBlank()) return AnnotatedString(text) + val startIndex = text.indexOf(query, ignoreCase = true) + if (startIndex < 0) return AnnotatedString(text) + val endIndex = (startIndex + query.length).coerceAtMost(text.length) + return buildAnnotatedString { + append(text.substring(0, startIndex)) + withStyle(SpanStyle(fontWeight = FontWeight.Bold)) { + append(text.substring(startIndex, endIndex)) + } + append(text.substring(endIndex)) + } +} diff --git a/app/src/main/java/com/bansify/browser/ui/screens/RecentTabsScreen.kt b/app/src/main/java/com/bansify/browser/ui/screens/RecentTabsScreen.kt new file mode 100644 index 00000000..650e1559 --- /dev/null +++ b/app/src/main/java/com/bansify/browser/ui/screens/RecentTabsScreen.kt @@ -0,0 +1,166 @@ +package com.bansify.browser.ui.screens + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +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.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.outlined.History +import androidx.compose.material.icons.outlined.Tab +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import com.bansify.browser.R +import com.bansify.browser.browser.UrlUtils +import com.bansify.browser.data.ClosedTab +import com.bansify.browser.ui.components.SiteAvatar + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun RecentTabsScreen( + recentlyClosedTabs: List, + onClose: () -> Unit, + onReopenTab: (String) -> Unit, + onOpenFullHistory: () -> Unit +) { + BackHandler { onClose() } + + Scaffold( + topBar = { + TopAppBar( + title = { Text(stringResource(R.string.recent_tabs)) }, + actions = { + IconButton(onClick = onClose) { + Icon( + imageVector = Icons.Default.Close, + contentDescription = stringResource(R.string.cd_close) + ) + } + }, + colors = TopAppBarDefaults.topAppBarColors( + containerColor = MaterialTheme.colorScheme.surface + ) + ) + } + ) { innerPadding -> + LazyColumn( + modifier = Modifier + .fillMaxSize() + .padding(innerPadding) + ) { + item { + Text( + text = "Recently closed", + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.primary, + modifier = Modifier.padding(horizontal = 20.dp, vertical = 14.dp) + ) + } + + if (recentlyClosedTabs.isEmpty()) { + item { + Box( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 20.dp, vertical = 24.dp), + contentAlignment = Alignment.CenterStart + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + Icon( + imageVector = Icons.Outlined.Tab, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(22.dp) + ) + Spacer(modifier = Modifier.width(14.dp)) + Text( + text = "No recently closed tabs in this session", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } + } else { + items(recentlyClosedTabs) { closed -> + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { onReopenTab(closed.url) } + .padding(horizontal = 20.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically + ) { + SiteAvatar(title = closed.title, url = closed.url, size = 34.dp) + Spacer(modifier = Modifier.width(14.dp)) + Column(modifier = Modifier.weight(1f)) { + Text( + text = closed.title, + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + Text( + text = "${UrlUtils.extractShortDomain(closed.url)} • ${UrlUtils.formatShortTime(closed.closedAt)}", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + } + } + } + + item { + Spacer(modifier = Modifier.height(6.dp)) + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) + Row( + modifier = Modifier + .fillMaxWidth() + .clickable(onClick = onOpenFullHistory) + .padding(horizontal = 20.dp, vertical = 16.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.Outlined.History, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(22.dp) + ) + Spacer(modifier = Modifier.width(14.dp)) + Text( + text = "Show full history", + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.primary + ) + } + } + } + } +} diff --git a/app/src/main/java/com/bansify/browser/ui/screens/SettingsScreen.kt b/app/src/main/java/com/bansify/browser/ui/screens/SettingsScreen.kt new file mode 100644 index 00000000..444b7d7e --- /dev/null +++ b/app/src/main/java/com/bansify/browser/ui/screens/SettingsScreen.kt @@ -0,0 +1,607 @@ +package com.bansify.browser.ui.screens + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +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.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Search +import androidx.compose.material.icons.outlined.AccountCircle +import androidx.compose.material.icons.outlined.HelpOutline +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.bansify.browser.R +import com.bansify.browser.data.BansifyAccountState +import com.bansify.browser.data.BrowserSettings +import com.bansify.browser.data.SettingsSubScreen +import com.bansify.browser.ui.components.ExpressiveGroupedCard +import com.bansify.browser.ui.components.expressiveCanvasColor +import com.bansify.browser.ui.theme.BrandBlue + +private data class SettingsEntry( + val title: String, + val subtitle: String? = null, + val testTag: String, + val target: SettingsSubScreen, + val keywords: String = "" +) + +/** + * Pixel-accurate clone of modern Chrome Android Settings (Screenshots 1 & 8): + * - Top bar with Back arrow, "Settings", and "?" Help icon + * - Live interactive pill "Search settings" bar + * - "You and Bansify" 2-card Expressive section (Profile + Bansify services) + * - "Basics" & "Advanced" Material 3 Expressive segmented card groups + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun SettingsScreen( + subScreen: SettingsSubScreen, + settings: BrowserSettings, + accountState: BansifyAccountState, + bookmarksCount: Int, + historyCount: Int, + openTabsCount: Int, + shortcutsCount: Int, + downloadsCount: Int, + onBack: () -> Unit, + onNavigateSubScreen: (SettingsSubScreen) -> Unit, + onOpenDeleteBrowsingData: () -> Unit, + onUpdateSettings: ((BrowserSettings) -> BrowserSettings) -> Unit, + onSignInBansify: (displayName: String, email: String, avatarColorHex: Long) -> Unit, + onUpdateBansifyProfile: (displayName: String, email: String, avatarColorHex: Long) -> Unit, + onSignOutBansify: () -> Unit, + onUpdateBansifySync: ((BansifyAccountState) -> BansifyAccountState) -> Unit, + onSyncNow: () -> Unit +) { + BackHandler { onBack() } + + when (subScreen) { + SettingsSubScreen.BANSIFY_ACCOUNT -> { + BansifyAccountScreen( + accountState = accountState, + bookmarksCount = bookmarksCount, + historyCount = historyCount, + openTabsCount = openTabsCount, + shortcutsCount = shortcutsCount, + downloadsCount = downloadsCount, + onBack = onBack, + onSignIn = onSignInBansify, + onUpdateProfile = onUpdateBansifyProfile, + onSignOut = onSignOutBansify, + onUpdateSync = onUpdateBansifySync, + onSyncNow = onSyncNow + ) + return + } + + SettingsSubScreen.BANSIFY_SERVICES -> { + BansifyServicesScreen( + accountState = accountState, + onBack = onBack, + onUpdateSync = onUpdateBansifySync + ) + return + } + + SettingsSubScreen.MAIN -> Unit + + else -> { + SettingsSubScreenContent( + subScreen = subScreen, + settings = settings, + onBack = onBack, + onNavigateSubScreen = onNavigateSubScreen, + onOpenDeleteBrowsingData = onOpenDeleteBrowsingData, + onUpdateSettings = onUpdateSettings + ) + return + } + } + + var searchQuery by remember { mutableStateOf("") } + val canvasBg = expressiveCanvasColor() + + val basicsItems = remember(settings) { + listOf( + SettingsEntry( + title = "Search engine", + subtitle = settings.searchEngine.displayName, + testTag = "settings_search_engine", + target = SettingsSubScreen.SEARCH_ENGINE, + keywords = "google bing duckduckgo yahoo brave ecosia" + ), + SettingsEntry( + title = "Address bar", + subtitle = settings.addressBarPosition.label, + testTag = "settings_address_bar", + target = SettingsSubScreen.ADDRESS_BAR, + keywords = "top bottom toolbar omnibox position" + ), + SettingsEntry( + title = "Privacy and security", + testTag = "settings_privacy", + target = SettingsSubScreen.PRIVACY_SECURITY, + keywords = "safe browsing https cookies delete browsing data do not track incognito" + ), + SettingsEntry( + title = "Safety check", + testTag = "settings_safety_check", + target = SettingsSubScreen.SAFETY_CHECK, + keywords = "security scan protection check" + ), + SettingsEntry( + title = "Default browser", + testTag = "settings_default_browser", + target = SettingsSubScreen.DEFAULT_BROWSER, + keywords = "system apps links" + ), + SettingsEntry( + title = "Autofill and passwords", + testTag = "settings_autofill", + target = SettingsSubScreen.AUTOFILL, + keywords = "forms addresses save" + ) + ) + } + + val advancedItems = remember(settings) { + listOf( + SettingsEntry( + title = "Tabs and tab groups", + testTag = "settings_tabs", + target = SettingsSubScreen.TABS, + keywords = "inactive auto close groups external links" + ), + SettingsEntry( + title = "Homepage", + subtitle = if (settings.homepageEnabled) "On" else "Off", + testTag = "settings_homepage", + target = SettingsSubScreen.HOMEPAGE, + keywords = "home button custom url start page" + ), + SettingsEntry( + title = "Notifications", + testTag = "settings_notifications", + target = SettingsSubScreen.NOTIFICATIONS, + keywords = "alerts downloads sites" + ), + SettingsEntry( + title = "Appearance", + testTag = "settings_appearance", + target = SettingsSubScreen.APPEARANCE, + keywords = "theme dark light system toolbar shortcut" + ), + SettingsEntry( + title = "Accessibility", + testTag = "settings_accessibility", + target = SettingsSubScreen.ACCESSIBILITY, + keywords = "text scaling font zoom simplified reading" + ), + SettingsEntry( + title = "Site settings", + testTag = "settings_site_settings", + target = SettingsSubScreen.SITE_SETTINGS, + keywords = "javascript cookies popups images desktop autoplay permissions" + ), + SettingsEntry( + title = "Languages", + testTag = "settings_languages", + target = SettingsSubScreen.LANGUAGES, + keywords = "translate english hindi spanish" + ), + SettingsEntry( + title = "Downloads", + testTag = "settings_downloads", + target = SettingsSubScreen.DOWNLOADS_SETTINGS, + keywords = "storage folder files save" + ), + SettingsEntry( + title = "About Bansify", + testTag = "settings_about", + target = SettingsSubScreen.ABOUT, + keywords = "version webview package android info" + ) + ) + } + + val query = searchQuery.trim() + val showYouAndBansify = remember(query, accountState) { + query.isEmpty() || + "you and bansify account sync login bookmarks profile services".contains(query, ignoreCase = true) || + accountState.displayName.contains(query, ignoreCase = true) || + accountState.email.contains(query, ignoreCase = true) + } + val filteredBasics = remember(basicsItems, query) { + if (query.isEmpty()) basicsItems + else basicsItems.filter { + it.title.contains(query, true) || + (it.subtitle?.contains(query, true) == true) || + it.keywords.contains(query, true) + } + } + val filteredAdvanced = remember(advancedItems, query) { + if (query.isEmpty()) advancedItems + else advancedItems.filter { + it.title.contains(query, true) || + (it.subtitle?.contains(query, true) == true) || + it.keywords.contains(query, true) + } + } + + Scaffold( + containerColor = canvasBg, + topBar = { + TopAppBar( + title = { + Text( + text = stringResource(R.string.settings), + style = MaterialTheme.typography.titleLarge.copy(fontSize = 22.sp) + ) + }, + navigationIcon = { + IconButton(onClick = onBack, modifier = Modifier.testTag("settings_back")) { + Icon( + imageVector = Icons.AutoMirrored.Filled.ArrowBack, + contentDescription = stringResource(R.string.cd_back) + ) + } + }, + actions = { + IconButton(onClick = { onNavigateSubScreen(SettingsSubScreen.ABOUT) }) { + Icon( + imageVector = Icons.Outlined.HelpOutline, + contentDescription = "Help and about Bansify" + ) + } + }, + colors = TopAppBarDefaults.topAppBarColors(containerColor = canvasBg) + ) + } + ) { innerPadding -> + LazyColumn( + modifier = Modifier + .fillMaxSize() + .background(canvasBg) + .padding(innerPadding), + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 6.dp), + verticalArrangement = Arrangement.spacedBy(2.dp) + ) { + // Pill "Search settings" Bar + item(key = "settings_search_bar") { + Surface( + shape = RoundedCornerShape(26.dp), + color = MaterialTheme.colorScheme.surfaceContainer, + modifier = Modifier + .fillMaxWidth() + .padding(bottom = 12.dp) + .height(50.dp) + ) { + Row( + modifier = Modifier + .fillMaxSize() + .padding(horizontal = 16.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.Default.Search, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(22.dp) + ) + Spacer(modifier = Modifier.width(12.dp)) + Box( + modifier = Modifier.weight(1f), + contentAlignment = Alignment.CenterStart + ) { + BasicTextField( + value = searchQuery, + onValueChange = { searchQuery = it }, + singleLine = true, + textStyle = MaterialTheme.typography.bodyLarge.copy( + color = MaterialTheme.colorScheme.onSurface, + fontSize = 16.sp + ), + cursorBrush = SolidColor(MaterialTheme.colorScheme.primary), + modifier = Modifier + .fillMaxWidth() + .testTag("settings_search_input"), + decorationBox = { inner -> + if (searchQuery.isEmpty()) { + Text( + text = "Search settings", + style = MaterialTheme.typography.bodyLarge.copy(fontSize = 16.sp), + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + inner() + } + ) + } + if (searchQuery.isNotEmpty()) { + IconButton( + onClick = { searchQuery = "" }, + modifier = Modifier.size(34.dp) + ) { + Icon( + imageVector = Icons.Default.Close, + contentDescription = "Clear search", + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(18.dp) + ) + } + } + } + } + } + + // "You and Bansify" Section (Exact match to Screenshot 8's "You and Google" 2-card group!) + if (showYouAndBansify) { + item(key = "header_you_and_bansify") { + ExpressiveSettingsSectionTitle("You and Bansify") + } + + // Card 1: Bansify Account Profile / Sign-in Card + item(key = "bansify_account_card") { + ExpressiveGroupedCard( + index = 0, + totalCount = 2, + modifier = Modifier.fillMaxWidth() + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { onNavigateSubScreen(SettingsSubScreen.BANSIFY_ACCOUNT) } + .testTag("settings_bansify_account") + .padding(horizontal = 18.dp, vertical = 16.dp), + verticalAlignment = Alignment.CenterVertically + ) { + if (accountState.isSignedIn) { + Box( + modifier = Modifier + .size(44.dp) + .clip(CircleShape) + .background(Color(accountState.avatarColorHex)), + contentAlignment = Alignment.Center + ) { + Text( + text = accountState.initialLetter, + color = Color.White, + fontSize = 19.sp, + fontWeight = FontWeight.Bold + ) + } + } else { + Box( + modifier = Modifier + .size(44.dp) + .clip(CircleShape) + .background(MaterialTheme.colorScheme.surfaceContainerHigh), + contentAlignment = Alignment.Center + ) { + Icon( + imageVector = Icons.Outlined.AccountCircle, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(28.dp) + ) + } + } + Spacer(modifier = Modifier.width(16.dp)) + Column(modifier = Modifier.weight(1f)) { + Text( + text = if (accountState.isSignedIn) accountState.displayName else "Sign in to Bansify", + style = MaterialTheme.typography.bodyLarge.copy( + fontSize = 16.5.sp, + fontWeight = FontWeight.Medium + ), + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + Spacer(modifier = Modifier.height(2.dp)) + Text( + text = if (accountState.isSignedIn) { + "${accountState.email} • Syncing ${accountState.activeSyncCategoriesCount}/6" + } else { + "Sync bookmarks, history, tabs & settings" + }, + style = MaterialTheme.typography.bodyMedium.copy(fontSize = 13.5.sp), + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + } + } + } + + // Card 2: Bansify services (matches Screenshot 8's blue G "Google services" card!) + item(key = "bansify_services_card") { + ExpressiveGroupedCard( + index = 1, + totalCount = 2, + modifier = Modifier.fillMaxWidth() + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { onNavigateSubScreen(SettingsSubScreen.BANSIFY_SERVICES) } + .testTag("settings_bansify_services") + .padding(horizontal = 18.dp, vertical = 16.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Box( + modifier = Modifier + .size(38.dp) + .clip(CircleShape) + .background(BrandBlue), + contentAlignment = Alignment.Center + ) { + Text( + text = "B", + color = Color.White, + fontSize = 20.sp, + fontWeight = FontWeight.Bold + ) + } + Spacer(modifier = Modifier.width(18.dp)) + Text( + text = "Bansify services", + style = MaterialTheme.typography.bodyLarge.copy(fontSize = 16.sp), + color = MaterialTheme.colorScheme.onSurface + ) + } + } + } + } + + // Basics Section + if (filteredBasics.isNotEmpty()) { + item(key = "header_basics") { + if (showYouAndBansify) Spacer(modifier = Modifier.height(14.dp)) + ExpressiveSettingsSectionTitle("Basics") + } + itemsIndexed(filteredBasics, key = { _, item -> item.testTag }) { index, item -> + ExpressiveSettingsCardRow( + index = index, + totalCount = filteredBasics.size, + title = item.title, + subtitle = item.subtitle, + testTag = item.testTag, + onClick = { onNavigateSubScreen(item.target) } + ) + } + } + + // Advanced Section + if (filteredAdvanced.isNotEmpty()) { + item(key = "header_advanced") { + Spacer(modifier = Modifier.height(14.dp)) + ExpressiveSettingsSectionTitle("Advanced") + } + itemsIndexed(filteredAdvanced, key = { _, item -> item.testTag }) { index, item -> + ExpressiveSettingsCardRow( + index = index, + totalCount = filteredAdvanced.size, + title = item.title, + subtitle = item.subtitle, + testTag = item.testTag, + onClick = { onNavigateSubScreen(item.target) } + ) + } + } + + if (!showYouAndBansify && filteredBasics.isEmpty() && filteredAdvanced.isEmpty()) { + item(key = "empty_search") { + Box( + modifier = Modifier + .fillMaxWidth() + .padding(vertical = 48.dp), + contentAlignment = Alignment.Center + ) { + Text( + text = "No settings found for \"$query\"", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } + + item { Spacer(modifier = Modifier.height(28.dp)) } + } + } +} + +@Composable +fun ExpressiveSettingsSectionTitle(title: String) { + Text( + text = title, + style = MaterialTheme.typography.titleSmall.copy( + fontSize = 14.sp, + fontWeight = FontWeight.Medium + ), + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(start = 16.dp, top = 8.dp, bottom = 10.dp) + ) +} + +@Composable +fun ExpressiveSettingsCardRow( + index: Int, + totalCount: Int, + title: String, + subtitle: String? = null, + testTag: String = "", + onClick: () -> Unit +) { + ExpressiveGroupedCard( + index = index, + totalCount = totalCount, + modifier = Modifier.fillMaxWidth() + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .clickable(onClick = onClick) + .then(if (testTag.isNotEmpty()) Modifier.testTag(testTag) else Modifier) + .padding(horizontal = 20.dp, vertical = 17.dp) + ) { + Text( + text = title, + style = MaterialTheme.typography.bodyLarge.copy(fontSize = 16.sp), + color = MaterialTheme.colorScheme.onSurface + ) + if (!subtitle.isNullOrBlank()) { + Spacer(modifier = Modifier.height(2.dp)) + Text( + text = subtitle, + style = MaterialTheme.typography.bodyMedium.copy(fontSize = 13.5.sp), + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } +} diff --git a/app/src/main/java/com/bansify/browser/ui/screens/SettingsSubScreens.kt b/app/src/main/java/com/bansify/browser/ui/screens/SettingsSubScreens.kt new file mode 100644 index 00000000..ad44b112 --- /dev/null +++ b/app/src/main/java/com/bansify/browser/ui/screens/SettingsSubScreens.kt @@ -0,0 +1,894 @@ +package com.bansify.browser.ui.screens + +import android.content.Intent +import android.os.Build +import android.provider.Settings +import android.webkit.WebView +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +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.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.outlined.CheckCircle +import androidx.compose.material.icons.outlined.OpenInNew +import androidx.compose.material.icons.outlined.WarningAmber +import androidx.compose.material3.Button +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.RadioButton +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Slider +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.bansify.browser.R +import com.bansify.browser.data.AddressBarPosition +import com.bansify.browser.data.BrowserSettings +import com.bansify.browser.data.SafeBrowsingLevel +import com.bansify.browser.data.SearchEngine +import com.bansify.browser.data.SettingsSubScreen +import com.bansify.browser.data.ThemeMode +import com.bansify.browser.data.ThirdPartyCookiePolicy +import com.bansify.browser.data.ToolbarShortcut +import com.bansify.browser.ui.components.ExpressiveGroupedCard +import com.bansify.browser.ui.components.expressiveCanvasColor +import com.bansify.browser.ui.theme.SecureGreen +import com.bansify.browser.ui.theme.SecureGreenDark +import com.bansify.browser.ui.theme.LocalIsDarkBrowserTheme +import kotlin.math.roundToInt + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun SettingsSubScreenContent( + subScreen: SettingsSubScreen, + settings: BrowserSettings, + onBack: () -> Unit, + onNavigateSubScreen: (SettingsSubScreen) -> Unit, + onOpenDeleteBrowsingData: () -> Unit, + onUpdateSettings: ((BrowserSettings) -> BrowserSettings) -> Unit +) { + val canvasBg = expressiveCanvasColor() + val context = LocalContext.current + + Scaffold( + containerColor = canvasBg, + topBar = { + TopAppBar( + title = { Text(subScreen.title) }, + navigationIcon = { + IconButton(onClick = onBack) { + Icon( + imageVector = Icons.AutoMirrored.Filled.ArrowBack, + contentDescription = stringResource(R.string.cd_back) + ) + } + }, + colors = TopAppBarDefaults.topAppBarColors(containerColor = canvasBg) + ) + } + ) { innerPadding -> + LazyColumn( + modifier = Modifier + .fillMaxSize() + .background(canvasBg) + .padding(innerPadding), + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(2.dp) + ) { + when (subScreen) { + SettingsSubScreen.SEARCH_ENGINE -> { + val engines = SearchEngine.entries + items(engines.size) { idx -> + val engine = engines[idx] + ExpressiveRadioCard( + index = idx, + totalCount = engines.size, + title = engine.displayName, + subtitle = engine.domain, + selected = settings.searchEngine == engine, + onSelect = { onUpdateSettings { it.copy(searchEngine = engine) } } + ) + } + } + + SettingsSubScreen.ADDRESS_BAR -> { + item { + ExpressiveSettingsSectionTitle("Choose address bar position") + } + val positions = AddressBarPosition.entries + items(positions.size) { idx -> + val pos = positions[idx] + ExpressiveGroupedCard(index = idx, totalCount = positions.size) { + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { onUpdateSettings { it.copy(addressBarPosition = pos) } } + .padding(horizontal = 16.dp, vertical = 16.dp), + verticalAlignment = Alignment.CenterVertically + ) { + RadioButton( + selected = settings.addressBarPosition == pos, + onClick = { onUpdateSettings { it.copy(addressBarPosition = pos) } } + ) + Spacer(modifier = Modifier.width(12.dp)) + Column(modifier = Modifier.weight(1f)) { + Text( + text = pos.label, + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurface + ) + Text( + text = pos.description, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + Spacer(modifier = Modifier.width(12.dp)) + AddressBarMiniPreview(isBottom = pos == AddressBarPosition.BOTTOM) + } + } + } + } + + SettingsSubScreen.SAFETY_CHECK -> { + item { + var hasRunCheck by remember { mutableStateOf(true) } + val okColor = if (LocalIsDarkBrowserTheme.current) SecureGreenDark else SecureGreen + val safeBrowsingOk = settings.safeBrowsingLevel != SafeBrowsingLevel.NONE + + ExpressiveGroupedCard(index = 0, totalCount = 1) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(20.dp), + verticalArrangement = Arrangement.spacedBy(12.dp) + ) { + Text( + text = "Bansify can help keep you safe from dangerous sites, insecure connections, and tracking cookies.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Button( + onClick = { hasRunCheck = true }, + shape = RoundedCornerShape(24.dp) + ) { + Text("Check now") + } + } + } + + Spacer(modifier = Modifier.height(14.dp)) + + if (hasRunCheck) { + SafetyCheckItemCard( + index = 0, + totalCount = 3, + title = "Safe Browsing", + subtitle = settings.safeBrowsingLevel.label, + isSafe = safeBrowsingOk, + safeColor = okColor, + onClick = { onNavigateSubScreen(SettingsSubScreen.SAFE_BROWSING) } + ) + Spacer(modifier = Modifier.height(2.dp)) + SafetyCheckItemCard( + index = 1, + totalCount = 3, + title = "Always use secure connections", + subtitle = if (settings.httpsFirstEnabled) "HTTPS-First protection is active" else "Tap to enable HTTPS-First mode", + isSafe = settings.httpsFirstEnabled, + safeColor = okColor, + onClick = { onNavigateSubScreen(SettingsSubScreen.PRIVACY_SECURITY) } + ) + Spacer(modifier = Modifier.height(2.dp)) + SafetyCheckItemCard( + index = 2, + totalCount = 3, + title = "Third-party cookies", + subtitle = settings.thirdPartyCookiePolicy.label, + isSafe = settings.thirdPartyCookiePolicy != ThirdPartyCookiePolicy.ALLOW, + safeColor = okColor, + onClick = { onNavigateSubScreen(SettingsSubScreen.THIRD_PARTY_COOKIES) } + ) + } + } + } + + SettingsSubScreen.DEFAULT_BROWSER -> { + item { + ExpressiveGroupedCard(index = 0, totalCount = 1) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(20.dp), + verticalArrangement = Arrangement.spacedBy(14.dp) + ) { + Text( + text = "Make Bansify Browser your default", + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onSurface + ) + Text( + text = "Open web links from messages, email, and other apps directly in Bansify Browser.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Button( + onClick = { + runCatching { + val intent = Intent(Settings.ACTION_MANAGE_DEFAULT_APPS_SETTINGS).apply { + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + } + context.startActivity(intent) + } + }, + shape = RoundedCornerShape(24.dp) + ) { + Text("Open Default Apps settings") + Spacer(modifier = Modifier.width(8.dp)) + Icon(Icons.Outlined.OpenInNew, contentDescription = null, modifier = Modifier.size(18.dp)) + } + } + } + } + } + + SettingsSubScreen.AUTOFILL -> { + item { + ExpressiveSwitchCard( + index = 0, + totalCount = 2, + title = "Save and fill form data", + subtitle = "Store basic non-sensitive form suggestions locally in WebView", + checked = settings.saveFormDataEnabled, + onCheckedChange = { v -> onUpdateSettings { it.copy(saveFormDataEnabled = v) } } + ) + Spacer(modifier = Modifier.height(2.dp)) + ExpressiveSwitchCard( + index = 1, + totalCount = 2, + title = "Autofill addresses and more", + subtitle = "Use Android Autofill service when filling web forms", + checked = settings.autofillAddressesEnabled, + onCheckedChange = { v -> onUpdateSettings { it.copy(autofillAddressesEnabled = v) } } + ) + } + } + + SettingsSubScreen.APPEARANCE -> { + item { + ExpressiveSettingsCardRow( + index = 0, + totalCount = 3, + title = "Theme", + subtitle = settings.themeMode.label, + onClick = { onNavigateSubScreen(SettingsSubScreen.THEME) } + ) + Spacer(modifier = Modifier.height(2.dp)) + ExpressiveSettingsCardRow( + index = 1, + totalCount = 3, + title = "Toolbar shortcut", + subtitle = settings.toolbarShortcut.label, + onClick = { onNavigateSubScreen(SettingsSubScreen.TOOLBAR_SHORTCUT) } + ) + Spacer(modifier = Modifier.height(2.dp)) + ExpressiveSwitchCard( + index = 2, + totalCount = 3, + title = "Show Continue browsing & Bookmarks on New Tab", + subtitle = "Display recent cards underneath shortcuts on the Home page", + checked = settings.showRecentCardsOnNtp, + onCheckedChange = { v -> onUpdateSettings { it.copy(showRecentCardsOnNtp = v) } } + ) + } + } + + SettingsSubScreen.THEME -> { + val modes = ThemeMode.entries + items(modes.size) { idx -> + val mode = modes[idx] + ExpressiveRadioCard( + index = idx, + totalCount = modes.size, + title = mode.label, + subtitle = when (mode) { + ThemeMode.SYSTEM -> "Follows your Android device theme" + ThemeMode.LIGHT -> "Always use light Chrome appearance" + ThemeMode.DARK -> "Always use dark Chrome appearance" + }, + selected = settings.themeMode == mode, + onSelect = { onUpdateSettings { it.copy(themeMode = mode) } } + ) + } + } + + SettingsSubScreen.TOOLBAR_SHORTCUT -> { + val options = ToolbarShortcut.entries + items(options.size) { idx -> + val shortcut = options[idx] + ExpressiveRadioCard( + index = idx, + totalCount = options.size, + title = shortcut.label, + subtitle = when (shortcut) { + ToolbarShortcut.NEW_TAB -> "Show '+' New tab button next to address bar" + ToolbarShortcut.SHARE -> "Quickly share the current page" + ToolbarShortcut.BOOKMARK -> "Star or unstar the current page" + ToolbarShortcut.NONE -> "Hide extra toolbar shortcut button" + }, + selected = settings.toolbarShortcut == shortcut, + onSelect = { onUpdateSettings { it.copy(toolbarShortcut = shortcut) } } + ) + } + } + + SettingsSubScreen.HOMEPAGE -> { + item { + ExpressiveSwitchCard( + index = 0, + totalCount = 1, + title = "On", + subtitle = "Show the Home button in the browser toolbar", + checked = settings.homepageEnabled, + onCheckedChange = { enabled -> + onUpdateSettings { it.copy(homepageEnabled = enabled) } + } + ) + if (settings.homepageEnabled) { + Spacer(modifier = Modifier.height(14.dp)) + ExpressiveSettingsSectionTitle("Open this page") + ExpressiveRadioCard( + index = 0, + totalCount = 2, + title = "Bansify's homepage", + subtitle = "Shows the New Tab page with search and shortcuts", + selected = !settings.useCustomHomepage, + onSelect = { onUpdateSettings { it.copy(useCustomHomepage = false) } } + ) + Spacer(modifier = Modifier.height(2.dp)) + ExpressiveRadioCard( + index = 1, + totalCount = 2, + title = "Enter custom web address", + subtitle = null, + selected = settings.useCustomHomepage, + onSelect = { onUpdateSettings { it.copy(useCustomHomepage = true) } } + ) + if (settings.useCustomHomepage) { + var urlDraft by remember(settings.customHomepageUrl) { + mutableStateOf(settings.customHomepageUrl) + } + Spacer(modifier = Modifier.height(10.dp)) + OutlinedTextField( + value = urlDraft, + onValueChange = { value -> + urlDraft = value + onUpdateSettings { it.copy(customHomepageUrl = value) } + }, + label = { Text("Homepage URL") }, + singleLine = true, + modifier = Modifier.fillMaxWidth() + ) + } + } + } + } + + SettingsSubScreen.TABS -> { + item { + ExpressiveSettingsSectionTitle("Tab behavior") + ExpressiveSwitchCard( + index = 0, + totalCount = 1, + title = "Open external links in a new tab", + subtitle = "Links opened from other apps open in a fresh Bansify tab", + checked = settings.openExternalLinksInNewTab, + onCheckedChange = { v -> + onUpdateSettings { it.copy(openExternalLinksInNewTab = v) } + } + ) + Spacer(modifier = Modifier.height(14.dp)) + ExpressiveSettingsSectionTitle("Auto-close inactive tabs") + val options = listOf(0 to "Never", 7 to "After 7 days", 14 to "After 14 days", 21 to "After 21 days") + options.forEachIndexed { idx, (days, label) -> + ExpressiveRadioCard( + index = idx, + totalCount = options.size, + title = label, + subtitle = null, + selected = settings.autoCloseTabsDays == days, + onSelect = { onUpdateSettings { it.copy(autoCloseTabsDays = days) } } + ) + if (idx < options.lastIndex) Spacer(modifier = Modifier.height(2.dp)) + } + } + } + + SettingsSubScreen.NOTIFICATIONS -> { + item { + ExpressiveSwitchCard( + index = 0, + totalCount = 2, + title = "Show notifications", + subtitle = "Allow browser status and download notifications", + checked = settings.notificationsEnabled, + onCheckedChange = { v -> onUpdateSettings { it.copy(notificationsEnabled = v) } } + ) + Spacer(modifier = Modifier.height(2.dp)) + ExpressiveSwitchCard( + index = 1, + totalCount = 2, + title = "Completed downloads", + subtitle = "Notify when downloaded files finish saving", + checked = settings.downloadNotificationsEnabled, + onCheckedChange = { v -> onUpdateSettings { it.copy(downloadNotificationsEnabled = v) } } + ) + } + } + + SettingsSubScreen.LANGUAGES -> { + item { + ExpressiveSettingsSectionTitle("Preferred language") + val languages = listOf( + "English (United States)", + "Hindi (India)", + "Spanish (Spain)", + "French (France)", + "German (Germany)", + "Japanese (Japan)" + ) + languages.forEachIndexed { idx, lang -> + ExpressiveRadioCard( + index = idx, + totalCount = languages.size, + title = lang, + subtitle = if (settings.preferredLanguage == lang) "Active Accept-Language header" else null, + selected = settings.preferredLanguage == lang, + onSelect = { onUpdateSettings { it.copy(preferredLanguage = lang) } } + ) + if (idx < languages.lastIndex) Spacer(modifier = Modifier.height(2.dp)) + } + Spacer(modifier = Modifier.height(14.dp)) + ExpressiveSettingsSectionTitle("Translation") + ExpressiveSwitchCard( + index = 0, + totalCount = 1, + title = "Offer to translate pages", + subtitle = "Allow quick page translation from the 3-dot menu", + checked = settings.offerTranslatePages, + onCheckedChange = { v -> onUpdateSettings { it.copy(offerTranslatePages = v) } } + ) + } + } + + SettingsSubScreen.PRIVACY_SECURITY -> { + item { + ExpressiveSettingsCardRow( + index = 0, + totalCount = 6, + title = "Delete browsing data", + subtitle = "Clear history, cookies, cache, and site data", + onClick = onOpenDeleteBrowsingData + ) + Spacer(modifier = Modifier.height(2.dp)) + ExpressiveSettingsCardRow( + index = 1, + totalCount = 6, + title = "Safe Browsing", + subtitle = settings.safeBrowsingLevel.label, + onClick = { onNavigateSubScreen(SettingsSubScreen.SAFE_BROWSING) } + ) + Spacer(modifier = Modifier.height(2.dp)) + ExpressiveSwitchCard( + index = 2, + totalCount = 6, + title = "Always use secure connections", + subtitle = "Upgrade navigations to HTTPS automatically", + checked = settings.httpsFirstEnabled, + onCheckedChange = { v -> onUpdateSettings { it.copy(httpsFirstEnabled = v) } } + ) + Spacer(modifier = Modifier.height(2.dp)) + ExpressiveSwitchCard( + index = 3, + totalCount = 6, + title = "Send a \"Do Not Track\" request", + subtitle = "Includes a DNT: 1 header with browsing traffic", + checked = settings.doNotTrackEnabled, + onCheckedChange = { v -> onUpdateSettings { it.copy(doNotTrackEnabled = v) } } + ) + Spacer(modifier = Modifier.height(2.dp)) + ExpressiveSettingsCardRow( + index = 4, + totalCount = 6, + title = "Third-party cookies", + subtitle = settings.thirdPartyCookiePolicy.label, + onClick = { onNavigateSubScreen(SettingsSubScreen.THIRD_PARTY_COOKIES) } + ) + Spacer(modifier = Modifier.height(2.dp)) + ExpressiveSwitchCard( + index = 5, + totalCount = 6, + title = "Lock Incognito tabs when you leave Bansify", + subtitle = "Adds privacy protection for open Incognito sessions", + checked = settings.lockIncognitoOnLeave, + onCheckedChange = { v -> onUpdateSettings { it.copy(lockIncognitoOnLeave = v) } } + ) + } + } + + SettingsSubScreen.SAFE_BROWSING -> { + val levels = SafeBrowsingLevel.entries + items(levels.size) { idx -> + val level = levels[idx] + ExpressiveRadioCard( + index = idx, + totalCount = levels.size, + title = level.label, + subtitle = level.summary, + selected = settings.safeBrowsingLevel == level, + onSelect = { onUpdateSettings { it.copy(safeBrowsingLevel = level) } } + ) + } + } + + SettingsSubScreen.THIRD_PARTY_COOKIES -> { + val policies = ThirdPartyCookiePolicy.entries + items(policies.size) { idx -> + val policy = policies[idx] + ExpressiveRadioCard( + index = idx, + totalCount = policies.size, + title = policy.label, + subtitle = policy.summary, + selected = settings.thirdPartyCookiePolicy == policy, + onSelect = { onUpdateSettings { it.copy(thirdPartyCookiePolicy = policy) } } + ) + } + } + + SettingsSubScreen.SITE_SETTINGS -> { + item { + ExpressiveSettingsSectionTitle("Content & Permissions") + ExpressiveSwitchCard( + index = 0, + totalCount = 6, + title = "JavaScript", + subtitle = if (settings.javascriptEnabled) "Allowed (recommended)" else "Blocked", + checked = settings.javascriptEnabled, + onCheckedChange = { v -> onUpdateSettings { it.copy(javascriptEnabled = v) } } + ) + Spacer(modifier = Modifier.height(2.dp)) + ExpressiveSwitchCard( + index = 1, + totalCount = 6, + title = "Cookies", + subtitle = if (settings.cookiesEnabled) "Sites can save and read cookie data" else "All cookies blocked", + checked = settings.cookiesEnabled, + onCheckedChange = { v -> onUpdateSettings { it.copy(cookiesEnabled = v) } } + ) + Spacer(modifier = Modifier.height(2.dp)) + ExpressiveSwitchCard( + index = 2, + totalCount = 6, + title = "Pop-ups and redirects", + subtitle = if (settings.popupsAllowed) "Allowed" else "Blocked (recommended)", + checked = settings.popupsAllowed, + onCheckedChange = { v -> onUpdateSettings { it.copy(popupsAllowed = v) } } + ) + Spacer(modifier = Modifier.height(2.dp)) + ExpressiveSwitchCard( + index = 3, + totalCount = 6, + title = "Images", + subtitle = if (settings.loadImagesEnabled) "Show all images (recommended)" else "Do not load images (saves data)", + checked = settings.loadImagesEnabled, + onCheckedChange = { v -> onUpdateSettings { it.copy(loadImagesEnabled = v) } } + ) + Spacer(modifier = Modifier.height(2.dp)) + ExpressiveSwitchCard( + index = 4, + totalCount = 6, + title = "Desktop site", + subtitle = if (settings.defaultDesktopSite) "Always request desktop view for new tabs" else "Request mobile view by default", + checked = settings.defaultDesktopSite, + onCheckedChange = { v -> onUpdateSettings { it.copy(defaultDesktopSite = v) } } + ) + Spacer(modifier = Modifier.height(2.dp)) + ExpressiveSwitchCard( + index = 5, + totalCount = 6, + title = "Media autoplay", + subtitle = if (settings.mediaAutoplayEnabled) "Allowed" else "Require tap before media plays", + checked = settings.mediaAutoplayEnabled, + onCheckedChange = { v -> onUpdateSettings { it.copy(mediaAutoplayEnabled = v) } } + ) + } + } + + SettingsSubScreen.ACCESSIBILITY -> { + item { + ExpressiveGroupedCard(index = 0, totalCount = 3) { + Column(modifier = Modifier.padding(20.dp)) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = "Text scaling", + style = MaterialTheme.typography.titleMedium, + color = MaterialTheme.colorScheme.onSurface + ) + Text( + text = "${settings.textZoomPercent}%", + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.primary + ) + } + Spacer(modifier = Modifier.height(6.dp)) + Slider( + value = settings.textZoomPercent.toFloat(), + onValueChange = { v -> + val snapped = (v / 5f).roundToInt() * 5 + onUpdateSettings { it.copy(textZoomPercent = snapped.coerceIn(50, 200)) } + }, + valueRange = 50f..200f, + steps = 29 + ) + Spacer(modifier = Modifier.height(8.dp)) + Text( + text = "Drag the slider until you can read this comfortably. Text on web pages scales immediately.", + fontSize = (14f * (settings.textZoomPercent / 100f)).sp, + lineHeight = (20f * (settings.textZoomPercent / 100f)).sp, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + Spacer(modifier = Modifier.height(2.dp)) + ExpressiveSwitchCard( + index = 1, + totalCount = 3, + title = "Force enable zoom", + subtitle = "Override a website's request to prevent zooming in", + checked = settings.forceEnableZoom, + onCheckedChange = { v -> onUpdateSettings { it.copy(forceEnableZoom = v) } } + ) + Spacer(modifier = Modifier.height(2.dp)) + ExpressiveSwitchCard( + index = 2, + totalCount = 3, + title = "Simplified view for web pages", + subtitle = "Prefer clean reading typography whenever supported", + checked = settings.simplifiedViewEnabled, + onCheckedChange = { v -> onUpdateSettings { it.copy(simplifiedViewEnabled = v) } } + ) + } + } + + SettingsSubScreen.DOWNLOADS_SETTINGS -> { + item { + ExpressiveSettingsCardRow( + index = 0, + totalCount = 2, + title = "Download location", + subtitle = "/storage/emulated/0/Download", + onClick = {} + ) + Spacer(modifier = Modifier.height(2.dp)) + ExpressiveSwitchCard( + index = 1, + totalCount = 2, + title = "Ask where to save files", + subtitle = "Prompt confirmation before saving downloads", + checked = settings.askWhereToSaveDownloads, + onCheckedChange = { v -> onUpdateSettings { it.copy(askWhereToSaveDownloads = v) } } + ) + } + } + + SettingsSubScreen.ABOUT -> { + item { + val webViewPkg = remember { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + WebView.getCurrentWebViewPackage() + } else { + null + } + } + val aboutItems = listOf( + "Application version" to "Bansify Browser 1.0.0", + "Package name" to "com.bansify.browser", + "WebView engine" to (webViewPkg?.let { "${it.packageName} (${it.versionName})" } + ?: "Android System WebView"), + "Operating system" to "Android ${Build.VERSION.RELEASE}; ${Build.MODEL}", + "Account & sync storage" to "Demo Bansify Account sync structure ready — sign in from Settings > You and Bansify to manage what syncs." + ) + aboutItems.forEachIndexed { idx, (label, value) -> + ExpressiveSettingsCardRow( + index = idx, + totalCount = aboutItems.size, + title = label, + subtitle = value, + onClick = {} + ) + if (idx < aboutItems.lastIndex) Spacer(modifier = Modifier.height(2.dp)) + } + } + } + + SettingsSubScreen.MAIN, + SettingsSubScreen.BANSIFY_ACCOUNT, + SettingsSubScreen.BANSIFY_SERVICES -> Unit + } + + item { Spacer(modifier = Modifier.height(28.dp)) } + } + } +} + +@Composable +private fun AddressBarMiniPreview(isBottom: Boolean) { + Box( + modifier = Modifier + .width(38.dp) + .height(54.dp) + .clip(RoundedCornerShape(8.dp)) + .border(1.5.dp, MaterialTheme.colorScheme.outline, RoundedCornerShape(8.dp)) + .padding(4.dp) + ) { + Box( + modifier = Modifier + .align(if (isBottom) Alignment.BottomCenter else Alignment.TopCenter) + .fillMaxWidth() + .height(8.dp) + .clip(RoundedCornerShape(4.dp)) + .background(MaterialTheme.colorScheme.primary) + ) + } +} + +@Composable +private fun SafetyCheckItemCard( + index: Int, + totalCount: Int, + title: String, + subtitle: String, + isSafe: Boolean, + safeColor: androidx.compose.ui.graphics.Color, + onClick: () -> Unit +) { + ExpressiveGroupedCard(index = index, totalCount = totalCount) { + Row( + modifier = Modifier + .fillMaxWidth() + .clickable(onClick = onClick) + .padding(horizontal = 20.dp, vertical = 16.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = if (isSafe) Icons.Outlined.CheckCircle else Icons.Outlined.WarningAmber, + contentDescription = null, + tint = if (isSafe) safeColor else MaterialTheme.colorScheme.error, + modifier = Modifier.size(22.dp) + ) + Spacer(modifier = Modifier.width(16.dp)) + Column(modifier = Modifier.weight(1f)) { + Text( + text = title, + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurface + ) + Text( + text = subtitle, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } +} + +@Composable +private fun ExpressiveRadioCard( + index: Int, + totalCount: Int, + title: String, + subtitle: String?, + selected: Boolean, + onSelect: () -> Unit +) { + ExpressiveGroupedCard(index = index, totalCount = totalCount) { + Row( + modifier = Modifier + .fillMaxWidth() + .clickable(onClick = onSelect) + .padding(horizontal = 16.dp, vertical = 15.dp), + verticalAlignment = Alignment.CenterVertically + ) { + RadioButton(selected = selected, onClick = onSelect) + Spacer(modifier = Modifier.width(12.dp)) + Column(modifier = Modifier.weight(1f)) { + Text( + text = title, + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurface + ) + if (!subtitle.isNullOrBlank()) { + Text( + text = subtitle, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } + } +} + +@Composable +private fun ExpressiveSwitchCard( + index: Int, + totalCount: Int, + title: String, + subtitle: String, + checked: Boolean, + onCheckedChange: (Boolean) -> Unit +) { + ExpressiveGroupedCard(index = index, totalCount = totalCount) { + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { onCheckedChange(!checked) } + .padding(horizontal = 20.dp, vertical = 15.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Column(modifier = Modifier.weight(1f)) { + Text( + text = title, + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurface + ) + Spacer(modifier = Modifier.height(2.dp)) + Text( + text = subtitle, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + Spacer(modifier = Modifier.width(12.dp)) + Switch(checked = checked, onCheckedChange = onCheckedChange) + } + } +} diff --git a/app/src/main/java/com/bansify/browser/ui/screens/TabSwitcherScreen.kt b/app/src/main/java/com/bansify/browser/ui/screens/TabSwitcherScreen.kt new file mode 100644 index 00000000..e79a07c7 --- /dev/null +++ b/app/src/main/java/com/bansify/browser/ui/screens/TabSwitcherScreen.kt @@ -0,0 +1,473 @@ +package com.bansify.browser.ui.screens + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +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.height +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.statusBarsPadding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.grid.GridCells +import androidx.compose.foundation.lazy.grid.LazyVerticalGrid +import androidx.compose.foundation.lazy.grid.items +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.MoreVert +import androidx.compose.material.icons.outlined.Public +import androidx.compose.material3.Button +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import com.bansify.browser.R +import com.bansify.browser.browser.UrlUtils +import com.bansify.browser.data.BrowserTab +import com.bansify.browser.ui.components.ChromeTabCountBadge +import com.bansify.browser.ui.components.IncognitoIcon +import com.bansify.browser.ui.components.SiteAvatar +import com.bansify.browser.ui.theme.IncognitoBackground +import com.bansify.browser.ui.theme.IncognitoOnSurface +import com.bansify.browser.ui.theme.IncognitoOnSurfaceVariant +import com.bansify.browser.ui.theme.IncognitoPrimary +import com.bansify.browser.ui.theme.IncognitoSurfaceContainer +import com.bansify.browser.ui.theme.IncognitoSurfaceContainerHigh + +@Composable +fun TabSwitcherScreen( + tabs: List, + activeTabId: String, + initialShowIncognito: Boolean, + onDismiss: () -> Unit, + onSelectTab: (String) -> Unit, + onCloseTab: (String) -> Unit, + onCreateNewTab: (isIncognito: Boolean) -> Unit, + onCloseAllTabs: (incognitoOnly: Boolean) -> Unit, + onOpenSettings: () -> Unit +) { + BackHandler { onDismiss() } + + var showingIncognito by remember(initialShowIncognito) { mutableStateOf(initialShowIncognito) } + var menuExpanded by remember { mutableStateOf(false) } + + val normalTabs = remember(tabs) { tabs.filter { !it.isIncognito } } + val incognitoTabs = remember(tabs) { tabs.filter { it.isIncognito } } + val displayedTabs = if (showingIncognito) incognitoTabs else normalTabs + + val bgColor = if (showingIncognito) IncognitoBackground else MaterialTheme.colorScheme.surfaceContainerLow + val cardBgColor = if (showingIncognito) IncognitoSurfaceContainer else MaterialTheme.colorScheme.surface + val textColor = if (showingIncognito) IncognitoOnSurface else MaterialTheme.colorScheme.onSurface + val mutedColor = if (showingIncognito) IncognitoOnSurfaceVariant else MaterialTheme.colorScheme.onSurfaceVariant + val activeBorderColor = if (showingIncognito) IncognitoPrimary else MaterialTheme.colorScheme.primary + + Surface( + color = bgColor, + modifier = Modifier + .fillMaxSize() + .statusBarsPadding() + .navigationBarsPadding() + ) { + Column(modifier = Modifier.fillMaxSize()) { + // Chrome Tab Switcher Top Bar (+ button | Segmented Normal/Incognito Switcher | 3-Dot Menu) + Row( + modifier = Modifier + .fillMaxWidth() + .height(58.dp) + .padding(horizontal = 6.dp), + verticalAlignment = Alignment.CenterVertically + ) { + IconButton( + onClick = { onCreateNewTab(showingIncognito) }, + modifier = Modifier.testTag("tab_switcher_add_button") + ) { + Icon( + imageVector = Icons.Default.Add, + contentDescription = stringResource(R.string.new_tab), + tint = textColor, + modifier = Modifier.size(26.dp) + ) + } + + Spacer(modifier = Modifier.weight(1f)) + + // Centered Chrome Segmented Normal / Incognito Pill + Surface( + shape = RoundedCornerShape(24.dp), + color = if (showingIncognito) IncognitoSurfaceContainerHigh else MaterialTheme.colorScheme.surfaceContainerHighest, + modifier = Modifier.height(40.dp) + ) { + Row( + modifier = Modifier.padding(3.dp), + verticalAlignment = Alignment.CenterVertically + ) { + // Normal Tabs Segment + Box( + modifier = Modifier + .clip(RoundedCornerShape(20.dp)) + .background( + if (!showingIncognito) MaterialTheme.colorScheme.surface + else androidx.compose.ui.graphics.Color.Transparent + ) + .clickable { showingIncognito = false } + .testTag("tab_switcher_normal_segment") + .padding(horizontal = 18.dp, vertical = 6.dp), + contentAlignment = Alignment.Center + ) { + ChromeTabCountBadge( + count = normalTabs.size, + color = if (!showingIncognito) MaterialTheme.colorScheme.primary else mutedColor + ) + } + + // Incognito Tabs Segment + Row( + modifier = Modifier + .clip(RoundedCornerShape(20.dp)) + .background( + if (showingIncognito) IncognitoBackground + else androidx.compose.ui.graphics.Color.Transparent + ) + .clickable { showingIncognito = true } + .testTag("tab_switcher_incognito_segment") + .padding(horizontal = 18.dp, vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp) + ) { + IncognitoIcon( + size = 20.dp, + tint = if (showingIncognito) IncognitoOnSurface else mutedColor + ) + if (incognitoTabs.isNotEmpty()) { + Text( + text = incognitoTabs.size.toString(), + style = MaterialTheme.typography.labelMedium, + color = if (showingIncognito) IncognitoOnSurface else mutedColor + ) + } + } + } + } + + Spacer(modifier = Modifier.weight(1f)) + + Box { + IconButton( + onClick = { menuExpanded = true }, + modifier = Modifier.testTag("tab_switcher_menu_button") + ) { + Icon( + imageVector = Icons.Default.MoreVert, + contentDescription = stringResource(R.string.cd_more_options), + tint = textColor + ) + } + DropdownMenu( + expanded = menuExpanded, + onDismissRequest = { menuExpanded = false }, + containerColor = MaterialTheme.colorScheme.surfaceContainerLow + ) { + DropdownMenuItem( + text = { Text(stringResource(R.string.new_tab)) }, + onClick = { + menuExpanded = false + onCreateNewTab(false) + } + ) + DropdownMenuItem( + text = { Text(stringResource(R.string.new_incognito_tab)) }, + onClick = { + menuExpanded = false + onCreateNewTab(true) + } + ) + DropdownMenuItem( + text = { + Text( + if (showingIncognito) "Close all Incognito tabs" else "Close all tabs" + ) + }, + onClick = { + menuExpanded = false + onCloseAllTabs(showingIncognito) + } + ) + DropdownMenuItem( + text = { Text(stringResource(R.string.settings)) }, + onClick = { + menuExpanded = false + onOpenSettings() + } + ) + } + } + } + + if (displayedTabs.isEmpty()) { + // Empty Incognito or Normal Tabs State + Box( + modifier = Modifier + .fillMaxSize() + .padding(32.dp), + contentAlignment = Alignment.Center + ) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Box( + modifier = Modifier + .size(68.dp) + .clip(CircleShape) + .background( + if (showingIncognito) IncognitoSurfaceContainerHigh + else MaterialTheme.colorScheme.surfaceContainerHigh + ), + contentAlignment = Alignment.Center + ) { + if (showingIncognito) { + IncognitoIcon(size = 38.dp, tint = textColor) + } else { + Icon( + imageVector = Icons.Outlined.Public, + contentDescription = null, + tint = textColor, + modifier = Modifier.size(34.dp) + ) + } + } + Spacer(modifier = Modifier.height(16.dp)) + Text( + text = if (showingIncognito) "No Incognito tabs" else "No open tabs", + style = MaterialTheme.typography.titleMedium, + color = textColor + ) + Spacer(modifier = Modifier.height(6.dp)) + Text( + text = if (showingIncognito) { + "Browse privately without saving history or cookies on this device." + } else { + "Tap + to start a new tab." + }, + style = MaterialTheme.typography.bodyMedium, + color = mutedColor, + textAlign = TextAlign.Center + ) + Spacer(modifier = Modifier.height(20.dp)) + Button(onClick = { onCreateNewTab(showingIncognito) }) { + Icon(Icons.Default.Add, contentDescription = null, modifier = Modifier.size(18.dp)) + Spacer(modifier = Modifier.width(8.dp)) + Text(if (showingIncognito) "New Incognito tab" else "New tab") + } + } + } + } else { + // Authentic Chrome 2-Column Tab Thumbnail Grid + LazyVerticalGrid( + columns = GridCells.Adaptive(minSize = 158.dp), + contentPadding = PaddingValues(12.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + modifier = Modifier.fillMaxSize() + ) { + items(displayedTabs, key = { it.id }) { tab -> + val isActive = tab.id == activeTabId + TabGridCard( + tab = tab, + isActive = isActive, + cardBgColor = cardBgColor, + textColor = textColor, + mutedColor = mutedColor, + activeBorderColor = activeBorderColor, + onSelect = { onSelectTab(tab.id) }, + onClose = { onCloseTab(tab.id) } + ) + } + } + } + } + } +} + +@Composable +private fun TabGridCard( + tab: BrowserTab, + isActive: Boolean, + cardBgColor: androidx.compose.ui.graphics.Color, + textColor: androidx.compose.ui.graphics.Color, + mutedColor: androidx.compose.ui.graphics.Color, + activeBorderColor: androidx.compose.ui.graphics.Color, + onSelect: () -> Unit, + onClose: () -> Unit +) { + Card( + shape = RoundedCornerShape(16.dp), + colors = CardDefaults.cardColors(containerColor = cardBgColor), + border = if (isActive) BorderStroke(2.5.dp, activeBorderColor) else BorderStroke(0.5.dp, mutedColor.copy(alpha = 0.25f)), + elevation = CardDefaults.cardElevation(defaultElevation = if (isActive) 4.dp else 1.dp), + modifier = Modifier + .fillMaxWidth() + .height(216.dp) + .clip(RoundedCornerShape(16.dp)) + .clickable(onClick = onSelect) + .testTag("tab_card_${tab.id}") + ) { + Column(modifier = Modifier.fillMaxSize()) { + // Card Header Bar (Favicon + Title + Close X) + Row( + modifier = Modifier + .fillMaxWidth() + .height(40.dp) + .padding(start = 10.dp, end = 4.dp), + verticalAlignment = Alignment.CenterVertically + ) { + if (tab.isIncognito && tab.isNewTab) { + IncognitoIcon(size = 16.dp, tint = textColor) + } else { + SiteAvatar( + title = tab.title, + url = tab.url, + favicon = tab.favicon, + size = 20.dp + ) + } + Spacer(modifier = Modifier.width(8.dp)) + Text( + text = tab.title.ifBlank { if (tab.isIncognito) "New Incognito tab" else "New tab" }, + style = MaterialTheme.typography.labelMedium, + fontWeight = if (isActive) FontWeight.SemiBold else FontWeight.Medium, + color = textColor, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f) + ) + IconButton( + onClick = onClose, + modifier = Modifier.size(32.dp) + ) { + Icon( + imageVector = Icons.Default.Close, + contentDescription = "Close tab", + tint = mutedColor, + modifier = Modifier.size(16.dp) + ) + } + } + + // Tab Group Chip (if tab belongs to a group) + if (!tab.groupName.isNullOrBlank()) { + val badgeColor = androidx.compose.ui.graphics.Color(tab.groupColor ?: 0xFF8AB4F8L) + Row( + modifier = Modifier + .padding(horizontal = 10.dp) + .padding(bottom = 4.dp) + .clip(RoundedCornerShape(8.dp)) + .background(badgeColor.copy(alpha = 0.22f)) + .padding(horizontal = 8.dp, vertical = 2.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Box( + modifier = Modifier + .size(7.dp) + .clip(CircleShape) + .background(badgeColor) + ) + Spacer(modifier = Modifier.width(5.dp)) + Text( + text = tab.groupName, + style = MaterialTheme.typography.labelSmall, + color = textColor, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + } + + // Tab Thumbnail Body + Box( + modifier = Modifier + .fillMaxSize() + .padding(start = 4.dp, end = 4.dp, bottom = 4.dp) + .clip(RoundedCornerShape(12.dp)) + .background( + if (tab.isIncognito) IncognitoBackground + else MaterialTheme.colorScheme.surfaceContainerLowest + ), + contentAlignment = Alignment.Center + ) { + val thumb = remember(tab.thumbnail) { tab.thumbnail?.asImageBitmap() } + if (thumb != null && !tab.isNewTab) { + Image( + bitmap = thumb, + contentDescription = tab.title, + contentScale = ContentScale.Crop, + alignment = Alignment.TopCenter, + modifier = Modifier.fillMaxSize() + ) + } else if (tab.isIncognito) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + IncognitoIcon(size = 34.dp, tint = mutedColor) + Spacer(modifier = Modifier.height(6.dp)) + Text( + text = if (tab.isNewTab) "Incognito" else UrlUtils.extractShortDomain(tab.url), + style = MaterialTheme.typography.labelSmall, + color = mutedColor, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.padding(horizontal = 8.dp) + ) + } + } else { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + SiteAvatar( + title = tab.title, + url = tab.url, + favicon = tab.favicon, + size = 40.dp + ) + Spacer(modifier = Modifier.height(8.dp)) + Text( + text = if (tab.isNewTab) "Bansify" else UrlUtils.extractShortDomain(tab.url), + style = MaterialTheme.typography.labelSmall, + color = mutedColor, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.padding(horizontal = 8.dp) + ) + } + } + } + } + } +} diff --git a/app/src/main/java/com/bansify/browser/ui/theme/Color.kt b/app/src/main/java/com/bansify/browser/ui/theme/Color.kt new file mode 100644 index 00000000..29f2fe13 --- /dev/null +++ b/app/src/main/java/com/bansify/browser/ui/theme/Color.kt @@ -0,0 +1,64 @@ +package com.bansify.browser.ui.theme + +import androidx.compose.ui.graphics.Color + +// Authentic Modern Chrome Material 3 Expressive Light Palette +val ChromeBluePrimary = Color(0xFF0B57D0) +val ChromeBlueOnPrimary = Color(0xFFFFFFFF) +val ChromeBluePrimaryContainer = Color(0xFFD3E3FD) +val ChromeBlueOnPrimaryContainer = Color(0xFF041E49) + +val ChromeLightBackground = Color(0xFFFFFFFF) +val ChromeLightSurface = Color(0xFFFFFFFF) +val ChromeLightSettingsCanvas = Color(0xFFF0F2F5) +val ChromeLightSurfaceContainerLow = Color(0xFFF4F6FA) +val ChromeLightSurfaceContainer = Color(0xFFECEFF4) +val ChromeLightSurfaceContainerHigh = Color(0xFFE7EDF7) +val ChromeLightSurfaceContainerHighest = Color(0xFFDDE3EC) +val ChromeLightOnSurface = Color(0xFF1F1F1F) +val ChromeLightOnSurfaceVariant = Color(0xFF444746) +val ChromeLightOutline = Color(0xFF747775) +val ChromeLightOutlineVariant = Color(0xFFE0E2E0) + +// Authentic Modern Chrome Material 3 Expressive Dark Palette (matches Chrome Android Dark screenshots) +val ChromeDarkPrimary = Color(0xFFA8C7FA) +val ChromeDarkOnPrimary = Color(0xFF062E6F) +val ChromeDarkPrimaryContainer = Color(0xFF0842A0) +val ChromeDarkOnPrimaryContainer = Color(0xFFD3E3FD) + +val ChromeDarkBackground = Color(0xFF131314) +val ChromeDarkSurface = Color(0xFF1A1B1C) +val ChromeDarkSettingsCanvas = Color(0xFF141416) +val ChromeDarkSurfaceContainerLow = Color(0xFF202124) +val ChromeDarkSurfaceContainer = Color(0xFF2B2C2E) +val ChromeDarkSurfaceContainerHigh = Color(0xFF2D313A) // Cool blue-slate NTP search pill & action pills +val ChromeDarkSurfaceContainerHighest = Color(0xFF38393C) +val ChromeDarkMenuSurface = Color(0xFF2C2D2F) +val ChromeDarkMenuCircle = Color(0xFF1D1E20) +val ChromeDarkOnSurface = Color(0xFFE8EAED) +val ChromeDarkOnSurfaceVariant = Color(0xFFAAB0B6) +val ChromeDarkOutline = Color(0xFF8E918F) +val ChromeDarkOutlineVariant = Color(0xFF3A3C3F) + +// Authentic Chrome Incognito Palette +val IncognitoBackground = Color(0xFF1B1C1E) +val IncognitoSurface = Color(0xFF1B1C1E) +val IncognitoOmnibox = Color(0xFF303134) +val IncognitoSurfaceContainer = Color(0xFF242528) +val IncognitoSurfaceContainerHigh = Color(0xFF383A3E) +val IncognitoPrimary = Color(0xFF8AB4F8) +val IncognitoOnSurface = Color(0xFFE8EAED) +val IncognitoOnSurfaceVariant = Color(0xFF9AA0A6) + +// Chrome Brand Accents +val BrandBlue = Color(0xFF1A73E8) +val BrandRed = Color(0xFFEA4335) +val BrandYellow = Color(0xFFFBBC04) +val BrandGreen = Color(0xFF34A853) +val SecureGreen = Color(0xFF188038) +val SecureGreenDark = Color(0xFF81C995) +val WarningAmber = Color(0xFFE37400) +val DangerRed = Color(0xFFD93025) +val DangerRedDark = Color(0xFFF28B82) +val ChromeLinkBlueDark = Color(0xFF8AB4F8) +val ChromeLinkBlueLight = Color(0xFF0B57D0) diff --git a/app/src/main/java/com/bansify/browser/ui/theme/Theme.kt b/app/src/main/java/com/bansify/browser/ui/theme/Theme.kt new file mode 100644 index 00000000..57a1c745 --- /dev/null +++ b/app/src/main/java/com/bansify/browser/ui/theme/Theme.kt @@ -0,0 +1,132 @@ +package com.bansify.browser.ui.theme + +import android.app.Activity +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.platform.LocalView +import androidx.core.view.WindowCompat +import com.bansify.browser.data.ThemeMode + +val LocalIsDarkBrowserTheme = staticCompositionLocalOf { false } + +private val ChromeLightColorScheme = lightColorScheme( + primary = ChromeBluePrimary, + onPrimary = ChromeBlueOnPrimary, + primaryContainer = ChromeBluePrimaryContainer, + onPrimaryContainer = ChromeBlueOnPrimaryContainer, + secondary = ChromeBluePrimary, + onSecondary = ChromeBlueOnPrimary, + secondaryContainer = ChromeLightSurfaceContainerHigh, + onSecondaryContainer = ChromeLightOnSurface, + background = ChromeLightBackground, + onBackground = ChromeLightOnSurface, + surface = ChromeLightSurface, + onSurface = ChromeLightOnSurface, + surfaceVariant = ChromeLightSurfaceContainer, + onSurfaceVariant = ChromeLightOnSurfaceVariant, + surfaceContainerLowest = ChromeLightSettingsCanvas, + surfaceContainerLow = ChromeLightSurfaceContainerLow, + surfaceContainer = ChromeLightSurfaceContainer, + surfaceContainerHigh = ChromeLightSurfaceContainerHigh, + surfaceContainerHighest = ChromeLightSurfaceContainerHighest, + outline = ChromeLightOutline, + outlineVariant = ChromeLightOutlineVariant, + error = DangerRed +) + +private val ChromeDarkColorScheme = darkColorScheme( + primary = ChromeDarkPrimary, + onPrimary = ChromeDarkOnPrimary, + primaryContainer = ChromeDarkPrimaryContainer, + onPrimaryContainer = ChromeDarkOnPrimaryContainer, + secondary = ChromeDarkPrimary, + onSecondary = ChromeDarkOnPrimary, + secondaryContainer = ChromeDarkSurfaceContainerHigh, + onSecondaryContainer = ChromeDarkOnSurface, + background = ChromeDarkBackground, + onBackground = ChromeDarkOnSurface, + surface = ChromeDarkSurface, + onSurface = ChromeDarkOnSurface, + surfaceVariant = ChromeDarkSurfaceContainer, + onSurfaceVariant = ChromeDarkOnSurfaceVariant, + surfaceContainerLowest = ChromeDarkSettingsCanvas, + surfaceContainerLow = ChromeDarkSurfaceContainerLow, + surfaceContainer = ChromeDarkSurfaceContainer, + surfaceContainerHigh = ChromeDarkSurfaceContainerHigh, + surfaceContainerHighest = ChromeDarkSurfaceContainerHighest, + outline = ChromeDarkOutline, + outlineVariant = ChromeDarkOutlineVariant, + error = DangerRedDark +) + +private val ChromeIncognitoColorScheme = darkColorScheme( + primary = IncognitoPrimary, + onPrimary = ChromeDarkOnPrimary, + primaryContainer = IncognitoSurfaceContainerHigh, + onPrimaryContainer = IncognitoOnSurface, + secondary = IncognitoPrimary, + onSecondary = ChromeDarkOnPrimary, + secondaryContainer = IncognitoOmnibox, + onSecondaryContainer = IncognitoOnSurface, + background = IncognitoBackground, + onBackground = IncognitoOnSurface, + surface = IncognitoSurface, + onSurface = IncognitoOnSurface, + surfaceVariant = IncognitoOmnibox, + onSurfaceVariant = IncognitoOnSurfaceVariant, + surfaceContainerLowest = IncognitoBackground, + surfaceContainerLow = IncognitoSurfaceContainer, + surfaceContainer = IncognitoOmnibox, + surfaceContainerHigh = IncognitoSurfaceContainerHigh, + surfaceContainerHighest = IncognitoSurfaceContainerHigh, + outline = ChromeDarkOutline, + outlineVariant = ChromeDarkOutlineVariant, + error = DangerRedDark +) + +@Composable +fun BansifyBrowserTheme( + themeMode: ThemeMode = ThemeMode.SYSTEM, + isIncognito: Boolean = false, + content: @Composable () -> Unit +) { + val systemDark = isSystemInDarkTheme() + val useDark = when { + isIncognito -> true + themeMode == ThemeMode.DARK -> true + themeMode == ThemeMode.LIGHT -> false + else -> systemDark + } + + val colorScheme = when { + isIncognito -> ChromeIncognitoColorScheme + useDark -> ChromeDarkColorScheme + else -> ChromeLightColorScheme + } + + val view = LocalView.current + if (!view.isInEditMode) { + SideEffect { + val window = (view.context as? Activity)?.window + if (window != null) { + val controller = WindowCompat.getInsetsController(window, view) + controller.isAppearanceLightStatusBars = !useDark + controller.isAppearanceLightNavigationBars = !useDark + } + } + } + + CompositionLocalProvider(LocalIsDarkBrowserTheme provides useDark) { + MaterialTheme( + colorScheme = colorScheme, + typography = Typography, + content = content + ) + } +} diff --git a/app/src/main/java/com/bansify/browser/ui/theme/Type.kt b/app/src/main/java/com/bansify/browser/ui/theme/Type.kt new file mode 100644 index 00000000..7b69722f --- /dev/null +++ b/app/src/main/java/com/bansify/browser/ui/theme/Type.kt @@ -0,0 +1,108 @@ +package com.bansify.browser.ui.theme + +import androidx.compose.material3.Typography +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.Font +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.sp +import com.bansify.browser.R + +val PlusJakartaSansFontFamily = FontFamily( + Font(R.font.plus_jakarta_sans, FontWeight.Normal), + Font(R.font.plus_jakarta_sans, FontWeight.Medium), + Font(R.font.plus_jakarta_sans, FontWeight.SemiBold), + Font(R.font.plus_jakarta_sans, FontWeight.Bold) +) + +val InterFontFamily = FontFamily( + Font(R.font.inter, FontWeight.Normal), + Font(R.font.inter, FontWeight.Medium), + Font(R.font.inter, FontWeight.SemiBold), + Font(R.font.inter, FontWeight.Bold) +) + +val Typography = Typography( + displayLarge = TextStyle( + fontFamily = PlusJakartaSansFontFamily, + fontWeight = FontWeight.Bold, + fontSize = 44.sp, + lineHeight = 52.sp, + letterSpacing = (-1.0).sp + ), + displayMedium = TextStyle( + fontFamily = PlusJakartaSansFontFamily, + fontWeight = FontWeight.Bold, + fontSize = 36.sp, + lineHeight = 44.sp, + letterSpacing = (-0.5).sp + ), + headlineMedium = TextStyle( + fontFamily = PlusJakartaSansFontFamily, + fontWeight = FontWeight.SemiBold, + fontSize = 24.sp, + lineHeight = 32.sp + ), + headlineSmall = TextStyle( + fontFamily = PlusJakartaSansFontFamily, + fontWeight = FontWeight.SemiBold, + fontSize = 20.sp, + lineHeight = 28.sp + ), + titleLarge = TextStyle( + fontFamily = PlusJakartaSansFontFamily, + fontWeight = FontWeight.Medium, + fontSize = 20.sp, + lineHeight = 26.sp + ), + titleMedium = TextStyle( + fontFamily = InterFontFamily, + fontWeight = FontWeight.Medium, + fontSize = 16.sp, + lineHeight = 22.sp, + letterSpacing = 0.1.sp + ), + titleSmall = TextStyle( + fontFamily = InterFontFamily, + fontWeight = FontWeight.Medium, + fontSize = 14.sp, + lineHeight = 20.sp, + letterSpacing = 0.1.sp + ), + bodyLarge = TextStyle( + fontFamily = InterFontFamily, + fontWeight = FontWeight.Normal, + fontSize = 15.sp, + lineHeight = 22.sp + ), + bodyMedium = TextStyle( + fontFamily = InterFontFamily, + fontWeight = FontWeight.Normal, + fontSize = 14.sp, + lineHeight = 20.sp + ), + bodySmall = TextStyle( + fontFamily = InterFontFamily, + fontWeight = FontWeight.Normal, + fontSize = 12.sp, + lineHeight = 16.sp + ), + labelLarge = TextStyle( + fontFamily = InterFontFamily, + fontWeight = FontWeight.Medium, + fontSize = 14.sp, + lineHeight = 20.sp + ), + labelMedium = TextStyle( + fontFamily = InterFontFamily, + fontWeight = FontWeight.Medium, + fontSize = 12.sp, + lineHeight = 16.sp + ), + labelSmall = TextStyle( + fontFamily = InterFontFamily, + fontWeight = FontWeight.Medium, + fontSize = 11.sp, + lineHeight = 14.sp + ) +) diff --git a/app/src/main/java/com/bansify/browser/viewmodel/BrowserViewModel.kt b/app/src/main/java/com/bansify/browser/viewmodel/BrowserViewModel.kt new file mode 100644 index 00000000..6e052580 --- /dev/null +++ b/app/src/main/java/com/bansify/browser/viewmodel/BrowserViewModel.kt @@ -0,0 +1,738 @@ +package com.bansify.browser.viewmodel + +import android.app.Application +import android.graphics.Bitmap +import android.webkit.CookieManager +import android.webkit.WebStorage +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.viewModelScope +import com.bansify.browser.browser.UrlUtils +import com.bansify.browser.data.BansifyAccountProvider +import com.bansify.browser.data.BansifyAccountState +import com.bansify.browser.data.BookmarkEntity +import com.bansify.browser.data.BrowserDatabase +import com.bansify.browser.data.BrowserOverlay +import com.bansify.browser.data.BrowserPreferences +import com.bansify.browser.data.BrowserRepository +import com.bansify.browser.data.BrowserSettings +import com.bansify.browser.data.BrowserTab +import com.bansify.browser.data.ClosedTab +import com.bansify.browser.data.DemoBansifyAccountProvider +import com.bansify.browser.data.DownloadEntity +import com.bansify.browser.data.FindInPageState +import com.bansify.browser.data.HistoryEntity +import com.bansify.browser.data.JsDialogState +import com.bansify.browser.data.ReadingModeContent +import com.bansify.browser.data.SettingsSubScreen +import com.bansify.browser.data.ShortcutEntity +import com.bansify.browser.data.SnackbarEvent +import com.bansify.browser.data.ThirdPartyCookiePolicy +import com.bansify.browser.data.TimeRange +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asSharedFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import java.net.URLEncoder + +class BrowserViewModel(application: Application) : AndroidViewModel(application) { + + private val database = BrowserDatabase.getInstance(application) + private val preferences = BrowserPreferences(application) + private val repository = BrowserRepository(database.browserDao(), preferences) + private val accountProvider: BansifyAccountProvider = DemoBansifyAccountProvider(application) + + private val _isSyncing = MutableStateFlow(false) + + val accountState: StateFlow = combine( + accountProvider.accountState, + _isSyncing + ) { state, syncing -> + state.copy(isSyncing = syncing) + }.stateIn( + scope = viewModelScope, + started = SharingStarted.Eagerly, + initialValue = BansifyAccountState() + ) + + val settings: StateFlow = repository.settings.stateIn( + scope = viewModelScope, + started = SharingStarted.Eagerly, + initialValue = BrowserSettings() + ) + + val bookmarks: StateFlow> = repository.bookmarks.stateIn( + scope = viewModelScope, + started = SharingStarted.WhileSubscribed(5000), + initialValue = emptyList() + ) + + val history: StateFlow> = repository.history.stateIn( + scope = viewModelScope, + started = SharingStarted.WhileSubscribed(5000), + initialValue = emptyList() + ) + + val downloads: StateFlow> = repository.downloads.stateIn( + scope = viewModelScope, + started = SharingStarted.WhileSubscribed(5000), + initialValue = emptyList() + ) + + val shortcuts: StateFlow> = repository.shortcuts.stateIn( + scope = viewModelScope, + started = SharingStarted.WhileSubscribed(5000), + initialValue = emptyList() + ) + + private val initialTab = BrowserTab() + private val _tabs = MutableStateFlow(listOf(initialTab)) + val tabs: StateFlow> = _tabs.asStateFlow() + + private val _activeTabId = MutableStateFlow(initialTab.id) + val activeTabId: StateFlow = _activeTabId.asStateFlow() + + val activeTab: StateFlow = combine(_tabs, _activeTabId) { list, id -> + list.firstOrNull { it.id == id } ?: list.firstOrNull() ?: BrowserTab() + }.stateIn( + scope = viewModelScope, + started = SharingStarted.Eagerly, + initialValue = initialTab + ) + + private val _recentlyClosedTabs = MutableStateFlow>(emptyList()) + val recentlyClosedTabs: StateFlow> = _recentlyClosedTabs.asStateFlow() + + private val _recentSearches = MutableStateFlow>(emptyList()) + val recentSearches: StateFlow> = _recentSearches.asStateFlow() + + private val _overlay = MutableStateFlow(BrowserOverlay.None) + val overlay: StateFlow = _overlay.asStateFlow() + + private val _findInPage = MutableStateFlow(FindInPageState()) + val findInPage: StateFlow = _findInPage.asStateFlow() + + private val _jsDialog = MutableStateFlow(null) + val jsDialog: StateFlow = _jsDialog.asStateFlow() + + private val _showPageInfoSheet = MutableStateFlow(false) + val showPageInfoSheet: StateFlow = _showPageInfoSheet.asStateFlow() + + private val _showTranslateSheet = MutableStateFlow(false) + val showTranslateSheet: StateFlow = _showTranslateSheet.asStateFlow() + + private val _readingModeContent = MutableStateFlow(null) + val readingModeContent: StateFlow = _readingModeContent.asStateFlow() + + private val _editingBookmark = MutableStateFlow(null) + val editingBookmark: StateFlow = _editingBookmark.asStateFlow() + + private val _snackbarEvents = MutableSharedFlow(extraBufferCapacity = 8) + val snackbarEvents = _snackbarEvents.asSharedFlow() + + private val _destroyedTabIds = MutableSharedFlow(extraBufferCapacity = 16) + val destroyedTabIds = _destroyedTabIds.asSharedFlow() + + private val _loadUrlCommands = MutableSharedFlow>(extraBufferCapacity = 8) + val loadUrlCommands = _loadUrlCommands.asSharedFlow() + + private var groupCounter = 1 + private val groupColors = listOf( + 0xFF8AB4F8L, + 0xFFF28B82L, + 0xFFFDD663L, + 0xFF81C995L, + 0xFFC58AF9L, + 0xFF78D9ECL + ) + + init { + viewModelScope.launch { + repository.ensureDefaultShortcuts() + val saved = repository.loadSavedTabs() + if (saved.isNotEmpty()) { + val restored = saved.map { + BrowserTab( + id = it.tabId, + url = it.url, + title = it.title, + isIncognito = false, + isDesktopSite = it.isDesktopSite, + isSecure = it.url.startsWith("https://", ignoreCase = true), + lastAccessedAt = it.lastAccessedAt + ) + } + _tabs.value = restored + _activeTabId.value = restored.last().id + } + } + } + + // --- Navigation & Tab Operations --- + + fun openUrlInActiveTab(rawInput: String) { + val trimmed = rawInput.trim() + val currentSettings = settings.value + val tab = activeTab.value + + // Record query in recent searches if it's a search query (not a direct URL) in non-Incognito mode + if (!tab.isIncognito && + trimmed.isNotEmpty() && + trimmed != BrowserTab.NEW_TAB_URL && + !trimmed.startsWith("http://", ignoreCase = true) && + !trimmed.startsWith("https://", ignoreCase = true) && + !trimmed.contains('.') + ) { + _recentSearches.update { prev -> + (listOf(trimmed) + prev.filterNot { it.equals(trimmed, ignoreCase = true) }).take(15) + } + } + + val resolved = UrlUtils.resolveInputToUrl( + rawInput = trimmed, + searchEngine = currentSettings.searchEngine, + httpsFirst = currentSettings.httpsFirstEnabled + ) + updateTab(tab.id) { + it.copy( + url = resolved, + title = if (resolved == BrowserTab.NEW_TAB_URL) "New tab" else UrlUtils.extractDisplayHost(resolved), + isSecure = resolved.startsWith("https://", ignoreCase = true), + isLoading = resolved != BrowserTab.NEW_TAB_URL, + progress = if (resolved != BrowserTab.NEW_TAB_URL) 10 else 0, + lastAccessedAt = System.currentTimeMillis() + ) + } + _overlay.value = BrowserOverlay.None + _findInPage.value = FindInPageState() + _readingModeContent.value = null + if (resolved != BrowserTab.NEW_TAB_URL) { + _loadUrlCommands.tryEmit(tab.id to resolved) + } + persistNormalTabs() + } + + fun navigateHome() { + val currentSettings = settings.value + val target = if (currentSettings.useCustomHomepage && currentSettings.customHomepageUrl.isNotBlank()) { + currentSettings.customHomepageUrl + } else { + BrowserTab.NEW_TAB_URL + } + openUrlInActiveTab(target) + } + + fun createNewTab(url: String = BrowserTab.NEW_TAB_URL, isIncognito: Boolean = false) { + val currentSettings = settings.value + val resolved = if (url == BrowserTab.NEW_TAB_URL) { + BrowserTab.NEW_TAB_URL + } else { + UrlUtils.resolveInputToUrl(url, currentSettings.searchEngine, currentSettings.httpsFirstEnabled) + } + val newTab = BrowserTab( + url = resolved, + title = if (resolved == BrowserTab.NEW_TAB_URL) { + if (isIncognito) "New Incognito tab" else "New tab" + } else { + UrlUtils.extractDisplayHost(resolved) + }, + isIncognito = isIncognito, + isDesktopSite = currentSettings.defaultDesktopSite, + isSecure = resolved.startsWith("https://", ignoreCase = true), + isLoading = resolved != BrowserTab.NEW_TAB_URL, + progress = if (resolved != BrowserTab.NEW_TAB_URL) 10 else 0 + ) + _tabs.update { it + newTab } + _activeTabId.value = newTab.id + _overlay.value = BrowserOverlay.None + _findInPage.value = FindInPageState() + _readingModeContent.value = null + if (resolved != BrowserTab.NEW_TAB_URL) { + _loadUrlCommands.tryEmit(newTab.id to resolved) + } + persistNormalTabs() + } + + fun addActiveTabToNewGroup() { + val tab = activeTab.value + val color = groupColors[(groupCounter - 1) % groupColors.size] + val groupLabel = "Group $groupCounter" + groupCounter++ + updateTab(tab.id) { + it.copy(groupName = groupLabel, groupColor = color) + } + showSnackbar( + message = "Added to $groupLabel", + actionLabel = "View tabs", + onAction = { openOverlay(BrowserOverlay.TabSwitcher(showIncognito = tab.isIncognito)) } + ) + } + + fun removeTabFromGroup(tabId: String) { + updateTab(tabId) { it.copy(groupName = null, groupColor = null) } + } + + fun selectTab(tabId: String) { + if (_tabs.value.any { it.id == tabId }) { + _activeTabId.value = tabId + updateTab(tabId) { it.copy(lastAccessedAt = System.currentTimeMillis()) } + _overlay.value = BrowserOverlay.None + _findInPage.value = FindInPageState() + _readingModeContent.value = null + persistNormalTabs() + } + } + + fun closeTab(tabId: String, allowUndo: Boolean = true) { + val currentList = _tabs.value + val target = currentList.firstOrNull { it.id == tabId } ?: return + val remaining = currentList.filterNot { it.id == tabId } + + if (!target.isIncognito && !target.isNewTab) { + _recentlyClosedTabs.update { list -> + (listOf(ClosedTab(title = target.title, url = target.url)) + list).take(25) + } + } + + _destroyedTabIds.tryEmit(tabId) + + if (remaining.isEmpty()) { + val replacement = BrowserTab(isIncognito = false) + _tabs.value = listOf(replacement) + _activeTabId.value = replacement.id + } else { + _tabs.value = remaining + if (_activeTabId.value == tabId) { + val sameMode = remaining.lastOrNull { it.isIncognito == target.isIncognito } + _activeTabId.value = (sameMode ?: remaining.last()).id + } + } + + if (allowUndo && !target.isNewTab && !target.isIncognito) { + showSnackbar( + message = "Closed ${target.title.take(28)}", + actionLabel = "Undo", + onAction = { createNewTab(url = target.url, isIncognito = false) } + ) + } + persistNormalTabs() + } + + fun closeAllTabs(incognitoOnly: Boolean) { + val currentList = _tabs.value + val toClose = currentList.filter { it.isIncognito == incognitoOnly } + toClose.forEach { tab -> + if (!tab.isIncognito && !tab.isNewTab) { + _recentlyClosedTabs.update { list -> + (listOf(ClosedTab(title = tab.title, url = tab.url)) + list).take(25) + } + } + _destroyedTabIds.tryEmit(tab.id) + } + + val remaining = currentList.filter { it.isIncognito != incognitoOnly } + if (remaining.isEmpty()) { + val fresh = BrowserTab(isIncognito = false) + _tabs.value = listOf(fresh) + _activeTabId.value = fresh.id + _overlay.value = BrowserOverlay.None + } else { + _tabs.value = remaining + if (remaining.none { it.id == _activeTabId.value }) { + _activeTabId.value = remaining.last().id + } + } + + showSnackbar(if (incognitoOnly) "Closed all Incognito tabs" else "Closed all tabs") + persistNormalTabs() + } + + fun toggleDesktopSiteForActiveTab(): Boolean { + val tab = activeTab.value + val newValue = !tab.isDesktopSite + updateTab(tab.id) { it.copy(isDesktopSite = newValue) } + persistNormalTabs() + return newValue + } + + // --- Translate & Reading Mode --- + + fun setTranslateSheetVisible(visible: Boolean) { + _showTranslateSheet.value = visible + } + + fun translateActivePage(targetLangCode: String, targetLangName: String) { + val tab = activeTab.value + _showTranslateSheet.value = false + if (tab.isNewTab) return + val encoded = URLEncoder.encode(tab.url, "UTF-8") + val translateUrl = "https://translate.google.com/translate?sl=auto&tl=$targetLangCode&u=$encoded" + openUrlInActiveTab(translateUrl) + showSnackbar("Translating page to $targetLangName") + } + + fun showReadingMode(content: ReadingModeContent) { + _readingModeContent.value = content + } + + fun closeReadingMode() { + _readingModeContent.value = null + } + + // --- WebView Callback Handlers --- + + fun onWebPageStarted(tabId: String, url: String) { + updateTab(tabId) { + it.copy( + url = url, + isSecure = url.startsWith("https://", ignoreCase = true), + isLoading = true, + progress = 15 + ) + } + } + + fun onWebPageFinished( + tabId: String, + url: String, + title: String, + canGoBack: Boolean, + canGoForward: Boolean + ) { + val tab = _tabs.value.firstOrNull { it.id == tabId } + updateTab(tabId) { + it.copy( + url = url, + title = title.ifBlank { UrlUtils.extractDisplayHost(url) }, + isSecure = url.startsWith("https://", ignoreCase = true), + isLoading = false, + progress = 100, + canGoBack = canGoBack, + canGoForward = canGoForward + ) + } + if (tab != null && !tab.isIncognito) { + viewModelScope.launch { + repository.recordHistory(title, url) + } + persistNormalTabs() + } + } + + fun onWebProgressChanged(tabId: String, progress: Int) { + updateTab(tabId) { + it.copy( + progress = progress, + isLoading = progress in 1..99 + ) + } + } + + fun onWebTitleReceived(tabId: String, title: String) { + updateTab(tabId) { it.copy(title = title) } + } + + fun onWebFaviconReceived(tabId: String, icon: Bitmap?) { + if (icon != null) { + updateTab(tabId) { it.copy(favicon = icon) } + } + } + + fun onThumbnailCaptured(tabId: String, bitmap: Bitmap) { + updateTab(tabId) { it.copy(thumbnail = bitmap) } + } + + fun onDownloadRecorded( + fileName: String, + url: String, + mimeType: String, + sizeBytes: Long, + localPath: String + ) { + viewModelScope.launch { + repository.insertDownload( + DownloadEntity( + fileName = fileName, + url = url, + mimeType = mimeType, + sizeBytes = sizeBytes, + category = UrlUtils.inferDownloadCategory(fileName, mimeType), + status = "Completed", + localPath = localPath + ) + ) + showSnackbar( + message = "Downloaded $fileName", + actionLabel = "Open", + onAction = { openOverlay(BrowserOverlay.Downloads) } + ) + } + } + + // --- Overlays & UI States --- + + fun openOverlay(overlay: BrowserOverlay) { + _overlay.value = overlay + } + + fun closeOverlay() { + _overlay.value = BrowserOverlay.None + } + + fun navigateSettingsSubScreen(subScreen: SettingsSubScreen) { + _overlay.value = BrowserOverlay.Settings(subScreen) + } + + fun navigateSettingsBack() { + val current = _overlay.value + if (current is BrowserOverlay.Settings) { + when (current.subScreen) { + SettingsSubScreen.MAIN -> _overlay.value = BrowserOverlay.None + SettingsSubScreen.SAFE_BROWSING, + SettingsSubScreen.THIRD_PARTY_COOKIES -> { + _overlay.value = BrowserOverlay.Settings(SettingsSubScreen.PRIVACY_SECURITY) + } + SettingsSubScreen.THEME, + SettingsSubScreen.TOOLBAR_SHORTCUT -> { + _overlay.value = BrowserOverlay.Settings(SettingsSubScreen.APPEARANCE) + } + else -> _overlay.value = BrowserOverlay.Settings(SettingsSubScreen.MAIN) + } + } else { + _overlay.value = BrowserOverlay.None + } + } + + fun setPageInfoVisible(visible: Boolean) { + _showPageInfoSheet.value = visible + } + + fun setFindInPageActive(active: Boolean) { + _findInPage.value = if (active) FindInPageState(isActive = true) else FindInPageState() + } + + fun updateFindQuery(query: String) { + _findInPage.update { it.copy(query = query) } + } + + fun updateFindResults(activeOrdinal: Int, total: Int) { + _findInPage.update { it.copy(activeMatchOrdinal = activeOrdinal, numberOfMatches = total) } + } + + fun showJsDialog(dialog: JsDialogState?) { + _jsDialog.value = dialog + } + + fun showSnackbar(message: String, actionLabel: String? = null, onAction: (() -> Unit)? = null) { + _snackbarEvents.tryEmit(SnackbarEvent(message, actionLabel, onAction)) + } + + // --- Bookmarks --- + + fun toggleBookmarkForActiveTab() { + val tab = activeTab.value + if (tab.isNewTab) return + viewModelScope.launch { + val existing = repository.getBookmarkByUrl(tab.url) + if (existing != null) { + repository.deleteBookmark(existing.id) + showSnackbar("Bookmark removed") + } else { + val id = repository.addBookmark(tab.title, tab.url) + val inserted = BookmarkEntity(id = id, title = tab.title, url = tab.url) + showSnackbar( + message = "Bookmarked", + actionLabel = "Edit", + onAction = { _editingBookmark.value = inserted } + ) + } + } + } + + fun startEditingBookmark(bookmark: BookmarkEntity?) { + _editingBookmark.value = bookmark + } + + fun saveBookmark(id: Long, title: String, url: String, folder: String) { + viewModelScope.launch { + if (id == 0L) { + repository.addBookmark(title, url, folder) + showSnackbar("Bookmark added") + } else { + repository.updateBookmark(BookmarkEntity(id = id, title = title, url = url, folder = folder)) + showSnackbar("Bookmark updated") + } + _editingBookmark.value = null + } + } + + fun deleteBookmark(id: Long) { + viewModelScope.launch { + repository.deleteBookmark(id) + showSnackbar("Bookmark deleted") + } + } + + // --- History & Downloads & Shortcuts --- + + fun deleteHistoryItem(id: Long) { + viewModelScope.launch { + repository.deleteHistoryItem(id) + } + } + + fun deleteDownload(id: Long) { + viewModelScope.launch { + repository.deleteDownload(id) + showSnackbar("Download removed") + } + } + + fun addShortcut(title: String, url: String) { + val normalized = if (url.startsWith("http://") || url.startsWith("https://")) url else "https://$url" + viewModelScope.launch { + repository.addShortcut( + title = title.ifBlank { UrlUtils.extractDisplayHost(normalized) }, + url = normalized, + accentColor = UrlUtils.colorForDomain(normalized) + ) + showSnackbar("Shortcut added") + } + } + + fun updateShortcut(shortcut: ShortcutEntity) { + viewModelScope.launch { + repository.updateShortcut(shortcut) + showSnackbar("Shortcut updated") + } + } + + fun deleteShortcut(id: Long) { + viewModelScope.launch { + repository.deleteShortcut(id) + showSnackbar("Shortcut removed") + } + } + + // --- Settings & Clear Browsing Data --- + + fun updateSettings(transform: (BrowserSettings) -> BrowserSettings) { + viewModelScope.launch { + repository.updateSettings(transform) + } + } + + fun toggleIncognitoBlockThirdPartyCookies(block: Boolean) { + updateSettings { + it.copy( + thirdPartyCookiePolicy = if (block) { + ThirdPartyCookiePolicy.BLOCK_INCOGNITO + } else { + ThirdPartyCookiePolicy.ALLOW + } + ) + } + } + + fun clearBrowsingData( + timeRange: TimeRange, + clearHistory: Boolean, + clearCookies: Boolean, + clearCache: Boolean, + clearSiteData: Boolean, + closeOpenTabs: Boolean, + onClearWebViewCache: () -> Unit + ) { + viewModelScope.launch { + if (clearHistory) { + repository.clearHistory(timeRange) + _recentSearches.value = emptyList() + } + if (clearCookies) { + CookieManager.getInstance().removeAllCookies(null) + CookieManager.getInstance().flush() + } + if (clearCache) { + onClearWebViewCache() + } + if (clearSiteData) { + WebStorage.getInstance().deleteAllData() + } + if (closeOpenTabs) { + closeAllTabs(incognitoOnly = false) + } + _overlay.value = BrowserOverlay.None + showSnackbar("Cleared Bansify browsing data") + } + } + + fun clearSiteDataForActiveSite(onClearWebViewCache: () -> Unit) { + CookieManager.getInstance().removeAllCookies(null) + CookieManager.getInstance().flush() + WebStorage.getInstance().deleteAllData() + onClearWebViewCache() + _showPageInfoSheet.value = false + showSnackbar("Cookies and site data cleared") + } + + // --- Bansify Account & Sync --- + + fun signInBansifyAccount(displayName: String, email: String, avatarColorHex: Long = 0xFF1A73E8L) { + viewModelScope.launch { + accountProvider.signIn(displayName, email, avatarColorHex) + showSnackbar("Signed in to Bansify Account (Demo)") + } + } + + fun updateBansifyProfile(displayName: String, email: String, avatarColorHex: Long) { + viewModelScope.launch { + accountProvider.updateProfile(displayName, email, avatarColorHex) + showSnackbar("Bansify profile updated") + } + } + + fun signOutBansifyAccount() { + viewModelScope.launch { + accountProvider.signOut() + showSnackbar("Signed out of Bansify Account") + } + } + + fun updateBansifySync(transform: (BansifyAccountState) -> BansifyAccountState) { + viewModelScope.launch { + accountProvider.updateSyncPreferences(transform) + } + } + + fun triggerManualSync() { + if (!accountState.value.isSignedIn || _isSyncing.value) return + viewModelScope.launch { + _isSyncing.value = true + try { + accountProvider.performSync() + val activeCount = accountState.value.activeSyncCategoriesCount + showSnackbar("Bansify sync complete ($activeCount categories synced)") + } finally { + _isSyncing.value = false + } + } + } + + private fun updateTab(tabId: String, transform: (BrowserTab) -> BrowserTab) { + _tabs.update { list -> + list.map { if (it.id == tabId) transform(it) else it } + } + } + + private fun persistNormalTabs() { + val current = _tabs.value + viewModelScope.launch { + repository.persistOpenTabs(current) + } + } +} diff --git a/app/src/main/java/com/bansify/internet/BrowserApp.kt b/app/src/main/java/com/bansify/internet/BrowserApp.kt deleted file mode 100644 index a9355a8e..00000000 --- a/app/src/main/java/com/bansify/internet/BrowserApp.kt +++ /dev/null @@ -1,182 +0,0 @@ -package com.bansify.internet - -import android.app.Activity -import android.app.Application -import android.app.NotificationChannel -import android.app.NotificationManager -import android.content.Context -import android.content.Intent -import android.os.Build -import android.os.Bundle -import android.os.SystemClock -import android.util.Log -import androidx.appcompat.app.AppCompatDelegate -import androidx.lifecycle.DefaultLifecycleObserver -import androidx.lifecycle.LifecycleOwner -import androidx.lifecycle.ProcessLifecycleOwner -import com.bansify.internet.activity.IncognitoModeMainActivity -import com.bansify.internet.activity.main.MainActivity -import com.bansify.internet.model.HostConfig -import com.bansify.internet.service.keepalive.BrowserKeepAliveService -import com.bansify.internet.singleton.AppDatabase -import com.bansify.internet.singleton.FaviconsPool -import com.bansify.internet.utils.activemodel.ActiveModelsRepository -import com.bansify.internet.webengine.webview.WebViewWebEngine -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.launch -import java.lang.ref.WeakReference -import java.net.CookieHandler -import java.net.CookieManager -import java.util.concurrent.ArrayBlockingQueue -import java.util.concurrent.ThreadPoolExecutor -import java.util.concurrent.TimeUnit -import kotlin.system.exitProcess - -/** - * Created by PDT on 09.09.2016. - */ -class BrowserApp : Application(), Application.ActivityLifecycleCallbacks { - companion object { - lateinit var instance: BrowserApp - const val CHANNEL_ID_DOWNLOADS: String = "downloads" - const val MAIN_PREFS_NAME = "main.xml" - val TAG = BrowserApp::class.simpleName - } - - lateinit var threadPool: ThreadPoolExecutor - private set - - var needToExitProcessAfterMainActivityFinish = false - var needRestartMainActivityAfterExitingProcess = false - - var isAppInForeground: Boolean = false - private set - private var currentActivityRef: WeakReference? = null - - val currentActivity: Activity? - get() = currentActivityRef?.get() - - override fun onCreate() { - Log.i(TAG, "onCreate") - super.onCreate() - - instance = this - - AppContext.init(this, Config(getSharedPreferences(MAIN_PREFS_NAME, MODE_MULTI_PROCESS))) - // Must run before the first tab is restored: it decides how many WebViews may stay live. - AppContext.provideConfig().applyMemoryAwareDefaults(this) - - val maxThreadsInOfflineJobsPool = Runtime.getRuntime().availableProcessors() - threadPool = ThreadPoolExecutor(0, maxThreadsInOfflineJobsPool, 20, - TimeUnit.SECONDS, ArrayBlockingQueue(maxThreadsInOfflineJobsPool)) - - initWebEngineStuff() - - initNotificationChannels() - - ActiveModelsRepository.init(this) - - when (AppContext.provideConfig().theme.value) { - Config.Theme.BLACK_AMOLED, - Config.Theme.BLACK_CHARCOAL, - Config.Theme.BLACK_MIDNIGHT -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) - Config.Theme.WHITE_PURE, - Config.Theme.WHITE_WARM, - Config.Theme.WHITE_COOL -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) - else -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) - } - - registerActivityLifecycleCallbacks(this) - - ProcessLifecycleOwner.get().lifecycle.addObserver(object : DefaultLifecycleObserver { - override fun onStart(owner: LifecycleOwner) { - isAppInForeground = true - Log.d(TAG, "Process entered foreground -> stopping keep-alive service") - BrowserKeepAliveService.stop(this@BrowserApp) - } - - override fun onStop(owner: LifecycleOwner) { - isAppInForeground = false - Log.d(TAG, "Process entered background -> starting keep-alive service") - BrowserKeepAliveService.start(this@BrowserApp) - } - }) - } - - fun isCurrentSessionIncognito(): Boolean { - val act = currentActivity - if (act is IncognitoModeMainActivity) return true - if (act is MainActivity) { - if (act.config.incognitoMode) return true - if (act.tabsModel.currentTab.value?.incognito == true) return true - } - return AppContext.provideConfig().incognitoMode - } - - @Suppress("KotlinConstantConditions") - private fun initWebEngineStuff() { - Log.i(TAG, "initWebEngineStuff") - - try { - Class.forName("com.bansify.internet.webengine.webview.WebViewWebEngine") - } catch (e: ClassNotFoundException) { - throw AssertionError(e) // WebViews are always available - } - - val cookieManager = CookieManager() - CookieHandler.setDefault(cookieManager) - FaviconsPool.databaseDelegate = object : FaviconsPool.DatabaseDelegate { - override fun findByHostName(host: String): HostConfig? { - return AppDatabase.db.hostsDao().findByHostName(host) - } - - override suspend fun update(hostConfig: HostConfig) { - AppDatabase.db.hostsDao().update(hostConfig) - } - - override suspend fun insert(newHostConfig: HostConfig) { - AppDatabase.db.hostsDao().insert(newHostConfig) - } - } - } - - private fun initNotificationChannels() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - val name = getString(R.string.downloads) - val descriptionText = getString(R.string.downloads_notifications_description) - val importance = NotificationManager.IMPORTANCE_DEFAULT - val channel = NotificationChannel(CHANNEL_ID_DOWNLOADS, name, importance) - channel.description = descriptionText - val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager - notificationManager.createNotificationChannel(channel) - } - } - - override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {} - override fun onActivityStarted(activity: Activity) {} - override fun onActivityResumed(activity: Activity) { - currentActivityRef = WeakReference(activity) - } - override fun onActivityPaused(activity: Activity) { - if (currentActivityRef?.get() === activity) { - currentActivityRef = null - } - } - override fun onActivityStopped(activity: Activity) {} - override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {} - - override fun onActivityDestroyed(activity: Activity) { - Log.i(TAG, "onActivityDestroyed: " + activity.javaClass.simpleName) - if (needToExitProcessAfterMainActivityFinish && activity is MainActivity) { - Log.i(TAG, "onActivityDestroyed: exiting process") - if (needRestartMainActivityAfterExitingProcess) { - Log.i(TAG, "onActivityDestroyed: restarting main activity") - val intent = Intent(this@BrowserApp, MainActivity::class.java) - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) - startActivity(intent) - } - exitProcess(0) - } - } -} diff --git a/app/src/main/java/com/bansify/internet/activity/IncognitoModeMainActivity.kt b/app/src/main/java/com/bansify/internet/activity/IncognitoModeMainActivity.kt deleted file mode 100644 index 805948a4..00000000 --- a/app/src/main/java/com/bansify/internet/activity/IncognitoModeMainActivity.kt +++ /dev/null @@ -1,44 +0,0 @@ -package com.bansify.internet.activity - -import android.app.AlertDialog -import android.os.Bundle -import android.util.Log -import com.bansify.internet.R -import com.bansify.internet.BrowserApp -import com.bansify.internet.activity.main.MainActivity - -//Same as MainActivity but runs in separate process -//and store all WebView data separately -class IncognitoModeMainActivity: MainActivity() { - companion object { - private val TAG = MainActivity::class.java.simpleName - } - - override fun onCreate(savedInstanceState: Bundle?) { - Log.d(TAG, "onCreate") - super.onCreate(savedInstanceState) - if (!config.incognitoModeHintSuppress) { - showIncognitoModeHintDialog() - } - } - - override fun onDestroy() { - if (isFinishing) { - BrowserApp.instance.needToExitProcessAfterMainActivityFinish = true - } - super.onDestroy() - } - - private fun showIncognitoModeHintDialog() { - AlertDialog.Builder(this) - .setTitle(R.string.incognito_mode) - .setIcon(R.drawable.ic_incognito) - .setMessage(R.string.incognito_mode_hint) - .setPositiveButton(android.R.string.ok) { dialog, _ -> dialog.dismiss() } - .setNeutralButton(R.string.don_t_show_again) { dialog, _ -> - config.incognitoModeHintSuppress = true - dialog.dismiss() - } - .show() - } -} \ No newline at end of file diff --git a/app/src/main/java/com/bansify/internet/activity/downloads/ActiveDownloadsModel.kt b/app/src/main/java/com/bansify/internet/activity/downloads/ActiveDownloadsModel.kt deleted file mode 100644 index 8454aea1..00000000 --- a/app/src/main/java/com/bansify/internet/activity/downloads/ActiveDownloadsModel.kt +++ /dev/null @@ -1,81 +0,0 @@ -package com.bansify.internet.activity.downloads - -import android.net.Uri -import android.os.Build -import android.util.Log -import com.bansify.internet.BrowserApp -import com.bansify.internet.model.Download -import com.bansify.internet.service.downloads.DownloadTask -import com.bansify.internet.service.downloads.FileDownloadTask -import com.bansify.internet.singleton.AppDatabase -import com.bansify.internet.utils.observable.ObservableList -import com.bansify.internet.utils.activemodel.ActiveModel -import java.io.File - -class ActiveDownloadsModel: ActiveModel() { - val activeDownloads = ObservableList() - private val listeners = java.util.ArrayList() - - interface Listener { - fun onDownloadUpdated(downloadInfo: Download) - fun onDownloadError(downloadInfo: Download, responseCode: Int, responseMessage: String) - fun onAllDownloadsComplete() - } - - suspend fun deleteItem(download: Download) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { - val contentResolver = BrowserApp.instance.contentResolver - val rowsDeleted = try { - contentResolver.delete(Uri.parse(download.filepath), null) - } catch (e: Exception) { - Log.w(FileDownloadTask.TAG, "Failed to delete file from MediaStore", e) - 0 - } - if (rowsDeleted < 1) { - Log.e(FileDownloadTask.TAG, "Failed to delete file from MediaStore") - } - } else { - File(download.filepath).delete() - } - AppDatabase.db.downloadDao().delete(download) - } - - fun registerListener(listener: Listener) { - listeners.add(listener) - } - - fun unregisterListener(listener: Listener) { - listeners.remove(listener) - } - - fun cancelDownload(download: Download) { - for (i in activeDownloads.indices) { - val task = activeDownloads[i] - if (task.downloadInfo.id == download.id) { - task.downloadInfo.cancelled = true - break - } - } - } - - fun notifyListenersAboutError(task: DownloadTask, responseCode: Int, responseMessage: String) { - for (i in listeners.indices) { - listeners[i].onDownloadError(task.downloadInfo, responseCode, responseMessage) - } - } - - fun notifyListenersAboutDownloadProgress(task: DownloadTask) { - for (i in listeners.indices) { - listeners[i].onDownloadUpdated(task.downloadInfo) - } - } - - fun onDownloadEnded(task: DownloadTask) { - activeDownloads.remove(task) - if (activeDownloads.isEmpty()) { - for (i in listeners.indices) { - listeners[i].onAllDownloadsComplete() - } - } - } -} \ No newline at end of file diff --git a/app/src/main/java/com/bansify/internet/activity/downloads/DownloadListAdapter.kt b/app/src/main/java/com/bansify/internet/activity/downloads/DownloadListAdapter.kt deleted file mode 100644 index 5dc1cb13..00000000 --- a/app/src/main/java/com/bansify/internet/activity/downloads/DownloadListAdapter.kt +++ /dev/null @@ -1,82 +0,0 @@ -package com.bansify.internet.activity.downloads - -import android.view.View -import android.view.ViewGroup -import android.widget.BaseAdapter - -import com.bansify.internet.model.Download -import com.bansify.internet.utils.Utils - -import java.util.ArrayList - -import de.halfbit.pinnedsection.PinnedSectionListView - -/** - * Created by PDT on 24.01.2017. - */ - -class DownloadListAdapter(private val downloadsActivity: DownloadsActivity) : BaseAdapter(), PinnedSectionListView.PinnedSectionListAdapter { - private val downloads = ArrayList() - private var lastHeaderDate: Long = -1 - var realCount: Long = 0 - private set - - fun addItems(items: List) { - if (items.isEmpty()) { - return - } - for (download in items) { - if (!Utils.isSameDate(download.time, lastHeaderDate)) { - lastHeaderDate = download.time - this.downloads.add(Download.createDateHeaderInfo(download.time)) - } - this.downloads.add(download) - realCount++ - } - notifyDataSetChanged() - } - - override fun getCount(): Int { - return downloads.size - } - - override fun getItem(i: Int): Any { - return downloads[i] - } - - override fun getItemId(i: Int): Long { - return i.toLong() - } - - override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { - val hiv = if (convertView != null) { - convertView as DownloadListItemView - } else { - DownloadListItemView(downloadsActivity, getItemViewType(position)) - } - hiv.download = downloads[position] - return hiv - } - - override fun getViewTypeCount(): Int { - return 2 - } - - override fun getItemViewType(position: Int): Int { - return if (downloads[position].isDateHeader) VIEW_TYPE_HEADER else VIEW_TYPE_DOWNLOAD_ITEM - } - - override fun isItemViewTypePinned(viewType: Int): Boolean { - return viewType == VIEW_TYPE_HEADER - } - - fun remove(download: Download) { - downloads.remove(download) - notifyDataSetChanged() - } - - companion object { - val VIEW_TYPE_DOWNLOAD_ITEM = 0 - val VIEW_TYPE_HEADER = 1 - } -} diff --git a/app/src/main/java/com/bansify/internet/activity/downloads/DownloadListItemView.kt b/app/src/main/java/com/bansify/internet/activity/downloads/DownloadListItemView.kt deleted file mode 100644 index fbbef918..00000000 --- a/app/src/main/java/com/bansify/internet/activity/downloads/DownloadListItemView.kt +++ /dev/null @@ -1,131 +0,0 @@ -package com.bansify.internet.activity.downloads - -import android.annotation.SuppressLint -import android.graphics.Color -import android.text.format.Formatter -import android.view.LayoutInflater -import android.view.View -import android.widget.FrameLayout -import android.widget.ProgressBar -import android.widget.TextView -import com.bansify.internet.R -import com.bansify.internet.model.Download -import java.text.SimpleDateFormat -import java.util.Date - -/** - * Created by PDT on 24.01.2017. - */ - -class DownloadListItemView(private val downloadsActivity: DownloadsActivity, private val viewType: Int) : FrameLayout(downloadsActivity), ActiveDownloadsModel.Listener { - private var defaultTextColor: Int = 0 - private var tvDate: TextView? = null - private var tvTitle: TextView? = null - private var tvURL: TextView? = null - private var tvTime: TextView? = null - private var progressBar: ProgressBar? = null - private var progressBar2: ProgressBar? = null - private var tvSize: TextView? = null - var download: Download? = null - set(value) { - field = value - if (field == null) return - when (viewType) { - DownloadListAdapter.VIEW_TYPE_HEADER -> { - val df = SimpleDateFormat.getDateInstance() - tvDate!!.text = df.format(Date(field!!.time)) - } - DownloadListAdapter.VIEW_TYPE_DOWNLOAD_ITEM -> { - tvTitle!!.text = field!!.filename - tvURL!!.text = field!!.url - val sdf = SimpleDateFormat("HH:mm") - tvTime!!.text = sdf.format(Date(field!!.time)) - updateUI(field!!) - } - } - } - - init { - LayoutInflater.from(downloadsActivity).inflate( - if (viewType == DownloadListAdapter.VIEW_TYPE_HEADER) - R.layout.view_history_header_item - else - R.layout.view_download_item, this) - when (viewType) { - DownloadListAdapter.VIEW_TYPE_HEADER -> tvDate = findViewById(R.id.tvDate) - DownloadListAdapter.VIEW_TYPE_DOWNLOAD_ITEM -> { - tvTitle = findViewById(R.id.tvTitle) - tvURL = findViewById(R.id.tvURL) - tvTime = findViewById(R.id.tvTime) - tvSize = findViewById(R.id.tvSize) - defaultTextColor = tvSize!!.currentTextColor - progressBar = findViewById(R.id.progressBar) - progressBar2 = findViewById(R.id.progressBar2) - } - } - } - - @SuppressLint("SetTextI18n") - private fun updateUI(download: Download) { - if (tvTitle?.text != download.filename) { - tvTitle?.text = download.filename - } - this.download?.size = download.size - this.download?.bytesReceived = download.bytesReceived - tvSize!!.setTextColor(defaultTextColor) - if (download.size == Download.CANCELLED_MARK) { - tvSize!!.setText(R.string.cancelled) - progressBar!!.visibility = View.INVISIBLE - progressBar2!!.visibility = View.GONE - } else if (download.size == Download.BROKEN_MARK) { - tvSize!!.setText(R.string.error) - tvSize!!.setTextColor(Color.RED) - progressBar!!.visibility = View.INVISIBLE - progressBar2!!.visibility = View.GONE - } else if (download.size == 0L) { - tvSize!!.text = Formatter.formatShortFileSize(context, download.bytesReceived) - progressBar!!.visibility = View.INVISIBLE - progressBar2!!.visibility = View.VISIBLE - } else if (download.size > 0) { - if (download.size == download.bytesReceived) { - tvSize!!.text = Formatter.formatShortFileSize(context, download.size) - progressBar!!.visibility = View.INVISIBLE - progressBar2!!.visibility = View.GONE - } else { - tvSize!!.text = Formatter.formatShortFileSize(context, download.bytesReceived) + "/\n" + - Formatter.formatShortFileSize(context, download.size) - progressBar!!.visibility = View.VISIBLE - progressBar2!!.visibility = View.GONE - if (download.bytesReceived > download.size) { - download.size = 0L//wrong value from server - ignore it for future updates - } else { - progressBar!!.progress = (download.bytesReceived * 100 / download.size).toInt() - } - } - } - } - - override fun onAttachedToWindow() { - super.onAttachedToWindow() - downloadsActivity.registerListener(this) - } - - override fun onDetachedFromWindow() { - downloadsActivity.unregisterListener(this) - super.onDetachedFromWindow() - } - - override fun onDownloadUpdated(downloadInfo: Download) { - if (downloadInfo.id == this.download?.id) { - updateUI(downloadInfo) - } - } - - override fun onDownloadError(downloadInfo: Download, responseCode: Int, responseMessage: String) { - if (downloadInfo.id == this.download?.id) { - updateUI(downloadInfo) - } - } - - override fun onAllDownloadsComplete() {} -} diff --git a/app/src/main/java/com/bansify/internet/activity/downloads/DownloadPromptDialog.kt b/app/src/main/java/com/bansify/internet/activity/downloads/DownloadPromptDialog.kt deleted file mode 100644 index fff7f21d..00000000 --- a/app/src/main/java/com/bansify/internet/activity/downloads/DownloadPromptDialog.kt +++ /dev/null @@ -1,78 +0,0 @@ -package com.bansify.internet.activity.downloads - -import android.app.Dialog -import android.content.Context -import android.os.Bundle -import android.text.format.Formatter -import android.view.Gravity -import android.view.ViewGroup -import android.view.Window -import android.widget.Button -import android.widget.ImageView -import android.widget.TextView -import com.bansify.internet.R - -class DownloadPromptDialog( - context: Context, - private val fileName: String, - private val fileSize: Long, - private val onConfirm: () -> Unit, - private val onCancel: () -> Unit = {} -) : Dialog(context, R.style.TvFullScreenDialog) { - - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - requestWindowFeature(Window.FEATURE_NO_TITLE) - setContentView(R.layout.dialog_download_prompt) - - window?.apply { - setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) - setGravity(Gravity.CENTER) - } - - val ivPromptFileIcon: ImageView = findViewById(R.id.ivPromptFileIcon) - val tvPromptFileName: TextView = findViewById(R.id.tvPromptFileName) - val tvPromptFileSize: TextView = findViewById(R.id.tvPromptFileSize) - val tvPromptDestination: TextView = findViewById(R.id.tvPromptDestination) - val btnPromptCancel: Button = findViewById(R.id.btnPromptCancel) - val btnPromptDownload: Button = findViewById(R.id.btnPromptDownload) - - tvPromptFileName.text = fileName - tvPromptDestination.text = "Download/$fileName" - - if (fileSize > 0) { - tvPromptFileSize.text = Formatter.formatFileSize(context, fileSize) - } else { - tvPromptFileSize.text = "Unknown size" - } - - val lower = fileName.lowercase() - when { - lower.endsWith(".apk") -> ivPromptFileIcon.setImageResource(R.drawable.ic_file_apk) - lower.endsWith(".zip") || lower.endsWith(".rar") || lower.endsWith(".7z") || lower.endsWith(".tar") || lower.endsWith(".gz") -> - ivPromptFileIcon.setImageResource(R.drawable.ic_file_zip) - lower.endsWith(".mp4") || lower.endsWith(".mkv") || lower.endsWith(".avi") || lower.endsWith(".webm") || lower.endsWith(".mov") -> - ivPromptFileIcon.setImageResource(R.drawable.ic_file_video) - lower.endsWith(".mp3") || lower.endsWith(".wav") || lower.endsWith(".ogg") || lower.endsWith(".m4a") || lower.endsWith(".flac") -> - ivPromptFileIcon.setImageResource(R.drawable.ic_file_audio) - lower.endsWith(".jpg") || lower.endsWith(".jpeg") || lower.endsWith(".png") || lower.endsWith(".webp") || lower.endsWith(".gif") -> - ivPromptFileIcon.setImageResource(R.drawable.ic_file_image) - lower.endsWith(".pdf") || lower.endsWith(".doc") || lower.endsWith(".docx") || lower.endsWith(".txt") -> - ivPromptFileIcon.setImageResource(R.drawable.ic_file_doc) - else -> ivPromptFileIcon.setImageResource(R.drawable.ic_file_generic) - } - - btnPromptDownload.isSelected = true - btnPromptDownload.requestFocus() - - btnPromptCancel.setOnClickListener { - dismiss() - onCancel() - } - - btnPromptDownload.setOnClickListener { - dismiss() - onConfirm() - } - } -} diff --git a/app/src/main/java/com/bansify/internet/activity/downloads/DownloadsActivity.kt b/app/src/main/java/com/bansify/internet/activity/downloads/DownloadsActivity.kt deleted file mode 100644 index 2b6a4720..00000000 --- a/app/src/main/java/com/bansify/internet/activity/downloads/DownloadsActivity.kt +++ /dev/null @@ -1,326 +0,0 @@ -package com.bansify.internet.activity.downloads - -import android.app.Activity -import android.app.AlertDialog -import android.content.* -import android.graphics.Color -import android.net.Uri -import android.os.Build -import android.os.Bundle -import com.bansify.internet.utils.setupAsSidebar -import android.os.Environment -import android.provider.Settings -import android.util.Log -import android.view.Gravity -import android.view.View -import android.webkit.MimeTypeMap -import android.widget.AbsListView -import android.widget.AdapterView -import android.widget.PopupMenu -import android.widget.Toast -import androidx.appcompat.app.AppCompatActivity -import androidx.core.content.FileProvider -import androidx.lifecycle.lifecycleScope -import com.bansify.internet.BuildConfig -import com.bansify.internet.R -import com.bansify.internet.databinding.ActivityDownloadsBinding -import com.bansify.internet.model.Download -import com.bansify.internet.utils.Utils -import com.bansify.internet.utils.setupAsSidebar -import com.bansify.internet.utils.activemodel.ActiveModelsRepository -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.launch -import java.io.File -import java.util.* - -class DownloadsActivity : AppCompatActivity(), AdapterView.OnItemClickListener, ActiveDownloadsModel.Listener, AdapterView.OnItemLongClickListener{ - private lateinit var vb: ActivityDownloadsBinding - private lateinit var adapter: DownloadListAdapter - private val listeners = ArrayList() - - private lateinit var activeDownloadsModel: ActiveDownloadsModel - private lateinit var downloadsHistoryModel: DownloadsHistoryModel - - internal var onListScrollListener: AbsListView.OnScrollListener = object : AbsListView.OnScrollListener { - override fun onScrollStateChanged(view: AbsListView, scrollState: Int) { - - } - - override fun onScroll(view: AbsListView, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) { - if (totalItemCount != 0 && firstVisibleItem + visibleItemCount >= totalItemCount - 1) { - downloadsHistoryModel.loadNextItems() - } - } - } - - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setupAsSidebar(true) - Log.d(TAG, "onCreate this:" + System.identityHashCode(this)) - vb = ActivityDownloadsBinding.inflate(layoutInflater) - setContentView(vb.root) - - vb.ibCloseDownloads.setOnClickListener { finish() } - - updateStorageSubtitle() - setupFilterPills() - - activeDownloadsModel = ActiveModelsRepository.get(ActiveDownloadsModel::class, this) - downloadsHistoryModel = ActiveModelsRepository.get(DownloadsHistoryModel::class, this) - - adapter = DownloadListAdapter(this) - vb.listView.adapter = adapter - - vb.listView.setOnScrollListener(onListScrollListener) - vb.listView.onItemClickListener = this - vb.listView.onItemLongClickListener = this - - downloadsHistoryModel.lastLoadedItems.subscribe(this, false, { - if (it.isNotEmpty()) { - vb.llEmptyState.visibility = View.GONE - adapter.addItems(it) - vb.listView.requestFocus() - } else if (adapter.count == 0) { - vb.llEmptyState.visibility = View.VISIBLE - } - }) - - if (downloadsHistoryModel.allItems.isEmpty()) { - downloadsHistoryModel.loadNextItems() - } else { - vb.llEmptyState.visibility = View.GONE - adapter.addItems(downloadsHistoryModel.allItems) - vb.listView.requestFocus() - } - } - - private fun updateStorageSubtitle() { - try { - val freeBytes = Environment.getDataDirectory().freeSpace - val freeStr = android.text.format.Formatter.formatFileSize(this, freeBytes) - val activeCount = activeDownloadsModel.activeDownloads.size - if (activeCount > 0) { - vb.tvDownloadsSubtitle.text = "$activeCount active · $freeStr free" - } else { - vb.tvDownloadsSubtitle.text = "Nothing in progress · $freeStr free" - } - } catch (e: Exception) { - vb.tvDownloadsSubtitle.text = "Downloads & Files" - } - } - - private fun setupFilterPills() { - val pills = listOf(vb.btnFilterAll, vb.btnFilterActive, vb.btnFilterCompleted, vb.btnFilterFailed) - pills.forEach { button -> - button.setOnClickListener { - pills.forEach { p -> - p.isSelected = false - p.setTextColor(Color.parseColor("#94A3B8")) - } - button.isSelected = true - button.setTextColor(Color.WHITE) - } - } - vb.btnFilterAll.isSelected = true - vb.btnFilterAll.setTextColor(Color.WHITE) - } - - override fun onResume() { - super.onResume() - activeDownloadsModel.registerListener(this) - } - - override fun onPause() { - activeDownloadsModel.unregisterListener(this@DownloadsActivity) - super.onPause() - } - - override fun onItemClick(adapterView: AdapterView<*>, view: View, i: Int, l: Long) { - val v = view as DownloadListItemView - val download = v.download ?: return - - if (download.isDateHeader) { - return - } - - if (download.size != download.bytesReceived) { - //file should be already marked in UI as broken - return - } - - - val fileURI = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { - Uri.parse(download.filepath) - } else { - val file = File(download.filepath) - if (!file.exists()) { - Utils.showToast(this, R.string.file_not_found) - return - } - - FileProvider.getUriForFile(this@DownloadsActivity, - BuildConfig.APPLICATION_ID + ".provider", - file) - } - - - val openIntent = Intent(Intent.ACTION_VIEW) - val mimeType = contentResolver.getType(fileURI) - openIntent.setDataAndType(fileURI, mimeType) - openIntent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION - try { - startActivity(openIntent) - } catch (e: ActivityNotFoundException) { - Utils.showToast(this, getString(R.string.no_app_for_file_type)) - } - - } - - override fun onItemLongClick(adapterView: AdapterView<*>, view: View, i: Int, l: Long): Boolean { - val v = view as DownloadListItemView - val download = v.download ?: return false - if (download.isDateHeader) { - return true - } - if (download.size == Download.BROKEN_MARK || download.size == Download.CANCELLED_MARK || - download.size == download.bytesReceived) { - showFinishedDownloadOptionsPopup(v) - } else { - showUnfinishedDownloadOptionsPopup(v) - } - return true - } - - private fun showUnfinishedDownloadOptionsPopup(v: DownloadListItemView) { - val pm = PopupMenu(this, v, Gravity.BOTTOM) - pm.menu.add(R.string.cancel) - pm.setOnMenuItemClickListener { - activeDownloadsModel.cancelDownload(v.download!!) - true - } - pm.show() - } - - private fun showFinishedDownloadOptionsPopup(v: DownloadListItemView) { - val download = v.download ?: return - val pm = PopupMenu(this, v, Gravity.BOTTOM) - if (download.filename.endsWith(".apk", true) && - download.size == download.bytesReceived) { - pm.menu.add(0, 0, 0, R.string.install) - } - pm.menu.add(0, 1, 1, R.string.open_folder) - pm.menu.add(0, 2, 2, R.string.delete) - pm.setOnMenuItemClickListener { menuItem -> - when (menuItem.itemId) { - 0 -> installAPK(download) - 1 -> openFolder(v) - 2 -> deleteItem(v) - } - true - } - pm.show() - } - - private fun installAPK(download: Download) { - val canInstallFromOtherSources = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - //packageManager.canRequestPackageInstalls() - true - } else - Settings.Secure.getInt(this.contentResolver, Settings.Secure.INSTALL_NON_MARKET_APPS) == 1 - - if(canInstallFromOtherSources) { - launchInstallAPKActivity(this, download) - } else { - AlertDialog.Builder(this) - .setTitle(R.string.app_name) - .setMessage(if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) - R.string.turn_on_unknown_sources_for_app else R.string.turn_on_unknown_sources) - .setPositiveButton(android.R.string.ok, DialogInterface.OnClickListener { dialog, which -> run { - val intentSettings = Intent() - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - intentSettings.action = Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES - intentSettings.data = Uri.parse("package:${BuildConfig.APPLICATION_ID}") - } else { - intentSettings.action = Settings.ACTION_SECURITY_SETTINGS - } - intentSettings.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK) - try { - startActivityForResult(intentSettings, REQUEST_CODE_UNKNOWN_APP_SOURCES) - } catch (e: Exception) { - e.printStackTrace() - Toast.makeText(this, R.string.error, Toast.LENGTH_SHORT).show() - } - }}) - .show() - - } - } - - private fun openFolder(v: DownloadListItemView) { - val uri = Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath) - val intent = Intent(Intent.ACTION_VIEW) - intent.setDataAndType(uri, "resource/folder") - if (intent.resolveActivityInfo(packageManager, 0) != null) { - startActivity(intent) - } else { - Utils.showToast(this, R.string.no_file_explorer_msg) - } - } - - private fun deleteItem(v: DownloadListItemView) = lifecycleScope.launch(Dispatchers.Main) { - v.download?.let { - activeDownloadsModel.deleteItem(it) - adapter.remove(it) - } - } - - override fun onDownloadUpdated(downloadInfo: Download) { - for (i in listeners.indices) { - listeners[i].onDownloadUpdated(downloadInfo) - } - } - - override fun onDownloadError(downloadInfo: Download, responseCode: Int, responseMessage: String) { - for (i in listeners.indices) { - listeners[i].onDownloadError(downloadInfo, responseCode, responseMessage) - } - } - - override fun onAllDownloadsComplete() {} - - fun registerListener(listener: ActiveDownloadsModel.Listener) { - listeners.add(listener) - } - - fun unregisterListener(listener: ActiveDownloadsModel.Listener) { - listeners.remove(listener) - } - - companion object { - const val REQUEST_CODE_UNKNOWN_APP_SOURCES = 10007 - private const val REQUEST_CODE_INSTALL_PACKAGE = 10008 - val TAG: String = DownloadsActivity::class.java.simpleName - - fun launchInstallAPKActivity(activity: Activity, download: Download) { - val mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("apk") - val apkURI = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { - Uri.parse(download.filepath) - } else { - val file = File(download.filepath) - FileProvider.getUriForFile( - activity, - activity.applicationContext.packageName + ".provider", file - ) - } - - val install = Intent(Intent.ACTION_INSTALL_PACKAGE) - install.setDataAndType(apkURI, mimeType) - install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) - try { - activity.startActivityForResult(install, REQUEST_CODE_INSTALL_PACKAGE)//we are not using result for now - } catch (e: Exception) { - Toast.makeText(activity, R.string.error, Toast.LENGTH_SHORT).show() - } - } - } -} diff --git a/app/src/main/java/com/bansify/internet/activity/downloads/DownloadsHistoryModel.kt b/app/src/main/java/com/bansify/internet/activity/downloads/DownloadsHistoryModel.kt deleted file mode 100644 index 3c0ee796..00000000 --- a/app/src/main/java/com/bansify/internet/activity/downloads/DownloadsHistoryModel.kt +++ /dev/null @@ -1,27 +0,0 @@ -package com.bansify.internet.activity.downloads - -import com.bansify.internet.model.Download -import com.bansify.internet.singleton.AppDatabase -import com.bansify.internet.utils.observable.ObservableValue -import com.bansify.internet.utils.activemodel.ActiveModel -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.launch - -class DownloadsHistoryModel: ActiveModel() { - val allItems = ArrayList() - val lastLoadedItems = ObservableValue>(ArrayList()) - private var loading = false - - fun loadNextItems() = modelScope.launch(Dispatchers.Main) { - if (loading) { - return@launch - } - loading = true - - val newItems = AppDatabase.db.downloadDao().allByLimitOffset(allItems.size.toLong()) - lastLoadedItems.value = newItems - allItems.addAll(newItems) - - loading = false - } -} \ No newline at end of file diff --git a/app/src/main/java/com/bansify/internet/activity/history/HistoryActivity.kt b/app/src/main/java/com/bansify/internet/activity/history/HistoryActivity.kt deleted file mode 100644 index 3c057de6..00000000 --- a/app/src/main/java/com/bansify/internet/activity/history/HistoryActivity.kt +++ /dev/null @@ -1,392 +0,0 @@ -package com.bansify.internet.activity.history - -import android.app.AlertDialog -import android.content.ClipData -import android.content.ClipboardManager -import android.content.Context -import android.content.Intent -import android.os.Bundle -import android.text.Editable -import android.text.TextWatcher -import android.view.KeyEvent -import android.view.View -import android.webkit.CookieManager -import android.webkit.WebStorage -import android.webkit.WebView -import android.widget.AbsListView -import android.widget.AdapterView -import android.widget.PopupMenu -import android.widget.Toast -import androidx.appcompat.app.AppCompatActivity -import androidx.lifecycle.lifecycleScope -import com.bansify.internet.R -import com.bansify.internet.databinding.ActivityHistoryBinding -import com.bansify.internet.model.HistoryItem -import com.bansify.internet.singleton.AppDatabase -import com.bansify.internet.utils.Utils -import com.bansify.internet.utils.setupAsSidebar -import com.bansify.internet.utils.VoiceSearchHelper -import com.bansify.internet.utils.activemodel.ActiveModelsRepository -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.launch - -class HistoryActivity : AppCompatActivity(), AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener { - - private lateinit var vb: ActivityHistoryBinding - private var adapter: HistoryAdapter? = null - private lateinit var historyModel: HistoryModel - private val voiceSearchHelper = VoiceSearchHelper( - this, - VOICE_SEARCH_REQUEST_CODE, - VOICE_SEARCH_PERMISSIONS_REQUEST_CODE - ) - - private val onListScrollListener = object : AbsListView.OnScrollListener { - override fun onScrollStateChanged(view: AbsListView, scrollState: Int) {} - - override fun onScroll(view: AbsListView, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) { - if (totalItemCount != 0 && firstVisibleItem + visibleItemCount >= totalItemCount - 1 && historyModel.searchQuery.isEmpty()) { - historyModel.loadItems(false, adapter?.realCount ?: 0) - } - } - } - - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setupAsSidebar(false) - vb = ActivityHistoryBinding.inflate(layoutInflater) - setContentView(vb.root) - - historyModel = ActiveModelsRepository.get(HistoryModel::class, this) - - setupTopBar() - setupSidebar() - setupListView() - observeHistory() - - historyModel.loadItems(false) - } - - private fun setupTopBar() { - vb.ibHistoryBack.setOnClickListener { finish() } - - vb.etSearchHistory.addTextChangedListener(object : TextWatcher { - override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} - override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { - val query = s?.toString().orEmpty() - vb.ibClearSearch.visibility = if (query.isNotEmpty()) View.VISIBLE else View.GONE - adapter?.erase() - historyModel.searchQuery = query - historyModel.loadItems(true) - } - override fun afterTextChanged(s: Editable?) {} - }) - - vb.ibClearSearch.setOnClickListener { - vb.etSearchHistory.text.clear() - } - - vb.ibVoiceSearch.setOnClickListener { - initiateVoiceSearch() - } - - vb.btnDeleteSelected.setOnClickListener { - showDeleteDialog(false) - } - - vb.btnCancelSelection.setOnClickListener { - adapter?.isMultiselectMode = false - updateSelectionBar() - } - } - - private fun setupSidebar() { - vb.llNavChromeHistory.setOnClickListener { - setFilter(HistoryModel.FILTER_ALL) - } - - vb.btnFilterAll.setOnClickListener { setFilter(HistoryModel.FILTER_ALL) } - vb.btnFilterToday.setOnClickListener { setFilter(HistoryModel.FILTER_TODAY) } - vb.btnFilterYesterday.setOnClickListener { setFilter(HistoryModel.FILTER_YESTERDAY) } - vb.btnFilterOlder.setOnClickListener { setFilter(HistoryModel.FILTER_OLDER) } - - vb.btnClearHistory.setOnClickListener { - showClearBrowsingDataDialog() - } - } - - private fun setFilter(filter: Int) { - historyModel.filterMode = filter - updateFilterUI(filter) - adapter?.erase() - historyModel.loadItems(true) - } - - private fun updateFilterUI(filter: Int) { - val activeColor = androidx.core.content.ContextCompat.getColor(this, R.color.app_accent) - val inactiveColor = androidx.core.content.ContextCompat.getColor(this, R.color.app_on_surface_muted) - - vb.btnFilterAll.setTextColor(if (filter == HistoryModel.FILTER_ALL) activeColor else inactiveColor) - vb.btnFilterToday.setTextColor(if (filter == HistoryModel.FILTER_TODAY) activeColor else inactiveColor) - vb.btnFilterYesterday.setTextColor(if (filter == HistoryModel.FILTER_YESTERDAY) activeColor else inactiveColor) - vb.btnFilterOlder.setTextColor(if (filter == HistoryModel.FILTER_OLDER) activeColor else inactiveColor) - } - - private fun setupListView() { - adapter = HistoryAdapter() - adapter?.onDeleteClickListener = { item -> - deleteSingleItem(item) - } - adapter?.onItemMenuClickListener = { item, anchorView -> - showItemContextMenu(item, anchorView) - } - - vb.listView.adapter = adapter - vb.listView.setOnScrollListener(onListScrollListener) - vb.listView.onItemClickListener = this - vb.listView.onItemLongClickListener = this - } - - private fun observeHistory() { - historyModel.lastLoadedItems.subscribe(this, false) { items -> - if (items.isEmpty()) { - if (adapter?.realCount == 0L) { - vb.llEmptyHistory.visibility = View.VISIBLE - vb.listView.visibility = View.GONE - } - updateSubtitle() - return@subscribe - } - vb.llEmptyHistory.visibility = View.GONE - vb.listView.visibility = View.VISIBLE - adapter?.addItems(items) - updateSubtitle() - } - } - - private fun updateSubtitle() { - val count = adapter?.realCount ?: 0 - vb.tvHistorySubtitle.text = "$count visits recorded" - } - - private fun deleteSingleItem(item: HistoryItem) { - lifecycleScope.launch(Dispatchers.Main) { - try { - AppDatabase.db.historyDao().delete(item) - adapter?.remove(item) - updateSubtitle() - if (adapter?.realCount == 0L) { - vb.llEmptyHistory.visibility = View.VISIBLE - vb.listView.visibility = View.GONE - } - Toast.makeText(this@HistoryActivity, "Removed from history", Toast.LENGTH_SHORT).show() - } catch (e: Exception) { - Toast.makeText(this@HistoryActivity, "Error deleting item", Toast.LENGTH_SHORT).show() - } - } - } - - private fun showItemContextMenu(item: HistoryItem, anchor: View) { - val popup = PopupMenu(this, anchor) - popup.menu.add(0, 1, 0, "Open in browser") - popup.menu.add(0, 2, 1, "Open in new tab") - popup.menu.add(0, 3, 2, "Copy link") - popup.menu.add(0, 4, 3, "Remove from history") - - popup.setOnMenuItemClickListener { menuItem -> - when (menuItem.itemId) { - 1 -> { - val resultIntent = Intent() - resultIntent.putExtra(KEY_URL, item.url) - resultIntent.putExtra(KEY_OPEN_IN_NEW_TAB, false) - setResult(RESULT_OK, resultIntent) - finish() - true - } - 2 -> { - val resultIntent = Intent() - resultIntent.putExtra(KEY_URL, item.url) - resultIntent.putExtra(KEY_OPEN_IN_NEW_TAB, true) - setResult(RESULT_OK, resultIntent) - finish() - true - } - 3 -> { - val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager - val clip = ClipData.newPlainText("URL", item.url) - clipboard.setPrimaryClip(clip) - Toast.makeText(this, this.getString(R.string.history_link_copied_to_clipboard), Toast.LENGTH_SHORT).show() - true - } - 4 -> { - deleteSingleItem(item) - true - } - else -> false - } - } - popup.show() - } - - override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) { - val hiv = view as? HistoryItemView ?: return - val hi = hiv.historyItem ?: return - if (hi.isDateHeader) return - - if (adapter?.isMultiselectMode == true) { - hiv.setSelection(!hi.selected) - updateSelectionBar() - } else { - val resultIntent = Intent() - resultIntent.putExtra(KEY_URL, hi.url) - resultIntent.putExtra(KEY_OPEN_IN_NEW_TAB, false) - setResult(RESULT_OK, resultIntent) - finish() - } - } - - override fun onItemLongClick(adapterView: AdapterView<*>, view: View, i: Int, l: Long): Boolean { - val hiv = view as? HistoryItemView ?: return false - val hi = hiv.historyItem ?: return false - if (hi.isDateHeader) return false - - if (adapter?.isMultiselectMode == false) { - adapter?.isMultiselectMode = true - hiv.setSelection(true) - updateSelectionBar() - return true - } - return false - } - - private fun updateSelectionBar() { - val selection = adapter?.selectedItems ?: emptyList() - if (selection.isEmpty()) { - vb.llSelectionBar.visibility = View.GONE - vb.llHistorySearchContainer.visibility = View.VISIBLE - } else { - vb.tvSelectedCount.text = "${selection.size} selected" - vb.llSelectionBar.visibility = View.VISIBLE - vb.llHistorySearchContainer.visibility = View.GONE - } - } - - override fun onBackPressed() { - if (adapter?.isMultiselectMode == true) { - adapter?.isMultiselectMode = false - updateSelectionBar() - return - } - super.onBackPressed() - } - - private fun showClearBrowsingDataDialog() { - AlertDialog.Builder(this) - .setTitle(R.string.history_clear_browsing_data) - .setMessage(R.string.history_delete_all_confirm) - .setPositiveButton("Clear Everything") { _, _ -> - lifecycleScope.launch(Dispatchers.Main) { - try { - AppDatabase.db.historyDao().deleteWhereTimeLessThan(Long.MAX_VALUE) - adapter?.erase() - CookieManager.getInstance().removeAllCookies(null) - WebStorage.getInstance().deleteAllData() - WebView(this@HistoryActivity).clearCache(true) - updateSubtitle() - vb.llEmptyHistory.visibility = View.VISIBLE - vb.listView.visibility = View.GONE - Toast.makeText(this@HistoryActivity, "Browsing history and data cleared", Toast.LENGTH_SHORT).show() - } catch (e: Exception) { - Toast.makeText(this@HistoryActivity, "History cleared", Toast.LENGTH_SHORT).show() - } - } - } - .setNegativeButton(android.R.string.cancel, null) - .show() - } - - private fun showDeleteDialog(deleteAll: Boolean) { - val selected = adapter?.selectedItems ?: emptyList() - if (adapter?.items?.isEmpty() == true || (selected.isEmpty() && !deleteAll)) return - - AlertDialog.Builder(this) - .setTitle(R.string.delete) - .setMessage(if (deleteAll) R.string.msg_delete_history_all else R.string.msg_delete_history) - .setPositiveButton(android.R.string.ok) { _, _ -> - lifecycleScope.launch(Dispatchers.Main) { - if (deleteAll) { - AppDatabase.db.historyDao().deleteWhereTimeLessThan(Long.MAX_VALUE) - adapter?.erase() - } else { - AppDatabase.db.historyDao().delete(*selected.toTypedArray()) - adapter?.remove(selected) - } - adapter?.isMultiselectMode = false - updateSelectionBar() - updateSubtitle() - if (adapter?.realCount == 0L) { - vb.llEmptyHistory.visibility = View.VISIBLE - vb.listView.visibility = View.GONE - } - } - } - .setNegativeButton(android.R.string.cancel, null) - .show() - } - - private fun initiateVoiceSearch() { - voiceSearchHelper.initiateVoiceSearch(object : VoiceSearchHelper.Callback { - override fun onPartialResult(text: String) { - vb.etSearchHistory.setText(text) - vb.etSearchHistory.setSelection(text.length) - } - - override fun onResult(text: String?) { - if (text.isNullOrBlank()) { - Utils.showToast(this@HistoryActivity, getString(R.string.can_not_recognize)) - return - } - vb.etSearchHistory.setText(text) - vb.etSearchHistory.setSelection(text.length) - } - }) - } - - override fun onDestroy() { - voiceSearchHelper.destroy() - super.onDestroy() - } - - override fun dispatchKeyEvent(event: KeyEvent): Boolean { - if (event.keyCode == KeyEvent.KEYCODE_SEARCH && event.action == KeyEvent.ACTION_UP) { - initiateVoiceSearch() - return true - } - return super.dispatchKeyEvent(event) - } - - @Deprecated("Deprecated in Java") - override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { - if (!voiceSearchHelper.processActivityResult(requestCode, resultCode, data)) { - super.onActivityResult(requestCode, resultCode, data) - } - } - - override fun onRequestPermissionsResult( - requestCode: Int, - permissions: Array, - grantResults: IntArray - ) { - if (!voiceSearchHelper.processPermissionsResult(requestCode, permissions, grantResults)) { - super.onRequestPermissionsResult(requestCode, permissions, grantResults) - } - } - - companion object { - private const val VOICE_SEARCH_REQUEST_CODE = 10001 - private const val VOICE_SEARCH_PERMISSIONS_REQUEST_CODE = 10002 - - const val KEY_URL = "url" - const val KEY_OPEN_IN_NEW_TAB = "open_in_new_tab" - } -} diff --git a/app/src/main/java/com/bansify/internet/activity/history/HistoryAdapter.kt b/app/src/main/java/com/bansify/internet/activity/history/HistoryAdapter.kt deleted file mode 100644 index b67775a3..00000000 --- a/app/src/main/java/com/bansify/internet/activity/history/HistoryAdapter.kt +++ /dev/null @@ -1,138 +0,0 @@ -package com.bansify.internet.activity.history - -import android.view.View -import android.view.ViewGroup -import android.widget.BaseAdapter -import com.bansify.internet.model.HistoryItem -import com.bansify.internet.utils.Utils -import de.halfbit.pinnedsection.PinnedSectionListView -import java.util.ArrayList - -class HistoryAdapter : BaseAdapter(), PinnedSectionListView.PinnedSectionListAdapter { - val items = ArrayList() - private var lastHeaderDate: Long = -1 - var realCount: Long = 0 - private set - var isMultiselectMode = false - set(multiselectMode) { - field = multiselectMode - if (!multiselectMode) { - for (hi in items) { - hi.selected = false - } - } - notifyDataSetChanged() - } - private val _tmpSelected = ArrayList() - - var onDeleteClickListener: ((HistoryItem) -> Unit)? = null - var onItemMenuClickListener: ((HistoryItem, View) -> Unit)? = null - - val selectedItems: List - get() { - _tmpSelected.clear() - for (hi in items) { - if (hi.selected) { - _tmpSelected.add(hi) - } - } - return _tmpSelected - } - - fun addItems(newItems: List) { - if (newItems.isEmpty()) { - return - } - for (hi in newItems) { - if (!Utils.isSameDate(hi.time, lastHeaderDate)) { - lastHeaderDate = hi.time - this.items.add(HistoryItem.createDateHeaderInfo(hi.time)) - } - this.items.add(hi) - realCount++ - } - notifyDataSetChanged() - } - - override fun getCount(): Int { - return items.size - } - - override fun getItem(position: Int): Any { - return items[position] - } - - override fun getItemId(position: Int): Long { - return position.toLong() - } - - override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { - val hiv: HistoryItemView = if (convertView is HistoryItemView) { - convertView - } else { - HistoryItemView(parent.context, getItemViewType(position)) - } - hiv.setHistoryItem( - items[position], - isMultiselectMode, - onDeleteClickListener, - onItemMenuClickListener - ) - return hiv - } - - override fun getViewTypeCount(): Int { - return 2 - } - - override fun getItemViewType(position: Int): Int { - return if (items[position].isDateHeader) VIEW_TYPE_HEADER else VIEW_TYPE_HISTORY_ITEM - } - - override fun isItemViewTypePinned(viewType: Int): Boolean { - return viewType == VIEW_TYPE_HEADER - } - - fun erase() { - items.clear() - lastHeaderDate = -1 - realCount = 0 - notifyDataSetChanged() - } - - fun remove(historyItem: HistoryItem) { - items.remove(historyItem) - if (!historyItem.isDateHeader && realCount > 0) { - realCount-- - } - // Cleanup orphaned date headers - cleanupHeaders() - notifyDataSetChanged() - } - - fun remove(selected: List) { - items.removeAll(selected) - realCount = (realCount - selected.count { !it.isDateHeader }).coerceAtLeast(0) - cleanupHeaders() - notifyDataSetChanged() - } - - private fun cleanupHeaders() { - val toRemove = ArrayList() - for (i in 0 until items.size) { - val item = items[i] - if (item.isDateHeader) { - // If header is at end of list or followed by another header, remove it - if (i == items.size - 1 || items[i + 1].isDateHeader) { - toRemove.add(item) - } - } - } - items.removeAll(toRemove) - } - - companion object { - const val VIEW_TYPE_HISTORY_ITEM = 0 - const val VIEW_TYPE_HEADER = 1 - } -} diff --git a/app/src/main/java/com/bansify/internet/activity/history/HistoryItemView.kt b/app/src/main/java/com/bansify/internet/activity/history/HistoryItemView.kt deleted file mode 100644 index 0fa82404..00000000 --- a/app/src/main/java/com/bansify/internet/activity/history/HistoryItemView.kt +++ /dev/null @@ -1,156 +0,0 @@ -package com.bansify.internet.activity.history - -import android.content.Context -import android.text.format.DateUtils -import android.view.LayoutInflater -import android.widget.CheckBox -import android.widget.FrameLayout -import android.widget.ImageButton -import android.widget.ImageView -import android.widget.TextView -import androidx.appcompat.app.AppCompatActivity -import androidx.lifecycle.lifecycleScope -import com.bansify.internet.R -import com.bansify.internet.model.HistoryItem -import com.bansify.internet.singleton.FaviconsPool -import com.bansify.internet.utils.activity -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.launch -import java.text.SimpleDateFormat -import java.util.Date -import java.util.Locale - -class HistoryItemView(context: Context, private val viewType: Int) : FrameLayout(context) { - private var tvDate: TextView? = null - private var tvHeaderCount: TextView? = null - private var tvTitle: TextView? = null - private var tvURL: TextView? = null - private var tvTime: TextView? = null - private var ivHistoryFavicon: ImageView? = null - private var cbSelection: CheckBox? = null - private var ibItemDelete: ImageButton? = null - private var ibItemMenu: ImageButton? = null - var historyItem: HistoryItem? = null - - var onItemDeleteListener: ((HistoryItem) -> Unit)? = null - var onItemMenuListener: ((HistoryItem, android.view.View) -> Unit)? = null - - init { - LayoutInflater.from(context).inflate( - if (viewType == HistoryAdapter.VIEW_TYPE_HEADER) - R.layout.view_history_header_item - else - R.layout.view_history_item, this - ) - when (viewType) { - HistoryAdapter.VIEW_TYPE_HEADER -> { - tvDate = findViewById(R.id.tvDate) - tvHeaderCount = findViewById(R.id.tvHeaderCount) - } - HistoryAdapter.VIEW_TYPE_HISTORY_ITEM -> { - tvTitle = findViewById(R.id.tvTitle) - tvURL = findViewById(R.id.tvURL) - tvTime = findViewById(R.id.tvTime) - ivHistoryFavicon = findViewById(R.id.ivHistoryFavicon) - cbSelection = findViewById(R.id.cbSelection) - ibItemDelete = findViewById(R.id.ibItemDelete) - ibItemMenu = findViewById(R.id.ibItemMenu) - - ibItemDelete?.setOnClickListener { - historyItem?.let { item -> onItemDeleteListener?.invoke(item) } - } - - ibItemMenu?.setOnClickListener { v -> - historyItem?.let { item -> onItemMenuListener?.invoke(item, v) } - } - } - } - } - - fun setHistoryItem( - historyItem: HistoryItem, - multiselectMode: Boolean, - onDelete: ((HistoryItem) -> Unit)? = null, - onMenu: ((HistoryItem, android.view.View) -> Unit)? = null - ) { - this.historyItem = historyItem - this.onItemDeleteListener = onDelete - this.onItemMenuListener = onMenu - - when (viewType) { - HistoryAdapter.VIEW_TYPE_HEADER -> { - val time = historyItem.time - val headerText = formatHeaderDate(time) - tvDate?.text = headerText - } - HistoryAdapter.VIEW_TYPE_HISTORY_ITEM -> { - tvTitle?.text = if (!historyItem.title.isNullOrBlank()) historyItem.title else historyItem.url - tvURL?.text = historyItem.url - val sdf = SimpleDateFormat("HH:mm", Locale.getDefault()) - tvTime?.text = sdf.format(Date(historyItem.time)) - cbSelection?.visibility = if (multiselectMode) VISIBLE else GONE - cbSelection?.isChecked = historyItem.selected - - // Favicon / logo - val url = historyItem.url ?: "" - val logoRes = getLogoForUrl(url) - if (logoRes != 0) { - ivHistoryFavicon?.setImageResource(logoRes) - } else { - ivHistoryFavicon?.setImageResource(R.drawable.ic_tab_default_favicon) - val activity = this.activity as? AppCompatActivity - activity?.lifecycleScope?.launch(Dispatchers.Main) { - try { - val favicon = FaviconsPool.get(url) - if (this@HistoryItemView.historyItem == historyItem && favicon != null) { - ivHistoryFavicon?.setImageBitmap(favicon) - } - } catch (_: Exception) {} - } - } - } - } - } - - private fun formatHeaderDate(timestamp: Long): String { - return try { - if (DateUtils.isToday(timestamp)) { - val dayFormat = SimpleDateFormat("EEEE, MMMM d, yyyy", Locale.getDefault()) - "Today – " + dayFormat.format(Date(timestamp)) - } else if (DateUtils.isToday(timestamp + DateUtils.DAY_IN_MILLIS)) { - val dayFormat = SimpleDateFormat("EEEE, MMMM d, yyyy", Locale.getDefault()) - "Yesterday – " + dayFormat.format(Date(timestamp)) - } else { - val fullFormat = SimpleDateFormat("EEEE, MMMM d, yyyy", Locale.getDefault()) - fullFormat.format(Date(timestamp)) - } - } catch (e: Exception) { - SimpleDateFormat.getDateInstance().format(Date(timestamp)) - } - } - - private fun getLogoForUrl(url: String): Int { - val lower = url.lowercase() - return when { - lower.contains("google.com") -> R.drawable.ic_logo_google - lower.contains("youtube.com") -> R.drawable.ic_logo_youtube - lower.contains("whatsapp.com") -> R.drawable.ic_logo_whatsapp - lower.contains("reddit.com") -> R.drawable.ic_logo_reddit - lower.contains("netflix.com") -> R.drawable.ic_logo_netflix - lower.contains("spotify.com") -> R.drawable.ic_logo_spotify - lower.contains("amazon.com") -> R.drawable.ic_logo_amazon - lower.contains("github.com") -> R.drawable.ic_logo_github - lower.contains("facebook.com") -> R.drawable.ic_logo_facebook - lower.contains("instagram.com") -> R.drawable.ic_logo_instagram - lower.contains("telegram.org") -> R.drawable.ic_logo_telegram - lower.contains("wikipedia.org") -> R.drawable.ic_logo_wikipedia - else -> 0 - } - } - - fun setSelection(selected: Boolean) { - if (viewType == HistoryAdapter.VIEW_TYPE_HEADER) return - cbSelection?.isChecked = selected - historyItem?.selected = selected - } -} diff --git a/app/src/main/java/com/bansify/internet/activity/history/HistoryModel.kt b/app/src/main/java/com/bansify/internet/activity/history/HistoryModel.kt deleted file mode 100644 index b2957ecf..00000000 --- a/app/src/main/java/com/bansify/internet/activity/history/HistoryModel.kt +++ /dev/null @@ -1,67 +0,0 @@ -package com.bansify.internet.activity.history - -import com.bansify.internet.model.HistoryItem -import com.bansify.internet.singleton.AppDatabase -import com.bansify.internet.utils.observable.ObservableValue -import com.bansify.internet.utils.activemodel.ActiveModel -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.launch -import java.util.Calendar - -class HistoryModel: ActiveModel() { - val lastLoadedItems = ObservableValue>(ArrayList()) - private var loading = false - var searchQuery = "" - var filterMode = FILTER_ALL - - fun loadItems(eraseOldResults: Boolean, offset: Long = 0) = modelScope.launch(Dispatchers.Main) { - if (loading) { - return@launch - } - loading = true - - val items = if (searchQuery.isNotBlank()) { - val queryPattern = "%${searchQuery.trim()}%" - AppDatabase.db.historyDao().search(queryPattern, queryPattern) - } else { - AppDatabase.db.historyDao().allByLimitOffset(offset) - } - - val filtered = when (filterMode) { - FILTER_TODAY -> { - val startOfDay = getStartOfDay(0) - items.filter { it.time >= startOfDay } - } - FILTER_YESTERDAY -> { - val startOfYesterday = getStartOfDay(1) - val startOfToday = getStartOfDay(0) - items.filter { it.time in startOfYesterday until startOfToday } - } - FILTER_OLDER -> { - val startOfYesterday = getStartOfDay(1) - items.filter { it.time < startOfYesterday } - } - else -> items - } - - lastLoadedItems.value = filtered - loading = false - } - - private fun getStartOfDay(daysAgo: Int): Long { - val cal = Calendar.getInstance() - cal.add(Calendar.DAY_OF_YEAR, -daysAgo) - cal.set(Calendar.HOUR_OF_DAY, 0) - cal.set(Calendar.MINUTE, 0) - cal.set(Calendar.SECOND, 0) - cal.set(Calendar.MILLISECOND, 0) - return cal.timeInMillis - } - - companion object { - const val FILTER_ALL = 0 - const val FILTER_TODAY = 1 - const val FILTER_YESTERDAY = 2 - const val FILTER_OLDER = 3 - } -} diff --git a/app/src/main/java/com/bansify/internet/activity/lock/AppLockActivity.kt b/app/src/main/java/com/bansify/internet/activity/lock/AppLockActivity.kt deleted file mode 100644 index 45834fe8..00000000 --- a/app/src/main/java/com/bansify/internet/activity/lock/AppLockActivity.kt +++ /dev/null @@ -1,201 +0,0 @@ -package com.bansify.internet.activity.lock - -import android.content.Context -import android.os.Bundle -import android.view.KeyEvent -import android.view.View -import android.widget.Button -import android.widget.TextView -import android.widget.Toast -import androidx.appcompat.app.AppCompatActivity -import androidx.appcompat.app.AppCompatDelegate -import com.bansify.internet.AppContext -import com.bansify.internet.Config -import com.bansify.internet.R -import com.bansify.internet.singleton.AppLockManager - -class AppLockActivity : AppCompatActivity() { - - private val inputPin = StringBuilder() - private lateinit var dot1: View - private lateinit var dot2: View - private lateinit var dot3: View - private lateinit var dot4: View - private var dotsContainer: View? = null - - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - applyThemeMode() - if (!AppLockManager.requiresUnlock(this)) { - AppLockManager.setSessionUnlocked(this, true) - setResult(RESULT_OK) - finish() - overridePendingTransition(0, 0) - return - } - setContentView(R.layout.activity_app_lock) - - dot1 = findViewById(R.id.dot1) - dot2 = findViewById(R.id.dot2) - dot3 = findViewById(R.id.dot3) - dot4 = findViewById(R.id.dot4) - dotsContainer = findViewById(R.id.llDotsContainer) - - setupKeypad() - } - - private fun applyThemeMode() { - when (AppContext.provideConfig().theme.value) { - Config.Theme.BLACK_AMOLED, - Config.Theme.BLACK_CHARCOAL, - Config.Theme.BLACK_MIDNIGHT -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) - Config.Theme.WHITE_PURE, - Config.Theme.WHITE_WARM, - Config.Theme.WHITE_COOL -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) - else -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) - } - } - - override fun attachBaseContext(newBase: Context?) { - if (newBase != null) { - val cfg = AppContext.provideConfig() - val scale = cfg.getUiScaleDensityMultiplier() - if (kotlin.math.abs(scale - 1.0f) > 0.001f) { - val overrideConfig = android.content.res.Configuration(newBase.resources.configuration) - val targetDpi = (newBase.resources.displayMetrics.densityDpi * scale).toInt().coerceAtLeast(1) - overrideConfig.densityDpi = targetDpi - val scaledContext = newBase.createConfigurationContext(overrideConfig) - super.attachBaseContext(scaledContext) - return - } - } - super.attachBaseContext(newBase) - } - - private fun setupKeypad() { - val keys = listOf( - R.id.btnKey0 to "0", - R.id.btnKey1 to "1", - R.id.btnKey2 to "2", - R.id.btnKey3 to "3", - R.id.btnKey4 to "4", - R.id.btnKey5 to "5", - R.id.btnKey6 to "6", - R.id.btnKey7 to "7", - R.id.btnKey8 to "8", - R.id.btnKey9 to "9" - ) - - for ((btnId, digit) in keys) { - findViewById