Compare commits

..

1 Commits

Author SHA1 Message Date
Sylvia van Os
7f64449167 Codedump 2023-09-27 22:54:03 +02:00
1240 changed files with 3919 additions and 12755 deletions

View File

@@ -2,29 +2,9 @@ version: 2
updates:
- package-ecosystem: "gradle"
directory: "/"
registries:
- google
- gradlePluginPortal
- jitpack
- mavenCentral
schedule:
interval: "daily"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
# Workaround for https://github.com/dependabot/dependabot-core/issues/6888
registries:
google:
type: maven-repository
url: "https://dl.google.com/dl/android/maven2/"
gradlePluginPortal:
type: maven-repository
url: "https://plugins.gradle.org/m2/"
jitpack:
type: maven-repository
url: "https://jitpack.io/"
mavenCentral:
type: maven-repository
url: "https://repo1.maven.org/maven2/"

View File

@@ -28,47 +28,27 @@ env:
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
flavor: [Foss, Gplay]
steps:
- uses: actions/checkout@v4.2.2
- name: Fail on bad translations
run: if grep -ri "<xliff" app/src/main/res/values*/strings.xml; then echo "Invalidly escaped translations found"; exit 1; fi
- uses: gradle/actions/wrapper-validation@v4
- name: set up OpenJDK 17
run: |
sudo apt-get update
sudo apt-get install -y openjdk-17-jdk-headless
sudo update-alternatives --auto java
- name: Build
run: ./gradlew assemble${{ matrix.flavor }}Release
- name: Check lint
run: ./gradlew lint${{ matrix.flavor }}Release
- name: Run unit tests
run: timeout 5m ./gradlew test${{ matrix.flavor }}ReleaseUnitTest || { ./gradlew --stop && timeout 5m ./gradlew test${{ matrix.flavor }}ReleaseUnitTest; }
- name: Enable KVM
run: |
echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules
sudo udevadm control --reload-rules
sudo udevadm trigger --name-match=kvm
- name: Run instrumented tests (API 21)
uses: ReactiveCircus/android-emulator-runner@v2
with:
api-level: 21
arch: x86_64
script: ./gradlew connected${{ matrix.flavor }}DebugAndroidTest
- name: Run instrumented tests (API 34)
uses: ReactiveCircus/android-emulator-runner@v2
with:
api-level: 34
arch: x86_64
script: ./gradlew connected${{ matrix.flavor }}DebugAndroidTest
- name: SpotBugs
run: ./gradlew spotbugs${{ matrix.flavor }}Release
- name: Archive test results
if: always()
uses: actions/upload-artifact@v4.6.0
with:
name: test-results-flavor${{ matrix.flavor }}
path: app/build/reports
- uses: actions/checkout@v4.0.0
- name: Fail on bad translations
run: if grep -ri "<xliff" app/src/main/res/values*/strings.xml; then echo "Invalidly escaped translations found"; exit 1; fi
- uses: gradle/wrapper-validation-action@v1
- name: set up OpenJDK 17
run: |
sudo apt-get update
sudo apt-get install -y openjdk-17-jdk-headless
sudo update-alternatives --auto java
- name: Build
run: ./gradlew assembleRelease
- name: Check lint
run: ./gradlew lintRelease
- name: Run unit tests
run: timeout 5m ./gradlew testReleaseUnitTest || { ./gradlew --stop && timeout 5m ./gradlew testReleaseUnitTest; }
- name: SpotBugs
run: ./gradlew spotbugsRelease
- name: Archive test results
if: always()
uses: actions/upload-artifact@v3.1.3
with:
name: test-results
path: app/build/reports

View File

@@ -27,15 +27,15 @@ jobs:
steps:
- name: Checkout repo
id: checkout
uses: actions/checkout@v4.2.2
uses: actions/checkout@v4.0.0
- name: Setup Python
uses: actions/setup-python@v5.3.0
uses: actions/setup-python@v4.7.0
with:
python-version: '3.x'
- name: Run converter script
run: python .scripts/changelog_to_fastlane.py
- name: Create Pull Request
uses: peter-evans/create-pull-request@v7.0.6
uses: peter-evans/create-pull-request@v5.0.2
with:
title: "Update Fastlane changelogs"
commit-message: "Update Fastlane changelogs"

View File

@@ -25,15 +25,14 @@ jobs:
steps:
- name: Checkout repo
id: checkout
uses: actions/checkout@v4.2.2
uses: actions/checkout@v4.0.0
- name: Update contributors
id: update_contributors
uses: TheLastProject/contributors-to-file-action@v3.2.0
uses: TheLastProject/contributors-to-file-action@v3.0.1
with:
file_in_repo: app/src/main/res/raw/contributors.txt
min_commit_count: 5
- name: Create Pull Request
uses: peter-evans/create-pull-request@v7.0.6
uses: peter-evans/create-pull-request@v5.0.2
with:
title: "Update contributors"
commit-message: "Update contributors"

View File

@@ -6,7 +6,6 @@ on:
- main
paths:
- 'fastlane/**/title.txt'
- '.scripts/generate_feature_graphic/**'
permissions:
actions: none
checks: none
@@ -25,7 +24,7 @@ jobs:
generate-feature-graphic:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4.2.2
- uses: actions/checkout@v4.0.0
- name: Install requirements
run: |
sudo apt-get update
@@ -37,9 +36,41 @@ jobs:
find .scripts/generate_feature_graphic/fonts -name '*.ttf' -exec cp {} "$HOME/.fonts" \;
fc-cache
- name: Generate featureGraphic.png for each language
run: .scripts/generate_feature_graphic/generate_feature_graphic.sh
run: |
for lang in fastlane/metadata/android/*; do
pushd "$lang"
# Place temporary copy for editing if needed
cp ../../../../.scripts/generate_feature_graphic/featureGraphic.svg featureGraphic.svg
# Extract text after 'Catima - '
export subtext="$(grep -oP '(?<=Catima \S ).*' title.txt || true)"
# If there is subtext, change the .svg accordingly
if [ -n "$subtext" ]; then
perl -pi -e 's/Loyalty Card Wallet/$ENV{subtext}/' featureGraphic.svg
# Set correct font for language if needed (Lexend Deca has limited support)
# We specifically need the Serif version because of the 200 weight
case "$(basename "$lang")" in
bg|el-GR|ru-RU|uk) sed -i "s/Lexend Deca/Noto Serif/" featureGraphic.svg ;;
ja-JP) sed -i "s/Lexend Deca/Noto Serif CJK JP/" featureGraphic.svg ;;
ko) sed -i "s/Lexend Deca/Noto Serif CJK KR/" featureGraphic.svg ;;
zh-CN) sed -i "s/Lexend Deca/Noto Serif CJK SC/" featureGraphic.svg ;;
zh-TW) sed -i "s/Lexend Deca/Noto Serif CJK TC/" featureGraphic.svg ;;
*) ;;
esac
fi
# Ensure images directory exists
mkdir -p images
# Generate .png
convert featureGraphic.svg images/featureGraphic.png
# Optimize .png
optipng images/featureGraphic.png
# Remove metadata (timestamps) from .png
mat2 --inplace images/featureGraphic.png
# Remove temporary .svg
rm featureGraphic.svg
popd
done
- name: Create Pull Request
uses: peter-evans/create-pull-request@v7.0.6
uses: peter-evans/create-pull-request@v5.0.2
with:
title: "Update feature graphic"
commit-message: "Update feature graphic"

View File

@@ -1,33 +0,0 @@
name: Gradle update
on:
workflow_dispatch:
schedule:
- cron: '3 6 * * *'
permissions:
actions: none
checks: none
contents: write
deployments: none
discussions: none
id-token: none
issues: none
packages: none
pages: none
pull-requests: write
repository-projects: none
security-events: none
statuses: none
jobs:
gradle-update:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4.2.2
- uses: obfusk/gradle-update-action@v3.0.0
id: gradle-update
- uses: gradle/actions/wrapper-validation@v4
- name: Create Pull Request
uses: peter-evans/create-pull-request@v7.0.6
with:
title: "Update Gradle to ${{ steps.gradle-update.outputs.version }}"
commit-message: "Update Gradle to ${{ steps.gradle-update.outputs.version }}"
branch-suffix: timestamp

View File

@@ -5,7 +5,6 @@ on:
branches:
- main
paths:
- app/src/main/res/values-*/strings.xml
- app/src/main/res/values/settings.xml
permissions:
actions: none
@@ -25,13 +24,11 @@ jobs:
update-locales:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4.2.2
- name: Add new locales
run: .scripts/new-locales.py
- uses: actions/checkout@v4.0.0
- name: Update locales
run: .scripts/locales.py
- name: Create Pull Request
uses: peter-evans/create-pull-request@v7.0.6
uses: peter-evans/create-pull-request@v5.0.2
with:
title: "Update locales"
commit-message: "Update locales"

29
.gitignore vendored
View File

@@ -1,30 +1,15 @@
# Android Studio generated (superseded/unused rules commented out)
*.iml
.gradle
/local.properties
#/.idea/caches
#/.idea/libraries
#/.idea/modules.xml
#/.idea/workspace.xml
#/.idea/navEditor.xml
#/.idea/assetWizardSettings.xml
local.properties
.idea/
.DS_Store
/build
/captures
.externalNativeBuild
.cxx
#local.properties
# Android extras
/app/*.log
/app/build
/app/release
/.idea
build/
captures/
**/release
**/debug
app/*.log
# Bundle
/.bundle/
/vendor/bundle
/lib/bundler/man/
# Catima-specific
SHA256SUMS

View File

@@ -1,60 +0,0 @@
#!/bin/bash
set -euo pipefail
script_location="$(dirname "$(readlink -f "$0")")"
for lang in "$script_location/../../fastlane/metadata/android/"*; do
# Skip languages without title.txt
if [ ! -f "$lang/title.txt" ]; then
continue
fi
pushd "$lang"
# Place temporary copy for editing if needed
cp "$script_location/featureGraphic.svg" featureGraphic.svg
if grep -q — title.txt; then
# Try splitting title.txt on — (em dash)
IFS='—' read -r appname subtext < title.txt
elif grep -q title.txt; then
# No result, try splitting title.txt on (en dash)
IFS='' read -r appname subtext < title.txt
elif grep -q - title.txt; then
# No result, try splitting on - (dash)
IFS='-' read -r appname subtext < title.txt
else
# No result, use the full title as app name and default subtext
appname=$(< title.txt)
subtext="Loyalty Card Wallet"
fi
export appname=${appname%% }
export subtext=${subtext## }
# If the appname isn't Catima or there is subtext, change the .svg accordingly
if [ "$appname" != "Catima" ] || [ -n "$subtext" ]; then
perl -pi -e 's/Catima/$ENV{appname}/' featureGraphic.svg
perl -pi -e 's/Loyalty Card Wallet/$ENV{subtext}/' featureGraphic.svg
# Set correct font or font size for language if needed
# (Lexend Deca has limited support and some characters are big)
# We specifically need the Serif version because of the 200 weight
case "$(basename "$lang")" in
bg|el-GR|ru-RU|uk) sed -i "s/Lexend Deca/Noto Serif/" featureGraphic.svg ;;
hi-IN) sed -i -e "s/Yesteryear/Noto Sans Devanagari/" -e "s/Lexend Deca/Noto Serif Devanagari/" featureGraphic.svg ;;
ja-JP) sed -i "s/Lexend Deca/Noto Serif CJK JP/" featureGraphic.svg ;;
kn-IN) sed -i -e 's/font-size="150"/font-size="100"/' -e "s/Yesteryear/Noto Serif Kannada/" featureGraphic.svg ;;
ko) sed -i "s/Lexend Deca/Noto Serif CJK KR/" featureGraphic.svg ;;
zh-CN) sed -i "s/Lexend Deca/Noto Serif CJK SC/" featureGraphic.svg ;;
zh-TW) sed -i -e "s/Yesteryear/Noto Sans CJK TC/" -e "s/Lexend Deca/Noto Serif CJK TC/" featureGraphic.svg ;;
*) ;;
esac
fi
# Ensure images directory exists
mkdir -p images
# Generate .png
convert featureGraphic.svg images/featureGraphic.png
# Optimize .png
optipng images/featureGraphic.png
# Remove metadata (timestamps) from .png
mat2 --inplace images/featureGraphic.png
# Remove temporary .svg
rm featureGraphic.svg
popd
done

View File

@@ -19,12 +19,12 @@ res = ", ".join(f'"{loc}"' for loc in locales)
sed = [
"sed",
"-i",
f"s/resourceConfigurations .*/resourceConfigurations += listOf({res})/",
"app/build.gradle.kts"
f"s/resourceConfigurations .*/resourceConfigurations += [{res}]/",
"app/build.gradle"
]
subprocess.run(sed, check=True)
with open("app/src/main/res/xml/locales_config.xml", "w", encoding="utf-8") as fh:
with open("app/src/main/res/xml/locales_config.xml", "w") as fh:
fh.write('<?xml version="1.0" encoding="utf-8"?>\n')
fh.write('<locale-config xmlns:android="http://schemas.android.com/apk/res/android">\n')
fh.write(' <locale android:name="en-US" />\n')

View File

@@ -1,132 +0,0 @@
#!/usr/bin/python3
import glob
import re
from typing import Iterator, List, Tuple
import requests
MIN_PERCENT = 90
NOT_LANGS = ("night", "w600dp")
REPLACE_CODES = {
"el": "el-rGR",
"id": "in-rID",
"ro": "ro-rRO",
"zh_Hans": "zh-rCN",
"zh_Hant": "zh-rTW",
}
STATS_URL = "https://hosted.weblate.org/api/components/catima/catima/statistics/"
class Error(Exception):
pass
def get_weblate_langs() -> List[Tuple[str, int]]:
url = STATS_URL
results = []
for _ in range(16): # avoid endless loops just in case
r = requests.get(url, timeout=5)
r.raise_for_status()
data = r.json()
for lang in data["results"]:
if lang["code"] != "en":
code = REPLACE_CODES.get(lang["code"], lang["code"]).replace("_", "-r")
results.append((code, round(lang["translated_percent"])))
url = data["next"]
if not url:
return sorted(results)
if not url.split("?")[0] == STATS_URL:
raise Error(f"Unexpected next URL: {url}")
raise Error("Too many pages")
def get_dir_langs() -> List[str]:
results = []
for d in glob.glob("app/src/main/res/values-*"):
code = d.split("-", 1)[1]
if code not in NOT_LANGS:
results.append(code)
return sorted(results)
def get_xml_langs() -> List[Tuple[str, bool]]:
results = []
in_section = False
with open("app/src/main/res/values/settings.xml", encoding="utf-8") as fh:
for line in fh:
if not in_section and 'name="locale_values"' in line:
in_section = True
elif in_section:
if "string-array" in line:
break
disabled = "<!--" in line
if m := re.search(r">(.*)<", line):
if m[1] != "en":
results.append((m[1], disabled))
return sorted(results)
def update_xml_langs(langs: List[Tuple[str, bool]]) -> None:
lines: List[str] = []
in_section = False
with open("app/src/main/res/values/settings.xml", encoding="utf-8") as fh:
for line in fh:
if not in_section and 'name="locale_values"' in line:
in_section = True
elif in_section:
if "string-array" in line:
in_section = False
lines.extend(_lang_lines(langs))
else:
continue
lines.append(line)
with open("app/src/main/res/values/settings.xml", "w", encoding="utf-8") as fh:
for line in lines:
fh.write(line)
def _lang_lines(langs: List[Tuple[str, bool]]) -> Iterator[str]:
yield " <item />\n"
for lang, disabled in sorted(langs + [("en", False)]):
if disabled:
yield f" <!-- <item>{lang}</item> -->\n"
else:
yield f" <item>{lang}</item>\n"
def main() -> None:
web_langs = get_weblate_langs()
dir_langs = get_dir_langs()
xml_langs = get_xml_langs()
web_codes = set(code for code, _ in web_langs)
dir_codes = set(dir_langs)
xml_codes = set(code for code, _ in xml_langs)
if diff := web_codes - dir_codes:
print(f"WARNING: Weblate codes w/o dir: {diff}")
if diff := xml_codes - dir_codes:
print(f"WARNING: XML codes w/o dir: {diff}")
percentages = dict(web_langs)
all_langs = xml_langs[:]
# add new langs as disabled
for code in dir_codes - xml_codes:
all_langs.append((code, True))
# enable disabled langs if they are at least MIN_PERCENT translated now
updated_langs = sorted(
(code, percentages[code] < MIN_PERCENT if disabled else disabled)
for code, disabled in all_langs
)
if updated_langs != xml_langs:
print("Updating...")
update_xml_langs(updated_langs)
if __name__ == "__main__":
main()

View File

@@ -1,85 +1,9 @@
# Changelog
## v2.34.3 - 145 (2025-01-15)
- Target Android 15
- Fix keyboard covering save button in edit screen
- Fix some pkpass files not being detected as pkpass (application/vnd-com.apple.pkpass mime type support)
## v2.34.2 - 144 (2024-12-26)
- Improve archive/starred icon display
## v2.34.1 - 143 (2024-12-12)
- Fix crash when opening invalid pkpass files
## v2.34.0 - 142 (2024-12-10)
- Add Passbook (.pkpass) support
- Fix import of transparent PDF files
- Improve display of transparent thumbnails
## v2.33.0 - 141 (2024-11-19)
- Change default column on wide screens to 4
- Allow overriding column counts for portrait and landscape in settings
- Keep main screen search filter when rotating screen or opening a card
- Limit max length of note display on main screen
## v2.32.1 - 140 (2024-10-29)
- Fix text wrapping on add dialog
## v2.32.0 - 139 (2024-10-28)
- Option to navigate cards using the volume buttons
- Fix Stocard import
- Fix "Import cancelled" message appearing after successful import
## v2.31.1 - 138 (2024-08-24)
- Fix back gesture on main screen dismissing keyboard and search on Android 13+
## v2.31.0 - 137 (2024-07-26)
- Allow long store names in preview to split over multiple lines
- Option to use front of back image in thumbnail menu
- Minor import/export fixes
- Minor UI fixes
## v2.30.0 - 136 (2024-06-18)
- Support for creating a card when sharing plain text
- Display image type instead of barcode below images
- Fix possible crash when trying to import a backup from the Nextcloud app
- Improved support for devices without camera
## v2.29.1 - 135 (2024-05-19)
- Various fixes and improvements to balance handling
## v2.29.0 - 134 (2024-04-19)
- Support for scanning PDF files for barcodes
- Support for image files with multiple barcodes
- Minor UI fixes
## v2.28.0 - 133 (2024-03-08)
- Target Android 14
- Open card icon in gallery on touch
- Improve design of Photos tab in edit view
- Update spending screen to also support receiving
## v2.27.0 - 132 (2024-01-30)
## Unreleased - 132
- Refine "Add card" workflow
- Validation flow improvements
- Fix edge case causing invalid UI state when toggling showing archive
- Use theme or card colour for navigation bar (Android 8.1+)
- Updated validity and expiry date selector
- Add option to always rotate (ignoring system settings)
## v2.26.0 - 131 (2023-09-14)

View File

@@ -1,128 +0,0 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
catima.g9ex3@hackerchick.me.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.

View File

@@ -1,15 +1,13 @@
# How to Submit Patches to the Catima Project
How to Submit Patches to the Catima Project
===============================================================================
https://github.com/TheLastProject/Catima
This document is intended to act as a guide to help you contribute to the
Catima project. It is not perfect, and there will always be exceptions
Catima project. It is not perfect, and there will always be exceptions
to the rules described here, but by following the instructions below you
should have a much easier time getting your work merged with the upstream
project.
When contributing, you certify that you agree to and have the rights to submit
your contribution under the project's license and understand that git will
store your name and email address in project history indefinitely.
## Translation Changes
Translation changes are managed through [Weblate](https://hosted.weblate.org/projects/catima/).
@@ -59,6 +57,44 @@ if you can describe/include a reproducer for the problem in the description as
well as instructions on how to test for the bug and verify that it has been
fixed.
### Sign Your Work
The sign-off is a simple line at the end of the patch description, which
certifies that you wrote it or otherwise have the right to pass it on as an
open-source patch. The "Developer's Certificate of Origin" pledge is taken
from the Linux Kernel and the rules are pretty simple:
Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
(b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
(c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
(d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.
... then you just add a line to the bottom of your patch description, with
your real name, saying:
Signed-off-by: Random J Developer <random@developer.example.org>
### Submit Patch(es) for Review
Finally, you will need to submit your patches so that they can be reviewed

View File

@@ -1,32 +1,29 @@
GEM
remote: https://rubygems.org/
specs:
CFPropertyList (3.0.7)
base64
nkf
CFPropertyList (3.0.6)
rexml
addressable (2.8.7)
public_suffix (>= 2.0.2, < 7.0)
artifactory (3.0.17)
addressable (2.8.5)
public_suffix (>= 2.0.2, < 6.0)
artifactory (3.0.15)
atomos (0.1.3)
aws-eventstream (1.3.0)
aws-partitions (1.1020.0)
aws-sdk-core (3.214.0)
aws-eventstream (~> 1, >= 1.3.0)
aws-partitions (~> 1, >= 1.992.0)
aws-sigv4 (~> 1.9)
aws-eventstream (1.2.0)
aws-partitions (1.824.0)
aws-sdk-core (3.181.1)
aws-eventstream (~> 1, >= 1.0.2)
aws-partitions (~> 1, >= 1.651.0)
aws-sigv4 (~> 1.5)
jmespath (~> 1, >= 1.6.1)
aws-sdk-kms (1.96.0)
aws-sdk-core (~> 3, >= 3.210.0)
aws-sigv4 (~> 1.5)
aws-sdk-s3 (1.176.0)
aws-sdk-core (~> 3, >= 3.210.0)
aws-sdk-kms (1.71.0)
aws-sdk-core (~> 3, >= 3.177.0)
aws-sigv4 (~> 1.1)
aws-sdk-s3 (1.134.0)
aws-sdk-core (~> 3, >= 3.181.0)
aws-sdk-kms (~> 1)
aws-sigv4 (~> 1.5)
aws-sigv4 (1.10.1)
aws-sigv4 (~> 1.6)
aws-sigv4 (1.6.0)
aws-eventstream (~> 1, >= 1.0.2)
babosa (1.0.4)
base64 (0.2.0)
claide (1.1.0)
colored (1.2)
colored2 (3.1.2)
@@ -35,11 +32,12 @@ GEM
declarative (0.0.20)
digest-crc (0.6.5)
rake (>= 12.0.0, < 14.0.0)
domain_name (0.6.20240107)
domain_name (0.5.20190701)
unf (>= 0.0.5, < 1.0.0)
dotenv (2.8.1)
emoji_regex (3.2.3)
excon (0.112.0)
faraday (1.10.4)
excon (0.103.0)
faraday (1.10.3)
faraday-em_http (~> 1.0)
faraday-em_synchrony (~> 1.0)
faraday-excon (~> 1.1)
@@ -60,22 +58,22 @@ GEM
faraday-httpclient (1.0.1)
faraday-multipart (1.0.4)
multipart-post (~> 2)
faraday-net_http (1.0.2)
faraday-net_http (1.0.1)
faraday-net_http_persistent (1.2.0)
faraday-patron (1.0.0)
faraday-rack (1.0.0)
faraday-retry (1.0.3)
faraday_middleware (1.2.1)
faraday_middleware (1.2.0)
faraday (~> 1.0)
fastimage (2.3.1)
fastlane (2.226.0)
fastimage (2.2.7)
fastlane (2.215.1)
CFPropertyList (>= 2.3, < 4.0.0)
addressable (>= 2.8, < 3.0.0)
artifactory (~> 3.0)
aws-sdk-s3 (~> 1.0)
babosa (>= 1.0.3, < 2.0.0)
bundler (>= 1.12.0, < 3.0.0)
colored (~> 1.2)
colored
commander (~> 4.6)
dotenv (>= 2.1.1, < 3.0.0)
emoji_regex (>= 0.1, < 4.0)
@@ -84,11 +82,9 @@ GEM
faraday-cookie_jar (~> 0.0.6)
faraday_middleware (~> 1.0)
fastimage (>= 2.1.0, < 3.0.0)
fastlane-sirp (>= 1.0.0)
gh_inspector (>= 1.1.2, < 2.0.0)
google-apis-androidpublisher_v3 (~> 0.3)
google-apis-playcustomapp_v1 (~> 0.1)
google-cloud-env (>= 1.6.0, < 2.0.0)
google-cloud-storage (~> 1.31)
highline (~> 2.0)
http-cookie (~> 1.0.5)
@@ -97,10 +93,10 @@ GEM
mini_magick (>= 4.9.4, < 5.0.0)
multipart-post (>= 2.0.0, < 3.0.0)
naturally (~> 2.2)
optparse (>= 0.1.1, < 1.0.0)
optparse (~> 0.1.1)
plist (>= 3.1.0, < 4.0.0)
rubyzip (>= 2.0.0, < 3.0.0)
security (= 0.1.5)
security (= 0.1.3)
simctl (~> 1.6.3)
terminal-notifier (>= 2.0.0, < 3.0.0)
terminal-table (~> 3)
@@ -108,14 +104,12 @@ GEM
tty-spinner (>= 0.8.0, < 1.0.0)
word_wrap (~> 1.0.0)
xcodeproj (>= 1.13.0, < 2.0.0)
xcpretty (~> 0.4.0)
xcpretty-travis-formatter (>= 0.0.3, < 2.0.0)
fastlane-sirp (1.0.0)
sysrandom (~> 1.0)
xcpretty (~> 0.3.0)
xcpretty-travis-formatter (>= 0.0.3)
gh_inspector (1.1.3)
google-apis-androidpublisher_v3 (0.54.0)
google-apis-androidpublisher_v3 (0.49.0)
google-apis-core (>= 0.11.0, < 2.a)
google-apis-core (0.11.3)
google-apis-core (0.11.1)
addressable (~> 2.5, >= 2.5.1)
googleauth (>= 0.16.2, < 2.a)
httpclient (>= 2.8.1, < 3.a)
@@ -123,63 +117,62 @@ GEM
representable (~> 3.0)
retriable (>= 2.0, < 4.a)
rexml
webrick
google-apis-iamcredentials_v1 (0.17.0)
google-apis-core (>= 0.11.0, < 2.a)
google-apis-playcustomapp_v1 (0.13.0)
google-apis-core (>= 0.11.0, < 2.a)
google-apis-storage_v1 (0.31.0)
google-apis-core (>= 0.11.0, < 2.a)
google-cloud-core (1.7.1)
google-cloud-env (>= 1.0, < 3.a)
google-apis-storage_v1 (0.19.0)
google-apis-core (>= 0.9.0, < 2.a)
google-cloud-core (1.6.0)
google-cloud-env (~> 1.0)
google-cloud-errors (~> 1.0)
google-cloud-env (1.6.0)
faraday (>= 0.17.3, < 3.0)
google-cloud-errors (1.4.0)
google-cloud-storage (1.47.0)
google-cloud-errors (1.3.1)
google-cloud-storage (1.44.0)
addressable (~> 2.8)
digest-crc (~> 0.4)
google-apis-iamcredentials_v1 (~> 0.1)
google-apis-storage_v1 (~> 0.31.0)
google-apis-storage_v1 (~> 0.19.0)
google-cloud-core (~> 1.6)
googleauth (>= 0.16.2, < 2.a)
mini_mime (~> 1.0)
googleauth (1.8.1)
googleauth (1.8.0)
faraday (>= 0.17.3, < 3.a)
jwt (>= 1.4, < 3.0)
multi_json (~> 1.11)
os (>= 0.9, < 2.0)
signet (>= 0.16, < 2.a)
highline (2.0.3)
http-cookie (1.0.8)
http-cookie (1.0.5)
domain_name (~> 0.5)
httpclient (2.8.3)
jmespath (1.6.2)
json (2.9.0)
jwt (2.9.3)
base64
mini_magick (4.13.2)
json (2.6.3)
jwt (2.7.1)
mini_magick (4.12.0)
mini_mime (1.1.5)
multi_json (1.15.0)
multipart-post (2.4.1)
nanaimo (0.4.0)
multipart-post (2.3.0)
nanaimo (0.3.0)
naturally (2.2.1)
nkf (0.2.0)
optparse (0.6.0)
optparse (0.1.1)
os (1.1.4)
plist (3.7.1)
public_suffix (6.0.1)
rake (13.2.1)
plist (3.7.0)
public_suffix (5.0.3)
rake (13.0.6)
representable (3.2.0)
declarative (< 0.1.0)
trailblazer-option (>= 0.1.1, < 0.2.0)
uber (< 0.2.0)
retriable (3.1.2)
rexml (3.3.9)
rouge (3.28.0)
rexml (3.2.6)
rouge (2.0.7)
ruby2_keywords (0.0.5)
rubyzip (2.3.2)
security (0.1.5)
signet (0.19.0)
security (0.1.3)
signet (0.18.0)
addressable (~> 2.8)
faraday (>= 0.17.5, < 3.a)
jwt (>= 1.5, < 3.0)
@@ -187,27 +180,30 @@ GEM
simctl (1.6.10)
CFPropertyList
naturally
sysrandom (1.0.5)
terminal-notifier (2.0.0)
terminal-table (3.0.2)
unicode-display_width (>= 1.1.1, < 3)
trailblazer-option (0.1.2)
tty-cursor (0.7.1)
tty-screen (0.8.2)
tty-screen (0.8.1)
tty-spinner (0.9.3)
tty-cursor (~> 0.7)
uber (0.1.0)
unicode-display_width (2.6.0)
unf (0.1.4)
unf_ext
unf_ext (0.0.8.2)
unicode-display_width (2.4.2)
webrick (1.8.1)
word_wrap (1.0.0)
xcodeproj (1.27.0)
xcodeproj (1.22.0)
CFPropertyList (>= 2.3.3, < 4.0)
atomos (~> 0.1.3)
claide (>= 1.0.2, < 2.0)
colored2 (~> 3.1)
nanaimo (~> 0.4.0)
rexml (>= 3.3.6, < 4.0)
xcpretty (0.4.0)
rouge (~> 3.28.0)
nanaimo (~> 0.3.0)
rexml (~> 3.2.4)
xcpretty (0.3.0)
rouge (~> 2.0.7)
xcpretty-travis-formatter (1.0.1)
xcpretty (~> 0.2, >= 0.0.7)
@@ -218,4 +214,4 @@ DEPENDENCIES
fastlane
BUNDLED WITH
2.5.22
2.3.26

165
app/build.gradle Normal file
View File

@@ -0,0 +1,165 @@
import com.github.spotbugs.snom.SpotBugsTask
plugins {
id 'com.android.application'
id 'com.github.spotbugs'
}
spotbugs {
ignoreFailures = false
effort = 'max'
excludeFilter = file("./config/spotbugs/exclude.xml")
reportsDir = file("$buildDir/reports/spotbugs/")
}
android {
compileSdk 33
defaultConfig {
applicationId "me.hackerchick.catima"
minSdk 21
targetSdk 33
versionCode 131
versionName "2.26.0"
vectorDrawables.useSupportLibrary true
multiDexEnabled true
resourceConfigurations += ["ar", "bg", "bn", "bn-rIN", "bs", "cs", "da", "de", "el-rGR", "en", "eo", "es", "es-rAR", "fi", "fr", "he-rIL", "hi", "hr", "hu", "in-rID", "is", "it", "ja", "ko", "lt", "lv", "nb-rNO", "nl", "oc", "pl", "pt", "ro-rRO", "ru", "sk", "sl", "sv", "tr", "uk", "zh-rTW", "zh-rCN"]
//testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
flavorDimensions "version"
productFlavors {
fdroid {
dimension "version"
}
screengrab {
dimension "version"
applicationIdSuffix = ".screengrab"
}
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
resValue "string", "app_name", "Catima"
}
debug {
applicationIdSuffix ".debug"
resValue "string", "app_name", "Catima Debug"
}
}
buildFeatures {
viewBinding true
}
bundle {
language {
enableSplit = false
}
}
compileOptions {
encoding "UTF-8"
// Flag to enable support for the new language APIs
coreLibraryDesugaringEnabled true
sourceCompatibility JavaVersion.VERSION_11
targetCompatibility JavaVersion.VERSION_11
}
sourceSets {
test {
resources.srcDirs += ['src/test/res']
}
}
// Starting with Android Studio 3 Robolectric is unable to find resources.
// The following allows it to find the resources.
testOptions {
unitTests {
all {
testLogging {
events 'started', 'passed', 'skipped', 'failed'
}
}
includeAndroidResources true
}
}
lint {
lintConfig file('lint.xml')
}
namespace 'protect.card_locker'
}
dependencies {
// AndroidX
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'androidx.exifinterface:exifinterface:1.3.6'
implementation 'androidx.palette:palette:1.0.0'
implementation 'androidx.preference:preference:1.2.0'
implementation 'com.google.android.material:material:1.9.0'
implementation 'com.github.yalantis:ucrop:2.2.8'
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:2.0.3'
// Splash Screen
implementation 'androidx.core:core-splashscreen:1.0.1'
// Third-party
implementation 'com.journeyapps:zxing-android-embedded:4.3.0@aar'
implementation 'com.google.zxing:core:3.5.2'
implementation 'org.apache.commons:commons-csv:1.9.0'
implementation 'com.jaredrummler:colorpicker:1.1.0'
implementation 'net.lingala.zip4j:zip4j:2.11.5'
// SpotBugs
implementation 'io.wcm.tooling.spotbugs:io.wcm.tooling.spotbugs.annotations:1.0.0'
// Testing
testImplementation 'androidx.test:core:1.5.0'
testImplementation 'junit:junit:4.13.2'
testImplementation 'org.robolectric:robolectric:4.10.3'
// Screenshots
testImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
testImplementation 'com.android.support.test:rules:1.0.2'
testImplementation 'com.android.support.test:runner:1.0.2'
testImplementation 'tools.fastlane:screengrab:2.1.1'
}
tasks.withType(SpotBugsTask) {
description 'Run spotbugs'
group 'verification'
//classes = fileTree('build/intermediates/javac/debug/compileDebugJavaWithJavac/classes')
//source = fileTree('src/main/java')
//classpath = files()
reports {
xml.enabled = false
html.enabled = true
}
}
tasks.register('copyRawResFiles', Copy) {
from layout.projectDirectory.file("../CHANGELOG.md"),
layout.projectDirectory.file("../PRIVACY.md")
into layout.projectDirectory.dir("src/main/res/raw")
rename { String fileName -> fileName.toLowerCase() }
}
project.afterEvaluate {
tasks.each { task ->
if (task != copyRawResFiles) {
task.dependsOn(copyRawResFiles)
}
}
}

View File

@@ -1,176 +0,0 @@
import com.android.build.gradle.internal.tasks.factory.dependsOn
import com.github.spotbugs.snom.SpotBugsTask
plugins {
id("com.android.application")
id("com.github.spotbugs")
id("org.jetbrains.kotlin.android")
}
spotbugs {
ignoreFailures.set(false)
setEffort("max")
excludeFilter.set(file("./config/spotbugs/exclude.xml"))
reportsDir.set(layout.buildDirectory.file("reports/spotbugs/").get().asFile)
}
android {
namespace = "protect.card_locker"
compileSdk = 35
defaultConfig {
applicationId = "me.hackerchick.catima"
minSdk = 21
targetSdk = 35
versionCode = 145
versionName = "2.34.3"
vectorDrawables.useSupportLibrary = true
multiDexEnabled = true
resourceConfigurations += listOf("ar", "bg", "bn", "bn-rIN", "bs", "cs", "da", "de", "el-rGR", "en", "eo", "es", "es-rAR", "et", "fi", "fr", "gl", "he-rIL", "hi", "hr", "hu", "in-rID", "is", "it", "ja", "ko", "lt", "lv", "nb-rNO", "nl", "oc", "pl", "pt-rBR", "pt-rPT", "ro-rRO", "ru", "sk", "sl", "sr", "sv", "ta", "tr", "uk", "vi", "zh-rCN", "zh-rTW")
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
buildConfigField("boolean", "showDonate", "true")
buildConfigField("boolean", "showRateOnGooglePlay", "false")
}
buildTypes {
release {
isMinifyEnabled = true
proguardFiles(
getDefaultProguardFile("proguard-android.txt"),
"proguard-rules.pro"
)
}
debug {
applicationIdSuffix = ".debug"
}
}
buildFeatures {
buildConfig = true
viewBinding = true
}
flavorDimensions.add("type")
productFlavors {
create("foss") {
dimension = "type"
isDefault = true
}
create("gplay") {
dimension = "type"
// Google doesn't allow donation links
buildConfigField("boolean", "showDonate", "false")
buildConfigField("boolean", "showRateOnGooglePlay", "true")
}
}
bundle {
language {
enableSplit = false
}
}
compileOptions {
encoding = "UTF-8"
// Flag to enable support for the new language APIs
isCoreLibraryDesugaringEnabled = true
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
sourceSets {
getByName("test") {
resources.srcDirs("src/test/res")
}
}
// Starting with Android Studio 3 Robolectric is unable to find resources.
// The following allows it to find the resources.
testOptions.unitTests.isIncludeAndroidResources = true
tasks.withType<Test>().configureEach {
testLogging {
events("started", "passed", "skipped", "failed")
}
}
lint {
lintConfig = file("lint.xml")
}
kotlinOptions {
jvmTarget = "17"
}
}
dependencies {
// AndroidX
implementation("androidx.appcompat:appcompat:1.7.0")
implementation("androidx.constraintlayout:constraintlayout:2.2.0")
implementation("androidx.core:core-ktx:1.15.0")
implementation("androidx.core:core-splashscreen:1.0.1")
implementation("androidx.exifinterface:exifinterface:1.3.7")
implementation("androidx.palette:palette:1.0.0")
implementation("androidx.preference:preference:1.2.1")
implementation("com.google.android.material:material:1.12.0")
coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4")
// Third-party
implementation("com.journeyapps:zxing-android-embedded:4.3.0@aar")
implementation("com.github.yalantis:ucrop:2.2.10")
implementation("com.google.zxing:core:3.5.3")
implementation("org.apache.commons:commons-csv:1.9.0")
implementation("com.jaredrummler:colorpicker:1.1.0")
implementation("net.lingala.zip4j:zip4j:2.11.5")
// SpotBugs
implementation("io.wcm.tooling.spotbugs:io.wcm.tooling.spotbugs.annotations:1.0.0")
// Testing
val androidXTestVersion = "1.6.1"
val junitVersion = "4.13.2"
testImplementation("androidx.test:core:$androidXTestVersion")
testImplementation("junit:junit:$junitVersion")
testImplementation("org.robolectric:robolectric:4.14.1")
androidTestImplementation("androidx.test:core:$androidXTestVersion")
androidTestImplementation("junit:junit:$junitVersion")
androidTestImplementation("androidx.test.ext:junit:1.2.1")
androidTestImplementation("androidx.test:runner:$androidXTestVersion")
androidTestImplementation("androidx.test.uiautomator:uiautomator:2.3.0")
androidTestImplementation("androidx.test.espresso:espresso-core:3.6.1")
}
tasks.withType<SpotBugsTask>().configureEach {
description = "Run spotbugs"
group = "verification"
//classes = fileTree("build/intermediates/javac/debug/compileDebugJavaWithJavac/classes")
//source = fileTree("src/main/java")
//classpath = files()
reports.maybeCreate("xml").required.set(false)
reports.maybeCreate("html").required.set(true)
}
tasks.register("copyRawResFiles", Copy::class) {
from(
layout.projectDirectory.file("../CHANGELOG.md"),
layout.projectDirectory.file("../PRIVACY.md")
)
into(layout.projectDirectory.dir("src/main/res/raw"))
rename { it.lowercase() }
}.also {
tasks.preBuild.dependsOn(it)
tasks.getByName<Delete>("clean") {
val filesNamesToDelete = listOf("CHANGELOG", "PRIVACY")
filesNamesToDelete.forEach { fileName ->
delete(layout.projectDirectory.file("src/main/res/raw/${fileName.lowercase()}.md"))
}
}
}

View File

@@ -2,7 +2,7 @@
# By default, the flags in this file are appended to flags specified
# in /Users/brarcher/Library/Android/sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.kts.
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html

View File

@@ -1,67 +0,0 @@
package protect.card_locker;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.action.ViewActions.typeText;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.withChild;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals;
import androidx.appcompat.widget.Toolbar;
import androidx.test.core.app.ActivityScenario;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.uiautomator.UiDevice;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
public class MainActivitySearchViewTest {
@Test
public void whenSearchViewIsExpandedAndBackIsPressedThenMenuItemShouldNotBeCollapsed() {
String query = "random arbitrary text";
try (ActivityScenario<MainActivity> mainActivityScenario = ActivityScenario.launch(MainActivity.class)) {
mainActivityScenario.onActivity(this::makeSearchMenuItemVisible);
onView(withId(R.id.action_search)).perform(click());
onView(withId(androidx.appcompat.R.id.search_src_text)).perform(typeText(query));
pressBack();
onView(withId(androidx.appcompat.R.id.search_src_text)).check(matches(withText(query)));
mainActivityScenario.onActivity(activity -> assertEquals(query, activity.mFilter));
}
}
@Test
public void whenSearchViewIsExpandedThenItShouldOnlyBeCollapsedWhenBackIsPressedTwice() {
try (ActivityScenario<MainActivity> mainActivityScenario = ActivityScenario.launch(MainActivity.class)) {
mainActivityScenario.onActivity(this::makeSearchMenuItemVisible);
onView(withId(R.id.action_search)).perform(click());
pressBack();
onView(withId(androidx.appcompat.R.id.search_src_text)).check(matches(isDisplayed()));
pressBack();
onView(withId(android.R.id.content)).check(matches(is(not(withChild(withId(androidx.appcompat.R.id.search_src_text))))));
}
}
private void makeSearchMenuItemVisible(MainActivity activity) {
Toolbar toolbar = activity.findViewById(R.id.toolbar);
toolbar.getMenu().findItem(R.id.action_search).setVisible(true);
}
private void pressBack() {
UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()).pressBack();
}
}

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">تصحيح Catima</string>
</resources>

View File

@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources></resources>

View File

@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources></resources>

View File

@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources></resources>

View File

@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources></resources>

View File

@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources></resources>

View File

@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources></resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Catima Debug</string>
</resources>

View File

@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources></resources>

View File

@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources></resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Catima Debug</string>
</resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Αποσφαλμάτωση Catima</string>
</resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Catima Debug</string>
</resources>

View File

@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources></resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Depuración de Catima</string>
</resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Catima Debug</string>
</resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Catima-vianmääritys</string>
</resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Débogage de Catima</string>
</resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Depuración de Catima</string>
</resources>

View File

@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources></resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">कैटिमा डीबग</string>
</resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Catima Debug</string>
</resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Catima Debug</string>
</resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Catima Debug</string>
</resources>

View File

@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources></resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Catima Debug</string>
</resources>

View File

@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources></resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">ಕ್ಯಾಟಿಮಾ ಡೀಬಗ್</string>
</resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Catima 디버그</string>
</resources>

View File

@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources></resources>

View File

@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources></resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Catima atkļūdošana</string>
</resources>

View File

@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources></resources>

View File

@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources></resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Catima-avlusing</string>
</resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Catima-foutopsporing</string>
</resources>

View File

@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources></resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Catima Debug</string>
</resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Depuração do Catima</string>
</resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Depuração Catima</string>
</resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Depanare Catima</string>
</resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Отладка Catima</string>
</resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Catima Debug</string>
</resources>

View File

@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources></resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Catima Debug</string>
</resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Catima Hata Ayaklama</string>
</resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Catima Debug</string>
</resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Gỡ lỗi Catima</string>
</resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Catima 调试</string>
</resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Catima 除錯版</string>
</resources>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_name">Catima Debug</string>
</resources>

View File

@@ -16,7 +16,7 @@
<uses-feature
android:name="android.hardware.camera"
android:required="false" />
android:required="true" />
<uses-feature
android:name="android.hardware.camera.autofocus"
android:required="false" />
@@ -24,7 +24,6 @@
<application
android:name=".LoyaltyCardLockerApplication"
android:allowBackup="true"
android:enableOnBackInvokedCallback="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
@@ -33,35 +32,18 @@
<activity
android:name=".MainActivity"
android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.App.Starting">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="content"/>
<data android:host="*"/>
<data android:mimeType="image/*" />
<data android:mimeType="application/pdf" />
<data android:mimeType="application/vnd.apple.pkpass" />
<data android:mimeType="application/vnd-com.apple.pkpass" />
<data android:mimeType="application/vnd.espass-espass" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
<data android:mimeType="application/pdf" />
<data android:mimeType="application/vnd.apple.pkpass" />
<data android:mimeType="application/vnd-com.apple.pkpass" />
<data android:mimeType="application/vnd.espass-espass" />
</intent-filter>
</activity>
<activity
@@ -79,12 +61,13 @@
<activity
android:name=".LoyaltyCardViewActivity"
android:exported="true"
android:theme="@style/AppTheme.NoActionBar" />
android:theme="@style/AppTheme.NoActionBar"
android:windowSoftInputMode="stateHidden" />
<activity
android:name=".LoyaltyCardEditActivity"
android:exported="true"
android:theme="@style/AppTheme.NoActionBar"
android:windowSoftInputMode="adjustResize">
android:windowSoftInputMode="stateHidden">
<intent-filter
android:autoVerify="true"
android:label="@string/app_name">
@@ -122,17 +105,16 @@
<activity
android:name=".BarcodeSelectorActivity"
android:label="@string/selectBarcodeTitle"
android:theme="@style/AppTheme.NoActionBar" />
android:theme="@style/AppTheme.NoActionBar"
android:windowSoftInputMode="stateHidden" />
<activity
android:name=".preferences.SettingsActivity"
android:label="@string/settings"
android:theme="@style/AppTheme.NoActionBar" />
<!-- FIXME: locked screenOrientation is a workaround for https://github.com/CatimaLoyalty/Android/issues/1715, remove when https://github.com/CatimaLoyalty/Android/issues/513 is fixed -->
<activity
android:name=".ImportExportActivity"
android:label="@string/importExport"
android:exported="true"
android:screenOrientation="locked"
android:theme="@style/AppTheme.NoActionBar">
<!-- ZIP Intent Filter -->
@@ -197,8 +179,7 @@
android:resource="@xml/file_provider_paths" />
</provider>
<service android:name=".CardsOnPowerScreenService" android:label="@string/app_name"
android:permission="android.permission.BIND_CONTROLS" android:exported="true"
tools:targetApi="r">
android:permission="android.permission.BIND_CONTROLS" android:exported="true">
<intent-filter>
<action android:name="android.service.controls.ControlsProviderService" />
</intent-filter>

View File

@@ -7,11 +7,11 @@ import android.view.View;
import android.widget.ScrollView;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import protect.card_locker.databinding.AboutActivityBinding;
public class AboutActivity extends CatimaAppCompatActivity {
@@ -43,12 +43,13 @@ public class AboutActivity extends CatimaAppCompatActivity {
binding.privacy.setTag("https://catima.app/privacy-policy/");
binding.reportError.setTag("https://github.com/CatimaLoyalty/Android/issues");
binding.rate.setTag("https://play.google.com/store/apps/details?id=me.hackerchick.catima");
binding.donate.setTag("https://catima.app/donate");
binding.donate.setTag("https://catima.app/contribute/#donating");
boolean installedFromGooglePlay = Utils.installedFromGooglePlay(this);
// Hide Google Play rate button if not on Google Play
binding.rate.setVisibility(BuildConfig.showRateOnGooglePlay ? View.VISIBLE : View.GONE);
binding.rate.setVisibility(installedFromGooglePlay ? View.VISIBLE : View.GONE);
// Hide donate button on Google Play (Google Play doesn't allow donation links)
binding.donate.setVisibility(BuildConfig.showDonate ? View.VISIBLE : View.GONE);
binding.donate.setVisibility(installedFromGooglePlay ? View.GONE : View.VISIBLE);
bindClickListeners();
}
@@ -97,7 +98,11 @@ public class AboutActivity extends CatimaAppCompatActivity {
}
private void showCredits() {
showHTML(R.string.credits, content.getContributorInfo(), null);
new MaterialAlertDialogBuilder(this)
.setTitle(R.string.credits)
.setMessage(content.getContributorInfo())
.setPositiveButton(R.string.ok, null)
.show();
}
private void showHistory(View view) {
@@ -112,7 +117,7 @@ public class AboutActivity extends CatimaAppCompatActivity {
showHTML(R.string.privacy_policy, content.getPrivacyInfo(), view);
}
private void showHTML(@StringRes int title, final Spanned text, @Nullable View view) {
private void showHTML(@StringRes int title, final Spanned text, View view) {
int dialogContentPadding = getResources().getDimensionPixelSize(R.dimen.alert_dialog_content_padding);
TextView textView = new TextView(this);
textView.setText(text);
@@ -120,21 +125,12 @@ public class AboutActivity extends CatimaAppCompatActivity {
ScrollView scrollView = new ScrollView(this);
scrollView.addView(textView);
scrollView.setPadding(dialogContentPadding, dialogContentPadding / 2, dialogContentPadding, 0);
// Create dialog
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(this);
materialAlertDialogBuilder
new MaterialAlertDialogBuilder(this)
.setTitle(title)
.setView(scrollView)
.setPositiveButton(R.string.ok, null);
// Add View online button if an URL is linked to this view
if (view != null && view.getTag() != null) {
materialAlertDialogBuilder.setNeutralButton(R.string.view_online, (dialog, which) -> openExternalBrowser(view));
}
// Show dialog
materialAlertDialogBuilder.show();
.setPositiveButton(R.string.ok, null)
.setNeutralButton(R.string.view_online, (dialog, which) -> openExternalBrowser(view))
.show();
}
private void openExternalBrowser(View view) {

View File

@@ -129,19 +129,19 @@ public class AboutContent {
return result.toString();
}
public Spanned getContributorInfo() {
public String getContributorInfo() {
StringBuilder contributorInfo = new StringBuilder();
contributorInfo.append(getCopyright());
contributorInfo.append("<br/><br/>");
contributorInfo.append("\n\n");
contributorInfo.append(context.getString(R.string.app_copyright_old));
contributorInfo.append("<br/><br/>");
contributorInfo.append(String.format(context.getString(R.string.app_contributors), getContributors()));
contributorInfo.append("<br/><br/>");
contributorInfo.append(String.format(context.getString(R.string.app_libraries), getThirdPartyLibraries()));
contributorInfo.append("<br/><br/>");
contributorInfo.append(String.format(context.getString(R.string.app_resources), getUsedThirdPartyAssets()));
contributorInfo.append("\n\n");
contributorInfo.append(HtmlCompat.fromHtml(String.format(context.getString(R.string.app_contributors), getContributors()), HtmlCompat.FROM_HTML_MODE_COMPACT));
contributorInfo.append("\n\n");
contributorInfo.append(HtmlCompat.fromHtml(String.format(context.getString(R.string.app_libraries), getThirdPartyLibraries()), HtmlCompat.FROM_HTML_MODE_COMPACT));
contributorInfo.append("\n\n");
contributorInfo.append(HtmlCompat.fromHtml(String.format(context.getString(R.string.app_resources), getUsedThirdPartyAssets()), HtmlCompat.FROM_HTML_MODE_COMPACT));
return HtmlCompat.fromHtml(contributorInfo.toString(), HtmlCompat.FROM_HTML_MODE_COMPACT);
return contributorInfo.toString();
}
public Spanned getHistoryInfo() {

View File

@@ -12,12 +12,12 @@ import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import com.google.zxing.BarcodeFormat;
import java.util.ArrayList;
import androidx.appcompat.widget.Toolbar;
import protect.card_locker.databinding.BarcodeSelectorActivityBinding;
/**
@@ -71,7 +71,7 @@ public class BarcodeSelectorActivity extends CatimaAppCompatActivity implements
});
final Bundle b = getIntent().getExtras();
final String initialCardId = b != null ? b.getString(LoyaltyCard.BUNDLE_LOYALTY_CARD_CARD_ID) : null;
final String initialCardId = b != null ? b.getString("initialCardId") : null;
if (initialCardId != null) {
cardId.setText(initialCardId);

View File

@@ -0,0 +1,23 @@
package protect.card_locker;
public class BarcodeValues {
private final String mFormat;
private final String mContent;
public BarcodeValues(String format, String content) {
mFormat = format;
mContent = content;
}
public String format() {
return mFormat;
}
public String content() {
return mContent;
}
public boolean isEmpty() {
return mFormat == null && mContent == null;
}
}

View File

@@ -12,15 +12,15 @@ import androidx.appcompat.widget.Toolbar;
import androidx.core.content.pm.ShortcutInfoCompat;
import androidx.core.content.pm.ShortcutManagerCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import protect.card_locker.databinding.CardShortcutConfigureActivityBinding;
import protect.card_locker.preferences.Settings;
import protect.card_locker.databinding.SimpleToolbarListActivityBinding;
/**
* The configuration screen for creating a shortcut.
*/
public class CardShortcutConfigure extends CatimaAppCompatActivity implements LoyaltyCardCursorAdapter.CardAdapterListener {
private CardShortcutConfigureActivityBinding binding;
private SimpleToolbarListActivityBinding binding;
static final String TAG = "Catima";
private SQLiteDatabase mDatabase;
private LoyaltyCardCursorAdapter mAdapter;
@@ -28,7 +28,7 @@ public class CardShortcutConfigure extends CatimaAppCompatActivity implements Lo
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
binding = CardShortcutConfigureActivityBinding.inflate(getLayoutInflater());
binding = SimpleToolbarListActivityBinding.inflate(getLayoutInflater());
mDatabase = new DBHelper(this).getReadableDatabase();
// Set the result to CANCELED. This will cause nothing to happen if the
@@ -47,26 +47,21 @@ public class CardShortcutConfigure extends CatimaAppCompatActivity implements Lo
finish();
}
final RecyclerView cardList = binding.list;
GridLayoutManager layoutManager = (GridLayoutManager) cardList.getLayoutManager();
if (layoutManager != null) {
layoutManager.setSpanCount(getResources().getInteger(R.integer.main_view_card_columns));
}
Cursor cardCursor = DBHelper.getLoyaltyCardCursor(mDatabase, DBHelper.LoyaltyCardArchiveFilter.All);
mAdapter = new LoyaltyCardCursorAdapter(this, cardCursor, this, null);
binding.list.setAdapter(mAdapter);
}
@Override
protected void onResume() {
super.onResume();
var layoutManager = (GridLayoutManager) binding.list.getLayoutManager();
if (layoutManager != null) {
var settings = new Settings(this);
layoutManager.setSpanCount(settings.getPreferredColumnCount());
}
cardList.setAdapter(mAdapter);
}
private void onClickAction(int position) {
Cursor selected = DBHelper.getLoyaltyCardCursor(mDatabase, DBHelper.LoyaltyCardArchiveFilter.All);
selected.moveToPosition(position);
LoyaltyCard loyaltyCard = LoyaltyCard.fromCursor(CardShortcutConfigure.this, selected);
LoyaltyCard loyaltyCard = LoyaltyCard.toLoyaltyCard(selected);
Log.d(TAG, "Creating shortcut for card " + loyaltyCard.store + "," + loyaltyCard.id);

View File

@@ -15,13 +15,13 @@ import android.service.controls.actions.ControlAction;
import android.service.controls.templates.StatelessTemplate;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import java.util.List;
import java.util.concurrent.Flow;
import java.util.function.Consumer;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
@RequiresApi(Build.VERSION_CODES.R)
public class CardsOnPowerScreenService extends ControlsProviderService {
@@ -42,10 +42,10 @@ public class CardsOnPowerScreenService extends ControlsProviderService {
Cursor loyaltyCardCursor = DBHelper.getLoyaltyCardCursor(mDatabase, DBHelper.LoyaltyCardArchiveFilter.Unarchived);
return subscriber -> {
while (loyaltyCardCursor.moveToNext()) {
LoyaltyCard card = LoyaltyCard.fromCursor(this, loyaltyCardCursor);
LoyaltyCard card = LoyaltyCard.toLoyaltyCard(loyaltyCardCursor);
Intent openIntent = new Intent(this, LoyaltyCardViewActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.putExtra(LoyaltyCardViewActivity.BUNDLE_ID, card.id);
.putExtra("id", card.id);
PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(), card.id, openIntent, PendingIntent.FLAG_IMMUTABLE);
subscriber.onNext(
new Control.StatelessBuilder(PREFIX + card.id, pendingIntent)
@@ -69,11 +69,11 @@ public class CardsOnPowerScreenService extends ControlsProviderService {
for (String controlId : controlIds) {
Control control;
Integer cardId = this.controlIdToCardId(controlId);
LoyaltyCard card = DBHelper.getLoyaltyCard(this, mDatabase, cardId);
LoyaltyCard card = DBHelper.getLoyaltyCard(mDatabase, cardId);
if (card != null) {
Intent openIntent = new Intent(this, LoyaltyCardViewActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.putExtra(LoyaltyCardViewActivity.BUNDLE_ID, card.id);
.putExtra("id", card.id);
PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(), card.id, openIntent, PendingIntent.FLAG_IMMUTABLE);
control = new Control.StatefulBuilder(controlId, pendingIntent)
.setTitle(card.store)
@@ -99,7 +99,7 @@ public class CardsOnPowerScreenService extends ControlsProviderService {
}
private Bitmap getIcon(Context context, LoyaltyCard loyaltyCard) {
Bitmap cardIcon = loyaltyCard.getImageThumbnail(context);
Bitmap cardIcon = Utils.retrieveCardImage(context, loyaltyCard.id, ImageLocationType.icon);
if (cardIcon != null) {
return cardIcon;
@@ -129,7 +129,7 @@ public class CardsOnPowerScreenService extends ControlsProviderService {
consumer.accept(ControlAction.RESPONSE_OK);
Intent openIntent = new Intent(this, LoyaltyCardViewActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.putExtra(LoyaltyCardViewActivity.BUNDLE_ID, controlIdToCardId(controlId));
.putExtra("id", controlIdToCardId(controlId));
startActivity(openIntent);
closePowerScreenOnAndroid11();

View File

@@ -5,7 +5,6 @@ import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
@@ -14,8 +13,6 @@ import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.WindowInsetsControllerCompat;
public class CatimaAppCompatActivity extends AppCompatActivity {
protected boolean activityOverridesNavBarColor = false;
@Override
protected void attachBaseContext(Context base) {
// Apply chosen language
@@ -33,31 +30,20 @@ public class CatimaAppCompatActivity extends AppCompatActivity {
super.onPostCreate(savedInstanceState);
// material 3 designer does not consider status bar colors
// XXX changing this in onCreate causes issues with the splash screen activity, so doing this here
Window window = getWindow();
if (window != null) {
boolean darkMode = Utils.isDarkModeEnabled(this);
if (Build.VERSION.SDK_INT >= 23) {
View decorView = window.getDecorView();
WindowInsetsControllerCompat wic = new WindowInsetsControllerCompat(window, decorView);
wic.setAppearanceLightStatusBars(!darkMode);
window.setStatusBarColor(Color.TRANSPARENT);
} else {
// icons are always white back then
window.setStatusBarColor(darkMode ? Color.TRANSPARENT : Color.argb(127, 0, 0, 0));
}
boolean darkMode = Utils.isDarkModeEnabled(this);
if (Build.VERSION.SDK_INT >= 23) {
View decorView = getWindow().getDecorView();
WindowInsetsControllerCompat wic = new WindowInsetsControllerCompat(getWindow(), decorView);
wic.setAppearanceLightStatusBars(!darkMode);
getWindow().setStatusBarColor(Color.TRANSPARENT);
} else {
// icons are always white back then
getWindow().setStatusBarColor(darkMode ? Color.TRANSPARENT : Color.argb(127, 0, 0, 0));
}
// XXX android 9 and below has a nasty rendering bug if the theme was patched earlier
Utils.postPatchColors(this);
}
@Override
protected void onResume() {
super.onResume();
if (!activityOverridesNavBarColor) {
Utils.setNavigationBarColor(this, null, Utils.resolveBackgroundColor(this), !Utils.isDarkModeEnabled(this));
}
}
protected void enableToolbarBackButton() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {

View File

@@ -1,7 +1,5 @@
package protect.card_locker;
import androidx.annotation.NonNull;
import com.google.zxing.BarcodeFormat;
import java.util.Arrays;
@@ -47,15 +45,15 @@ public class CatimaBarcode {
mBarcodeFormat = barcodeFormat;
}
public static CatimaBarcode fromBarcode(@NonNull BarcodeFormat barcodeFormat) {
public static CatimaBarcode fromBarcode(BarcodeFormat barcodeFormat) {
return new CatimaBarcode(barcodeFormat);
}
public static CatimaBarcode fromName(@NonNull String name) {
public static CatimaBarcode fromName(String name) {
return new CatimaBarcode(BarcodeFormat.valueOf(name));
}
public static CatimaBarcode fromPrettyName(@NonNull String prettyName) {
public static CatimaBarcode fromPrettyName(String prettyName) {
try {
return new CatimaBarcode(barcodeFormats.get(barcodePrettyNames.indexOf(prettyName)));
} catch (IndexOutOfBoundsException e) {

View File

@@ -4,24 +4,22 @@ import android.app.Activity;
import android.content.Context;
import android.widget.Toast;
import androidx.core.util.Consumer;
import com.journeyapps.barcodescanner.CaptureManager;
import com.journeyapps.barcodescanner.DecoratedBarcodeView;
public class CatimaCaptureManager extends CaptureManager {
private final Consumer<String> mErrorCallback;
private final Context mContext;
public CatimaCaptureManager(Activity activity, DecoratedBarcodeView barcodeView, Consumer<String> errorCallback) {
public CatimaCaptureManager(Activity activity, DecoratedBarcodeView barcodeView) {
super(activity, barcodeView);
mErrorCallback = errorCallback;
mContext = activity.getApplicationContext();
}
@Override
protected void displayFrameworkBugMessageAndExit(String message) {
// We don't want to exit, as we also have a enter from card image and add manually button here
// So, instead, we call our error callback
mErrorCallback.accept(message);
// So we show a toast instead
Toast.makeText(mContext, message, Toast.LENGTH_LONG).show();
}
}

View File

@@ -332,10 +332,10 @@ public class DBHelper extends SQLiteOpenHelper {
Set<String> files = new HashSet<>();
Cursor cardCursor = getLoyaltyCardCursor(database);
while (cardCursor.moveToNext()) {
LoyaltyCard card = LoyaltyCard.fromCursor(context, cardCursor);
LoyaltyCard card = LoyaltyCard.toLoyaltyCard(cardCursor);
for (ImageLocationType imageLocationType : ImageLocationType.values()) {
String name = Utils.getCardImageFileName(card.id, imageLocationType);
if (card.getImageForImageLocationType(context, imageLocationType) != null) {
if (Utils.retrieveCardImageAsFile(context, name).exists()) {
files.add(name);
}
}
@@ -535,14 +535,14 @@ public class DBHelper extends SQLiteOpenHelper {
return (rowsUpdated == 1);
}
public static LoyaltyCard getLoyaltyCard(Context context, SQLiteDatabase database, final int id) {
public static LoyaltyCard getLoyaltyCard(SQLiteDatabase database, final int id) {
Cursor data = database.query(LoyaltyCardDbIds.TABLE, null, whereAttrs(LoyaltyCardDbIds.ID), withArgs(id), null, null, null);
LoyaltyCard card = null;
if (data.getCount() == 1) {
data.moveToFirst();
card = LoyaltyCard.fromCursor(context, data);
card = LoyaltyCard.toLoyaltyCard(data);
}
data.close();

View File

@@ -8,12 +8,14 @@ import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import protect.card_locker.databinding.GroupLayoutBinding;
import protect.card_locker.preferences.Settings;
public class GroupCursorAdapter extends BaseCursorAdapter<GroupCursorAdapter.GroupListItemViewHolder> {
public final Context mContext;

View File

@@ -1,36 +1,38 @@
package protect.card_locker;
import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.textfield.TextInputLayout;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import protect.card_locker.async.TaskHandler;
import protect.card_locker.databinding.ImportExportActivityBinding;
import protect.card_locker.importexport.DataFormat;
@@ -81,21 +83,15 @@ public class ImportExportActivity extends CatimaAppCompatActivity {
Log.e(TAG, "Activity returned NULL uri");
return;
}
// Running this in a thread prevents Android from throwing a NetworkOnMainThreadException for large files
// FIXME: This is still suboptimal, because showing that the export started is delayed until the network request finishes
new Thread() {
@Override
public void run() {
try {
OutputStream writer = getContentResolver().openOutputStream(uri);
Log.d(TAG, "Starting file export with: " + result);
startExport(writer, uri, exportPassword.toCharArray(), true);
} catch (IOException e) {
Log.e(TAG, "Failed to export file: " + result, e);
onExportComplete(new ImportExportResult(ImportExportResultType.GenericFailure, result.toString()), uri);
}
}
}.start();
try {
OutputStream writer = getContentResolver().openOutputStream(uri);
Log.e(TAG, "Starting file export with: " + result.toString());
startExport(writer, uri, exportPassword.toCharArray(), true);
} catch (IOException e) {
Log.e(TAG, "Failed to export file: " + result.toString(), e);
onExportComplete(new ImportExportResult(ImportExportResultType.GenericFailure, result.toString()), uri);
}
});
fileOpenLauncher = registerForActivityResult(new ActivityResultContracts.GetContent(), result -> {
if (result == null) {
@@ -130,19 +126,16 @@ public class ImportExportActivity extends CatimaAppCompatActivity {
builder.setTitle(R.string.exportPassword);
FrameLayout container = new FrameLayout(ImportExportActivity.this);
final TextInputLayout textInputLayout = new TextInputLayout(ImportExportActivity.this);
textInputLayout.setEndIconMode(TextInputLayout.END_ICON_PASSWORD_TOGGLE);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(50, 10, 50, 0);
textInputLayout.setLayoutParams(params);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.leftMargin = 50;
params.rightMargin = 50;
final EditText input = new EditText(ImportExportActivity.this);
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
input.setLayoutParams(params);
input.setHint(R.string.exportPasswordHint);
textInputLayout.addView(input);
container.addView(textInputLayout);
container.addView(input);
builder.setView(container);
builder.setPositiveButton(R.string.ok, (dialogInterface, i) -> {
exportPassword = input.getText().toString();
@@ -155,6 +148,7 @@ public class ImportExportActivity extends CatimaAppCompatActivity {
});
builder.setNegativeButton(R.string.cancel, (dialogInterface, i) -> dialogInterface.cancel());
builder.show();
});
// Check that there is a file manager available
@@ -164,28 +158,17 @@ public class ImportExportActivity extends CatimaAppCompatActivity {
// Check that there is an app that data can be imported from
Button importApplication = binding.importOptionApplicationButton;
importApplication.setOnClickListener(v -> chooseImportType(true, null));
// FIXME: The importer/exporter is currently quite broken
// To prevent the screen from turning off during import/export and some devices killing Catima as it's no longer foregrounded, force the screen to stay on here
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
private void openFileForImport(Uri uri, char[] password) {
// Running this in a thread prevents Android from throwing a NetworkOnMainThreadException for large files
// FIXME: This is still suboptimal, because showing that the import started is delayed until the network request finishes
new Thread() {
@Override
public void run() {
try {
InputStream reader = getContentResolver().openInputStream(uri);
Log.d(TAG, "Starting file import with: " + uri);
startImport(reader, uri, importDataFormat, password, true);
} catch (IOException e) {
Log.e(TAG, "Failed to import file: " + uri, e);
onImportComplete(new ImportExportResult(ImportExportResultType.GenericFailure, e.toString()), uri, importDataFormat);
}
}
}.start();
try {
InputStream reader = getContentResolver().openInputStream(uri);
Log.e(TAG, "Starting file import with: " + uri.toString());
startImport(reader, uri, importDataFormat, password, true);
} catch (IOException e) {
Log.e(TAG, "Failed to import file: " + uri.toString(), e);
onImportComplete(new ImportExportResult(ImportExportResultType.GenericFailure, e.toString()), uri, importDataFormat);
}
}
private void chooseImportType(boolean choosePicker,
@@ -337,21 +320,9 @@ public class ImportExportActivity extends CatimaAppCompatActivity {
AlertDialog.Builder builder = new MaterialAlertDialogBuilder(this);
builder.setTitle(R.string.passwordRequired);
FrameLayout container = new FrameLayout(ImportExportActivity.this);
final TextInputLayout textInputLayout = new TextInputLayout(ImportExportActivity.this);
textInputLayout.setEndIconMode(TextInputLayout.END_ICON_PASSWORD_TOGGLE);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(50, 10, 50, 0);
textInputLayout.setLayoutParams(params);
final EditText input = new EditText(ImportExportActivity.this);
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
input.setHint(R.string.exportPasswordHint);
textInputLayout.addView(input);
container.addView(textInputLayout);
builder.setView(container);
builder.setView(input);
builder.setPositiveButton(R.string.ok, (dialogInterface, i) -> {
openFileForImport(uri, input.getText().toString().toCharArray());

View File

@@ -6,7 +6,6 @@ import android.content.Context;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
@@ -91,16 +90,16 @@ public class ImportExportTask implements CompatCallable<ImportExportResult> {
progress = new ProgressDialog(activity);
progress.setTitle(doImport ? R.string.importing : R.string.exporting);
progress.setOnCancelListener(dialog -> cancel());
progress.setOnDismissListener(dialog -> cancel());
progress.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
ImportExportTask.this.stop();
}
});
progress.show();
}
private void cancel() {
ImportExportTask.this.stop();
}
protected ImportExportResult doInBackground(Void... nothing) {
final SQLiteDatabase database = new DBHelper(activity).getWritableDatabase();
ImportExportResult result;

View File

@@ -125,29 +125,7 @@ public class ImportURIHelper {
headerColor = Integer.parseInt(unparsedHeaderColor);
}
return new LoyaltyCard(
-1,
store,
note,
validFrom,
expiry,
balance,
balanceType,
cardId,
barcodeId,
barcodeType,
headerColor,
0,
Utils.getUnixTime(),
100,
0,
null,
null,
null,
null,
null,
null
);
return new LoyaltyCard(-1, store, note, validFrom, expiry, balance, balanceType, cardId, barcodeId, barcodeType, headerColor, 0, Utils.getUnixTime(), 100, 0);
} catch (NumberFormatException | UnsupportedEncodingException | ArrayIndexOutOfBoundsException ex) {
throw new InvalidObjectException("Not a valid import URI");
}

View File

@@ -1,561 +1,150 @@
package protect.card_locker;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.os.Parcel;
import android.os.Parcelable;
import java.math.BigDecimal;
import java.util.Currency;
import java.util.Date;
import java.util.List;
import java.util.Objects;
public class LoyaltyCard {
public int id;
public String store;
public String note;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
public class LoyaltyCard implements Parcelable {
public final int id;
public final String store;
public final String note;
@Nullable
public Date validFrom;
public final Date validFrom;
@Nullable
public Date expiry;
public BigDecimal balance;
public final Date expiry;
public final BigDecimal balance;
@Nullable
public Currency balanceType;
public String cardId;
public final Currency balanceType;
public final String cardId;
@Nullable
public String barcodeId;
public final String barcodeId;
@Nullable
public CatimaBarcode barcodeType;
public final CatimaBarcode barcodeType;
@Nullable
public Integer headerColor;
public int starStatus;
public long lastUsed;
public final Integer headerColor;
public final int starStatus;
public final int archiveStatus;
public final long lastUsed;
public int zoomLevel;
public int archiveStatus;
@Nullable
private Bitmap imageThumbnail;
@Nullable
private String imageThumbnailPath;
@Nullable
private Bitmap imageFront;
@Nullable
private String imageFrontPath;
@Nullable
private Bitmap imageBack;
@Nullable
private String imageBackPath;
public static final String BUNDLE_LOYALTY_CARD_ID = "loyaltyCardId";
public static final String BUNDLE_LOYALTY_CARD_STORE = "loyaltyCardStore";
public static final String BUNDLE_LOYALTY_CARD_NOTE = "loyaltyCardNote";
public static final String BUNDLE_LOYALTY_CARD_VALID_FROM = "loyaltyCardValidFrom";
public static final String BUNDLE_LOYALTY_CARD_EXPIRY = "loyaltyCardExpiry";
public static final String BUNDLE_LOYALTY_CARD_BALANCE = "loyaltyCardBalance";
public static final String BUNDLE_LOYALTY_CARD_BALANCE_TYPE = "loyaltyCardBalanceType";
public static final String BUNDLE_LOYALTY_CARD_CARD_ID = "loyaltyCardCardId";
public static final String BUNDLE_LOYALTY_CARD_BARCODE_ID = "loyaltyCardBarcodeId";
public static final String BUNDLE_LOYALTY_CARD_BARCODE_TYPE = "loyaltyCardBarcodeType";
public static final String BUNDLE_LOYALTY_CARD_HEADER_COLOR = "loyaltyCardHeaderColor";
public static final String BUNDLE_LOYALTY_CARD_STAR_STATUS = "loyaltyCardStarStatus";
public static final String BUNDLE_LOYALTY_CARD_LAST_USED = "loyaltyCardLastUsed";
public static final String BUNDLE_LOYALTY_CARD_ZOOM_LEVEL = "loyaltyCardZoomLevel";
public static final String BUNDLE_LOYALTY_CARD_ARCHIVE_STATUS = "loyaltyCardArchiveStatus";
public static final String BUNDLE_LOYALTY_CARD_IMAGE_THUMBNAIL = "loyaltyCardImageThumbnail";
public static final String BUNDLE_LOYALTY_CARD_IMAGE_FRONT = "loyaltyCardImageFront";
public static final String BUNDLE_LOYALTY_CARD_IMAGE_BACK = "loyaltyCardImageBack";
private static final String TEMP_IMAGE_THUMBNAIL_FILE_NAME = "loyaltyCardTempImageThumbnailFileName";
private static final String TEMP_IMAGE_FRONT_FILE_NAME = "loyaltyCardTempImageFrontFileName";
private static final String TEMP_IMAGE_BACK_FILE_NAME = "loyaltyCardTempImageBackFileName";
/**
* Create a loyalty card object with default values
*/
public LoyaltyCard() {
setId(-1);
setStore("");
setNote("");
setValidFrom(null);
setExpiry(null);
setBalance(new BigDecimal("0"));
setBalanceType(null);
setCardId("");
setBarcodeId(null);
setBarcodeType(null);
setHeaderColor(null);
setStarStatus(0);
setLastUsed(Utils.getUnixTime());
setZoomLevel(100);
setArchiveStatus(0);
setImageThumbnail(null, null);
setImageFront(null, null);
setImageBack(null, null);
}
/**
* Create a new loyalty card
*
* @param id
* @param store
* @param note
* @param validFrom
* @param expiry
* @param balance
* @param balanceType
* @param cardId
* @param barcodeId
* @param barcodeType
* @param headerColor
* @param starStatus
* @param lastUsed
* @param zoomLevel
* @param archiveStatus
*/
public LoyaltyCard(final int id, final String store, final String note, @Nullable final Date validFrom,
@Nullable final Date expiry, final BigDecimal balance, @Nullable final Currency balanceType,
final String cardId, @Nullable final String barcodeId, @Nullable final CatimaBarcode barcodeType,
@Nullable final Integer headerColor, final int starStatus,
final long lastUsed, final int zoomLevel, final int archiveStatus,
@Nullable Bitmap imageThumbnail, @Nullable String imageThumbnailPath,
@Nullable Bitmap imageFront, @Nullable String imageFrontPath,
@Nullable Bitmap imageBack, @Nullable String imageBackPath) {
setId(id);
setStore(store);
setNote(note);
setValidFrom(validFrom);
setExpiry(expiry);
setBalance(balance);
setBalanceType(balanceType);
setCardId(cardId);
setBarcodeId(barcodeId);
setBarcodeType(barcodeType);
setHeaderColor(headerColor);
setStarStatus(starStatus);
setLastUsed(lastUsed);
setZoomLevel(zoomLevel);
setArchiveStatus(archiveStatus);
setImageThumbnail(imageThumbnail, imageThumbnailPath);
setImageFront(imageFront, imageFrontPath);
setImageBack(imageBack, imageBackPath);
}
@Nullable
public Bitmap getImageThumbnail(Context context) {
if (imageThumbnailPath != null) {
if (imageThumbnailPath.equals(TEMP_IMAGE_THUMBNAIL_FILE_NAME)) {
imageThumbnail = Utils.loadTempImage(context, imageThumbnailPath);
} else {
imageThumbnail = Utils.retrieveCardImage(context, imageThumbnailPath);
}
imageThumbnailPath = null;
}
if (imageThumbnail == null) {
return null;
}
return imageThumbnail.copy(imageThumbnail.getConfig(), imageThumbnail.isMutable());
}
@Nullable
public Bitmap getImageFront(Context context) {
if (imageFrontPath != null) {
if (imageFrontPath.equals(TEMP_IMAGE_FRONT_FILE_NAME)) {
imageFront = Utils.loadTempImage(context, imageFrontPath);
} else {
imageFront = Utils.retrieveCardImage(context, imageFrontPath);
}
imageFrontPath = null;
}
if (imageFront == null) {
return null;
}
return imageFront.copy(imageFront.getConfig(), imageFront.isMutable());
}
@Nullable
public Bitmap getImageBack(Context context) {
if (imageBackPath != null) {
if (imageBackPath.equals(TEMP_IMAGE_BACK_FILE_NAME)) {
imageBack = Utils.loadTempImage(context, imageBackPath);
} else {
imageBack = Utils.retrieveCardImage(context, imageBackPath);
}
imageBackPath = null;
}
if (imageBack == null) {
return null;
}
return imageBack.copy(imageBack.getConfig(), imageBack.isMutable());
}
public void setId(int id) {
final long lastUsed, final int zoomLevel, final int archiveStatus) {
this.id = id;
}
public void setStore(@NonNull String store) {
this.store = store;
}
public void setNote(@NonNull String note) {
this.note = note;
}
public void setValidFrom(@Nullable Date validFrom) {
this.validFrom = validFrom;
}
public void setExpiry(@Nullable Date expiry) {
this.expiry = expiry;
}
public void setBalance(@NonNull BigDecimal balance) {
this.balance = balance;
}
public void setBalanceType(@Nullable Currency balanceType) {
this.balanceType = balanceType;
}
public void setCardId(@NonNull String cardId) {
this.cardId = cardId;
}
public void setBarcodeId(@Nullable String barcodeId) {
this.barcodeId = barcodeId;
}
public void setBarcodeType(@Nullable CatimaBarcode barcodeType) {
this.barcodeType = barcodeType;
}
public void setHeaderColor(@Nullable Integer headerColor) {
this.headerColor = headerColor;
}
public void setStarStatus(int starStatus) {
if (starStatus != 0 && starStatus != 1) {
throw new IllegalArgumentException("starStatus must be 0 or 1");
}
this.starStatus = starStatus;
}
public void setLastUsed(long lastUsed) {
this.lastUsed = lastUsed;
}
public void setZoomLevel(int zoomLevel) {
if (zoomLevel < 0 || zoomLevel > 100) {
throw new IllegalArgumentException("zoomLevel must be in range 0-100");
}
this.zoomLevel = zoomLevel;
}
public void setArchiveStatus(int archiveStatus) {
if (archiveStatus != 0 && archiveStatus != 1) {
throw new IllegalArgumentException("archiveStatus must be 0 or 1");
}
this.archiveStatus = archiveStatus;
}
public void setImageThumbnail(@Nullable Bitmap imageThumbnail, @Nullable String imageThumbnailPath) {
if (imageThumbnail != null && imageThumbnailPath != null) {
throw new IllegalArgumentException("Cannot set both thumbnail and path");
}
this.imageThumbnailPath = imageThumbnailPath;
this.imageThumbnail = imageThumbnail != null ? imageThumbnail.copy(imageThumbnail.getConfig(), imageThumbnail.isMutable()) : null;
protected LoyaltyCard(Parcel in) {
id = in.readInt();
store = in.readString();
note = in.readString();
long tmpValidFrom = in.readLong();
validFrom = tmpValidFrom != -1 ? new Date(tmpValidFrom) : null;
long tmpExpiry = in.readLong();
expiry = tmpExpiry != -1 ? new Date(tmpExpiry) : null;
balance = (BigDecimal) in.readValue(BigDecimal.class.getClassLoader());
balanceType = (Currency) in.readValue(Currency.class.getClassLoader());
cardId = in.readString();
barcodeId = in.readString();
String tmpBarcodeType = in.readString();
barcodeType = !tmpBarcodeType.isEmpty() ? CatimaBarcode.fromName(tmpBarcodeType) : null;
int tmpHeaderColor = in.readInt();
headerColor = tmpHeaderColor != -1 ? tmpHeaderColor : null;
starStatus = in.readInt();
lastUsed = in.readLong();
zoomLevel = in.readInt();
archiveStatus = in.readInt();
}
public void setImageFront(@Nullable Bitmap imageFront, @Nullable String imageFrontPath) {
if (imageFront != null && imageFrontPath != null) {
throw new IllegalArgumentException("Cannot set both thumbnail and path");
}
this.imageFrontPath = imageFrontPath;
this.imageFront = imageFront != null ? imageFront.copy(imageFront.getConfig(), imageFront.isMutable()) : null;
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(id);
parcel.writeString(store);
parcel.writeString(note);
parcel.writeLong(validFrom != null ? validFrom.getTime() : -1);
parcel.writeLong(expiry != null ? expiry.getTime() : -1);
parcel.writeValue(balance);
parcel.writeValue(balanceType);
parcel.writeString(cardId);
parcel.writeString(barcodeId);
parcel.writeString(barcodeType != null ? barcodeType.name() : "");
parcel.writeInt(headerColor != null ? headerColor : -1);
parcel.writeInt(starStatus);
parcel.writeLong(lastUsed);
parcel.writeInt(zoomLevel);
parcel.writeInt(archiveStatus);
}
public void setImageBack(@Nullable Bitmap imageBack, @Nullable String imageBackPath) {
if (imageBack != null && imageBackPath != null) {
throw new IllegalArgumentException("Cannot set both thumbnail and path");
}
this.imageBackPath = imageBackPath;
this.imageBack = imageBack != null ? imageBack.copy(imageBack.getConfig(), imageBack.isMutable()) : null;
}
@Nullable
public Bitmap getImageForImageLocationType(Context context, ImageLocationType imageLocationType) {
if (imageLocationType == ImageLocationType.icon) {
return getImageThumbnail(context);
} else if (imageLocationType == ImageLocationType.front) {
return getImageFront(context);
} else if (imageLocationType == ImageLocationType.back) {
return getImageBack(context);
}
throw new IllegalArgumentException("Unknown image location type");
}
public void updateFromBundle(@NonNull Bundle bundle, boolean requireFull) {
if (bundle.containsKey(BUNDLE_LOYALTY_CARD_ID)) {
setId(bundle.getInt(BUNDLE_LOYALTY_CARD_ID));
} else if (requireFull) {
throw new IllegalArgumentException("Missing key " + BUNDLE_LOYALTY_CARD_ID);
}
if (bundle.containsKey(BUNDLE_LOYALTY_CARD_STORE)) {
setStore(Objects.requireNonNull(bundle.getString(BUNDLE_LOYALTY_CARD_STORE)));
} else if (requireFull) {
throw new IllegalArgumentException("Missing key " + BUNDLE_LOYALTY_CARD_STORE);
}
if (bundle.containsKey(BUNDLE_LOYALTY_CARD_NOTE)) {
setNote(Objects.requireNonNull(bundle.getString(BUNDLE_LOYALTY_CARD_NOTE)));
} else if (requireFull) {
throw new IllegalArgumentException("Missing key " + BUNDLE_LOYALTY_CARD_NOTE);
}
if (bundle.containsKey(BUNDLE_LOYALTY_CARD_VALID_FROM)) {
long tmpValidFrom = bundle.getLong(BUNDLE_LOYALTY_CARD_VALID_FROM);
setValidFrom(tmpValidFrom > 0 ? new Date(tmpValidFrom) : null);
} else if (requireFull) {
throw new IllegalArgumentException("Missing key " + BUNDLE_LOYALTY_CARD_VALID_FROM);
}
if (bundle.containsKey(BUNDLE_LOYALTY_CARD_EXPIRY)) {
long tmpExpiry = bundle.getLong(BUNDLE_LOYALTY_CARD_EXPIRY);
setExpiry(tmpExpiry > 0 ? new Date(tmpExpiry) : null);
} else if (requireFull) {
throw new IllegalArgumentException("Missing key " + BUNDLE_LOYALTY_CARD_EXPIRY);
}
if (bundle.containsKey(BUNDLE_LOYALTY_CARD_BALANCE)) {
setBalance(new BigDecimal(bundle.getString(BUNDLE_LOYALTY_CARD_BALANCE)));
} else if (requireFull) {
throw new IllegalArgumentException("Missing key " + BUNDLE_LOYALTY_CARD_BALANCE);
}
if (bundle.containsKey(BUNDLE_LOYALTY_CARD_BALANCE_TYPE)) {
String tmpBalanceType = bundle.getString(BUNDLE_LOYALTY_CARD_BALANCE_TYPE);
setBalanceType(tmpBalanceType != null ? Currency.getInstance(tmpBalanceType) : null);
} else if (requireFull) {
throw new IllegalArgumentException("Missing key " + BUNDLE_LOYALTY_CARD_BALANCE_TYPE);
}
if (bundle.containsKey(BUNDLE_LOYALTY_CARD_CARD_ID)) {
setCardId(Objects.requireNonNull(bundle.getString(BUNDLE_LOYALTY_CARD_CARD_ID)));
} else if (requireFull) {
throw new IllegalArgumentException("Missing key " + BUNDLE_LOYALTY_CARD_CARD_ID);
}
if (bundle.containsKey(BUNDLE_LOYALTY_CARD_BARCODE_ID)) {
setBarcodeId(bundle.getString(BUNDLE_LOYALTY_CARD_BARCODE_ID));
} else if (requireFull) {
throw new IllegalArgumentException("Missing key " + BUNDLE_LOYALTY_CARD_BARCODE_ID);
}
if (bundle.containsKey(BUNDLE_LOYALTY_CARD_BARCODE_TYPE)) {
String tmpBarcodeType = bundle.getString(BUNDLE_LOYALTY_CARD_BARCODE_TYPE);
setBarcodeType(tmpBarcodeType != null ? CatimaBarcode.fromName(tmpBarcodeType) : null);
} else if (requireFull) {
throw new IllegalArgumentException("Missing key " + BUNDLE_LOYALTY_CARD_BARCODE_TYPE);
}
if (bundle.containsKey(BUNDLE_LOYALTY_CARD_HEADER_COLOR)) {
int tmpHeaderColor = bundle.getInt(BUNDLE_LOYALTY_CARD_HEADER_COLOR);
setHeaderColor(tmpHeaderColor != -1 ? tmpHeaderColor : null);
} else if (requireFull) {
throw new IllegalArgumentException("Missing key " + BUNDLE_LOYALTY_CARD_HEADER_COLOR);
}
if (bundle.containsKey(BUNDLE_LOYALTY_CARD_STAR_STATUS)) {
setStarStatus(bundle.getInt(BUNDLE_LOYALTY_CARD_STAR_STATUS));
} else if (requireFull) {
throw new IllegalArgumentException("Missing key " + BUNDLE_LOYALTY_CARD_STAR_STATUS);
}
if (bundle.containsKey(BUNDLE_LOYALTY_CARD_LAST_USED)) {
setLastUsed(bundle.getLong(BUNDLE_LOYALTY_CARD_LAST_USED));
} else if (requireFull) {
throw new IllegalArgumentException("Missing key " + BUNDLE_LOYALTY_CARD_LAST_USED);
}
if (bundle.containsKey(BUNDLE_LOYALTY_CARD_ZOOM_LEVEL)) {
setZoomLevel(bundle.getInt(BUNDLE_LOYALTY_CARD_ZOOM_LEVEL));
} else if (requireFull) {
throw new IllegalArgumentException("Missing key " + BUNDLE_LOYALTY_CARD_ZOOM_LEVEL);
}
if (bundle.containsKey(BUNDLE_LOYALTY_CARD_ARCHIVE_STATUS)) {
setArchiveStatus(bundle.getInt(BUNDLE_LOYALTY_CARD_ARCHIVE_STATUS));
} else if (requireFull) {
throw new IllegalArgumentException("Missing key " + BUNDLE_LOYALTY_CARD_ARCHIVE_STATUS);
}
if (bundle.containsKey(BUNDLE_LOYALTY_CARD_IMAGE_THUMBNAIL)) {
setImageThumbnail(null, bundle.getString(BUNDLE_LOYALTY_CARD_IMAGE_THUMBNAIL));
} else if (requireFull) {
throw new IllegalArgumentException("Missing key " + BUNDLE_LOYALTY_CARD_IMAGE_THUMBNAIL);
}
if (bundle.containsKey(BUNDLE_LOYALTY_CARD_IMAGE_FRONT)) {
setImageFront(null, bundle.getString(BUNDLE_LOYALTY_CARD_IMAGE_FRONT));
} else if (requireFull) {
throw new IllegalArgumentException("Missing key " + BUNDLE_LOYALTY_CARD_IMAGE_FRONT);
}
if (bundle.containsKey(BUNDLE_LOYALTY_CARD_IMAGE_BACK)) {
setImageBack(null, bundle.getString(BUNDLE_LOYALTY_CARD_IMAGE_BACK));
} else if (requireFull) {
throw new IllegalArgumentException("Missing key " + BUNDLE_LOYALTY_CARD_IMAGE_BACK);
}
}
public Bundle toBundle(Context context, List<String> exportLimit) {
boolean exportIsLimited = !exportLimit.isEmpty();
Bundle bundle = new Bundle();
if (!exportIsLimited || exportLimit.contains(BUNDLE_LOYALTY_CARD_ID)) {
bundle.putInt(BUNDLE_LOYALTY_CARD_ID, id);
}
if (!exportIsLimited || exportLimit.contains(BUNDLE_LOYALTY_CARD_STORE)) {
bundle.putString(BUNDLE_LOYALTY_CARD_STORE, store);
}
if (!exportIsLimited || exportLimit.contains(BUNDLE_LOYALTY_CARD_NOTE)) {
bundle.putString(BUNDLE_LOYALTY_CARD_NOTE, note);
}
if (!exportIsLimited || exportLimit.contains(BUNDLE_LOYALTY_CARD_VALID_FROM)) {
bundle.putLong(BUNDLE_LOYALTY_CARD_VALID_FROM, validFrom != null ? validFrom.getTime() : -1);
}
if (!exportIsLimited || exportLimit.contains(BUNDLE_LOYALTY_CARD_EXPIRY)) {
bundle.putLong(BUNDLE_LOYALTY_CARD_EXPIRY, expiry != null ? expiry.getTime() : -1);
}
if (!exportIsLimited || exportLimit.contains(BUNDLE_LOYALTY_CARD_BALANCE)) {
bundle.putString(BUNDLE_LOYALTY_CARD_BALANCE, balance.toString());
}
if (!exportIsLimited || exportLimit.contains(BUNDLE_LOYALTY_CARD_BALANCE_TYPE)) {
bundle.putString(BUNDLE_LOYALTY_CARD_BALANCE_TYPE, balanceType != null ? balanceType.toString() : null);
}
if (!exportIsLimited || exportLimit.contains(BUNDLE_LOYALTY_CARD_CARD_ID)) {
bundle.putString(BUNDLE_LOYALTY_CARD_CARD_ID, cardId);
}
if (!exportIsLimited || exportLimit.contains(BUNDLE_LOYALTY_CARD_BARCODE_ID)) {
bundle.putString(BUNDLE_LOYALTY_CARD_BARCODE_ID, barcodeId);
}
if (!exportIsLimited || exportLimit.contains(BUNDLE_LOYALTY_CARD_BARCODE_TYPE)) {
bundle.putString(BUNDLE_LOYALTY_CARD_BARCODE_TYPE, barcodeType != null ? barcodeType.name() : null);
}
if (!exportIsLimited || exportLimit.contains(BUNDLE_LOYALTY_CARD_HEADER_COLOR)) {
bundle.putInt(BUNDLE_LOYALTY_CARD_HEADER_COLOR, headerColor != null ? headerColor : -1);
}
if (!exportIsLimited || exportLimit.contains(BUNDLE_LOYALTY_CARD_STAR_STATUS)) {
bundle.putInt(BUNDLE_LOYALTY_CARD_STAR_STATUS, starStatus);
}
if (!exportIsLimited || exportLimit.contains(BUNDLE_LOYALTY_CARD_LAST_USED)) {
bundle.putLong(BUNDLE_LOYALTY_CARD_LAST_USED, lastUsed);
}
if (!exportIsLimited || exportLimit.contains(BUNDLE_LOYALTY_CARD_ZOOM_LEVEL)) {
bundle.putInt(BUNDLE_LOYALTY_CARD_ZOOM_LEVEL, zoomLevel);
}
if (!exportIsLimited || exportLimit.contains(BUNDLE_LOYALTY_CARD_ARCHIVE_STATUS)) {
bundle.putInt(BUNDLE_LOYALTY_CARD_ARCHIVE_STATUS, archiveStatus);
}
// There is an (undocumented) size limit to bundles of around 2MB(?), when going over it you will experience a random crash
// So, instead of storing the bitmaps directly, we write the bitmap to a temp file and store the path
if (!exportIsLimited || exportLimit.contains(BUNDLE_LOYALTY_CARD_IMAGE_THUMBNAIL)) {
Bitmap thumbnail = getImageThumbnail(context);
if (thumbnail != null) {
Utils.saveTempImage(context, thumbnail, TEMP_IMAGE_THUMBNAIL_FILE_NAME, Bitmap.CompressFormat.PNG);
bundle.putString(BUNDLE_LOYALTY_CARD_IMAGE_THUMBNAIL, TEMP_IMAGE_THUMBNAIL_FILE_NAME);
} else {
bundle.putString(BUNDLE_LOYALTY_CARD_IMAGE_THUMBNAIL, null);
}
}
if (!exportIsLimited || exportLimit.contains(BUNDLE_LOYALTY_CARD_IMAGE_FRONT)) {
Bitmap front = getImageFront(context);
if (front != null) {
Utils.saveTempImage(context, front, TEMP_IMAGE_FRONT_FILE_NAME, Bitmap.CompressFormat.PNG);
bundle.putString(BUNDLE_LOYALTY_CARD_IMAGE_FRONT, TEMP_IMAGE_FRONT_FILE_NAME);
} else {
bundle.putString(BUNDLE_LOYALTY_CARD_IMAGE_FRONT, null);
}
}
if (!exportIsLimited || exportLimit.contains(BUNDLE_LOYALTY_CARD_IMAGE_BACK)) {
Bitmap back = getImageBack(context);
if (back != null) {
Utils.saveTempImage(context, back, TEMP_IMAGE_BACK_FILE_NAME, Bitmap.CompressFormat.PNG);
bundle.putString(BUNDLE_LOYALTY_CARD_IMAGE_BACK, TEMP_IMAGE_BACK_FILE_NAME);
} else {
bundle.putString(BUNDLE_LOYALTY_CARD_IMAGE_BACK, null);
}
}
return bundle;
}
public static LoyaltyCard fromCursor(Context context, Cursor cursor) {
// id
public static LoyaltyCard toLoyaltyCard(Cursor cursor) {
int id = cursor.getInt(cursor.getColumnIndexOrThrow(DBHelper.LoyaltyCardDbIds.ID));
// store
String store = cursor.getString(cursor.getColumnIndexOrThrow(DBHelper.LoyaltyCardDbIds.STORE));
// note
String note = cursor.getString(cursor.getColumnIndexOrThrow(DBHelper.LoyaltyCardDbIds.NOTE));
// validFrom
long validFromLong = cursor.getLong(cursor.getColumnIndexOrThrow(DBHelper.LoyaltyCardDbIds.VALID_FROM));
Date validFrom = validFromLong > 0 ? new Date(validFromLong) : null;
// expiry
long expiryLong = cursor.getLong(cursor.getColumnIndexOrThrow(DBHelper.LoyaltyCardDbIds.EXPIRY));
Date expiry = expiryLong > 0 ? new Date(expiryLong) : null;
// balance
BigDecimal balance = new BigDecimal(cursor.getString(cursor.getColumnIndexOrThrow(DBHelper.LoyaltyCardDbIds.BALANCE)));
// balanceType
int balanceTypeColumn = cursor.getColumnIndexOrThrow(DBHelper.LoyaltyCardDbIds.BALANCE_TYPE);
Currency balanceType = !cursor.isNull(balanceTypeColumn) ? Currency.getInstance(cursor.getString(balanceTypeColumn)) : null;
// cardId
String cardId = cursor.getString(cursor.getColumnIndexOrThrow(DBHelper.LoyaltyCardDbIds.CARD_ID));
// barcodeId
int barcodeIdColumn = cursor.getColumnIndexOrThrow(DBHelper.LoyaltyCardDbIds.BARCODE_ID);
String barcodeId = !cursor.isNull(barcodeIdColumn) ? cursor.getString(barcodeIdColumn) : null;
// barcodeType
int barcodeTypeColumn = cursor.getColumnIndexOrThrow(DBHelper.LoyaltyCardDbIds.BARCODE_TYPE);
CatimaBarcode barcodeType = !cursor.isNull(barcodeTypeColumn) ? CatimaBarcode.fromName(cursor.getString(barcodeTypeColumn)) : null;
// headerColor
int headerColorColumn = cursor.getColumnIndexOrThrow(DBHelper.LoyaltyCardDbIds.HEADER_COLOR);
Integer headerColor = !cursor.isNull(headerColorColumn) ? cursor.getInt(headerColorColumn) : null;
// starStatus
int starStatus = cursor.getInt(cursor.getColumnIndexOrThrow(DBHelper.LoyaltyCardDbIds.STAR_STATUS));
// lastUsed
String barcodeId = cursor.getString(cursor.getColumnIndexOrThrow(DBHelper.LoyaltyCardDbIds.BARCODE_ID));
int starred = cursor.getInt(cursor.getColumnIndexOrThrow(DBHelper.LoyaltyCardDbIds.STAR_STATUS));
long lastUsed = cursor.getLong(cursor.getColumnIndexOrThrow(DBHelper.LoyaltyCardDbIds.LAST_USED));
// zoomLevel
int zoomLevel = cursor.getInt(cursor.getColumnIndexOrThrow(DBHelper.LoyaltyCardDbIds.ZOOM_LEVEL));
// archiveStatus
int archiveStatus = cursor.getInt(cursor.getColumnIndexOrThrow(DBHelper.LoyaltyCardDbIds.ARCHIVE_STATUS));
int archived = cursor.getInt(cursor.getColumnIndexOrThrow(DBHelper.LoyaltyCardDbIds.ARCHIVE_STATUS));
return new LoyaltyCard(
id,
store,
note,
validFrom,
expiry,
balance,
balanceType,
cardId,
barcodeId,
barcodeType,
headerColor,
starStatus,
lastUsed,
zoomLevel,
archiveStatus,
null,
Utils.getCardImageFileName(id, ImageLocationType.icon),
null,
Utils.getCardImageFileName(id, ImageLocationType.front),
null,
Utils.getCardImageFileName(id, ImageLocationType.back)
);
int barcodeTypeColumn = cursor.getColumnIndexOrThrow(DBHelper.LoyaltyCardDbIds.BARCODE_TYPE);
int balanceTypeColumn = cursor.getColumnIndexOrThrow(DBHelper.LoyaltyCardDbIds.BALANCE_TYPE);
int headerColorColumn = cursor.getColumnIndexOrThrow(DBHelper.LoyaltyCardDbIds.HEADER_COLOR);
CatimaBarcode barcodeType = null;
Currency balanceType = null;
Date validFrom = null;
Date expiry = null;
Integer headerColor = null;
if (cursor.isNull(barcodeTypeColumn) == false) {
barcodeType = CatimaBarcode.fromName(cursor.getString(barcodeTypeColumn));
}
if (cursor.isNull(balanceTypeColumn) == false) {
balanceType = Currency.getInstance(cursor.getString(balanceTypeColumn));
}
if (validFromLong > 0) {
validFrom = new Date(validFromLong);
}
if (expiryLong > 0) {
expiry = new Date(expiryLong);
}
if (cursor.isNull(headerColorColumn) == false) {
headerColor = cursor.getInt(headerColorColumn);
}
return new LoyaltyCard(id, store, note, validFrom, expiry, balance, balanceType, cardId, barcodeId, barcodeType, headerColor, starred, lastUsed, zoomLevel, archived);
}
public static boolean isDuplicate(Context context, final LoyaltyCard a, final LoyaltyCard b) {
// Note: Bitmap comparing is slow, be careful when calling this method
public static boolean isDuplicate(final LoyaltyCard a, final LoyaltyCard b) {
// Skip lastUsed & zoomLevel
return a.id == b.id && // non-nullable int
a.store.equals(b.store) && // non-nullable String
@@ -570,23 +159,12 @@ public class LoyaltyCard {
b.barcodeType == null ? null : b.barcodeType.format()) && // nullable CatimaBarcode with no overridden .equals(), so we need to check .format()
Utils.equals(a.headerColor, b.headerColor) && // nullable Integer
a.starStatus == b.starStatus && // non-nullable int
a.archiveStatus == b.archiveStatus && // non-nullable int
nullableBitmapsEqual(a.getImageThumbnail(context), b.getImageThumbnail(context)) && // nullable Bitmap
nullableBitmapsEqual(a.getImageFront(context), b.getImageFront(context)) && // nullable Bitmap
nullableBitmapsEqual(a.getImageBack(context), b.getImageBack(context)); // nullable Bitmap
a.archiveStatus == b.archiveStatus; // non-nullable int
}
public static boolean nullableBitmapsEqual(@Nullable Bitmap a, @Nullable Bitmap b) {
if (a == null && b == null) {
return true;
}
if (a != null && b != null) {
return a.sameAs(b);
}
// One is null and the other isn't, so it's not equal
return false;
@Override
public int describeContents() {
return id;
}
@NonNull
@@ -595,8 +173,7 @@ public class LoyaltyCard {
return String.format(
"LoyaltyCard{%n id=%s,%n store=%s,%n note=%s,%n validFrom=%s,%n expiry=%s,%n"
+ " balance=%s,%n balanceType=%s,%n cardId=%s,%n barcodeId=%s,%n barcodeType=%s,%n"
+ " headerColor=%s,%n starStatus=%s,%n lastUsed=%s,%n zoomLevel=%s,%n archiveStatus=%s%n"
+ " imageThumbnail=%s,%n imageThumbnailPath=%s,%n imageFront=%s,%n imageFrontPath=%s,%n imageBack=%s,%n imageBackPath=%s,%n}",
+ " headerColor=%s,%n starStatus=%s,%n lastUsed=%s,%n zoomLevel=%s,%n archiveStatus=%s%n}",
this.id,
this.store,
this.note,
@@ -611,13 +188,19 @@ public class LoyaltyCard {
this.starStatus,
this.lastUsed,
this.zoomLevel,
this.archiveStatus,
this.imageThumbnail,
this.imageThumbnailPath,
this.imageFront,
this.imageFrontPath,
this.imageBack,
this.imageBackPath
this.archiveStatus
);
}
public static final Creator<LoyaltyCard> CREATOR = new Creator<LoyaltyCard>() {
@Override
public LoyaltyCard createFromParcel(Parcel in) {
return new LoyaltyCard(in);
}
@Override
public LoyaltyCard[] newArray(int size) {
return new LoyaltyCard[size];
}
};
}

View File

@@ -15,13 +15,6 @@ import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.BlendModeColorFilterCompat;
import androidx.core.graphics.BlendModeCompat;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.card.MaterialCardView;
import com.google.android.material.color.MaterialColors;
@@ -29,8 +22,14 @@ import java.math.BigDecimal;
import java.text.DateFormat;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.BlendModeColorFilterCompat;
import androidx.core.graphics.BlendModeCompat;
import androidx.recyclerview.widget.RecyclerView;
import protect.card_locker.databinding.LoyaltyCardLayoutBinding;
import protect.card_locker.preferences.Settings;
public class LoyaltyCardCursorAdapter extends BaseCursorAdapter<LoyaltyCardCursorAdapter.LoyaltyCardListItemViewHolder> {
private int mCurrentSelectedIndex = -1;
@@ -80,7 +79,7 @@ public class LoyaltyCardCursorAdapter extends BaseCursorAdapter<LoyaltyCardCurso
public LoyaltyCard getCard(int position) {
mCursor.moveToPosition(position);
return LoyaltyCard.fromCursor(mContext, mCursor);
return LoyaltyCard.toLoyaltyCard(mCursor);
}
public void onBindViewHolder(LoyaltyCardListItemViewHolder inputHolder, Cursor inputCursor) {
@@ -88,8 +87,8 @@ public class LoyaltyCardCursorAdapter extends BaseCursorAdapter<LoyaltyCardCurso
boolean showDivider = false;
inputHolder.mDivider.setVisibility(View.GONE);
LoyaltyCard loyaltyCard = LoyaltyCard.fromCursor(mContext, inputCursor);
Bitmap icon = loyaltyCard.getImageThumbnail(mContext);
LoyaltyCard loyaltyCard = LoyaltyCard.toLoyaltyCard(inputCursor);
Bitmap icon = Utils.retrieveCardImage(mContext, loyaltyCard.id, ImageLocationType.icon);
if (mLoyaltyCardListDisplayOptions.showingNameBelowThumbnail() && icon != null) {
showDivider = true;
@@ -112,21 +111,22 @@ public class LoyaltyCardCursorAdapter extends BaseCursorAdapter<LoyaltyCardCurso
}
if (mLoyaltyCardListDisplayOptions.showingValidity() && loyaltyCard.validFrom != null) {
inputHolder.setExtraField(inputHolder.mValidFromField, DateFormat.getDateInstance(DateFormat.MEDIUM).format(loyaltyCard.validFrom), Utils.isNotYetValid(loyaltyCard.validFrom) ? Color.RED : null, showDivider);
inputHolder.setExtraField(inputHolder.mValidFromField, DateFormat.getDateInstance(DateFormat.LONG).format(loyaltyCard.validFrom), Utils.isNotYetValid(loyaltyCard.validFrom) ? Color.RED : null, showDivider);
} else {
inputHolder.setExtraField(inputHolder.mValidFromField, null, null, false);
}
if (mLoyaltyCardListDisplayOptions.showingValidity() && loyaltyCard.expiry != null) {
inputHolder.setExtraField(inputHolder.mExpiryField, DateFormat.getDateInstance(DateFormat.MEDIUM).format(loyaltyCard.expiry), Utils.hasExpired(loyaltyCard.expiry) ? Color.RED : null, showDivider);
inputHolder.setExtraField(inputHolder.mExpiryField, DateFormat.getDateInstance(DateFormat.LONG).format(loyaltyCard.expiry), Utils.hasExpired(loyaltyCard.expiry) ? Color.RED : null, showDivider);
} else {
inputHolder.setExtraField(inputHolder.mExpiryField, null, null, false);
}
inputHolder.mCardIcon.setContentDescription(loyaltyCard.store);
Utils.setIconOrTextWithBackground(mContext, loyaltyCard, icon, inputHolder.mCardIcon, inputHolder.mCardText, new Settings(mContext).getPreferredColumnCount());
Utils.setIconOrTextWithBackground(mContext, loyaltyCard, icon, inputHolder.mCardIcon, inputHolder.mCardText);
inputHolder.setIconBackgroundColor(Utils.getHeaderColor(mContext, loyaltyCard));
inputHolder.toggleCardStateIcon(loyaltyCard.starStatus != 0, loyaltyCard.archiveStatus != 0);
inputHolder.toggleCardStateIcon(loyaltyCard.starStatus != 0, loyaltyCard.archiveStatus != 0, itemSelected(inputCursor.getPosition()));
inputHolder.itemView.setActivated(mSelectedItems.get(inputCursor.getPosition(), false));
applyIconAnimation(inputHolder, inputCursor.getPosition());
@@ -193,7 +193,7 @@ public class LoyaltyCardCursorAdapter extends BaseCursorAdapter<LoyaltyCardCurso
int i;
for (i = 0; i < mSelectedItems.size(); i++) {
mCursor.moveToPosition(mSelectedItems.keyAt(i));
result.add(LoyaltyCard.fromCursor(mContext, mCursor));
result.add(LoyaltyCard.toLoyaltyCard(mCursor));
}
return result;
@@ -212,11 +212,13 @@ public class LoyaltyCardCursorAdapter extends BaseCursorAdapter<LoyaltyCardCurso
public class LoyaltyCardListItemViewHolder extends RecyclerView.ViewHolder {
public TextView mCardText, mStoreField, mNoteField, mBalanceField, mValidFromField, mExpiryField;
public ImageView mCardIcon, mTickIcon;
public ImageView mCardIcon, mStarBackground, mStarBorder, mTickIcon, mArchivedBackground;
public MaterialCardView mRow;
public ConstraintLayout mStar, mArchived;
public View mDivider;
private int mIconBackgroundColor;
protected LoyaltyCardListItemViewHolder(LoyaltyCardLayoutBinding loyaltyCardLayoutBinding, CardAdapterListener inputListener) {
super(loyaltyCardLayoutBinding.getRoot());
View inputView = loyaltyCardLayoutBinding.getRoot();
@@ -230,7 +232,10 @@ public class LoyaltyCardCursorAdapter extends BaseCursorAdapter<LoyaltyCardCurso
mCardIcon = loyaltyCardLayoutBinding.thumbnail;
mCardText = loyaltyCardLayoutBinding.thumbnailText;
mStar = loyaltyCardLayoutBinding.star;
mStarBackground = loyaltyCardLayoutBinding.starBackground;
mStarBorder = loyaltyCardLayoutBinding.starBorder;
mArchived = loyaltyCardLayoutBinding.archivedIcon;
mArchivedBackground = loyaltyCardLayoutBinding.archiveBackground;
mTickIcon = loyaltyCardLayoutBinding.selectedThumbnail;
inputView.setOnLongClickListener(view -> {
inputListener.onRowClicked(getAdapterPosition());
@@ -292,7 +297,31 @@ public class LoyaltyCardCursorAdapter extends BaseCursorAdapter<LoyaltyCardCurso
mNoteField.requestLayout();
}
public void toggleCardStateIcon(boolean enableStar, boolean enableArchive) {
public void toggleCardStateIcon(boolean enableStar, boolean enableArchive, boolean colorByTheme) {
/* the below code does not work in android 5! hence the change of drawable instead
boolean needDarkForeground = Utils.needsDarkForeground(mIconBackgroundColor);
Drawable borderDrawable = mStarBorder.getDrawable().mutate();
Drawable backgroundDrawable = mStarBackground.getDrawable().mutate();
DrawableCompat.setTint(borderDrawable, needsDarkForeground ? Color.BLACK : Color.WHITE);
DrawableCompat.setTint(backgroundDrawable, needsDarkForeground ? Color.BLACK : Color.WHITE);
mStarBorder.setImageDrawable(borderDrawable);
mStarBackground.setImageDrawable(backgroundDrawable);
*/
boolean dark = Utils.needsDarkForeground(mIconBackgroundColor);
if (colorByTheme) {
dark = !mDarkModeEnabled;
}
if (dark) {
mStarBorder.setImageResource(R.drawable.ic_unstarred_white);
mStarBackground.setImageResource(R.drawable.ic_starred_black);
mArchivedBackground.setImageResource(R.drawable.ic_baseline_archive_24_black);
} else {
mStarBorder.setImageResource(R.drawable.ic_unstarred_black);
mStarBackground.setImageResource(R.drawable.ic_starred_white);
mArchivedBackground.setImageResource(R.drawable.ic_baseline_archive_24);
}
if (enableStar) {
mStar.setVisibility(View.VISIBLE);
} else{
@@ -304,6 +333,22 @@ public class LoyaltyCardCursorAdapter extends BaseCursorAdapter<LoyaltyCardCurso
} else{
mArchived.setVisibility(View.GONE);
}
mStarBorder.invalidate();
mStarBackground.invalidate();
mArchivedBackground.invalidate();
}
public void setIconBackgroundColor(int color) {
mIconBackgroundColor = color;
mCardIcon.setBackgroundColor(color);
}
}
public int dpToPx(int dp, Context mContext) {
Resources r = mContext.getResources();
int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics());
return px;
}
}

View File

File diff suppressed because it is too large Load Diff

View File

@@ -3,7 +3,6 @@ package protect.card_locker;
import android.app.Application;
import androidx.appcompat.app.AppCompatDelegate;
import protect.card_locker.preferences.Settings;
public class LoyaltyCardLockerApplication extends Application {

View File

@@ -1,6 +1,7 @@
package protect.card_locker;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.ColorStateList;
@@ -19,7 +20,7 @@ import android.text.method.DigitsKeyListener;
import android.text.style.ForegroundColorSpan;
import android.text.util.Linkify;
import android.util.Log;
import android.view.KeyEvent;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
@@ -37,17 +38,19 @@ import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.OnBackPressedCallback;
import androidx.annotation.StringRes;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.FileProvider;
import androidx.core.graphics.BlendModeColorFilterCompat;
import androidx.core.graphics.BlendModeCompat;
import androidx.core.graphics.ColorUtils;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.core.view.ViewCompat;
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat;
import androidx.core.widget.TextViewCompat;
import com.google.android.material.color.MaterialColors;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
@@ -60,6 +63,7 @@ import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Currency;
import java.util.Date;
import java.util.List;
import java.util.function.Predicate;
@@ -98,35 +102,9 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
static final String STATE_IMAGEINDEX = "imageIndex";
static final String STATE_FULLSCREEN = "isFullscreen";
static final String BUNDLE_ID = "id";
static final String BUNDLE_CARDLIST = "cardList";
static final String BUNDLE_TRANSITION_RIGHT = "transition_right";
final private TaskHandler mTasks = new TaskHandler();
Runnable barcodeImageGenerationFinishedCallback;
private long initTime = System.currentTimeMillis();
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (settings.useVolumeKeysForNavigation()) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
// Navigate to the previous card
if (initTime < (System.currentTimeMillis() - 1000)) {
prevNextCard(false);
}
return true;
} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
// Navigate to the next card
if (initTime < (System.currentTimeMillis() - 1000)) {
prevNextCard(true);
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
public void onMainImageTap() {
// If we're in fullscreen, leave fullscreen
if (isFullscreen) {
@@ -134,25 +112,22 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
return;
}
ImageType imageType = imageTypes.get(mainImageIndex);
// If the barcode is shown, switch to fullscreen layout
if (imageType == ImageType.BARCODE) {
if (imageTypes.get(mainImageIndex) == ImageType.BARCODE) {
setFullscreen(true);
return;
}
// If this is an image, open it in the gallery.
openImageInGallery(imageType);
openCurrentMainImageInGallery();
}
private void openImageInGallery(ImageType imageType) {
private void openCurrentMainImageInGallery() {
ImageType wantedImageType = imageTypes.get(mainImageIndex);
File file = null;
switch (imageType) {
case ICON:
file = Utils.retrieveCardImageAsFile(this, loyaltyCardId, ImageLocationType.icon);
break;
switch (wantedImageType) {
case IMAGE_FRONT:
file = Utils.retrieveCardImageAsFile(this, loyaltyCardId, ImageLocationType.front);
break;
@@ -200,7 +175,6 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
enum ImageType {
NONE,
ICON,
BARCODE,
IMAGE_FRONT,
IMAGE_BACK
@@ -208,8 +182,8 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
private void extractIntentFields(Intent intent) {
final Bundle b = intent.getExtras();
loyaltyCardId = b != null ? b.getInt(BUNDLE_ID) : 0;
cardList = b != null ? b.getIntegerArrayList(BUNDLE_CARDLIST) : null;
loyaltyCardId = b != null ? b.getInt("id") : 0;
cardList = b != null ? b.getIntegerArrayList("cardList") : null;
Log.d(TAG, "View activity: id=" + loyaltyCardId);
}
@@ -235,7 +209,7 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
return;
}
int transitionRight = incomingIntentExtras.getInt(BUNDLE_TRANSITION_RIGHT, -1);
int transitionRight = incomingIntentExtras.getInt("transition_right", -1);
if (transitionRight == 1) {
// right side transition
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
@@ -254,9 +228,7 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
settings = new Settings(this);
String cardOrientation = settings.getCardViewOrientation();
if (cardOrientation.equals(getString(R.string.settings_key_follow_sensor_orientation))) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
} else if (cardOrientation.equals(getString(R.string.settings_key_lock_on_opening_orientation))) {
if (cardOrientation.equals(getString(R.string.settings_key_lock_on_opening_orientation))) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
} else if (cardOrientation.equals(getString(R.string.settings_key_portrait_orientation))) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
@@ -328,13 +300,7 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
binding.bottomAppBarNextButton.setOnClickListener(view -> prevNextCard(true));
binding.bottomAppBarUpdateBalanceButton.setOnClickListener(view -> showBalanceUpdateDialog());
binding.iconContainer.setOnClickListener(view -> {
if (loyaltyCard.getImageThumbnail(this) != null) {
openImageInGallery(ImageType.ICON);
} else {
Toast.makeText(LoyaltyCardViewActivity.this, R.string.icon_header_click_text, Toast.LENGTH_LONG).show();
}
});
binding.iconContainer.setOnClickListener(view -> Toast.makeText(LoyaltyCardViewActivity.this, R.string.icon_header_click_text, Toast.LENGTH_LONG).show());
binding.iconContainer.setOnLongClickListener(view -> {
Intent intent = new Intent(getApplicationContext(), LoyaltyCardEditActivity.class);
Bundle bundle = new Bundle();
@@ -356,17 +322,6 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
return true;
});
binding.fullscreenImage.setOnClickListener(view -> onMainImageTap());
getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
if (isFullscreen) {
setFullscreen(false);
} else {
finish();
}
}
});
}
private SpannableStringBuilder padSpannableString(SpannableStringBuilder spannableStringBuilder) {
@@ -445,11 +400,7 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
private void showBalanceUpdateDialog() {
AlertDialog.Builder builder = new MaterialAlertDialogBuilder(this);
// Header
builder.setTitle(R.string.updateBalanceTitle);
// Layout
FrameLayout container = new FrameLayout(this);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
@@ -467,91 +418,61 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
currentTextview.setText(getString(R.string.currentBalanceSentence, Utils.formatBalance(this, loyaltyCard.balance, loyaltyCard.balanceType)));
layout.addView(currentTextview);
TextView updateTextView = new TextView(this);
updateTextView.setText(getString(R.string.newBalanceSentence, Utils.formatBalance(this, loyaltyCard.balance, loyaltyCard.balanceType)));
layout.addView(updateTextView);
final TextInputEditText input = new TextInputEditText(this);
input.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
Context dialogContext = this;
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setKeyListener(DigitsKeyListener.getInstance("0123456789,."));
input.setHint(R.string.updateBalanceHint);
input.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
BigDecimal newBalance;
try {
newBalance = calculateNewBalance(loyaltyCard.balance, loyaltyCard.balanceType, s.toString());
} catch (ParseException e) {
input.setTag(null);
updateTextView.setText(getString(R.string.newBalanceSentence, Utils.formatBalance(dialogContext, loyaltyCard.balance, loyaltyCard.balanceType)));
return;
}
// Save new balance into this element
input.setTag(newBalance);
updateTextView.setText(getString(R.string.newBalanceSentence, Utils.formatBalance(dialogContext, newBalance, loyaltyCard.balanceType)));
}
});
layout.addView(input);
layout.setLayoutParams(params);
container.addView(layout);
// Set layout
builder.setView(container);
// Buttons
builder.setPositiveButton(R.string.spend, (dialogInterface, i) -> {
// Calculate and update balance
try {
BigDecimal balanceChange = Utils.parseBalance(input.getText().toString(), loyaltyCard.balanceType);
BigDecimal newBalance = loyaltyCard.balance.subtract(balanceChange).max(new BigDecimal(0));
DBHelper.updateLoyaltyCardBalance(database, loyaltyCardId, newBalance);
} catch (ParseException e) {
Toast.makeText(getApplicationContext(), R.string.amountParsingFailed, Toast.LENGTH_LONG).show();
builder.setPositiveButton(R.string.ok, (dialogInterface, i) -> {
// Grab calculated balance from input field
BigDecimal newBalance = (BigDecimal) input.getTag();
if (newBalance == null) {
return;
}
// Reload state
// Actually update balance
DBHelper.updateLoyaltyCardBalance(database, loyaltyCardId, newBalance);
// Reload UI
this.onResume();
// Show new balance
Toast.makeText(getApplicationContext(), getString(R.string.newBalanceSentence, Utils.formatBalance(this, loyaltyCard.balance, loyaltyCard.balanceType)), Toast.LENGTH_LONG).show();
});
builder.setNegativeButton(R.string.receive, (dialogInterface, i) -> {
// Calculate and update balance
try {
BigDecimal balanceChange = Utils.parseBalance(input.getText().toString(), loyaltyCard.balanceType);
BigDecimal newBalance = loyaltyCard.balance.add(balanceChange);
DBHelper.updateLoyaltyCardBalance(database, loyaltyCardId, newBalance);
} catch (ParseException e) {
Toast.makeText(getApplicationContext(), R.string.amountParsingFailed, Toast.LENGTH_LONG).show();
}
// Reload state
this.onResume();
// Show new balance
Toast.makeText(getApplicationContext(), getString(R.string.newBalanceSentence, Utils.formatBalance(this, loyaltyCard.balance, loyaltyCard.balanceType)), Toast.LENGTH_LONG).show();
});
builder.setNeutralButton(getString(R.string.cancel), (dialog, which) -> dialog.cancel());
builder.setNegativeButton(getString(R.string.cancel), (dialog, which) -> dialog.cancel());
AlertDialog dialog = builder.create();
// Now that the dialog exists, we can bind something that affects the buttons
input.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
BigDecimal balanceChange;
try {
balanceChange = Utils.parseBalance(s.toString(), loyaltyCard.balanceType);
} catch (ParseException e) {
input.setError(getString(R.string.amountParsingFailed));
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setEnabled(false);
return;
}
input.setError(null);
if (balanceChange.equals(new BigDecimal(0))) {
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setEnabled(false);
} else {
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setEnabled(true);
}
}
});
dialog.show();
// Disable buttons (must be done **after** dialog is shown to prevent crash
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setEnabled(false);
// Set focus on input field
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
input.requestFocus();
}
private BigDecimal calculateNewBalance(BigDecimal currentBalance, Currency currency, String unparsedSubtraction) throws ParseException {
BigDecimal subtraction = Utils.parseBalance(unparsedSubtraction, currency);
return currentBalance.subtract(subtraction).max(new BigDecimal(0));
}
private void setBottomAppBarButtonState() {
if (!loyaltyCard.note.isEmpty() || !loyaltyCardGroups.isEmpty() || hasBalance(loyaltyCard) || loyaltyCard.validFrom != null || loyaltyCard.expiry != null) {
binding.bottomAppBarInfoButton.setVisibility(View.VISIBLE);
@@ -599,8 +520,8 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
// Restart activity with new card id and index
Intent intent = getIntent();
Bundle b = intent.getExtras();
b.putInt(BUNDLE_ID, loyaltyCardId);
b.putInt(BUNDLE_TRANSITION_RIGHT, transitionRight ? 1 : 0);
b.putInt("id", loyaltyCardId);
b.putInt("transition_right", transitionRight ? 1 : 0);
intent.putExtras(b);
intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
@@ -623,8 +544,7 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
@Override
protected void onResume() {
activityOverridesNavBarColor = true;
public void onResume() {
super.onResume();
Log.i(TAG, "To view card: " + loyaltyCardId);
@@ -660,7 +580,7 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
window.setAttributes(attributes);
}
loyaltyCard = DBHelper.getLoyaltyCard(this, database, loyaltyCardId);
loyaltyCard = DBHelper.getLoyaltyCard(database, loyaltyCardId);
if (loyaltyCard == null) {
Log.w(TAG, "Could not lookup loyalty card " + loyaltyCardId);
Toast.makeText(this, R.string.noCardExistsError, Toast.LENGTH_LONG).show();
@@ -678,15 +598,10 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
cardIdString = loyaltyCard.cardId;
barcodeIdString = loyaltyCard.barcodeId;
binding.mainImageDescription.setText(loyaltyCard.cardId);
binding.cardIdView.setText(loyaltyCard.cardId);
// Display full text on click in case it doesn't fit in a single line
binding.mainImageDescription.setOnClickListener(v -> {
if (mainImageIndex != 0) {
// Don't show cardId dialog, we're displaying something else
return;
}
binding.cardIdView.setOnClickListener(v -> {
TextView cardIdView = new TextView(LoyaltyCardViewActivity.this);
cardIdView.setText(loyaltyCard.cardId);
cardIdView.setTextIsSelectable(true);
@@ -707,11 +622,7 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
int darkenedColor = ColorUtils.blendARGB(backgroundHeaderColor, Color.BLACK, 0.1f);
binding.barcodeScaler.setProgressTintList(ColorStateList.valueOf(darkenedColor));
binding.barcodeScaler.setThumbTintList(ColorStateList.valueOf(darkenedColor));
// Set bottomAppBar and system navigation bar color
binding.bottomAppBar.setBackgroundColor(darkenedColor);
Utils.setNavigationBarColor(null, window, darkenedColor, Utils.needsDarkForeground(darkenedColor));
int complementaryColor = Utils.getComplementaryColor(darkenedColor);
binding.fabEdit.setBackgroundTintList(ColorStateList.valueOf(complementaryColor));
Drawable editButtonIcon = binding.fabEdit.getDrawable();
@@ -719,8 +630,8 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
editButtonIcon.setTint(Utils.needsDarkForeground(complementaryColor) ? Color.BLACK : Color.WHITE);
binding.fabEdit.setImageDrawable(editButtonIcon);
Bitmap icon = loyaltyCard.getImageThumbnail(this);
Utils.setIconOrTextWithBackground(this, loyaltyCard, icon, binding.iconImage, binding.iconText, 1);
Bitmap icon = Utils.retrieveCardImage(this, loyaltyCard.id, ImageLocationType.icon);
Utils.setIconOrTextWithBackground(this, loyaltyCard, icon, binding.iconImage, binding.iconText);
// If the background is very bright, we should use dark icons
backgroundNeedsDarkIcons = Utils.needsDarkForeground(backgroundHeaderColor);
@@ -748,12 +659,12 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
imageTypes.add(ImageType.BARCODE);
}
frontImageBitmap = loyaltyCard.getImageFront(this);
frontImageBitmap = Utils.retrieveCardImage(this, loyaltyCard.id, ImageLocationType.front);
if (frontImageBitmap != null) {
imageTypes.add(ImageType.IMAGE_FRONT);
}
backImageBitmap = loyaltyCard.getImageBack(this);
backImageBitmap = Utils.retrieveCardImage(this, loyaltyCard.id, ImageLocationType.back);
if (backImageBitmap != null) {
imageTypes.add(ImageType.IMAGE_BACK);
}
@@ -765,8 +676,6 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
DBHelper.updateLoyaltyCardLastUsed(database, loyaltyCard.id);
invalidateOptionsMenu();
ShortcutHelper.updateShortcuts(this, loyaltyCard);
}
private void setStateBasedOnImageTypes() {
@@ -795,6 +704,16 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
imageButton.setColorFilter(BlendModeColorFilterCompat.createBlendModeColorFilterCompat(backgroundNeedsDarkIcons ? Color.BLACK : Color.WHITE, BlendModeCompat.SRC_ATOP));
}
@Override
public void onBackPressed() {
if (isFullscreen) {
setFullscreen(false);
return;
}
super.onBackPressed();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.card_view_menu, menu);
@@ -866,8 +785,6 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
DBHelper.updateLoyaltyCardArchiveStatus(database, loyaltyCardId, 1);
Toast.makeText(LoyaltyCardViewActivity.this, R.string.archived, Toast.LENGTH_LONG).show();
ShortcutHelper.removeShortcut(LoyaltyCardViewActivity.this, loyaltyCardId);
// Re-init loyaltyCard with new data from DB
onResume();
invalidateOptionsMenu();
@@ -959,9 +876,7 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
if (imageTypes.isEmpty()) {
barcodeRenderTarget.setVisibility(View.GONE);
binding.mainCardView.setCardBackgroundColor(Color.TRANSPARENT);
binding.mainImageDescription.setTextColor(MaterialColors.getColor(binding.mainImageDescription, com.google.android.material.R.attr.colorOnSurfaceVariant));
binding.mainImageDescription.setText(loyaltyCard.cardId);
binding.cardIdView.setTextColor(MaterialColors.getColor(binding.cardIdView, com.google.android.material.R.attr.colorOnSurfaceVariant));
return;
}
@@ -970,7 +885,7 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
if (wantedImageType == ImageType.BARCODE) {
barcodeRenderTarget.setBackgroundColor(Color.WHITE);
binding.mainCardView.setCardBackgroundColor(Color.WHITE);
binding.mainImageDescription.setTextColor(getResources().getColor(R.color.md_theme_light_onSurfaceVariant));
binding.cardIdView.setTextColor(getResources().getColor(R.color.md_theme_light_onSurfaceVariant));
if (waitForResize) {
redrawBarcodeAfterResize(!isFullscreen);
@@ -978,23 +893,18 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
drawBarcode(!isFullscreen);
}
binding.mainImageDescription.setText(loyaltyCard.cardId);
barcodeRenderTarget.setContentDescription(getString(R.string.barcodeImageDescriptionWithType, format.prettyName()));
} else if (wantedImageType == ImageType.IMAGE_FRONT) {
barcodeRenderTarget.setImageBitmap(frontImageBitmap);
barcodeRenderTarget.setBackgroundColor(Color.TRANSPARENT);
binding.mainCardView.setCardBackgroundColor(Color.TRANSPARENT);
binding.mainImageDescription.setTextColor(MaterialColors.getColor(binding.mainImageDescription, com.google.android.material.R.attr.colorOnSurfaceVariant));
binding.mainImageDescription.setText(getString(R.string.frontImageDescription));
binding.cardIdView.setTextColor(MaterialColors.getColor(binding.cardIdView, com.google.android.material.R.attr.colorOnSurfaceVariant));
barcodeRenderTarget.setContentDescription(getString(R.string.frontImageDescription));
} else if (wantedImageType == ImageType.IMAGE_BACK) {
barcodeRenderTarget.setImageBitmap(backImageBitmap);
barcodeRenderTarget.setBackgroundColor(Color.TRANSPARENT);
binding.mainCardView.setCardBackgroundColor(Color.TRANSPARENT);
binding.mainImageDescription.setTextColor(MaterialColors.getColor(binding.mainImageDescription, com.google.android.material.R.attr.colorOnSurfaceVariant));
binding.mainImageDescription.setText(getString(R.string.backImageDescription));
binding.cardIdView.setTextColor(MaterialColors.getColor(binding.cardIdView, com.google.android.material.R.attr.colorOnSurfaceVariant));
barcodeRenderTarget.setContentDescription(getString(R.string.backImageDescription));
} else {
throw new IllegalArgumentException("Unknown image type: " + wantedImageType);
@@ -1145,14 +1055,10 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
// Set Android to fullscreen mode
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
Window window = getWindow();
if (window != null) {
window.setDecorFitsSystemWindows(false);
WindowInsetsController wic = window.getInsetsController();
if (wic != null) {
wic.hide(WindowInsets.Type.statusBars() | WindowInsets.Type.navigationBars());
wic.setSystemBarsBehavior(WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE);
}
getWindow().setDecorFitsSystemWindows(false);
if (getWindow().getInsetsController() != null) {
getWindow().getInsetsController().hide(WindowInsets.Type.statusBars() | WindowInsets.Type.navigationBars());
getWindow().getInsetsController().setSystemBarsBehavior(WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE);
}
} else {
setFullscreenModeSdkLessThan30();
@@ -1179,14 +1085,10 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
// Unset fullscreen mode
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
Window window = getWindow();
if (window != null) {
window.setDecorFitsSystemWindows(true);
WindowInsetsController wic = window.getInsetsController();
if (wic != null) {
wic.show(WindowInsets.Type.statusBars() | WindowInsets.Type.navigationBars());
wic.setSystemBarsBehavior(WindowInsetsController.BEHAVIOR_DEFAULT);
}
getWindow().setDecorFitsSystemWindows(true);
if (getWindow().getInsetsController() != null) {
getWindow().getInsetsController().show(WindowInsets.Type.statusBars() | WindowInsets.Type.navigationBars());
getWindow().getInsetsController().setSystemBarsBehavior(WindowInsetsController.BEHAVIOR_DEFAULT);
}
} else {
unsetFullscreenModeSdkLessThan30();
@@ -1198,25 +1100,19 @@ public class LoyaltyCardViewActivity extends CatimaAppCompatActivity implements
@SuppressWarnings("deprecation")
private void unsetFullscreenModeSdkLessThan30() {
Window window = getWindow();
if (window != null) {
window.getDecorView().setSystemUiVisibility(
window.getDecorView().getSystemUiVisibility()
& ~View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
& ~View.SYSTEM_UI_FLAG_FULLSCREEN
);
}
getWindow().getDecorView().setSystemUiVisibility(
getWindow().getDecorView().getSystemUiVisibility()
& ~View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
& ~View.SYSTEM_UI_FLAG_FULLSCREEN
);
}
@SuppressWarnings("deprecation")
private void setFullscreenModeSdkLessThan30() {
Window window = getWindow();
if (window != null) {
window.getDecorView().setSystemUiVisibility(
window.getDecorView().getSystemUiVisibility()
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_FULLSCREEN
);
}
getWindow().getDecorView().setSystemUiVisibility(
getWindow().getDecorView().getSystemUiVisibility()
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_FULLSCREEN
);
}
}

View File

@@ -2,13 +2,15 @@ package protect.card_locker;
import android.app.Activity;
import android.app.SearchManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.CursorIndexOutOfBoundsException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
@@ -20,33 +22,28 @@ import android.view.View;
import android.widget.CheckBox;
import android.widget.Toast;
import androidx.activity.OnBackPressedCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.view.ActionMode;
import androidx.appcompat.widget.SearchView;
import androidx.core.splashscreen.SplashScreen;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.tabs.TabLayout;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import protect.card_locker.databinding.ContentMainBinding;
import protect.card_locker.databinding.MainActivityBinding;
import protect.card_locker.databinding.SortingOptionBinding;
import protect.card_locker.preferences.Settings;
import protect.card_locker.preferences.SettingsActivity;
public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCardCursorAdapter.CardAdapterListener {
@@ -56,7 +53,6 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard
public static final String RESTART_ACTIVITY_INTENT = "restart_activity_intent";
private static final int MEDIUM_SCALE_FACTOR_DIP = 460;
static final String STATE_SEARCH_QUERY = "SEARCH_QUERY";
private SQLiteDatabase mDatabase;
private LoyaltyCardCursorAdapter mAdapter;
@@ -64,8 +60,6 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard
private SearchView mSearchView;
private int mLoyaltyCardCount = 0;
protected String mFilter = "";
private String currentQuery = "";
private String finalQuery = "";
protected Object mGroup = null;
protected DBHelper.LoyaltyCardOrder mOrder = DBHelper.LoyaltyCardOrder.Alpha;
protected DBHelper.LoyaltyCardOrderDirection mOrderDirection = DBHelper.LoyaltyCardOrderDirection.Ascending;
@@ -75,7 +69,9 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard
private View mNoMatchingCardsText;
private View mNoGroupCardsText;
private TabLayout groupsTabLayout;
private Runnable mUpdateLoyaltyCardListRunnable;
private Runnable mSwapLoyaltyCardListCursor;
private ActivityResultLauncher<Intent> mBarcodeScannerLauncher;
private ActivityResultLauncher<Intent> mSettingsLauncher;
@@ -93,7 +89,35 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard
@Override
public boolean onActionItemClicked(ActionMode inputMode, MenuItem inputItem) {
if (inputItem.getItemId() == R.id.action_share) {
if (inputItem.getItemId() == R.id.action_copy_to_clipboard) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
String clipboardData;
int cardCount = mAdapter.getSelectedItemCount();
if (cardCount == 1) {
clipboardData = mAdapter.getSelectedItems().get(0).cardId;
} else {
StringBuilder cardIds = new StringBuilder();
for (int i = 0; i < cardCount; i++) {
LoyaltyCard loyaltyCard = mAdapter.getSelectedItems().get(i);
cardIds.append(loyaltyCard.store + ": " + loyaltyCard.cardId);
if (i < (cardCount - 1)) {
cardIds.append("\n");
}
}
clipboardData = cardIds.toString();
}
ClipData clip = ClipData.newPlainText(getString(R.string.card_ids_copied), clipboardData);
clipboard.setPrimaryClip(clip);
Toast.makeText(MainActivity.this, cardCount > 1 ? R.string.copy_to_clipboard_multiple_toast : R.string.copy_to_clipboard_toast, Toast.LENGTH_LONG).show();
inputMode.finish();
return true;
} else if (inputItem.getItemId() == R.id.action_share) {
final ImportURIHelper importURIHelper = new ImportURIHelper(MainActivity.this);
try {
importURIHelper.startShareIntent(mAdapter.getSelectedItems());
@@ -155,7 +179,6 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard
for (LoyaltyCard loyaltyCard : mAdapter.getSelectedItems()) {
Log.d(TAG, "Archiving card: " + loyaltyCard.id);
DBHelper.updateLoyaltyCardArchiveStatus(mDatabase, loyaltyCard.id, 1);
ShortcutHelper.removeShortcut(MainActivity.this, loyaltyCard.id);
updateLoyaltyCardList(false);
inputMode.finish();
invalidateOptionsMenu();
@@ -200,34 +223,12 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard
@Override
protected void onCreate(Bundle inputSavedInstanceState) {
extractIntentFields(getIntent());
SplashScreen.installSplashScreen(this);
super.onCreate(inputSavedInstanceState);
// Delete old cache files
// These could be temporary images for the cropper, temporary images in LoyaltyCard toBundle/writeParcel/ etc.
new Thread(() -> {
long twentyFourHoursAgo = System.currentTimeMillis() - (1000 * 60 * 60 * 24);
File[] tempFiles = getCacheDir().listFiles();
if (tempFiles == null) {
Log.e(TAG, "getCacheDir().listFiles() somehow returned null, this should never happen... Skipping cache cleanup...");
return;
}
for (File file : tempFiles) {
if (file.lastModified() < twentyFourHoursAgo) {
if (!file.delete()) {
Log.w(TAG, "Failed to delete cache file " + file.getPath());
}
};
}
}).start();
// We should extract the share intent after we called the super.onCreate as it may need to spawn a dialog window and the app needs to be initialized to not crash
extractIntentFields(getIntent());
binding = MainActivityBinding.inflate(getLayoutInflater());
setTitle(R.string.app_name);
setContentView(binding.getRoot());
setSupportActionBar(binding.toolbar);
groupsTabLayout = binding.groups;
@@ -235,8 +236,13 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard
mDatabase = new DBHelper(this).getWritableDatabase();
mUpdateLoyaltyCardListRunnable = () -> {
updateLoyaltyCardList(false);
mSwapLoyaltyCardListCursor = () -> {
Group group = null;
if (mGroup != null) {
group = (Group) mGroup;
}
mAdapter.swapCursor(DBHelper.getLoyaltyCardCursor(mDatabase, mFilter, group, mOrder, mOrderDirection, mAdapter.showingArchivedCards() ? DBHelper.LoyaltyCardArchiveFilter.All : DBHelper.LoyaltyCardArchiveFilter.Unarchived));
};
groupsTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@@ -271,19 +277,56 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard
mNoGroupCardsText = contentMainBinding.noGroupCardsText;
mCardList = contentMainBinding.list;
mAdapter = new LoyaltyCardCursorAdapter(this, null, this, mUpdateLoyaltyCardListRunnable);
mAdapter = new LoyaltyCardCursorAdapter(this, null, this, mSwapLoyaltyCardListCursor);
mCardList.setAdapter(mAdapter);
registerForContextMenu(mCardList);
mGroup = null;
updateLoyaltyCardList(true);
/*
* This was added for Huawei, but Huawei is just too much of a fucking pain.
* Just leaving this commented out if needed for the future idk
* https://twitter.com/SylvieLorxu/status/1379437902741012483
*
// Show privacy policy on first run
SharedPreferences privacyPolicyShownPref = getApplicationContext().getSharedPreferences(
getString(R.string.sharedpreference_privacy_policy_shown),
Context.MODE_PRIVATE);
if (privacyPolicyShownPref.getInt(getString(R.string.sharedpreference_privacy_policy_shown), 0) == 0) {
SharedPreferences.Editor privacyPolicyShownPrefEditor = privacyPolicyShownPref.edit();
privacyPolicyShownPrefEditor.putInt(getString(R.string.sharedpreference_privacy_policy_shown), 1);
privacyPolicyShownPrefEditor.apply();
new AlertDialog.Builder(this)
.setTitle(R.string.privacy_policy)
.setMessage(R.string.privacy_policy_popup_text)
.setPositiveButton(R.string.accept, null)
.setNegativeButton(R.string.privacy_policy, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
openPrivacyPolicy();
}
})
.setIcon(android.R.drawable.ic_dialog_info)
.show();
}
*/
mBarcodeScannerLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
// Exit early if the user cancelled the scan (pressed back/home)
if (result.getResultCode() != RESULT_OK) {
return;
}
Intent editIntent = new Intent(getApplicationContext(), LoyaltyCardEditActivity.class);
editIntent.putExtras(result.getData().getExtras());
startActivity(editIntent);
Intent intent = result.getData();
BarcodeValues barcodeValues = Utils.parseSetBarcodeActivityResult(Utils.BARCODE_SCAN, result.getResultCode(), intent, this);
Bundle inputBundle = intent.getExtras();
String group = inputBundle != null ? inputBundle.getString(LoyaltyCardEditActivity.BUNDLE_ADDGROUP) : null;
processBarcodeValues(barcodeValues, group);
});
mSettingsLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
@@ -294,17 +337,6 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard
}
}
});
getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
if (mSearchView != null && !mSearchView.isIconified()) {
mSearchView.setIconified(true);
} else {
finish();
}
}
});
}
@Override
@@ -319,6 +351,7 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard
if (mSearchView != null && !mSearchView.isIconified()) {
mFilter = mSearchView.getQuery().toString();
}
// Start of active tab logic
updateTabGroups(groupsTabLayout);
@@ -376,12 +409,16 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard
mBarcodeScannerLauncher.launch(intent);
});
addButton.bringToFront();
}
var layoutManager = (GridLayoutManager) mCardList.getLayoutManager();
if (layoutManager != null) {
var settings = new Settings(this);
layoutManager.setSpanCount(settings.getPreferredColumnCount());
@Override
public void onBackPressed() {
if (mSearchView != null && !mSearchView.isIconified()) {
mSearchView.setIconified(true);
return;
}
super.onBackPressed();
}
private void displayCardSetupOptions(Menu menu, boolean shouldShow) {
@@ -395,12 +432,7 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard
}
private void updateLoyaltyCardList(boolean updateCount) {
Group group = null;
if (mGroup != null) {
group = (Group) mGroup;
}
mAdapter.swapCursor(DBHelper.getLoyaltyCardCursor(mDatabase, mFilter, group, mOrder, mOrderDirection, mAdapter.showingArchivedCards() ? DBHelper.LoyaltyCardArchiveFilter.All : DBHelper.LoyaltyCardArchiveFilter.Unarchived));
mSwapLoyaltyCardListCursor.run();
if (updateCount) {
updateLoyaltyCardCount();
@@ -443,83 +475,64 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard
}
}
private void processParseResultList(List<ParseResult> parseResultList, String group, boolean closeAppOnNoBarcode) {
if (parseResultList.isEmpty()) {
throw new IllegalArgumentException("parseResultList may not be empty");
private void processBarcodeValues(BarcodeValues barcodeValues, String group) {
if (barcodeValues.isEmpty()) {
throw new IllegalArgumentException("barcodesValues may not be empty");
}
Utils.makeUserChooseParseResultFromList(MainActivity.this, parseResultList, new ParseResultListDisambiguatorCallback() {
@Override
public void onUserChoseParseResult(ParseResult parseResult) {
Intent intent = new Intent(getApplicationContext(), LoyaltyCardEditActivity.class);
Bundle bundle = parseResult.toLoyaltyCardBundle(MainActivity.this);
if (group != null) {
bundle.putString(LoyaltyCardEditActivity.BUNDLE_ADDGROUP, group);
}
intent.putExtras(bundle);
startActivity(intent);
}
@Override
public void onUserDismissedSelector() {
if (closeAppOnNoBarcode) {
finish();
}
}
});
Intent newIntent = new Intent(getApplicationContext(), LoyaltyCardEditActivity.class);
Bundle newBundle = new Bundle();
newBundle.putString(LoyaltyCardEditActivity.BUNDLE_BARCODETYPE, barcodeValues.format());
newBundle.putString(LoyaltyCardEditActivity.BUNDLE_CARDID, barcodeValues.content());
if (group != null) {
newBundle.putString(LoyaltyCardEditActivity.BUNDLE_ADDGROUP, group);
}
newIntent.putExtras(newBundle);
startActivity(newIntent);
}
private void onSharedIntent(Intent intent) {
String receivedAction = intent.getAction();
String receivedType = intent.getType();
if (receivedAction == null || receivedType == null) {
return;
}
List<ParseResult> parseResultList;
// Check for shared text
if (receivedAction.equals(Intent.ACTION_SEND) && receivedType.equals("text/plain")) {
LoyaltyCard loyaltyCard = new LoyaltyCard();
loyaltyCard.setCardId(intent.getStringExtra(Intent.EXTRA_TEXT));
parseResultList = Collections.singletonList(new ParseResult(ParseResultType.BARCODE_ONLY, loyaltyCard));
} else {
// Parse whatever file was sent, regardless of opening or sharing
Uri data;
if (receivedAction.equals(Intent.ACTION_VIEW)) {
data = intent.getData();
} else if (receivedAction.equals(Intent.ACTION_SEND)) {
data = intent.getParcelableExtra(Intent.EXTRA_STREAM);
} else {
Log.e(TAG, "Wrong action type to parse intent");
return;
}
if (receivedType.startsWith("image/")) {
parseResultList = Utils.retrieveBarcodesFromImage(this, data);
} else if (receivedType.equals("application/pdf")) {
parseResultList = Utils.retrieveBarcodesFromPdf(this, data);
} else if (Arrays.asList("application/vnd.apple.pkpass", "application/vnd-com.apple.pkpass").contains(receivedType)) {
parseResultList = Utils.retrieveBarcodesFromPkPass(this, data);
} else if (receivedType.equals("application/vnd.espass-espass")) {
// FIXME: espass is not pkpass
// However, several users stated in https://github.com/CatimaLoyalty/Android/issues/2197 that the formats are extremely similar to the point they could rename an .espass file to .pkpass and have it imported
// So it makes sense to "unofficially" treat it as a PKPASS for now, even though not completely correct
parseResultList = Utils.retrieveBarcodesFromPkPass(this, data);
} else {
// Check if an image was shared to us
if (Intent.ACTION_SEND.equals(receivedAction)) {
if (!receivedType.startsWith("image/")) {
Log.e(TAG, "Wrong mime-type");
return;
}
}
// Give up if we should parse but there is nothing to parse
if (parseResultList == null || parseResultList.isEmpty()) {
finish();
return;
}
BarcodeValues barcodeValues;
Bitmap bitmap;
processParseResultList(parseResultList, null, true);
Uri data = intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (data == null) {
Toast.makeText(this, R.string.errorReadingImage, Toast.LENGTH_LONG).show();
finish();
return;
}
try {
bitmap = Utils.retrieveImageFromUri(this, data);
} catch (IOException e) {
Log.e(TAG, "Error getting data from image file");
e.printStackTrace();
Toast.makeText(this, R.string.errorReadingImage, Toast.LENGTH_LONG).show();
finish();
return;
}
barcodeValues = Utils.getBarcodeFromBitmap(bitmap);
if (barcodeValues.isEmpty()) {
Log.i(TAG, "No barcode found in image file");
Toast.makeText(this, R.string.noBarcodeFound, Toast.LENGTH_LONG).show();
finish();
return;
}
processBarcodeValues(barcodeValues, null);
}
}
private void extractIntentFields(Intent intent) {
@@ -553,24 +566,6 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard
}
@Override
// Saving currentQuery to finalQuery for user, this will be used to restore search history, happens when user clicks a card from list
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
finalQuery = currentQuery;
// Putting the query also into outState for later use in onRestoreInstanceState when rotating screen
if (mSearchView != null) {
outState.putString(STATE_SEARCH_QUERY, finalQuery);
}
}
@Override
// Restoring instance state when rotation of screen happens with the goal to restore search query for user
protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
finalQuery = savedInstanceState.getString(STATE_SEARCH_QUERY, "");
}
@Override
public boolean onCreateOptionsMenu(Menu inputMenu) {
getMenuInflater().inflate(R.menu.main_menu, inputMenu);
@@ -579,42 +574,15 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
if (searchManager != null) {
MenuItem searchMenuItem = inputMenu.findItem(R.id.action_search);
mSearchView = (SearchView) searchMenuItem.getActionView();
mSearchView = (SearchView) inputMenu.findItem(R.id.action_search).getActionView();
mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
mSearchView.setSubmitButtonEnabled(false);
mSearchView.setOnCloseListener(() -> {
invalidateOptionsMenu();
return false;
});
/*
* On Android 13 and later, pressing Back while the search view is open hides the keyboard
* and collapses the search view at the same time.
* This brings back the old behavior on Android 12 and lower: pressing Back once
* hides the keyboard, press again while keyboard is hidden to collapse the search view.
*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
searchMenuItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(@NonNull MenuItem item) {
return true;
}
@Override
public boolean onMenuItemActionCollapse(@NonNull MenuItem item) {
if (mSearchView.hasFocus()) {
mSearchView.clearFocus();
return false;
}
currentQuery = "";
mFilter = "";
updateLoyaltyCardList(false);
return true;
}
});
}
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
@@ -624,21 +592,7 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard
@Override
public boolean onQueryTextChange(String newText) {
mFilter = newText;
// New logic to ensure search history after coming back from picked card - user will see the last search query
if (newText.isEmpty()) {
if(!finalQuery.isEmpty()){
// Setting the query text for user after coming back from picked card from finalQuery
mSearchView.setQuery(finalQuery, false);
}
else if(!currentQuery.isEmpty()){
// Else if is needed in case user deletes search - expected behaviour is to show all cards
currentQuery = "";
mSearchView.setQuery(currentQuery, false);
}
} else {
// Setting search query each time user changes the text in search to temporary variable to be used later in finalQuery String which will be used to restore search history
currentQuery = newText;
}
TabLayout.Tab currentTab = groupsTabLayout.getTabAt(groupsTabLayout.getSelectedTabPosition());
mGroup = currentTab != null ? currentTab.getTag() : null;
@@ -647,14 +601,6 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard
return true;
}
});
// Check if we came from a picked card back to search, in that case we want to show the search view with previous search query
if(!finalQuery.isEmpty()){
// Expand the search view to show the query
searchMenuItem.expandActionView();
// Setting the query text to empty String due to behaviour of onQueryTextChange after coming back from picked card - onQueryTextChange is called automatically without users interaction
finalQuery = "";
mSearchView.setQuery(currentQuery, false);
}
}
return super.onCreateOptionsMenu(inputMenu);
@@ -665,7 +611,7 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard
int id = inputItem.getItemId();
if (id == android.R.id.home) {
getOnBackPressedDispatcher().onBackPressed();
onBackPressed();
}
if (id == R.id.action_display_options) {
@@ -871,16 +817,18 @@ public class MainActivity extends CatimaAppCompatActivity implements LoyaltyCard
Intent intent = new Intent(this, LoyaltyCardViewActivity.class);
intent.setAction("");
final Bundle b = new Bundle();
b.putInt(LoyaltyCardViewActivity.BUNDLE_ID, loyaltyCard.id);
b.putInt("id", loyaltyCard.id);
ArrayList<Integer> cardList = new ArrayList<>();
for (int i = 0; i < mAdapter.getItemCount(); i++) {
cardList.add(mAdapter.getCard(i).id);
}
b.putIntegerArrayList(LoyaltyCardViewActivity.BUNDLE_CARDLIST, cardList);
b.putIntegerArrayList("cardList", cardList);
intent.putExtras(b);
ShortcutHelper.updateShortcuts(MainActivity.this, loyaltyCard);
startActivity(intent);
}
}

View File

@@ -13,12 +13,6 @@ import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
@@ -26,6 +20,11 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.RecyclerView;
import protect.card_locker.databinding.ActivityManageGroupBinding;
public class ManageGroupActivity extends CatimaAppCompatActivity implements ManageGroupCursorAdapter.CardAdapterListener {
@@ -134,13 +133,6 @@ public class ManageGroupActivity extends CatimaAppCompatActivity implements Mana
// this setText is here because content_main.xml is reused from main activity
noGroupCardsText.setText(getResources().getText(R.string.noGiftCardsGroup));
updateLoyaltyCardList();
getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
leaveWithoutSaving();
}
});
}
private ArrayList<Integer> adapterStateToIntegerArray(HashMap<Integer, Boolean> adapterState) {
@@ -218,9 +210,14 @@ public class ManageGroupActivity extends CatimaAppCompatActivity implements Mana
}
}
@Override
public void onBackPressed() {
leaveWithoutSaving();
}
@Override
public boolean onSupportNavigateUp() {
getOnBackPressedDispatcher().onBackPressed();
onBackPressed();
return true;
}

View File

@@ -33,7 +33,7 @@ public class ManageGroupCursorAdapter extends LoyaltyCardCursorAdapter {
@Override
public void onBindViewHolder(LoyaltyCardListItemViewHolder inputHolder, Cursor inputCursor) {
LoyaltyCard loyaltyCard = LoyaltyCard.fromCursor(mContext, inputCursor);
LoyaltyCard loyaltyCard = LoyaltyCard.toLoyaltyCard(inputCursor);
Boolean overlayValue = mInGroupOverlay.get(loyaltyCard.id);
if ((overlayValue != null ? overlayValue : isLoyaltyCardInGroup(loyaltyCard.id))) {
mAnimationItemsIndex.put(inputCursor.getPosition(), true);

View File

@@ -14,17 +14,17 @@ import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.List;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.List;
import protect.card_locker.databinding.ManageGroupsActivityBinding;
public class ManageGroupsActivity extends CatimaAppCompatActivity implements GroupCursorAdapter.GroupAdapterListener {
@@ -71,6 +71,11 @@ public class ManageGroupsActivity extends CatimaAppCompatActivity implements Gro
updateGroupList();
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
private void updateGroupList() {
mAdapter.swapCursor(DBHelper.getGroupCursor(mDatabase));
@@ -243,4 +248,4 @@ public class ManageGroupsActivity extends CatimaAppCompatActivity implements Gro
AlertDialog dialog = builder.create();
dialog.show();
}
}
}

View File

@@ -1,31 +0,0 @@
package protect.card_locker
import android.content.Context
import android.os.Bundle
class ParseResult(
val parseResultType: ParseResultType,
val loyaltyCard: LoyaltyCard) {
var note: String? = null
fun toLoyaltyCardBundle(context: Context): Bundle {
when (parseResultType) {
ParseResultType.FULL -> return loyaltyCard.toBundle(context, listOf())
ParseResultType.BARCODE_ONLY -> {
val defaultLoyaltyCard = LoyaltyCard()
defaultLoyaltyCard.setBarcodeId(null)
defaultLoyaltyCard.setBarcodeType(loyaltyCard.barcodeType)
defaultLoyaltyCard.setCardId(loyaltyCard.cardId)
return defaultLoyaltyCard.toBundle(
context,
listOf(
LoyaltyCard.BUNDLE_LOYALTY_CARD_BARCODE_ID,
LoyaltyCard.BUNDLE_LOYALTY_CARD_BARCODE_TYPE,
LoyaltyCard.BUNDLE_LOYALTY_CARD_CARD_ID
)
)
}
}
}
}

View File

@@ -1,6 +0,0 @@
package protect.card_locker;
public interface ParseResultListDisambiguatorCallback {
void onUserChoseParseResult(ParseResult parseResult);
void onUserDismissedSelector();
}

View File

@@ -1,6 +0,0 @@
package protect.card_locker
enum class ParseResultType {
FULL,
BARCODE_ONLY
}

View File

@@ -1,437 +0,0 @@
package protect.card_locker
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Color
import android.net.Uri
import android.util.ArrayMap
import android.util.Log
import com.google.zxing.BarcodeFormat
import net.lingala.zip4j.io.inputstream.ZipInputStream
import net.lingala.zip4j.model.LocalFileHeader
import org.json.JSONException
import org.json.JSONObject
import java.io.FileNotFoundException
import java.io.IOException
import java.math.BigDecimal
import java.text.DateFormat
import java.text.ParseException
import java.time.ZonedDateTime
import java.time.format.DateTimeParseException
import java.util.Currency
import java.util.Date
class PkpassParser(context: Context, uri: Uri?) {
private var mContext = context
private var translations: ArrayMap<String, Map<String, String>> = ArrayMap()
private var passContent: JSONObject? = null
private var store: String? = null
private var note: String? = null
private var validFrom: Date? = null
private var expiry: Date? = null
private val balance: BigDecimal = BigDecimal(0)
private val balanceType: Currency? = null
private var cardId: String? = null
private var barcodeId: String? = null
private var barcodeType: CatimaBarcode? = null
private var headerColor: Int? = null
private val starStatus = 0
private val lastUsed: Long = 0
private val zoomLevel = DBHelper.DEFAULT_ZOOM_LEVEL
private var archiveStatus = 0
var image: Bitmap? = null
private set
private var logoSize = 0
init {
if (passContent != null) {
throw IllegalStateException("Pkpass instance already initialized!")
}
mContext = context
Log.i(TAG, "Received Pkpass file")
if (uri == null) {
Log.e(TAG, "Uri did not contain any data")
throw IOException(context.getString(R.string.errorReadingFile))
}
try {
mContext.contentResolver.openInputStream(uri).use { inputStream ->
ZipInputStream(inputStream).use { zipInputStream ->
var localFileHeader: LocalFileHeader
while ((zipInputStream.nextEntry.also { localFileHeader = it }) != null) {
// Ignore directories
if (localFileHeader.isDirectory) continue
// We assume there are three options, as per spec:
// language.lproj/pass.strings
// file.extension
// More directories are ignored
val filenameParts = localFileHeader.fileName.split('/')
if (filenameParts.size > 2) {
continue
} else if (filenameParts.size == 2) {
// Doesn't seem like a language directory, ignore
if (!filenameParts[0].endsWith(".lproj")) continue
val locale = filenameParts[0].removeSuffix(".lproj")
translations[locale] = parseLanguageStrings(ZipUtils.read(zipInputStream))
}
// Not a language, parse as normal files
when (localFileHeader.fileName) {
"logo.png" -> loadImageIfBiggerSize(1, zipInputStream)
"logo@2x.png" -> loadImageIfBiggerSize(2, zipInputStream)
"logo@3x.png" -> loadImageIfBiggerSize(3, zipInputStream)
"pass.json" -> passContent = ZipUtils.readJSON(zipInputStream) // Parse this last, so we're sure we have all language info
}
}
checkNotNull(passContent) { "File lacks pass.json" }
}
}
} catch (e: FileNotFoundException) {
throw IOException(mContext.getString(R.string.errorReadingFile))
} catch (e: Exception) {
throw e
}
}
fun listLocales(): List<String> {
return translations.keys.toList()
}
fun toLoyaltyCard(locale: String?): LoyaltyCard {
parsePassJSON(checkNotNull(passContent) { "Pkpass instance not yet initialized!" }, locale)
return LoyaltyCard(
-1,
store,
note,
validFrom,
expiry,
balance,
balanceType,
cardId,
barcodeId,
barcodeType,
headerColor,
starStatus,
lastUsed,
zoomLevel,
archiveStatus,
image,
null,
null,
null,
null,
null
)
}
private fun getTranslation(string: String, locale: String?): String {
if (locale == null) {
return string
}
val localeStrings = translations[locale]
return localeStrings?.get(string) ?: string
}
private fun loadImageIfBiggerSize(fileLogoSize: Int, zipInputStream: ZipInputStream) {
if (logoSize < fileLogoSize) {
image = ZipUtils.readImage(zipInputStream)
logoSize = fileLogoSize
}
}
private fun parseColor(color: String): Int? {
// First, try formats supported by Android natively
try {
return Color.parseColor(color)
} catch (ignored: IllegalArgumentException) {}
// If that didn't work, try parsing it as a rbg(0,0,255) value
val red: Int;
val green: Int;
val blue: Int;
// Parse rgb(0,0,0) string
val rgbInfo = Regex("""^rgb\(\s*(?<red>\d+)\s*,\s*(?<green>\d+)\s*,\s*(?<blue>\d+)\s*\)$""").find(color)
if (rgbInfo == null) {
return null
}
// Convert to integers
try {
red = rgbInfo.groups[1]!!.value.toInt()
green = rgbInfo.groups[2]!!.value.toInt()
blue = rgbInfo.groups[3]!!.value.toInt()
} catch (e: NumberFormatException) {
return null
}
// Ensure everything is in a valid range as Color.rgb does not do range checks
if (red < 0 || red > 255) return null
if (green < 0 || green > 255) return null
if (blue < 0 || blue > 255) return null
return Color.rgb(red, green, blue)
}
private fun parseDateTime(dateTime: String): Date {
return Date.from(ZonedDateTime.parse(dateTime).toInstant())
}
private fun parseLanguageStrings(data: String): Map<String, String> {
val output = ArrayMap<String, String>()
// Translations look like this:
// "key_name" = "Translated value";
//
// However, "Translated value" may be multiple lines and may contain " (however, it'll be escaped)
var translationLine = StringBuilder()
for (line in data.lines()) {
translationLine.append(line)
// Make sure we don't have a false ending (this is the escaped double quote: \";)
if (!line.endsWith("\\\";") and line.endsWith("\";")) {
// We reached a translation ending, time to parse it
// 1. Split into key and value
// 2. Remove cruft of each
// 3. Clean up escape sequences
val keyValue = translationLine.toString().split("=", ignoreCase = false, limit = 2)
val key = keyValue[0].trim().removePrefix("\"").removeSuffix("\"")
val value = keyValue[1].trim().removePrefix("\"").removeSuffix("\";").replace("\\", "")
output[key] = value
translationLine = StringBuilder()
} else {
translationLine.append("\n")
}
}
return output
}
private fun parsePassJSON(jsonObject: JSONObject, locale: String?) {
if (jsonObject.getInt("formatVersion") != 1) {
throw IllegalArgumentException(mContext.getString(R.string.unsupportedFile))
}
// Prefer logoText for store, it's generally shorter
try {
store = jsonObject.getString("logoText")
} catch (ignored: JSONException) {}
if (store.isNullOrEmpty()) {
store = jsonObject.getString("organizationName")
}
val noteText = StringBuilder()
noteText.append(getTranslation(jsonObject.getString("description"), locale))
try {
validFrom = parseDateTime(jsonObject.getString("relevantDate"))
} catch (ignored: JSONException) {}
try {
expiry = parseDateTime(jsonObject.getString("expirationDate"))
} catch (ignored: JSONException) {}
try {
headerColor = parseColor(jsonObject.getString("backgroundColor"))
} catch (ignored: JSONException) {}
var pkPassHasBarcodes = false
var validBarcodeFound = false
// Create a list of possible barcodes
val barcodes = ArrayList<JSONObject>()
// Append the non-deprecated entries
try {
val foundInBarcodesField = jsonObject.getJSONArray("barcodes")
for (i in 0 until foundInBarcodesField.length()) {
barcodes.add(foundInBarcodesField.getJSONObject(i))
}
} catch (ignored: JSONException) {}
// Append the deprecated entry if it exists
try {
barcodes.add(jsonObject.getJSONObject("barcode"))
} catch (ignored: JSONException) {}
for (barcode in barcodes) {
pkPassHasBarcodes = true
try {
parsePassJSONBarcodeField(barcode)
validBarcodeFound = true
break
} catch (ignored: IllegalArgumentException) {}
}
if (pkPassHasBarcodes && !validBarcodeFound) {
throw FormatException(mContext.getString(R.string.errorReadingFile))
}
// An used card being "archived" probably is the most sensible way to map "voided"
archiveStatus = try {
if (jsonObject.getBoolean("voided")) 1 else 0
} catch (ignored: JSONException) {
0
}
// Append type-specific info to the pass
noteText.append("\n\n")
// Find the relevant pass type and parse it
var hasPassData = false
for (passType in listOf("boardingPass", "coupon", "eventTicket", "generic")) {
try {
noteText.append(
parsePassJSONPassFields(
jsonObject.getJSONObject(passType),
locale
)
)
hasPassData = true
break
} catch (ignored: JSONException) {}
}
// Failed to parse anything, error out
if (!hasPassData) {
throw FormatException(mContext.getString(R.string.errorReadingFile))
}
note = noteText.toString()
}
/* Return success or failure */
private fun parsePassJSONBarcodeField(barcodeInfo: JSONObject) {
val format = barcodeInfo.getString("format")
// We only need to check these 4 formats as no other options are valid in the PkPass spec
barcodeType = when(format) {
"PKBarcodeFormatQR" -> CatimaBarcode.fromBarcode(BarcodeFormat.QR_CODE)
"PKBarcodeFormatPDF417" -> CatimaBarcode.fromBarcode(BarcodeFormat.PDF_417)
"PKBarcodeFormatAztec" -> CatimaBarcode.fromBarcode(BarcodeFormat.AZTEC)
"PKBarcodeFormatCode128" -> CatimaBarcode.fromBarcode(BarcodeFormat.CODE_128)
else -> throw IllegalArgumentException("No valid barcode type")
}
// FIXME: We probably need to do something with the messageEncoding field
try {
cardId = barcodeInfo.getString("altText")
barcodeId = barcodeInfo.getString("message")
} catch (ignored: JSONException) {
cardId = barcodeInfo.getString("message")
barcodeId = null
}
// Don't set barcodeId if it's the same as cardId
if (cardId == barcodeId) {
barcodeId = null
}
}
private fun parsePassJSONPassFields(fieldsParent: JSONObject, locale: String?): String {
// These fields contain a lot of info on where we're supposed to display them, but Catima doesn't really have anything for that
// So for now, throw them all into the description field in a logical order
val noteContents: MutableList<String> = ArrayList()
// Collect all the groups of fields that exist
for (fieldType in listOf("headerFields", "primaryFields", "secondaryFields", "auxiliaryFields", "backFields")) {
val content = StringBuilder()
try {
val fieldArray = fieldsParent.getJSONArray(fieldType)
for (i in 0 until fieldArray.length()) {
val entry = fieldArray.getJSONObject(i)
content.append(parsePassJSONPassField(entry, locale))
// If this is not the last part, add spacing on the end
if (i < (fieldArray.length() - 1)) {
content.append("\n")
}
}
} catch (ignore: JSONException) {
} catch (ignore: ParseException) {
}
if (content.isNotEmpty()) {
noteContents.add(content.toString())
}
}
// Merge all field groups together, one paragraph for field group
val output = StringBuilder()
for (i in 0 until noteContents.size) {
output.append(noteContents[i])
// If this is not the last part, add newlines to separate
if (i < (noteContents.size - 1)) {
output.append("\n\n")
}
}
return output.toString()
}
private fun parsePassJSONPassField(field: JSONObject, locale: String?): String {
// Value may be a localizable string, a date or a number. So let's try to parse it as a date first
var value = getTranslation(field.getString("value"), locale)
try {
value = DateFormat.getDateTimeInstance().format(parseDateTime(value))
} catch (ignored: DateTimeParseException) {
// It's fine if it's not a date
}
// FIXME: Use the Android thing for formatted strings here
if (field.has("currencyCode")) {
val valueCurrency = Currency.getInstance(field.getString("currencyCode"))
value = Utils.formatBalance(
mContext,
Utils.parseBalance(value, valueCurrency),
valueCurrency
)
} else if (field.has("numberStyle")) {
if (field.getString("numberStyle") == "PKNumberStylePercent") {
// FIXME: Android formatting string
value = "${value}%"
}
}
val label = getTranslation(field.getString("label"), locale)
if (label.isNotEmpty()) {
return "$label: $value"
}
return value
}
companion object {
private const val TAG = "Catima"
}
}

View File

@@ -24,8 +24,6 @@ import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
@@ -34,6 +32,7 @@ import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
@@ -44,8 +43,6 @@ import com.journeyapps.barcodescanner.BarcodeResult;
import com.journeyapps.barcodescanner.CaptureManager;
import com.journeyapps.barcodescanner.DecoratedBarcodeView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import protect.card_locker.databinding.CustomBarcodeScannerBinding;
@@ -66,8 +63,6 @@ public class ScanActivity extends CatimaAppCompatActivity {
private static final int COMPAT_SCALE_FACTOR_DIP = 320;
private static final int PERMISSION_SCAN_ADD_FROM_IMAGE = 100;
private static final int PERMISSION_SCAN_ADD_FROM_PDF = 101;
private static final int PERMISSION_SCAN_ADD_FROM_PKPASS = 102;
private CaptureManager capture;
private DecoratedBarcodeView barcodeScannerView;
@@ -79,16 +74,13 @@ public class ScanActivity extends CatimaAppCompatActivity {
private ActivityResultLauncher<Intent> manualAddLauncher;
// can't use the pre-made contract because that launches the file manager for image type instead of gallery
private ActivityResultLauncher<Intent> photoPickerLauncher;
private ActivityResultLauncher<Intent> pdfPickerLauncher;
private ActivityResultLauncher<Intent> pkpassPickerLauncher;
static final String STATE_SCANNER_ACTIVE = "scannerActive";
private boolean mScannerActive = true;
private boolean mHasError = false;
private void extractIntentFields(Intent intent) {
final Bundle b = intent.getExtras();
cardId = b != null ? b.getString(LoyaltyCard.BUNDLE_LOYALTY_CARD_CARD_ID) : null;
cardId = b != null ? b.getString(LoyaltyCardEditActivity.BUNDLE_CARDID) : null;
addGroup = b != null ? b.getString(LoyaltyCardEditActivity.BUNDLE_ADDGROUP) : null;
Log.d(TAG, "Scan activity: id=" + cardId);
}
@@ -108,47 +100,17 @@ public class ScanActivity extends CatimaAppCompatActivity {
manualAddLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> handleActivityResult(Utils.SELECT_BARCODE_REQUEST, result.getResultCode(), result.getData()));
photoPickerLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> handleActivityResult(Utils.BARCODE_IMPORT_FROM_IMAGE_FILE, result.getResultCode(), result.getData()));
pdfPickerLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> handleActivityResult(Utils.BARCODE_IMPORT_FROM_PDF_FILE, result.getResultCode(), result.getData()));
pkpassPickerLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> handleActivityResult(Utils.BARCODE_IMPORT_FROM_PKPASS_FILE, result.getResultCode(), result.getData()));
customBarcodeScannerBinding.fabOtherOptions.setOnClickListener(view -> {
setScannerActive(false);
ArrayList<HashMap<String, Object>> list = new ArrayList<>();
String[] texts = new String[]{
getString(R.string.addWithoutBarcode),
getString(R.string.addManually),
getString(R.string.addFromImage),
getString(R.string.addFromPdfFile),
getString(R.string.addFromPkpass)
};
Object[] icons = new Object[]{
R.drawable.baseline_block_24,
R.drawable.ic_edit,
R.drawable.baseline_image_24,
R.drawable.baseline_picture_as_pdf_24,
R.drawable.local_activity_24px
};
String[] columns = new String[]{"text", "icon"};
for (int i = 0; i < texts.length; i++) {
HashMap<String, Object> map = new HashMap<>();
map.put(columns[0], texts[i]);
map.put(columns[1], icons[i]);
list.add(map);
}
ListAdapter adapter = new SimpleAdapter(
ScanActivity.this,
list,
R.layout.alertdialog_row_with_icon,
columns,
new int[]{R.id.textView, R.id.imageView}
);
MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(ScanActivity.this);
builder.setTitle(getString(R.string.add_a_card_in_a_different_way));
builder.setAdapter(
adapter,
builder.setItems(
new CharSequence[]{
getString(R.string.addWithoutBarcode),
getString(R.string.addManually),
getString(R.string.addFromImage)
},
(dialogInterface, i) -> {
switch (i) {
case 0:
@@ -160,12 +122,6 @@ public class ScanActivity extends CatimaAppCompatActivity {
case 2:
addFromImage();
break;
case 3:
addFromPdf();
break;
case 4:
addFromPkPass();
break;
default:
throw new IllegalArgumentException("Unknown 'Add a card in a different way' dialog option");
}
@@ -179,7 +135,7 @@ public class ScanActivity extends CatimaAppCompatActivity {
// Even though we do the actual decoding with the barcodeScannerView
// CaptureManager needs to be running to show the camera and scanning bar
capture = new CatimaCaptureManager(this, barcodeScannerView, this::onCaptureManagerError);
capture = new CatimaCaptureManager(this, barcodeScannerView);
Intent captureIntent = new Intent();
Bundle captureIntentBundle = new Bundle();
captureIntentBundle.putBoolean(Intents.Scan.BEEP_ENABLED, false);
@@ -189,11 +145,16 @@ public class ScanActivity extends CatimaAppCompatActivity {
barcodeScannerView.decodeSingle(new BarcodeCallback() {
@Override
public void barcodeResult(BarcodeResult result) {
LoyaltyCard loyaltyCard = new LoyaltyCard();
loyaltyCard.setCardId(result.getText());
loyaltyCard.setBarcodeType(CatimaBarcode.fromBarcode(result.getBarcodeFormat()));
returnResult(new ParseResult(ParseResultType.BARCODE_ONLY, loyaltyCard));
Intent scanResult = new Intent();
Bundle scanResultBundle = new Bundle();
scanResultBundle.putString(BARCODE_CONTENTS, result.getText());
scanResultBundle.putString(BARCODE_FORMAT, result.getBarcodeFormat().name());
if (addGroup != null) {
scanResultBundle.putString(LoyaltyCardEditActivity.BUNDLE_ADDGROUP, addGroup);
}
scanResult.putExtras(scanResultBundle);
ScanActivity.this.setResult(RESULT_OK, scanResult);
finish();
}
@Override
@@ -211,14 +172,9 @@ public class ScanActivity extends CatimaAppCompatActivity {
capture.onResume();
}
if (!Utils.deviceHasCamera(this)) {
showCameraError(getString(R.string.noCameraFoundGuideText), false);
} else if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
showCameraPermissionMissingText();
} else {
hideCameraError();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
showCameraPermissionMissingText(false);
}
scaleScreen();
}
@@ -297,38 +253,30 @@ public class ScanActivity extends CatimaAppCompatActivity {
mScannerActive = isActive;
}
private void returnResult(ParseResult parseResult) {
Intent result = new Intent();
Bundle bundle = parseResult.toLoyaltyCardBundle(ScanActivity.this);
private void returnResult(String barcodeContents, String barcodeFormat) {
Intent manualResult = new Intent();
Bundle manualResultBundle = new Bundle();
manualResultBundle.putString(BARCODE_CONTENTS, barcodeContents);
manualResultBundle.putString(BARCODE_FORMAT, barcodeFormat);
if (addGroup != null) {
bundle.putString(LoyaltyCardEditActivity.BUNDLE_ADDGROUP, addGroup);
manualResultBundle.putString(LoyaltyCardEditActivity.BUNDLE_ADDGROUP, addGroup);
}
result.putExtras(bundle);
ScanActivity.this.setResult(RESULT_OK, result);
manualResult.putExtras(manualResultBundle);
ScanActivity.this.setResult(RESULT_OK, manualResult);
finish();
}
private void handleActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
List<ParseResult> parseResultList = Utils.parseSetBarcodeActivityResult(requestCode, resultCode, intent, this);
BarcodeValues barcodeValues = Utils.parseSetBarcodeActivityResult(requestCode, resultCode, intent, this);
if (parseResultList.isEmpty()) {
if (barcodeValues.isEmpty()) {
setScannerActive(true);
return;
}
Utils.makeUserChooseParseResultFromList(this, parseResultList, new ParseResultListDisambiguatorCallback() {
@Override
public void onUserChoseParseResult(ParseResult parseResult) {
returnResult(parseResult);
}
@Override
public void onUserDismissedSelector() {
setScannerActive(true);
}
});
returnResult(barcodeValues.content(), barcodeValues.format());
}
private void addWithoutBarcode() {
@@ -368,9 +316,7 @@ public class ScanActivity extends CatimaAppCompatActivity {
// Buttons
builder.setPositiveButton(getString(R.string.ok), (dialog, which) -> {
LoyaltyCard loyaltyCard = new LoyaltyCard();
loyaltyCard.setCardId(input.getText().toString());
returnResult(new ParseResult(ParseResultType.BARCODE_ONLY, loyaltyCard));
returnResult(input.getText().toString(), "");
});
builder.setNegativeButton(getString(R.string.cancel), (dialog, which) -> dialog.cancel());
AlertDialog dialog = builder.create();
@@ -398,83 +344,42 @@ public class ScanActivity extends CatimaAppCompatActivity {
}
public void addManually() {
MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(ScanActivity.this);
builder.setTitle(R.string.add_manually_warning_title);
builder.setMessage(R.string.add_manually_warning_message);
builder.setPositiveButton(R.string.continue_, (dialog, which) -> {
Intent i = new Intent(getApplicationContext(), BarcodeSelectorActivity.class);
if (cardId != null) {
final Bundle b = new Bundle();
b.putString(LoyaltyCard.BUNDLE_LOYALTY_CARD_CARD_ID, cardId);
i.putExtras(b);
}
manualAddLauncher.launch(i);
});
builder.setNegativeButton(R.string.cancel, (dialog, which) -> setScannerActive(true));
builder.setOnCancelListener(dialog -> setScannerActive(true));
builder.show();
Intent i = new Intent(getApplicationContext(), BarcodeSelectorActivity.class);
if (cardId != null) {
final Bundle b = new Bundle();
b.putString("initialCardId", cardId);
i.putExtras(b);
}
manualAddLauncher.launch(i);
}
public void addFromImage() {
PermissionUtils.requestStorageReadPermission(this, PERMISSION_SCAN_ADD_FROM_IMAGE);
}
public void addFromPdf() {
PermissionUtils.requestStorageReadPermission(this, PERMISSION_SCAN_ADD_FROM_PDF);
}
public void addFromPkPass() {
PermissionUtils.requestStorageReadPermission(this, PERMISSION_SCAN_ADD_FROM_PKPASS);
}
private void addFromImageOrFileAfterPermission(String mimeType, ActivityResultLauncher<Intent> launcher, int chooserText, int errorMessage) {
private void addFromImageAfterPermission() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType(mimeType);
photoPickerIntent.setType("image/*");
Intent contentIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentIntent.setType(mimeType);
contentIntent.setType("image/*");
Intent chooserIntent = Intent.createChooser(photoPickerIntent, getString(chooserText));
Intent chooserIntent = Intent.createChooser(photoPickerIntent, getString(R.string.addFromImage));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { contentIntent });
try {
launcher.launch(chooserIntent);
photoPickerLauncher.launch(chooserIntent);
} catch (ActivityNotFoundException e) {
setScannerActive(true);
Toast.makeText(getApplicationContext(), errorMessage, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), R.string.failedLaunchingPhotoPicker, Toast.LENGTH_LONG).show();
Log.e(TAG, "No activity found to handle intent", e);
}
}
public void onCaptureManagerError(String errorMessage) {
if (mHasError) {
// We're already showing an error, ignore this new error
return;
}
showCameraError(errorMessage, false);
}
private void showCameraPermissionMissingText() {
showCameraError(getString(R.string.noCameraPermissionDirectToSystemSetting), true);
}
private void showCameraError(String message, boolean setOnClick) {
customBarcodeScannerBinding.cameraErrorLayout.cameraErrorMessage.setText(message);
setCameraErrorState(true, setOnClick);
}
private void hideCameraError() {
setCameraErrorState(false, false);
}
private void setCameraErrorState(boolean visible, boolean setOnClick) {
mHasError = visible;
customBarcodeScannerBinding.cameraErrorLayout.cameraErrorClickableArea.setOnClickListener(visible && setOnClick ? v -> {
private void showCameraPermissionMissingText(boolean show) {
customBarcodeScannerBinding.cameraPermissionDeniedLayout.cameraPermissionDeniedClickableArea.setOnClickListener(show ? v -> {
navigateToSystemPermissionSetting();
} : null);
customBarcodeScannerBinding.cardInputContainer.setBackgroundColor(visible ? obtainThemeAttribute(com.google.android.material.R.attr.colorSurface) : Color.TRANSPARENT);
customBarcodeScannerBinding.cameraErrorLayout.getRoot().setVisibility(visible ? View.VISIBLE : View.GONE);
customBarcodeScannerBinding.cardInputContainer.setBackgroundColor(show ? obtainThemeAttribute(com.google.android.material.R.attr.colorSurface) : Color.TRANSPARENT);
customBarcodeScannerBinding.cameraPermissionDeniedLayout.getRoot().setVisibility(show ? View.VISIBLE : View.GONE);
}
private void scaleScreen() {
@@ -484,8 +389,8 @@ public class ScanActivity extends CatimaAppCompatActivity {
float mediumSizePx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,MEDIUM_SCALE_FACTOR_DIP,getResources().getDisplayMetrics());
boolean shouldScaleSmaller = screenHeight < mediumSizePx;
customBarcodeScannerBinding.cameraErrorLayout.cameraErrorIcon.setVisibility(shouldScaleSmaller ? View.GONE : View.VISIBLE);
customBarcodeScannerBinding.cameraErrorLayout.cameraErrorTitle.setVisibility(shouldScaleSmaller ? View.GONE : View.VISIBLE);
customBarcodeScannerBinding.cameraPermissionDeniedLayout.cameraPermissionDeniedIcon.setVisibility(shouldScaleSmaller ? View.GONE : View.VISIBLE);
customBarcodeScannerBinding.cameraPermissionDeniedLayout.cameraPermissionDeniedTitle.setVisibility(shouldScaleSmaller ? View.GONE : View.VISIBLE);
}
private int obtainThemeAttribute(int attribute) {
@@ -511,20 +416,10 @@ public class ScanActivity extends CatimaAppCompatActivity {
boolean granted = grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (requestCode == CaptureManager.getCameraPermissionReqCode()) {
showCameraPermissionMissingText(!granted);
} else if (requestCode == PERMISSION_SCAN_ADD_FROM_IMAGE) {
if (granted) {
hideCameraError();
} else {
showCameraPermissionMissingText();
}
} else if (requestCode == PERMISSION_SCAN_ADD_FROM_IMAGE || requestCode == PERMISSION_SCAN_ADD_FROM_PDF || requestCode == PERMISSION_SCAN_ADD_FROM_PKPASS) {
if (granted) {
if (requestCode == PERMISSION_SCAN_ADD_FROM_IMAGE) {
addFromImageOrFileAfterPermission("image/*", photoPickerLauncher, R.string.addFromImage, R.string.failedLaunchingPhotoPicker);
} else if (requestCode == PERMISSION_SCAN_ADD_FROM_PDF) {
addFromImageOrFileAfterPermission("application/pdf", pdfPickerLauncher, R.string.addFromPdfFile, R.string.failedLaunchingFileManager);
} else {
addFromImageOrFileAfterPermission("application/*", pkpassPickerLauncher, R.string.addFromPkpass, R.string.failedLaunchingFileManager);
}
addFromImageAfterPermission();
} else {
setScannerActive(true);
Toast.makeText(this, R.string.storageReadPermissionRequired, Toast.LENGTH_LONG).show();

View File

@@ -8,11 +8,6 @@ import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import androidx.core.content.pm.ShortcutInfoCompat;
import androidx.core.content.pm.ShortcutManagerCompat;
import androidx.core.graphics.ColorUtils;
import androidx.core.graphics.drawable.IconCompat;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
@@ -20,6 +15,11 @@ import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import androidx.core.content.pm.ShortcutInfoCompat;
import androidx.core.content.pm.ShortcutManagerCompat;
import androidx.core.graphics.ColorUtils;
import androidx.core.graphics.drawable.IconCompat;
class ShortcutHelper {
// Android documentation says that no more than 5 shortcuts
// are supported. However, that may be too many, as not all
@@ -33,6 +33,7 @@ class ShortcutHelper {
private static final int ADAPTIVE_BITMAP_SIZE = 108 * ADAPTIVE_BITMAP_SCALE;
private static final int ADAPTIVE_BITMAP_VISIBLE_SIZE = 72 * ADAPTIVE_BITMAP_SCALE;
private static final int ADAPTIVE_BITMAP_IMAGE_SIZE = ADAPTIVE_BITMAP_VISIBLE_SIZE + 5 * ADAPTIVE_BITMAP_SCALE;
private static final int PADDING_COLOR_OVERLAY = Color.argb(127, 0, 0, 0);
/**
* Add a card to the app shortcuts, and maintain a list of the most
@@ -42,11 +43,6 @@ class ShortcutHelper {
* used card shortcut is discarded.
*/
static void updateShortcuts(Context context, LoyaltyCard card) {
if (card.archiveStatus == 1) {
// Don't add archived card to menu
return;
}
LinkedList<ShortcutInfoCompat> list = new LinkedList<>(ShortcutManagerCompat.getDynamicShortcuts(context));
SQLiteDatabase database = new DBHelper(context).getReadableDatabase();
@@ -86,7 +82,7 @@ class ShortcutHelper {
for (int index = 0; index < list.size(); index++) {
ShortcutInfoCompat prevShortcut = list.get(index);
LoyaltyCard loyaltyCard = DBHelper.getLoyaltyCard(context, database, Integer.parseInt(prevShortcut.getId()));
LoyaltyCard loyaltyCard = DBHelper.getLoyaltyCard(database, Integer.parseInt(prevShortcut.getId()));
// skip outdated cards that no longer exist
if (loyaltyCard != null) {
@@ -112,14 +108,25 @@ class ShortcutHelper {
* shortcut exists.
*/
static void removeShortcut(Context context, int cardId) {
ShortcutManagerCompat.removeDynamicShortcuts(context, Collections.singletonList(Integer.toString(cardId)));
List<ShortcutInfoCompat> list = ShortcutManagerCompat.getDynamicShortcuts(context);
String shortcutId = Integer.toString(cardId);
for (int index = 0; index < list.size(); index++) {
if (list.get(index).getId().equals(shortcutId)) {
list.remove(index);
break;
}
}
ShortcutManagerCompat.setDynamicShortcuts(context, list);
}
static @NotNull
Bitmap createAdaptiveBitmap(@NotNull Bitmap in, int paddingColor) {
Bitmap ret = Bitmap.createBitmap(ADAPTIVE_BITMAP_SIZE, ADAPTIVE_BITMAP_SIZE, Bitmap.Config.ARGB_8888);
Canvas output = new Canvas(ret);
output.drawColor(paddingColor);
output.drawColor(ColorUtils.compositeColors(PADDING_COLOR_OVERLAY, paddingColor));
Bitmap resized = Utils.resizeBitmap(in, ADAPTIVE_BITMAP_IMAGE_SIZE);
output.drawBitmap(resized, (ADAPTIVE_BITMAP_SIZE - resized.getWidth()) / 2f, (ADAPTIVE_BITMAP_SIZE - resized.getHeight()) / 2f, null);
return ret;
@@ -132,14 +139,15 @@ class ShortcutHelper {
// one replace it.
intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_SINGLE_TOP);
final Bundle bundle = new Bundle();
bundle.putInt(LoyaltyCardViewActivity.BUNDLE_ID, loyaltyCard.id);
bundle.putInt("id", loyaltyCard.id);
bundle.putBoolean("view", true);
intent.putExtras(bundle);
Bitmap iconBitmap = loyaltyCard.getImageThumbnail(context);
Bitmap iconBitmap = Utils.retrieveCardImage(context, loyaltyCard.id, ImageLocationType.icon);
if (iconBitmap == null) {
iconBitmap = Utils.generateIcon(context, loyaltyCard, true).getLetterTile();
} else {
iconBitmap = createAdaptiveBitmap(iconBitmap, Utils.needsDarkForeground(Utils.getHeaderColor(context, loyaltyCard)) ? Color.BLACK : Color.WHITE);
iconBitmap = createAdaptiveBitmap(iconBitmap, Utils.getHeaderColor(context, loyaltyCard));
}
IconCompat icon = IconCompat.createWithAdaptiveBitmap(iconBitmap);

Some files were not shown because too many files have changed in this diff Show More