Compare commits

...
905 Commits
Author SHA1 Message Date
Markus Fisch 8859c61119 Advance version number to 1.72.1 2026-04-11 13:06:04 +02:00
Andrew GunnersonandGitHub c52778f59d Fix crash on upgrades due to missing DATA_BAR entry
Commit 73047cdee6 merged the old
migrateToNativeFormatNames() and migrateBarcodeFormatName() mapping
functions, but the new map was based on the former, which happened to be
missing the entry for DATA_BAR.

Fixes: #636

Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2026-04-11 12:53:08 +02:00
bovirusandGitHub 5bde3947e3 Italian language update 2026-04-10 22:19:16 +02:00
Markus Fisch 08be31814f Advance version number to 1.72.0 2026-04-09 23:05:29 +02:00
Markus Fisch c5db04b84e Add headlines for result sections
Makes result sections easier to digest.
2026-04-09 21:16:27 +02:00
Markus Fisch 9dccc6a7f5 Fix EPC QR parser tests 2026-04-09 16:46:20 +02:00
Markus Fisch a5deab656b Clamp invalid ROIs to prevent crashes
Fixes a crash path where rounding in the view-to-frame
mapping could produce crop rectangles outside the Y plane.
2026-04-09 16:46:20 +02:00
Markus Fisch b773dfa392 Remove double signature date item for IDB codes 2026-04-09 16:46:20 +02:00
Markus Fisch 7b5106f09d Parse JSON content and show pretty-printed dump 2026-04-09 16:46:16 +02:00
Markus Fisch 16ce45093e Use list selector for parsed data items
So there is some touch feedback.
2026-04-09 19:47:44 +02:00
Markus Fisch e6345f09b3 Reformat code 2026-04-09 12:59:04 +02:00
Markus Fisch de00ed779a Update vdstools to latest version
And migrate the code to use the public API only.

This version doesn't include the Kermit logging library
which would have required a minSdk raise.
2026-04-09 10:58:34 +02:00
Markus Fisch d740aa121b Advance version number to 1.71.0 2026-04-08 21:56:07 +02:00
Markus Fisch 38c40d36bb Preserve parsed data while editing
Keep the last successfully parsed data rows visible in the decode
view while the barcode content is being edited. Avoids jumping of
the layout.
2026-04-08 19:49:25 +02:00
Markus Fisch 3e51f70c7c Decode nested IDB messages
Flatten nested IDB messages into seal fields and decode child values
using the schema-defined coding from vdstools. This fixes nested
content such as MRZ fields inside IDB container messages being shown
as raw byte counts instead of decoded text.
2026-04-08 19:11:26 +02:00
Markus Fisch 502702c7a5 Remove unused indent fields 2026-04-08 19:10:03 +02:00
Markus Fisch 96ff9b6239 Change data table to a label/value list
So values have more space and can be read more easily.
2026-04-08 19:10:03 +02:00
Markus Fisch afd6c74c80 Verify IDB barcodes
Using the german CSCA master list.
2026-04-08 19:09:52 +02:00
Markus Fisch 5ffea2edd8 Fix detecting web URLs with a subdomain 2026-04-08 19:50:05 +02:00
Markus Fisch 78d62395e2 Add missing translations for IDL/EPC labels 2026-04-08 19:38:33 +02:00
Markus Fisch a5d1465528 Remove unnecessary EpcQrInfo wrapper class
And return the map directly.
2026-04-08 19:16:19 +02:00
Markus Fisch 14517bad17 Add vdstools to parse VDS and IDB barcodes
Without verifying yet.
2026-04-08 19:14:15 +02:00
Markus Fisch 7a5e07fb3c Handle deep link in onNewIntent for EncodeActivity
Calendar apps reuse the existing task instead of creating a
new one, so Android calls onNewIntent() rather than onCreate().
Without an onNewIntent() override the intent's query parameters
(format, content, execute) were silently ignored.

Extract intent application into applyIntent() and call it from
both onCreate() and a new onNewIntent() override.
2026-04-07 20:11:52 +02:00
Markus Fisch c6b3ca08f4 Restrict scans to horizontal crosshair
Only accept camera scan results that intersect the horizontal
crosshair when crosshairs are enabled. For 1D linear barcodes,
expand collapsed position lines into a narrow band first so the
same rule works reliably for formats that do not report full
symbol bounds.
2026-04-07 21:34:26 +02:00
Markus Fisch 73047cdee6 Simplify old to new format name translation
To have that list only once.
2026-04-07 19:23:56 +02:00
Markus Fisch bec4aa3120 Replace Code39 with the more specific Code39Std
So users get only Code39Std when they restrict reading to
this format.
2026-04-07 18:17:25 +02:00
Markus Fisch eaaaaf14c2 Add barcode format descriptions
To DecodeActivity and EncodeActivity.

Enables/Disables with meta data.
2026-04-07 20:59:10 +02:00
Markus Fisch 971742aff4 Fix barcode format preference summary
Sort the selected barcode formats alphabetically in the
preferences summary and map stored values back to their
display labels.
2026-04-07 15:46:47 +02:00
Markus Fisch 28915eacdb Simplify setting preference summaries 2026-04-06 23:37:35 +02:00
Markus Fisch a2c1d11b5b Include barcode format in history search
So we can use for barcode formats too.
2026-04-06 23:09:04 +02:00
Markus Fisch e9dd396f34 Add a dedicated barcode icon for PDF417 2026-04-07 12:02:08 +02:00
Markus Fisch c7edba746c Advance version number to 1.70.0 2026-04-03 23:39:44 +02:00
Markus Fisch 34c8dfd169 Add barcode format icons in history 2026-04-03 23:34:45 +02:00
bovirusandGitHub 459980899f Italian language update 2026-04-03 23:10:31 +02:00
Markus Fisch 2e0693cb45 Add beep audio stream preference
Let users choose whether confirmation beeps use the media or
notification audio stream, with media as the default.

Recreate the tone generator when the selected stream changes so the
new preference takes effect immediately, and add the required
localized labels for the new setting.
2026-04-03 12:00:14 +02:00
Markus Fisch 187825932e Parse EPC-QR codes and show the data 2026-04-01 21:30:51 +02:00
Markus Fisch a80802b4bc Improve layout of decode screen
Move the things a user cares most about to the top of the
screen, and everything else to the bottom.
2026-04-01 20:58:02 +02:00
Markus Fisch aa589a5d53 Improve size of generated PDF417 barcodes
PDF417 requires a bit more horizontal width because it
has many modules and doesn't fit into a square shape.
2026-04-01 20:20:46 +02:00
Markus Fisch 6a42e54f0b Fix parsing first field of subfile in IDLParser
Per the AAMVA spec, each subfile in the data section starts with its
2-char type marker (e.g. "ZV", "ZI") directly prepended to the first
field, with no separator between them. The key-value parser had no
awareness of this, so the marker was absorbed into the field key
(e.g. "ZVA" was parsed as "ZVZ" with value "VA01" instead of "01").
2026-04-01 19:55:30 +02:00
Markus Fisch e134b18bba Use quiet zone from library
Which uses zint for linear barcodes but avoids it for all
other types because zint doesn't generate reasonable margins
for other barcodes.

This fixes too thin margins for linear barcodes.
2026-03-31 22:27:59 +02:00
bovirusandGitHub a112484dcb Italian language update 2026-03-27 12:16:26 +01:00
Markus Fisch 4f36030e38 Advance version number to 1.69.1 2026-03-26 19:35:24 +01:00
Yurt PageandMarkus Fisch 90c2c03d12 Update translations 2026-03-26 19:30:24 +01:00
Markus Fisch 3f853be51a Advance version number to 1.69.0 2026-03-26 19:30:03 +01:00
Markus Fisch 835a348fad Fix confirm beep by switching to STREAM_MUSIC
STREAM_NOTIFICATION volume can be zero independently of ringer
mode, so isSilent() would pass but no sound played. STREAM_MUSIC
is the correct stream for in-app sound effects and is not                       affected by this.
2026-03-26 19:30:03 +01:00
Markus Fisch 198a35fc15 Clean up fragments to activities transition 2026-03-26 19:30:03 +01:00
Markus Fisch 6be1b25c38 Add format restrictions to automated actions
And ignored codes too.
2026-03-26 19:30:03 +01:00
Markus Fisch ac632e3aac Restrict searching to a specific format 2026-03-26 19:30:03 +01:00
Markus Fisch ddc5a14558 Clean up naming of search term dialog 2026-03-26 19:30:01 +01:00
Markus Fisch 8b1ffe3e5a Add preference for codes that should not be saved
So short-lived one-shot links like FIDO:// URLs don't
end up in the history.
2026-03-26 19:29:19 +01:00
Markus Fisch e9ba66848f Add an option to show crosshairs 2026-03-26 19:29:19 +01:00
Markus Fisch 7bdef27a50 Pin history items
So it's easy to keep important scans at the top.
2026-03-23 22:14:26 +01:00
Markus Fisch ccd16a0f95 Improve preference icons
And add better ones where appropriate.
2026-03-21 17:51:02 +01:00
Markus Fisch a385678de1 Optimize vector drawables 2026-03-21 17:32:31 +01:00
Markus Fisch 43c597f6fb Add leak canary for debugging 2026-03-21 17:28:09 +01:00
Markus Fisch ecccf34418 Advance version number to 1.68.7 2026-03-20 21:56:20 +01:00
Markus Fisch 4027ce2cc6 Reformat new code 2026-03-20 21:56:07 +01:00
Markus Fisch 209e6c5c30 Add icons to preferences screen
Assign existing action icons to preference rows in the settings
screen so related options are easier to scan.
2026-03-20 21:55:37 +01:00
Markus Fisch 5e29f3fbe9 Update kotlin version 2026-03-20 21:26:05 +01:00
Markus Fisch ba3d63277a Update gradle wrapper 2026-03-20 21:15:56 +01:00
Markus Fisch fe34b7209d Fix quiet zone for recreated barcodes
Older history entries can miss the stored symbol matrix and
therefore fall back to re-encoding the barcode content.

After the ZXingCpp 3 migration, that fallback used a zero margin,
so recreated barcodes from those records lost their quiet zone.
2026-03-20 21:08:20 +01:00
Markus Fisch 0efdca7b4a Remove unnecessary null checking of error message
Because it's always non-null now.
2026-03-20 15:46:38 +01:00
Markus Fisch 827fbedc1f Fix automatic screen brightening
And remove lateinit from `brightenScreenItem` to check
if it's null or not.

Also delay automatic brightening to give Android a bit
more time to sort things out.
2026-03-20 15:46:38 +01:00
Markus Fisch 107b5bafd4 Update history listing on resume
To immediately show label changes, for example.
2026-03-20 15:46:38 +01:00
Markus Fisch 19a71480fa Update tools version 2026-03-20 15:46:38 +01:00
Markus Fisch 909e97a591 Map zoom bar to zoom ratio instead of linear zoom
Linear zoom 0 switches to the ultra-wide lens on devices
that support it, causing blurry images. Mapping to zoom ratios
from 1.0x to maxZoomRatio keeps the main lens in use.
2026-03-17 21:54:34 +01:00
Markus Fisch bc2be96871 Simplify updating the flash FAB
It's much simpler if we invert the availability parameter.
2026-03-20 10:53:39 +01:00
Markus Fisch d834621d99 Reset stored zoom level and always start at 0
Because the previous zoom levels were for the legacy camera API
and they don't carry over to CameraX.

With CameraX, it's also better to start with no zoom.
2026-03-20 10:53:39 +01:00
Markus Fisch ad83be1a60 Use ResolutionStrategy.HIGHEST_AVAILABLE_STRATEGY
Which greatly improves the initial sharpness of the camera image.

Without this, despite autofocus, the initial camera frame can be
a bit blurry on some devices.
2026-03-20 10:53:39 +01:00
Markus Fisch d65ea02b49 Focus on taps but not on swipes 2026-03-20 10:53:32 +01:00
Markus Fisch c8d1357ceb Use CONTINUOUS_PICTURE AF
CameraX defaults to CONTINUOUS_VIDEO autofocus, which trades
focus accuracy for smooth transitions. For barcode scanning we
need the sharpest possible lock, so switch to CONTINUOUS_PICTURE.

But this still isn't enough to have the same quick autofocus the
legacy API had.
2026-03-20 10:52:44 +01:00
Markus Fisch 4c05d046e6 Set CONTROL_SCENE_MODE_BARCODE
To configure the camera for barcode reading (macro focus range,
disabled stabilisation). Same way the legacy Camera API's
SCENE_MODE_BARCODE did.

Unfortunately, this mode isn't supported by some camera drivers
and it doesn't really improve focusing near barcodes on my test
devices.
2026-03-20 10:52:44 +01:00
Markus Fisch 4423ee62c8 Migrate to CameraX
Since the app is on minSDK 21 now, and because some camera
drivers apparently don't support the torch feature through
the legacy API.
2026-03-20 10:52:21 +01:00
Markus Fisch bc69f99f8b Advance version number to 1.68.6 2026-03-14 14:53:30 +01:00
Markus Fisch 6b088031fd Remove unused plural quantities
Delete plural forms that Android never selects for the affected
locales, based on the lint report.
2026-03-13 22:43:31 +01:00
Markus Fisch b27d03e9c0 Ask for confirmation before deleting a scan
From the decode view.
2026-03-13 22:37:43 +01:00
Markus Fisch 9a13838f28 Fix RTL hardcoded layout attributes
Remove redundant left/right layout attributes and keep the
start/end variants that match RTL-aware behavior.
2026-03-13 22:34:08 +01:00
Markus Fisch cce2a460f6 Update material library 2026-03-12 23:34:05 +01:00
Markus Fisch 36352ecde2 Apply KTX extensions from lint
Replace lint-flagged platform calls with their Kotlin extension
equivalents and add the core-ktx dependency they rely on.
2026-03-13 16:33:54 +01:00
Markus Fisch 9a0bc324cb Migrate support libraries to AndroidX
Replace legacy support dependencies and namespaces with AndroidX and
Material equivalents so the app builds on the modern stack again.

Update Kotlin imports, XML widget class names, and manifest provider
references, then fix AndroidX nullability fallout and missing lifecycle
super calls reported by lint.
2026-03-12 23:19:02 +01:00
Markus Fisch 6dabafd6a3 Replace fragments with standalone activities
Remove MainActivity as a single fragment host and convert each
fragment (Barcode, Decode, Encode, History, Profiles, Automated
Actions, Network Suggestions) into its own Activity.

Update CameraActivity to launch each Activity directly instead of
routing through MainActivity intent factories.
2026-03-12 23:10:18 +01:00
Markus Fisch dde4b1e0bd Update gradle wrapper 2026-03-12 22:58:58 +01:00
Markus Fisch 8a8c7bd1ff Remove values-v21 for minSDK is 21 now
No longer required. Merged the Button style with
`res/values/styles.xml`.
2026-03-12 22:16:02 +01:00
Markus Fisch a2aed42e25 Remove Scan parcel compatibility code
Stop transporting Scan as a Parcelable and keep only the
bundle-based handoff for decoded results.

This removes version-sensitive parcel decoding entirely and makes
scan navigation stable across app updates.
2026-03-12 21:51:55 +01:00
Markus Fisch a38b7b647f Use bundles for decoded scan handoff
Replace Scan parcelables in the decode navigation flow with plain
Bundle data.

This avoids BadParcelableException when Android lazily unparcels a
Scan written with a different layout or legacy ZXingCpp format names.
A bundle of primitives is stable across app updates and does not depend
on custom parcel compatibility.
2026-03-12 21:44:57 +01:00
Markus Fisch 76e82ed842 Migrate to ZXingCpp 3.x and raise minSdk to 21
Which is required (to build and run) version 3 of ZXingCpp,
because ZXingCpp requires C++20, which in turn requires an
NDK with minSdk 21.

So to use the new version, we need to raise the minSdk
and cut off old devices just because C++17 didn't cut the
mustard anymore. Well, I guess this had to happen at some
point, and because SDK 21 is 12 years old now, it's probably
even reasonable to raise the bar.
2026-03-12 20:53:23 +01:00
Markus Fisch fd54bc604e Advance version number to 1.68.5 2026-03-02 19:07:06 +01:00
Markus Fisch 59b62ecbc4 Revert ZXingC++ to v2.3.0.4
Because 3.x requires C++20, what requires minSdk 21.

While ZXingC++ 3.x compiles and runs on some devices (with the
current minSdk), the library does crash on other devices.

So updating to ZXingC++ 3.x requires more work, unfortunately.

This reverts commit
a90bdad117
4b2eb80612
7a59126312
2026-03-02 18:59:41 +01:00
Markus Fisch de6a2863f3 Advance version number to 1.68.4 2026-02-24 23:57:27 +01:00
Markus Fisch 4b2eb80612 Fix margin for 1D barcodes
Since ZXingCpp v3.0.0+ changed the default from -1 to 0.

Using -1 results in an exception in `BitMatrix::setRegion()`
because of invalid top/left coordinates.
2026-02-24 23:52:04 +01:00
Markus Fisch 2de40d2277 Advance version number to 1.68.3 2026-02-23 23:13:10 +01:00
Markus Fisch 7673b7cb0d Fallback to getParcelableExtra(name)
When getting the DECODE extra.

`getParcelableExtra(name, Class)` can throw on some versions
of Android when the ClassLoader associated with the Bundle's
lazy-decoded value is null in certain scenarios (e.g., after
an activity restart where the system re-delivers the intent).
Simply fallback to the "deprecated" `getParcelableExtra(name)`
which works in this case, because it doesn't verify the
parcelable's class against Scan::class.java.
2026-02-23 21:00:30 +01:00
Markus Fisch 097c5e4453 Improve getting fragment for MainActivity
And properly finish the MainActivity for malformed intents.
2026-02-23 17:21:30 +01:00
Markus Fisch 1fab30089e Advance version number to 1.68.2 2026-02-22 21:15:25 +01:00
Markus Fisch f9bf16dd47 Update ZXingCpp 2026-02-22 21:03:20 +01:00
Markus Fisch 7a59126312 Use 1 as the new default for margin/quiet zone
Since ZXingCpp v3.0.0+ changed the default from -1 to 0.

Using -1 results in an exception in `BitMatrix::setRegion()`
because of invalid top/left coordinates.
2026-02-22 20:58:24 +01:00
Markus Fisch 694c854650 Advance version number to 1.68.1 2026-02-21 21:50:51 +01:00
Markus Fisch b1cd12ec77 Validate frame data before giving it to ZXing
And refactor preview callback to use an early exit for clarity.

According to Vitals, `frameData` can apparently be `null` on
some devices sometimes.
2026-02-21 21:40:38 +01:00
Markus Fisch 0c27b15025 Check if fragment is still added
Before setting brightness, which may happen later because
it's called from the queue.
2026-02-21 21:20:31 +01:00
Markus Fisch 5de950bdbf Update tools version 2026-02-21 19:14:54 +01:00
Markus Fisch ae9e304ef6 Handle bad decoded intent parcelables safely
Guard reading the `decoded` Scan extra in MainActivity against
framework unparcel exceptions. Some external or malformed intents can
trigger a NullPointerException in Parcel before app-level checks run.

Return null when unparceling fails so the app falls back to the default
DecodeFragment path instead of crashing on launch.
2026-02-21 19:13:47 +01:00
Dominik StadlerandMarkus Fisch c4cc14554b Clear search-term on empty input, not on "Cancel"
Clearing search-term on cancel and not on empty input is
unexpected. "Cancel" usually does not change the state.

Rather clear the searchTerm on empty input and do not
handle the "Cancel"-button at all.
2026-02-20 13:52:50 +01:00
Dominik StadlerandMarkus Fisch d6afccf562 Apply some IDE suggestions 2026-02-20 13:52:50 +01:00
Markus Fisch a90bdad117 Update ZXingCpp
And remove the now missing `returnCodabarStartEnd` feature.
2026-02-13 19:05:35 +01:00
solokotandGitHub 52d4f082f2 Update Russian translation
Small Improvements
2026-02-12 19:45:38 +01:00
Markus Fisch 1c63f5b3ac Advance version number to 1.68.0 2026-02-07 20:18:43 +01:00
Markus Fisch 21985b4533 Remove deprecated flags from gradle.properties
Stuff only added because Google deemed it necessary.
Now the Google propeller caps have apparently changed
their minds. Don't care.
2026-02-07 20:15:41 +01:00
bovirusandGitHub 012ac644aa Italian language update 2026-02-07 12:21:26 +01:00
Markus Fisch 19f19739fd Fix up navigation for setting fragments 2026-02-06 17:42:18 +01:00
Markus Fisch f01f9fcd91 Add a dedicated fragement for managing profiles
And the missing option to remove profiles.
2026-02-06 17:42:18 +01:00
Markus Fisch 4177b248c3 Clean up AutomatedActionsFragment 2026-02-06 17:42:18 +01:00
Markus Fisch e4182a265b Add a ViewHolder to ActionsAdapter 2026-02-06 17:42:18 +01:00
Markus Fisch 98df5a447c Move adding an action into its own function
For readability.
2026-02-06 17:42:18 +01:00
Markus Fisch a0a1405359 Allow alphanumeric profile names only
Since a profile name is also used as a preference name,
it cannot contain path separators or anything like that.
So keep names alphanumeric for robustness.
2026-02-06 17:42:18 +01:00
bovirusandGitHub 76922c421c Italian language update 2026-02-06 17:41:42 +01:00
Markus Fisch cac9dd16da Add automated actions
To automatically execute actions when certain barcodes
are scanned.
2026-02-04 22:40:39 +01:00
Markus Fisch a1f9ba1056 Update gradle wrapper 2026-02-04 21:45:58 +01:00
Markus Fisch 0b67c272b6 Update robolectric to latest version 2026-02-03 19:16:54 +01:00
Markus Fisch 9b8be5305d Update tools and gradle wrapper to Gradle 9
And remove the now unnecessary kotlin-android plugin.
2026-02-03 18:15:33 +01:00
Markus Fisch a026ade13b Remove own toHexString() implementation
In favor of the new Kotlin API.
2026-01-26 20:31:07 +01:00
Markus Fisch b1771bc5ea Advance version number to 1.67.1 2026-01-14 23:19:07 +01:00
Markus Fisch 5199460669 Open file:// Uris as documents from Android N+
Because file:// can't be used with Scoped Storage anymore.
2026-01-14 23:16:05 +01:00
Markus Fisch fd040e1660 Remove lateinit from PickActivity members
Because `onCreate()` may return before the `lateinit`
members have been initialized, which would raise a
`kotlin.UninitializedPropertyAccessException`.
2026-01-13 14:53:27 +01:00
Markus Fisch 2e1528364e Fix auto closing of DecodeFragment
Some actions require the `Activity` object to stay alive, e.g.
`OpenOrSearchAction` or `WifiAction` may show a dialog first and
only then may trigger `startActivity`.

Before this commit, with the preferences `openImmediately` or
`closeAutomatically` enabled, the app crashed for content that
would show a dialog through `DecodeFragment.executeAction()`.
2026-01-13 21:20:35 +01:00
KamaleiZestriandGitHub d21af142bb Catch all exceptions for socket.connect()
`socket.connect()` can throw `IOException`s, too.

Occurs with Windows when the bluetooth service gets killed and
restarted in the background.
2026-01-13 09:52:50 +01:00
Markus Fisch 8395e135f9 Update Kotlin version 2025-12-11 20:04:25 +01:00
Markus Fisch c0caa0ce44 Update tools version 2025-12-11 20:03:10 +01:00
Markus Fisch 96927ef9b2 Add line breaks in README 2025-11-14 19:11:18 +01:00
TheRedCyclopsandGitHub 84d9a3b55a Remove double "at" in README 2025-11-14 11:14:34 +01:00
Markus Fisch ffe8e4c5ba Advance version number to 1.67.0 2025-10-10 20:06:03 +02:00
Markus Fisch bc7c5dca97 Fix restoring crop and zoom on profile changes 2025-10-09 20:45:52 +02:00
Markus Fisch d9737f4df1 Store crop handle position per view size
So we have a crop handle configuration for each view size.
2025-10-05 22:42:00 +02:00
Markus Fisch 0e8147713a Use default preferences for welcome screen marker
Since the welcome screen is intended to be shown for the first
start only.
2025-10-05 22:39:54 +02:00
Markus Fisch 3d425a097a Update robolectric version 2025-09-30 23:24:26 +02:00
Markus Fisch c26765cc63 Update Kotlin version 2025-09-30 23:22:15 +02:00
Markus Fisch fb6dc8ba55 Update kotlinx coroutines library 2025-09-30 23:21:54 +02:00
Markus Fisch 70f4d166a0 Support having multiple preference profiles
Requested in #558.
2025-09-30 23:20:30 +02:00
Markus Fisch 6c136ce719 Support regex when searching for a barcode 2025-09-30 16:36:14 +02:00
Markus Fisch c6dee80c0a Quote search term and remove comma
Between search term and barcode restriction.

Cleaner and less irritating.
2025-09-29 22:24:54 +02:00
Markus Fisch 1f43dd4827 Refactor scan_format to scan_for
Since this label is used for barcode formats and search terms.
2025-09-29 22:19:56 +02:00
Markus Fisch a366157977 Fix setting title with format and search term 2025-09-29 22:18:30 +02:00
Markus Fisch 6bb72672a3 Show a message for unmatching barcodes
So it's clear that the app recognized the barcode, but it's
not the one we're looking for.
2025-09-29 22:12:26 +02:00
Markus Fisch 04774527a0 Fix string capitalization for consistency 2025-09-29 21:36:44 +02:00
Markus Fisch 6f3e644aa8 Update tools version 2025-09-23 21:48:02 +02:00
Markus Fisch 5e3176b703 Update ZXingC++ for 16 KB ELF alignment
Because starting November 1st, 2025, all new apps and updates to
existing apps submitted to Google Play and targeting Android 15+
devices must support 16 KB page sizes on 64-bit devices.
2025-09-23 21:38:46 +02:00
zicaandGitHub 0f0aaff284 Improve zh-tw and ja translations 2025-09-12 18:39:29 +02:00
Markus Fisch f0d09e81b4 Advance version number to 1.66.2 2025-08-26 21:16:08 +02:00
Markus Fisch 771258cb5c Update tools version 2025-08-18 20:33:59 +02:00
Markus Fisch 9482086666 Reformat code 2025-08-18 20:33:21 +02:00
CertainBotandGitHub bcad50c3e8 Update Spanish translation
Few corrections over the AI translations.
2025-08-08 09:45:07 +02:00
Markus Fisch dbd055699e Remove adding ?content= to forward URL
When no other query was given.

This was meant to make it clear that the scanned content will
just be added to the given URL. But it's too restrictive as
there can be URLs without query strings.
2025-08-04 21:52:05 +02:00
Markus Fisch d67f8273d6 Update to target SDK 36 2025-07-30 21:03:48 +02:00
Markus Fisch 649be0ceb6 Update Kotlin version 2025-07-30 20:59:22 +02:00
Markus Fisch f5eb5dd8d2 Update gradle wrapper 2025-07-30 20:52:46 +02:00
Markus Fisch eb805dad2f Update tools version and gradle wrapper 2025-06-11 17:44:40 +02:00
Markus Fisch 202bb32b29 Advance version number to 1.66.1 2025-05-28 18:33:03 +02:00
Markus Fisch 50b8a4d329 Add missing curly braces
We always use curly braces around here.

When in doubt, google for "Apple's SSL Bug".
2025-05-28 18:27:26 +02:00
Markus Fisch fa15478fb4 Remove unused parameter from Bluetooth send method 2025-05-28 18:26:51 +02:00
Markus Fisch 20c2a5a8aa Catch Bluetooth SecurityExceptions explicitly
These are thrown when the user denies access to Bluetooth,
and `$ ./gradlew lintDebug` complains rightly about this.
2025-05-28 18:25:10 +02:00
Markus Fisch 00b95678ed Remove now unnecessary cast 2025-05-19 21:31:39 +02:00
Markus Fisch 5df3517563 Use an underscore for unused exception parameters
To get rid of the warnings.
2025-05-19 21:29:02 +02:00
Markus Fisch fd6946d2c2 Fix checking scan.id instead of fragment id 2025-05-19 21:05:22 +02:00
Markus Fisch c74d229e1f Update tools and gradle wrapper 2025-05-19 21:04:33 +02:00
Unknownman820andGitHub fa99a19db5 Update chinese translation 2025-05-07 19:07:44 +02:00
Markus Fisch b083fcf213 Show elements of invalid Wifi configurations too
So users can still access the elements even when the configuration
is invalid.
2025-05-07 18:47:34 +02:00
Markus Fisch 46930ddea6 Unescape Wifi elements in parseMap()
Instead of unescaping elements selectively in `SimpleDataAccessor`.

This is much simpler and this way the `Map` `parseMap()` returns has
always unescaped values. This `Map` is also layed out in the
`DecodeFragment`, which still displayed the escaped values before
this commit.
2025-05-07 18:47:34 +02:00
Markus Fisch 7bef77b96e Add test for unescaping emojis in Wifi credentials
Because of #544.
2025-05-07 18:47:34 +02:00
NathanandGitHub c5f4c088b4 Update french locale
Correction of automatic translations.
2025-05-01 21:58:36 +02:00
Yurt PageandGitHub 73f7210e18 Update translations from Toolate 2025-04-25 23:50:20 +02:00
Markus Fisch 469429e663 Advance version number to 1.66.0 2025-04-25 23:49:16 +02:00
Markus Fisch 1a7ac59740 Refactor BinaryEyeDeeplink to just Deeplink 2025-04-25 12:54:50 +02:00
Markus Fisch c13c59e728 Refactor IDLParser/ElementMap to use camel case
And match these names with other symbols in this code base
that don't use all caps for abbreviations like `Url` or
`UrlDialogFragment` and so on.
2025-04-25 12:51:30 +02:00
Markus Fisch bc17e25717 Reformat with Android Studio 2025-04-25 12:48:51 +02:00
Yurt PageandGitHub 5017bd4c8d fastlane: simplify short description
And add "QR code" to make it easier to find.
2025-04-25 12:43:58 +02:00
Anton SerebryakovandGitHub a44a913eca Support deep links to encode content via web links
To open barcode://encode via a HTTP deep link.

Also adds actions to copy the deep link to the clipboard.
2025-04-25 12:42:42 +02:00
Yurt PageandGitHub 007e83e243 fastlane: merge summary.txt into short_description.txt
summary.txt was used by Tripple-T but the default Fastlane file name is short_description.txt. It supports the summary.txt too but we have a duplication problem and some languages has both.
So I removed the duplicated summary.txt and renamed existing summary.txt into short_description.txt.
2025-04-23 21:43:47 +02:00
Markus Fisch de8f97c246 Parse International Driver Licenses
Usually from PDF417 barcodes.
2025-04-06 15:10:36 +02:00
Markus Fisch 1287591e53 Clean up Bluetooth instructions
Use proper bold syntax instead of making things headlines that
aren't headlines. Markdown is not source code for HTML but a human
readable document format. So semantics are important.

Also removes detailed install instructions for the companion apps.
These should be in the README of the corresponding application.
2025-04-03 21:44:40 +02:00
Markus Fisch 8c17238572 Only show clipboard toast before Android 13
Because there is a clipboard popup from Android 13 on.
2025-04-03 09:17:12 +02:00
Curious, aren't we?andGitHub 5dbb36e6a9 Add Bluetooth howto to the README 2025-04-02 23:33:14 +02:00
Markus Fisch ca7dfb3a33 Add new WiFi's via Settings intent
From API level 30, Android R, on.

This has the advantage that Binary Eye doesn't take ownership of
the newly added WiFi. See #482
2025-03-30 19:53:12 +02:00
Markus Fisch 419b7d5765 Give share file its own icon
So that we can clearly distinguish this action from the share
action when all actions are layed out next to each other.
2025-03-16 21:20:23 +01:00
Markus Fisch fa38866669 Update missing string resources
With a little help from the OpenAI API ;)
2025-03-27 14:19:44 +01:00
bovirusandGitHub 19ca521f59 Italian language update 2025-03-16 11:43:37 +01:00
Markus Fisch be657d86cf Show parsed data for MatMsgAction and WebAction 2025-03-14 12:27:06 +01:00
Markus Fisch 5199a4a526 Remove log messages
From debugging.
2025-03-14 12:27:06 +01:00
Markus Fisch ff48a543c9 Show parsed VType items in data view 2025-03-14 12:27:06 +01:00
Markus Fisch 2eadd01a87 Use apply scope function initialize valueView
Removes repetitions.
2025-03-14 12:27:06 +01:00
Markus Fisch dd2abe7d89 Copy password as every other content
And remove the corresponding special message.

It's probably clear enough with the generic message.
2025-03-14 12:27:06 +01:00
Markus Fisch 8e05caac70 Add click listener to copy data items
Into the clipboard for easy access.

Now, the data items should be bigger and also have some click feedback.
2025-03-14 12:27:06 +01:00
Markus Fisch 46aeced09f Separate Deep Links from Intents in README
And add some links on how to integrate a barcode scanner in an app.
2025-03-14 12:27:06 +01:00
NathanandGitHub 3681c5d011 Update french translation
Added strings for latest features.
2025-03-14 12:23:53 +01:00
Markus Fisch 20b4f7aac5 Advance version number to 1.65.2 2025-03-12 18:55:50 +01:00
Markus Fisch bc6e350271 Sanity check view, ROI and frame metrics
Because `roundToInt` in `Rect.setFrameRoi()` throws an
`IllegalArgumentException: Cannot round NaN value` for
some people out there.
2025-03-12 18:52:27 +01:00
Markus Fisch c9c1b2f5bf Advance version number to 1.65.1 2025-03-12 12:23:43 +01:00
Markus Fisch 1dbc0f0fa1 Fix fastlane changelogs
And insert the missing log for version code 141.
2025-03-12 12:20:20 +01:00
solokotandGitHub ab8170ee72 Update Russian translation
Fix machine translation
2025-03-12 12:11:05 +01:00
Markus Fisch 551464dc6f Refactor for an early return when content is empty
Easier to read and less indent.
2025-03-12 00:54:59 +01:00
Markus Fisch c3aac0a1e1 Set a default search URL for simple mode
So any (otherwise unregistered) content is always redirected to
the browser.
2025-03-12 00:53:37 +01:00
Markus Fisch d678e1cfd0 Hide keyboard when expanding recreated barcode
So the layout of `BarcodeFragment` isn't affected by it.
2025-03-12 00:49:30 +01:00
Markus Fisch a445ade877 Reduce height for 1D barcodes
1D barcodes don't need as much vertical space.
2025-03-12 00:48:20 +01:00
Markus Fisch 1fd0b7637f Add execute argument for binaryeye://encode
For immediate code generation.
2025-03-12 00:37:47 +01:00
Markus Fisch fdc88df897 Remember quiet zone settings
And use a quiet zone by default because it's recommended.
2025-03-12 00:19:41 +01:00
Markus Fisch d0f133ae00 Fix showing a scan from history
When `openImmediately` is `true`.

Of course, the action should only be executed when we're coming
from the scanner, not the history.
2025-03-12 00:11:14 +01:00
Markus Fisch 67646261e7 Remove unnecessary id field 2025-03-12 00:08:11 +01:00
Markus Fisch faeae9e904 Advance version number to 1.65.0 2025-03-11 23:23:55 +01:00
Markus Fisch 77b21a9e83 Add a welcome screen to choose a mode
To address these bad reviews when people don't understand that
they have to press this little green button.
2025-03-11 23:17:36 +01:00
Markus Fisch cbe7860a3d Add a deep link to encode a barcode 2025-03-11 22:58:45 +01:00
Markus Fisch fc29267d3d Update ZXing-C++ library 2025-03-11 22:58:10 +01:00
Markus Fisch 890506328b Fix show crop handle setting
This switch isn't part of the crop configuration, but controls if
the crop handle is actually visible or not.
2025-03-11 22:58:10 +01:00
Markus Fisch 04036b6cd6 Use apply scope function to initialize views
And remove all this repetition of names.
2025-03-11 22:58:10 +01:00
Markus Fisch 2602021c1c Remove unused import from PickActivity 2025-03-11 22:58:10 +01:00
Markus Fisch 17a0bdc0a9 Allow shrinking of image samples too
So they can fit in the crop window.
2025-03-11 22:58:10 +01:00
Markus Fisch d71a220eca Remember zoom level of barcodes in view
Solves #490.
2025-03-11 22:58:10 +01:00
Markus Fisch 0c2e711d79 Add a comment why Scan.text can be an empty string
So it's immediately clear why `Scan.text` can be empty.
2025-03-11 22:58:10 +01:00
Markus Fisch ca342a83d3 Configure ZXingCpp to return plain text only
And remove the HRI decoration because it's confusing people and
doesn't work well when the barcode is re-generated from this
content.

Alternatively, we could filter the HRI decoration for generation,
but that's probably overkill.

Solves #506.
2025-03-11 22:58:10 +01:00
Markus Fisch 3c44ff56eb Refactor SCAN_CONTENT to SCAN_TEXT
To match the refactoring of `Scan.text` in 5189fc.
2025-03-11 22:58:10 +01:00
bovirusandGitHub bcae64c0d0 Italian language update 2025-03-11 22:57:50 +01:00
Markus Fisch c2f673729b Advance version number to 1.64.2 2025-03-10 21:23:52 +01:00
Markus Fisch 2043e0f349 Use separate crop handle config for image scanning
These are two different use cases.
2025-03-10 21:11:41 +01:00
Markus Fisch b93eb5963e Use raw content for Barcode<*> when text is empty
So binary content is supported here, too.
2025-03-10 11:01:15 +01:00
Markus Fisch 5189fc9c5a Refactor Scan.content to Scan.text
Because `text` is more specific, and the term `content` is often
used for generics.
2025-03-10 10:54:44 +01:00
Markus Fisch 2d311ff92a Fix initializing dataMask
And show this item for QR Codes only.
2025-03-10 19:50:19 +01:00
solokotandGitHub 14bb08003d Update Russian translation 2025-03-10 10:31:50 +01:00
Markus Fisch 42f9887030 Advance version number to 1.64.1 2025-03-09 22:39:37 +01:00
Markus Fisch a59d241b50 Handle empty input for recreation 2025-03-09 22:35:28 +01:00
Markus Fisch 9f31160c7b Add missing symbol fields to initial db creation 2025-03-09 22:14:06 +01:00
Markus Fisch 2eb4e51c17 Advance version number to 1.64.0 2025-03-09 19:43:00 +01:00
Markus Fisch 53a554e7a2 Add a menu item to find a specific barcode
The searched barcode needs to include the given term.

Solves #516.
2025-03-09 19:09:19 +01:00
Markus Fisch 7f6887716a Use Barcode for recreation too
And move `Barcode` into its own file.

So a given `BitMatrix` can be used for `BarcodeFragment` (and sharing
and exporting) as well.
2025-03-09 14:19:27 +01:00
Markus Fisch 5ef93802ce Make margin optional for BarcodeFragment
Just like `ecLevel` and `colors`.
2025-03-09 12:57:23 +01:00
Markus Fisch c1eff08bb9 Remove unnecessary semicolons
Too much context change.
2025-03-09 12:56:48 +01:00
Markus Fisch 8798d44ec7 Fix showing QR Code data mask
The first data mask is 0.
2025-03-09 12:55:55 +01:00
Markus Fisch d4e31ff97e Update ZXing-C++ library
To fix data mask initialization.
2025-03-09 12:55:28 +01:00
solokotandGitHub ae8b08a85a Update Russian translation 2025-03-09 12:10:10 +01:00
Markus Fisch 09430d776e Replace margin with add quiet zone switch
Giving a margin in pixels doesn't scale with (the size) of the
barcode.
2025-03-08 22:18:04 +01:00
Markus Fisch ef88c3179d Use detected barcode matrix for recreation
If it is provided by ZXing-C++. Currently, this is only supported
for some 2D barcodes. But it's probably only really useful for them
because there's padding and and other stuff that 1D barcodes don't
have.

This may solve #507.
2025-03-08 21:57:13 +01:00
Markus Fisch c732ec726b Show data mask of QR Codes 2025-03-08 21:54:54 +01:00
Markus Fisch 801c768df4 Update ZXing-C++ library 2025-03-08 21:53:19 +01:00
Markus Fisch 552a2f6d57 Only color status bar in context mode before SDK35
Has no effect from SDK35 on anyway.
2025-03-04 21:31:55 +01:00
Markus Fisch 7fa8810197 Make getIdOfScanByContent() private
Because it can be.
2025-03-04 21:27:12 +01:00
Markus Fisch 254af25bbb Update database functions to non-nullable Cursors
Because `SQLiteDatabase.rawQuery` returns a non-nullable `Cursor` now.
2025-03-07 16:55:58 +01:00
Markus Fisch a27656c174 Add a translucent nav bar background on SDK35+
Because the system doesn't draw one anymore.
2025-03-05 15:24:44 +01:00
Markus Fisch 2ca55ebccc Fix setting window insets on SDK35+
The bottom padding from the navigation bar needs to be set, too.
2025-03-04 19:47:41 +01:00
Markus Fisch ec1d40942d Optimize vector drawables with avocado 2025-03-04 00:21:30 +01:00
Markus Fisch 7852e5ce9d Use color literal in vector drawable
Because resource references will not work correctly in images
generated for API < 21.
2025-03-04 00:20:31 +01:00
Markus Fisch f36a81d4a0 Update Kotlin version 2025-03-04 12:50:50 +01:00
Markus Fisch d86ea4073c Remove unused quantity for Brazilian Portuguese
Following the corresponding lint warning.
2025-03-04 12:50:37 +01:00
Markus Fisch a69530621d Add autoVerify for URL intent filter 2025-03-04 12:50:28 +01:00
Markus Fisch 3c0f29a768 Add targetApi notation for quick settings tile
Since this is only available from Android N+.
2025-03-04 00:09:12 +01:00
Markus Fisch ccf5157fa7 Mark autofocus as optional
As it isn't strictly required.
2025-03-04 00:08:58 +01:00
Markus Fisch c1ebb1c154 Specify an explicit locale for String.format()
To silent the corresponding lint warning.

Doesn't really matter here probably.
2025-03-04 00:07:59 +01:00
Markus Fisch a4778bcc02 Replace removeFirst with removeAt
Because `java.util.List#removeFirst` requires SDK35, and resolved
to a Kotlin stdlib extension function before.
2025-03-04 00:04:04 +01:00
Markus Fisch 24d2c6d8d6 Only color system bars before SDK35
And ignore deprecation warning in this branch.

System bars no longer have a background from SDK35+.
2025-03-03 23:59:14 +01:00
Markus Fisch 0f3a07f602 Name SDK that requires a change explicitly
Instead of using greater than, because this way we can search
for VANILLA_ICE_CREAM changes.
2025-03-04 12:34:33 +01:00
Markus Fisch 751d8932f8 Immediately replace toasts
Instead of showing them in sequence.

Because in this app, only the last message is important.

Speeds up continuous scanning. Especially when the scanned code is
also forwarded and the server result is displayed in the next toast
(see #523).
2025-03-03 23:47:16 +01:00
Markus Fisch 9c2d063c24 Update tools version 2025-03-03 20:55:16 +01:00
Markus Fisch 0f9bbf5b2f Extend toolbar under status bar on SDK35+
Because SDK 35 is edge-to-edge by default, and doesn't color the
status or navigation bar anymore.
2025-02-18 21:34:27 +01:00
Markus Fisch 530280981e Fix image rotation calculation 2025-02-18 21:30:46 +01:00
Markus Fisch ddfbb305c7 Check Bitmap.getConfig() for null before use 2025-02-18 21:27:30 +01:00
Markus Fisch 8d1a29922b Update to SDK 35 2025-02-18 21:26:52 +01:00
Markus Fisch c710f7c6ab Move Toolate link below the reference section
Reference-style links should be derefenced after the content.

Also add a proper header for the matter.
2025-02-14 20:40:33 +01:00
Yurt PageandGitHub 111c587eef Add link to Toolate in CONTRIBUTING 2025-02-14 20:39:35 +01:00
Markus Fisch 264e494487 Update tools version and gradle wrapper 2025-01-23 19:59:08 +01:00
Markus Fisch 8135b2a3dc Update build tools 2024-12-19 22:23:45 +01:00
kraloandGitHub dce62b70d3 Update README to explain non-clickable binaryeye:// url 2024-12-05 21:56:06 +01:00
Markus Fisch 533812c638 Revert removing http deep linking intent filter
This is required for "http(s)://markusfisch.de/BinaryEye?ret=".

This reverts commit 12554e63e2.
2024-12-05 19:52:56 +01:00
Markus Fisch 5dc5bed281 Fix indent in Portuguese (Brazil) translation 2024-12-01 17:58:36 +01:00
Too Late (bot)andGitHub 2a13561962 Update Portuguese (Brazil) translation 2024-12-01 17:57:46 +01:00
Markus Fisch 1476f41cda Advance version number to 1.63.13 2024-11-24 19:37:04 +01:00
Markus Fisch 0da1ffbe02 Use JavaVersion.VERSION_1_8 for compatibility
Instead of just the version literal. Using the literal breaks
when the host has a higher Java version installed.
2024-11-19 20:08:34 +01:00
Markus Fisch 980679b6a3 Avoid UTF-8 conversion for binary input data
Otherwise the data is modified and doesn't match the desired input.

Still, it's probably better to introduce another CheckBox to explicity
control charset conversion.
2024-11-17 16:50:02 +01:00
Markus Fisch 28cbb55299 Use early returns when handling escape sequences
Improves readability.
2024-11-17 16:47:23 +01:00
Markus Fisch 1a4e7d100a Improve readability of expanding escape sequences 2024-11-17 16:46:23 +01:00
Markus Fisch 265e43b439 Fix argument order for assertEquals()
In EscapeTest.
2024-11-17 16:44:56 +01:00
NathanandGitHub 03a58c3412 Update French translation 2024-11-13 21:37:17 +01:00
Markus Fisch 327cad48f0 Update coroutines library 2024-11-06 21:50:30 +01:00
Markus Fisch 8e64fe2f56 Update Kotlin version 2024-11-06 21:50:14 +01:00
Markus Fisch 368d4dbb66 Fix typo in german translation 2024-10-18 19:39:38 +02:00
Manuel CovasandGitHub c8c3c094db Fix chronological order of scans taken less than 1 second apart 2024-10-17 16:36:24 +02:00
Wiktor PerskawiecandGitHub aa4aefe35f Fix typos in README and PRIVACY 2024-10-17 16:34:34 +02:00
AhmedandGitHub 536b3d77c1 Update arabian zero plural translation 2024-10-02 16:14:54 +02:00
Markus Fisch bbf2a80981 Add missing plurals for arabic
To silence lint from complaining that these are missing.
2024-10-02 15:39:33 +02:00
AhmedandGitHub ae99214d6c Update plurals in arabic translation 2024-10-02 15:36:54 +02:00
AhmedandGitHub 73b5a0969c Add arabic translation 2024-10-02 12:42:07 +02:00
Markus Fisch bf5dc96ac9 Advance version number to 1.63.12 2024-09-26 21:30:48 +02:00
Markus Fisch 301d9c2513 Fix argument list of recreation in onClickListener 2024-09-26 21:24:49 +02:00
Markus Fisch 0a11611b8f Advance version number to 1.63.11 2024-09-21 20:20:24 +02:00
Markus Fisch 249e310e43 Simplify asking for a size when sharing/exporting 2024-09-20 12:10:06 +02:00
Sergiy StuparandGitHub 6279c5731a Update Ukrainian translation 2024-09-20 12:09:46 +02:00
bovirusandGitHub df98637951 Update Italian language 2024-09-18 12:09:08 +02:00
solokotandGitHub 08b3558e46 Update Russian translation 2024-09-18 12:08:45 +02:00
Markus Fisch 648ef6fdf8 Update Kotlin coroutines library 2024-09-17 22:38:04 +02:00
Markus Fisch 807f075a51 Update Kotlin version 2024-09-17 22:37:08 +02:00
Markus Fisch 27789beeed Simplify ellipsis regex 2024-09-17 22:31:42 +02:00
Markus Fisch 97bee27827 Replace View casts for generic denotation 2024-09-17 22:29:02 +02:00
Markus Fisch 3fee49301e Only ask for barcode size when exporting/sharing
Because this parameter is just relevant when exporting/sharing
a raster image format.
2024-09-17 22:28:37 +02:00
Markus Fisch 8a6073291b Improve size slider for barcode generation
Reduce size options to popular powers of two.

And add the option to generate a barcode in the smallest
possible size of one pixel per module.
2024-09-17 20:54:07 +02:00
Markus Fisch 47151de4a4 Fix indent in Portuguese (Brazil) translation 2024-09-06 16:19:41 +02:00
Too Late (bot)andGitHub 248c4edca1 Update Portuguese (Brazil) translation 2024-09-06 16:18:21 +02:00
Markus Fisch 2c7386d536 Fix indent in Chinese translation 2024-08-17 18:12:32 +02:00
Too Late (bot)andGitHub e19cad4c87 Update Chinese translation 2024-08-17 18:09:47 +02:00
ZahnstocherandGitHub 585e0f3372 Update parcel tracking URL 2024-07-25 12:04:37 +02:00
Markus Fisch 2b7f611774 Fix showing tooltip on action FAB 2024-07-24 20:21:50 +02:00
Markus Fisch 05b2a0d9c9 Support hyphens in the second level domain
To correctly recognize URLs as WebAction.
2024-07-24 20:08:57 +02:00
Markus Fisch e7287eb088 Update tools version and gradle wrapper 2024-07-24 19:41:43 +02:00
NathanandGitHub 4b45ad3fe7 Update French translation
Added translations for checksum calculation (1.63.8) and screen brightening (1.63.10) features.
2024-07-13 19:58:04 +02:00
Markus Fisch 449d8fdbbd Advance version number to 1.63.10 2024-06-30 19:41:13 +02:00
Markus Fisch f44cff9912 Use type in getParcelableExtra() on Tiramisu+
And ignore the deprecation warning for earlier Android versions.

Also use a scope function to remove the local variable in the
parent context.
2024-06-30 19:06:02 +02:00
ThetaDevandGitHub 24730dfde3 Allow file input from share menu
Updates the handleSendText method to support both types of intents.

Also extends the accepted file types to text/* to also accept VCards
and other text-based files.
2024-06-30 18:54:20 +02:00
Sergiy StuparandGitHub be6539d41f Update Ukrainian translation 2024-06-16 13:41:14 +02:00
bovirusandGitHub 60dd40554e Update Italian language 2024-06-12 09:05:24 +02:00
solokotandGitHub 837119b6ec Update Russian translation 2024-06-12 09:04:57 +02:00
Markus Fisch abe11b82e5 Fix indent in Polish translation 2024-07-11 12:49:33 +02:00
Markus Fisch 4fc1e36d04 Add a menu item to toggle screen brightness
So this setting can be enabled/disabled where it's required, too.
2024-06-11 14:22:22 +02:00
Markus Fisch 54aa15e1be Set maximum brightness when showing a barcode
To make scanning from screen easier.
2024-06-11 14:22:18 +02:00
Too Late (bot)andGitHub 876d8fc7b3 Update Polish translation 2024-06-10 20:31:07 +02:00
Markus Fisch 7bdcdaaa5d Advance version number to 1.63.9 2024-06-02 18:15:53 +02:00
Markus Fisch fd44728e89 Ignore "URL:" before URLs in barcode content
Apparently some people think it's necessary to add an "URL:" prefix
before an actual URL, so let's cut that rubbish.
2024-06-02 15:24:22 +02:00
Markus Fisch 8242520a0b Export/share generated barcode as JPG
On request.

Generally, using a lossless format like PNG makes more sense.
2024-06-02 14:00:27 +02:00
Markus Fisch 2e7e9a942b Fix indent in new translations 2024-06-02 13:51:43 +02:00
Too Late (bot)andGitHub dcc9d5b3ff Update Brazilian translation 2024-06-02 11:54:14 +02:00
Markus Fisch 607aab854c Update build tools 2024-05-27 19:39:46 +02:00
Markus Fisch cc2b2f076b Fix exporting/sharing multiple history items
By their ID.

`?` is only one argument so a list of numbers becomes just one ID,
which cannot work, of course.
2024-05-27 19:37:43 +02:00
Too Late (bot)andGitHub 90e9723de5 Update Chinese translation 2024-05-13 10:38:54 +02:00
Sergiy StuparandGitHub ab6787e60b Update Ukrainian translation 2024-05-12 10:40:14 +02:00
solokotandGitHub 698686a45a Update Russian translation 2024-05-11 15:35:51 +02:00
Markus Fisch 95bdaa1252 Reformat imports with Android Studio
Seems like wildcard imports are back in fashion.
2024-05-11 14:13:39 +02:00
Markus Fisch f0c02e5156 Reformat with Android Studio 2024-05-11 14:13:20 +02:00
Markus Fisch a8c50308d0 Add Ko-fi for donations 2024-05-11 13:20:31 +02:00
bovirusandGitHub 6b359d4c65 Update Italian language 2024-05-10 21:08:07 +02:00
Markus Fisch 863caed387 Advance version number to 1.63.8 2024-05-10 20:56:25 +02:00
Markus Fisch e4f17b9bdf Add an option to show a checksum
For the decoded content. On request of #452.
2024-05-10 20:37:32 +02:00
Markus Fisch c2071d8d81 Treat LF/CR/Tab as printable characters
When encoding "something\nlike\tthüs". This string should be encoded
as text rather than binary, of course.
2024-05-08 19:49:19 +02:00
Markus Fisch 4758c2d337 Update tools and gradle wrapper 2024-05-07 21:57:36 +02:00
Markus Fisch 91336fe15c Encode as ByteArray if text contains non-printable
To support escape sequences containing non-printable characters.
2024-05-07 21:54:57 +02:00
Markus Fisch 2c437f3771 Add Liberapay to README 2024-04-27 15:58:37 +02:00
bovirusandGitHub cb082b20fe Update Italian language 2024-04-21 21:27:57 +02:00
Markus Fisch bce3630686 Advance version number to 1.63.7 2024-04-17 21:48:31 +02:00
Markus Fisch 4feb4d066c Update ZXingCpp for Aztec Runes 2024-04-17 21:24:30 +02:00
Markus Fisch e7d84cd916 Update tools version 2024-04-17 21:22:53 +02:00
Giovanni DonisiandGitHub 84e2917694 Update Italian translation 2024-04-14 13:58:07 +02:00
Markus Fisch b87464ec40 Advance version number to 1.63.6 2024-04-13 14:38:27 +02:00
Markus Fisch 269e0f41a6 Correct spelling mistakes in Spanish translation
Following the recommendations from the linter.
2024-04-13 14:32:27 +02:00
NathanandGitHub aefbc4a296 Update French translation 2024-04-13 14:26:19 +02:00
Sergiy StuparandGitHub c64984dc6a Update Ukrainian translation 2024-03-31 12:49:47 +02:00
Markus Fisch 24c7ad0ba4 Return Codabar start/stop codes
As requested in #445.

The start/stop codes determine if a barcode is complete or if there
is a continuation code to scan.
2024-03-30 12:46:15 +01:00
Markus Fisch 643a935852 Move buildConfig from properties into build.gradle
Apparently setting 'android.defaults.buildfeatures.buildconfig=true'
is deprecated and will be removed in version 9.0 of the Android Gradle
plugin.
2024-03-30 12:46:15 +01:00
solokotandGitHub 4fcb836b53 Update Russian translation 2024-03-26 12:12:30 +01:00
Markus Fisch 48ed5f1a2c Add history shortcut 2024-03-25 21:36:53 +01:00
Markus Fisch 3aa2371eeb Advance version number to 1.63.5 2024-03-24 21:15:31 +01:00
solokotandGitHub 88f92943c0 Update Russian translation 2024-03-24 14:53:36 +01:00
Sergiy StuparandGitHub 39710d4ab9 Update Ukrainian translation 2024-03-24 14:53:03 +01:00
Markus Fisch 93f7cd3cb8 Map old ignore setting to new one
For existing installations that changed this value.
2024-03-23 20:21:08 +01:00
Markus Fisch 69baa3b824 Add an option to ignore any duplicates
As requested in issue #439.
2024-03-23 14:20:42 +01:00
Markus Fisch bb05e38278 Update tools version 2024-03-21 21:23:28 +01:00
KamaleiZestriandGitHub 554f5a5e73 Fix failing send due to invalid bluetooth connection
Try reconnect to socket once before failing.
2024-03-21 21:19:51 +01:00
Markus Fisch 2dcf7772f2 Update tools version and gradle wrapper 2024-03-17 13:52:49 +01:00
Markus Fisch 3c7012e3c4 Advance version number to 1.63.4 2024-03-17 13:35:31 +01:00
Markus Fisch 08e11c3c40 Update ZXingCpp to fix support for old devices 2024-03-16 21:38:51 +01:00
Unknownman820andGitHub 31854dab0c Update Chinese translation 2024-03-16 21:38:04 +01:00
Markus Fisch 4f12c3e270 Advance version number to 1.63.3 2024-03-04 21:06:50 +01:00
Markus Fisch 3ec43dabce Update AndroidX SCAN Intent sample 2024-03-03 18:34:42 +01:00
Markus Fisch 0d4f536f71 Fix returning barcode format in return Intent
The class `BarcodeFormat` is not known to callers, of course.
2024-03-03 18:30:55 +01:00
Markus Fisch b064a293fb Add donation options to the README 2024-02-29 20:25:50 +01:00
Markus Fisch d124c29919 Advance version number to 1.63.2 2024-02-19 22:08:22 +01:00
Markus Fisch 2e89f1530a Add DX_FILM_EDGE barcode format
And add it to the selected barcodes so it's immediately
available for existing installations too.
2024-02-17 13:41:49 +01:00
Markus Fisch ef7e2a4b0d Update build tools 2024-02-17 13:40:28 +01:00
Markus Fisch f680533819 Update ZXingCpp for DX_FILM_EDGE format 2024-02-17 13:21:06 +01:00
Oğuz ErsenandGitHub a8c977c40e Update Turkish translation 2024-01-21 17:31:20 +01:00
Markus Fisch 1e89b22953 Update ZXingCpp to latest version
For QRCode: fix crash reported in #700
2024-01-15 20:14:50 +01:00
Markus Fisch 11f028e0f3 Update Kotlin version 2024-01-15 20:13:37 +01:00
Markus Fisch 1f7f4a23b5 Update tools version 2024-01-15 20:11:50 +01:00
Sergiy StuparandGitHub 41581d07ec Update Ukrainian translation 2024-01-14 20:53:17 +01:00
Markus Fisch dc819a6e1a Advance version number to 1.63.1 2024-01-13 13:47:32 +01:00
Markus Fisch 5b51072f1a Include custom label in json/csv exports/shares 2024-01-13 13:29:45 +01:00
solokotandGitHub 1b10e82cb2 Update Russian translation 2024-01-12 08:55:55 +01:00
Markus Fisch eeae1eb0ad Advance version number to 1.63.0 2024-01-11 20:27:27 +01:00
Markus Fisch 21c29ca373 Set sendScanActive to false by default
Was enabled by default because this setting came after `sendScanUrl`
and I didn't want to annoy users using this feature already.

But it's probably too suspicious to have it enabled by default, even
if it does nothing, of course.
2024-01-11 17:10:22 +01:00
Markus Fisch 8bcb72e91b Use getParcelableExtra(String, Class) on Tiramisu+ 2024-01-11 00:23:15 +01:00
Markus Fisch 8f345fbfbe Remove redundant suppress annotation 2024-01-11 00:14:04 +01:00
Markus Fisch 2c88dbca02 Reformat scanWithinBounds()
Apply autoformat.
2024-01-11 00:12:45 +01:00
Markus Fisch bd1c629c85 Reformat imports
Let Android Studio do its thing.
2024-01-11 00:11:48 +01:00
Markus Fisch f89e6612c4 Replace Enum.values() with Enum.entries
Following the recommendation.
2024-01-11 00:09:27 +01:00
Markus Fisch 7a0cd0ce19 Use isNullOrEmpty instead of checking both 2024-01-11 00:08:22 +01:00
Markus Fisch 8544affa1e Edit scan label in DecodeFragment
Which makes this feature more prominent and also easier to access.
2024-01-10 23:56:44 +01:00
Markus Fisch 48d3588341 Add a button to add generated codes to the history
So generated barcodes can be saved, too.
2024-01-10 23:37:51 +01:00
Markus Fisch 783f6e4892 Refactor edit_scan to edit_label
This action is used to edit the (optional) label of a scan.
2024-01-10 23:03:24 +01:00
Markus Fisch 032cd64daf Avoid asking multiple times for camera permission
Otherwise ActivityCompat.requestPermissions() will trigger onResume()
again and again.
2024-01-11 10:59:29 +01:00
Markus Fisch 96626e6b00 Move origin subtraction out of min()
Simplifies the calculation of the width and height of the crop
section.
2024-01-10 22:38:31 +01:00
Markus Fisch 11ae65ec3e Refactor Bitmap.erect to rotate
The original task of this function was to straighten a picture
lying on its side. However, the function is now used for any rotation.
2024-01-10 22:36:02 +01:00
Markus Fisch 91e3acb647 Disable free rotation by default
This is probably too delicate to use, most barcodes are still
recognized when skewed (a little), and it can be quite an expensive
operation to rotate a very big image. So it's better to disable
this feature by default (for new installations).
2024-01-09 20:25:21 +01:00
Markus Fisch 40c2f5947b Crop imported images in background thread
Because rotating and cropping a big photo can take some time.
2024-01-09 20:03:26 +01:00
Markus Fisch 58b9466cfc Fix margin/error correction for recreated codes
The `margin` argument position was incorrectly used for the
error correction level.
2024-01-09 19:28:50 +01:00
Markus Fisch 12210e1768 Update CameraView library 2024-01-09 12:13:12 +01:00
Sergiy StuparandGitHub ad2ac457c9 Update Ukrainian translation 2024-01-09 12:06:05 +01:00
Markus Fisch 634b6e8d2b Limit duration of error beep to 1s
Since `ToneGenerator.TONE_SUP_ERROR` keeps on playing which
is quite annoying.
2024-01-03 19:21:29 +01:00
CertainBotandGitHub 6dd47f4dd0 Update Spanish translation 2023-12-19 22:00:31 +01:00
Markus Fisch 8426f66cfb Fix indent in settings.gradle
Match this with the rest of the project.
2023-12-18 12:27:34 +01:00
Meen BeeseandGitHub 3dfa84a33e Simplification and clean up of Gradle files
* Some linting suggestions by Android Studio
* Move all repository declarations to settings
2023-12-18 09:41:07 +01:00
Markus Fisch 38f658e253 Advance version number to 1.62.3 2023-12-15 12:18:14 +01:00
Markus Fisch 287d99e2b4 Make clicks select list items when in action mode
Avoids having to do long presses for every item you want to add
to the selection.
2023-12-14 22:57:31 +01:00
Markus Fisch 5cfcde9d4a Update pt-br translation
Thanks to m_s_
2023-12-12 23:05:47 +01:00
Markus Fisch b2730259fc Advance version number to 1.62.2 2023-12-12 21:56:37 +01:00
Markus Fisch 61a2d3023c Add rMQR Code on existing installations
So it's working immediately after an update.
2023-12-12 21:50:28 +01:00
CertainBotandGitHub 239ac7bd1a Update Spanish translation
- New strings translated. Typos ammended.
- Términos nuevos traducidos. Corrección de erratas.
2023-12-11 21:58:35 +01:00
Markus Fisch 4048314cf7 Advance version number to 1.62.1 2023-12-11 20:19:18 +01:00
Markus Fisch 3dbd772847 Add rMQR Code to barcode format resources
To make it selectable, too.
2023-12-11 20:12:23 +01:00
Markus Fisch 3a08465c35 Add rMQR Code list of supported codes in README 2023-12-10 18:24:08 +01:00
Markus Fisch 92e3669ee5 Advance version number to 1.62.0 2023-12-10 15:49:33 +01:00
Markus Fisch 8b297f4768 Ignore plurals warning for qr_version_and_modules
Because a QR Code always has more than one module.
2023-12-10 15:45:13 +01:00
Markus Fisch 42b7f1179b Remove incomplete zh-rTW locales translation
Because this got incomplete and so won't work with the values
array anymore.

Also it's probably a really bad idea to translate locales anyway.
If you pick a wrong one by accident, you'll have a hard time
changing it back to something you can understand.
2023-12-10 15:40:37 +01:00
Markus Fisch 9d6854c282 Suppress false-positive warning about TileService
`TileService#startActivityAndCollapse(Intent)` is only ever run
below UpsideDownCake, but Lint doesn't understand this yet.
2023-12-10 15:37:48 +01:00
Markus Fisch d943b7deff Suppress warning about commit()ing prefs
Because `commit()` is intentional where it's used.
2023-12-10 15:36:10 +01:00
Markus Fisch a138da9d9b Update Kotlin version 2023-12-10 15:35:28 +01:00
Markus Fisch 194338a0d2 Remove "many" quantity from French plural
Lint says this isn't relevant to French.
2023-12-10 15:34:27 +01:00
Markus Fisch 7eb8fdcce1 Add Brave search to and de/fa/tr locales
This was missing from the original commit.
2023-12-10 15:33:21 +01:00
Markus Fisch 2bf1796340 Improve naming of shared wrapper files
And add extensions so it's easier to deal with these files
in other contexts.
2023-12-10 15:14:31 +01:00
Markus Fisch cc42015da2 Wipe share file in HistoryFragment too 2023-12-09 22:20:33 +01:00
Markus Fisch 648c39c439 Rename share file to just "contents"
A better fit when sharing the history in this file.
2023-12-09 22:20:00 +01:00
Markus Fisch 8c25b05cda Remove menu group to make actions fold 2023-12-09 22:16:16 +01:00
Markus Fisch 780bebc9d1 Share history as a file
To make sharing the history via Bluetooth more easily, as Android
converts plain text to HTML there.
2023-12-09 22:01:51 +01:00
Markus Fisch bf7eb7efd5 Update tools version and gradle wrapper
And finally add the `compileOptions` block to make Gradle 8
work, because the Google guys are still unable to fix their bugs.
2023-12-09 16:29:48 +01:00
Markus Fisch d00d08bae3 Update to latest ZXingCpp 2023-12-09 15:13:45 +01:00
Markus Fisch 379256a7fe Share selected scans only from history
If there is a selection. Otherwise use the search filter as before.
2023-11-26 19:54:08 +01:00
Markus Fisch 180339269f Advance version number to 1.61.2 2023-11-22 19:16:16 +01:00
v72807647andGitHub 49af17cba8 Fix quick setting tile failed to launch on Android 14
SDK 34 deprecates startActivityAndCollapse(Intent), making it
throws an UnsupportedOperationException on Android 14 devices
instead of launching the app.

Added new function call for API 34, tested with Android 14 and
Android 9 devices.
2023-11-22 09:24:30 +01:00
Markus Fisch a03a187d2d Escape apostrophes in french translation
Apostrophe characters need to be escaped in XML.
2023-11-20 10:55:29 +01:00
solokotandGitHub 84806e70d7 Update Russian translation 2023-11-20 10:09:02 +01:00
NathanandGitHub 058de5a141 Update french locale 2023-11-18 12:28:07 +01:00
Kryštof ČernýandGitHub d330fbd195 Update CZ translation 2023-11-16 13:45:59 +01:00
Markus Fisch f5bc6f664f Fix Xiaomi MIUI lockscreen barcode shortcut 2023-11-15 22:07:50 +01:00
Markus Fisch 464279807c Advance version number to 1.61.1 2023-11-14 23:10:09 +01:00
Markus Fisch f7e5ef473a Add menu item to share scanned contents as a file
Because when sharing plain text via Bluetooth, Android explicitly
converts anything to HTML, which is not always what we want.

Details here:
https://stackoverflow.com/q/29907030

This feature is also useful to share binary contents more easily.
2023-11-13 20:26:31 +01:00
Markus Fisch ff733ef59e Fix opening recreated barcodes with binary content
Use the raw bytes not only for the recreated image but also
when opening the barcode in BarcodeFragment.
2023-11-10 21:16:05 +01:00
Markus Fisch 35b110a472 Fix key of general format restriction preference
Makes this setting have an effect again.

I somehow forgot to update the keys in the XMLs as well.
2023-11-08 20:41:32 +01:00
Markus Fisch 58eabf4754 Update to SDK 34 2023-11-01 18:12:57 +01:00
Markus Fisch 1f273a48a5 Catch IAE when parsing a WIFI configuration
Because some arguments may be out of range.

For example, SSIDs cannot be longer than 32 characters in some
versions of Android.

See: https://github.com/markusfisch/BinaryEye/issues/402
2023-10-29 13:53:58 +01:00
solokotandGitHub 785a64725d Update Russian translation 2023-10-24 08:56:32 +02:00
Markus Fisch 7a42e1de73 Recreate binary barcodes too
Since this is easily possible now.
2023-10-23 21:11:01 +02:00
7heMechandGitHub 9856ab7b6b Add Bulgarian translation and Brave search engine 2023-10-20 14:14:36 +02:00
Markus Fisch 746ff143d8 Advance version number to 1.61.0 2023-10-13 23:49:38 +02:00
Markus Fisch b0d4d94973 Add test for a VCARD with an explicit TYPE
And make the other tests fail if null was returned.
2023-10-13 21:11:22 +02:00
Markus Fisch c604ad5ef2 Fix type regex for VCARDs
The previous regex captured just the first letter of the type argument
because it was modified to be not greedy.
2023-10-13 21:08:01 +02:00
Markus Fisch 91c2b324ac Refactor pick_file to pick_image_file
And use `pick_file` to pick any file, not just an image.
2023-10-12 22:23:27 +02:00
Markus Fisch df59fd7446 Update Kotlin and coroutines library version 2023-10-12 22:15:19 +02:00
Markus Fisch 449fd1f26c Limit read binary data for encoding
And use just the first 4096 bytes, which is way too optimistic
as there is no barcode format available that can save that much
data.

This is just to avoid an OutOfMemoryError. Maybe it's better to
just show an error message for files that are too big?
2023-10-13 13:16:24 +02:00
Markus Fisch 72d839c6e2 Support encoding binary data from a file
So binary data can finally be re-encoded too.
2023-10-13 12:48:13 +02:00
Markus Fisch ab8c993a81 Add padding for spinners on encode fragment
Enlarges the touch area and makes the spinners easier to use.
2023-10-13 11:47:36 +02:00
Markus Fisch 5f5bd913d6 Move content EditText to the top
As this is probably the most important input field.
2023-10-13 11:47:36 +02:00
Markus Fisch 92fe4dd55f Reformat code with Android Studio
And apply the latest style changes.
2023-10-12 20:32:01 +02:00
Markus Fisch dab95176f0 Remember last selected margin for generation
More convenient.

Maybe we should store these settings for each barcode format.
2023-10-12 20:29:23 +02:00
Markus Fisch 650503ba70 Update camera library to latest version 2023-10-08 20:17:58 +02:00
solokotandGitHub 61078f214e Update Russian translation 2023-10-02 13:33:45 +02:00
Markus Fisch a4b639edfe Add margin parameter for encoding barcodes 2023-09-20 13:46:34 +02:00
Markus Fisch f37878dbb8 Replace toUpperCase() with uppercase()
Because toUpperCase(Locale) is deprecated.
2023-09-19 22:19:35 +02:00
Markus Fisch 10fde7c3d6 Add intent for MIUI fingerprint shortcut
So it's possible to start BinaryEye from the MIUI of Xiaomi devices.
2023-09-19 14:46:34 +02:00
Markus Fisch a098fcb48c Always save and use rawBytes from ZXingCpp
If available.

Because the text member may already be UTF-8 encoded, and this
cannot simply be converted back into a byte array for the hex dump.

So for ContentType.GS1, ContentType.ISO15434 and ContentType.TEXT
there could be inconsistencies between the displayed content and the
hex dump, because the latter was generated from the (already encoded)
content.
2023-09-15 19:08:29 +02:00
m_s_andMarkus Fisch f162977640 Update Brazilian Portuguese translation 2023-09-03 20:18:50 +02:00
Oleg KoretskyandGitHub 66cab58d7b Fix missing Copy button for binary QRs 2023-08-31 13:54:29 +02:00
John VenessandGitHub e99e2d7dcc Update English strings 2023-08-20 11:23:53 +02:00
Sergiy StuparandGitHub 9045a27a5d Update Ukrainian translation 2023-08-14 12:00:14 +02:00
Markus Fisch 9e1208c72b Update ZXing C++ wrapper 2023-08-13 19:09:32 +02:00
Markus Fisch 90410f232a Update Kotlin version 2023-08-13 18:09:29 +02:00
ddarfantasyandGitHub 6769fa7e37 Update zh-CN translation 2023-08-13 17:50:26 +02:00
Markus Fisch 72444f5081 Update ZXing C++ wrapper 2023-07-06 12:40:12 +02:00
Markus Fisch 9a3ca4ffa3 Update ZXing C++ wrapper 2023-05-20 14:24:34 +02:00
Markus Fisch f572923720 Add changelog for latest version for f-droid 2023-05-19 18:57:15 +02:00
Markus Fisch 4971f58f44 Advance version number to 1.60.3 2023-05-19 18:55:49 +02:00
m_s_andMarkus Fisch 0bf24080a8 Update Brazilian Portuguese translation 2023-05-19 18:49:51 +02:00
Markus Fisch 04a21f71ef Update Kotlin version 2023-05-11 20:37:39 +02:00
Unknownman820andGitHub e22a215863 Update Chinese translation 2023-05-04 12:10:51 +02:00
Markus Fisch 881829e7b2 Fix saving custom language
This preference needs to be committed so it is written to disk
immediately.

Otherwise the app will restart before this preference is presisted.
2023-05-03 20:48:40 +02:00
Kryštof ČernýandGitHub 2ad261f3b6 Update Czech localisation 2023-05-01 19:25:05 +02:00
Kryštof ČernýandGitHub e0fdda78b3 Fix library name in en-US/full_description.txt 2023-05-01 19:24:42 +02:00
solokotandGitHub 9c3710c56d Update Russian translation 2023-04-28 12:11:22 +02:00
bovirusandGitHub ddcab46d47 Update Italian language 2023-04-25 21:20:15 +02:00
Markus Fisch 076da26075 Advance version number to 1.60.2 2023-04-25 19:28:27 +02:00
Markus Fisch dbc37714f9 Remember checkbox state for unescaping input 2023-04-24 23:22:00 +02:00
Markus Fisch 50e57eaf25 Expand escape sequences in encoding input
So escape sequences can be used when encoding a barcode.
2023-04-24 23:14:58 +02:00
Markus Fisch 340f7f9d1d Remove lateinit for BT members
And use safe calls (?.) instead of catching the NullPointerException.

If something can be null, we should use the appropriate type for it
to make things explicit.
2023-04-19 21:13:05 +02:00
Unknownman820andGitHub a42bd793bb Update Taiwan translation 2023-04-04 08:56:49 +02:00
KamaleiZestriandGitHub 6e531f5395 Fix crash when not connected to a Bluetooth server 2023-03-29 12:06:20 +02:00
Markus Fisch 79b3fddcf8 Set BT results from return values
So the result variables can be immutable.

And use simpler terms for their names to make this easier to
read and understand.
2023-03-28 21:28:22 +02:00
Markus Fisch 09f3c8f193 Use "when" instead of "if/else"
More Kotlin idiomatic.

Also use full words instead of abbreviations for clarity.
2023-03-28 21:26:37 +02:00
Markus Fisch 5f82f216fd Advance version number to 1.60.1 2023-03-27 22:11:43 +02:00
Markus Fisch 8424e3ea31 Add Bluetooth permissions to PRIVACY
And explain why these are required.
2023-03-27 22:05:31 +02:00
Markus Fisch 15ce34aa92 Add legacy Bluetooth permissions for SDK < 12
According to the docs, BLUETOOTH and BLUETOOTH_ADMIN are required
for Android versions below SDK 31.

See:
https://developer.android.com/guide/topics/connectivity/bluetooth/permissions
2023-03-27 22:02:09 +02:00
Markus Fisch 8dfc1e37c0 Assign sendScanBluetooth properly
getBoolean() returns the current value.
2023-03-27 21:41:42 +02:00
Markus Fisch a0d3b7ba87 Catch SecurityExc when BT permission is missing
Make sure not to crash the app because the bluetooth permission is
missing. The app should gracefully handle this situation. It's
perfectly okay when the app doesn't have the permission to use
bluetooth. This is really a very niche use-case.
2023-03-27 19:04:39 +02:00
Markus Fisch a234dc3a9a Only ask for BT permission on activation
Doesn't make sense to ask for permssion when we deactivate bluetooth.

Also simplify this code a bit.
2023-03-27 19:04:39 +02:00
Markus Fisch a00f70e25b Check bluetooth permission before using API
Without this check, the app will crash as soon as the PreferencesFragment
is initialized when the user didn't already grant Bluetooth permission.

Always make sure to check the permissions.
2023-03-27 21:17:30 +02:00
Markus Fisch ef555c0153 Disable bluetooth sending by default
This is a pretty niche use-case and so it should be disabled by
default. Especially because it requires runtime permissions.
2023-03-27 21:14:37 +02:00
Markus Fisch 9fffb53f73 Remove stray character from Italian translation 2023-03-16 23:05:13 +01:00
bovirusandGitHub b82c6200c0 Update italian language 2023-03-16 23:03:16 +01:00
solokotandGitHub 5bb347c392 Update Russian translation 2023-03-16 18:34:30 +01:00
bovirusandGitHub f8033614fa Update italian language 2023-03-16 00:23:21 +01:00
Markus Fisch 46cc2fb1a1 Make showResult an extension of Activity
And remove all the "activity." prefixes.
2023-03-15 20:57:10 +01:00
Markus Fisch f2ac1e77bb Update gradle wrapper 2023-03-15 20:53:18 +01:00
Markus Fisch 89c84880c6 Update Kotlin version 2023-03-15 20:52:58 +01:00
Markus Fisch 352fe07850 Remove useless class wrapping for BluetoothSender
Since all members and properties are static so it's more idiomatic
to make them simple top-level functions.
2023-03-15 20:51:38 +01:00
Markus Fisch 00abe33314 Add new string resources to translations
Otherwise lint will fail.
2023-03-15 20:37:30 +01:00
Markus Fisch 142df25d7e Only check BLUETOOTH_CONNECT on Android S+
This symbol doesn't exist before Android S.
2023-03-15 20:31:01 +01:00
Markus Fisch 021d775835 Clean up new additions
Fix indent, apply auto format, remove commented out code, etc.
2023-03-15 20:29:44 +01:00
KamaleiZestriandGitHub 06df0c4d64 Support sending scans via bluetooth
Makes it possible to send scanned codes to a bluetooth device.

Should work with any bluetooth receiver that shares it's UUID
of "8a8478c9-2ca8-404b-a0de-101f34ab71ae".
2023-03-15 12:09:06 +01:00
Markus Fisch 32c70af812 Remove plural for one for Korean translation
Because lint tells me it's not required for Korean.
2023-03-01 21:42:10 +01:00
Markus Fisch 7cc1777e7a Add barcode_info plurals for polish translation
With the default strings, silly enough.

Otherwise Lint will throw an error (!) because these plurals
are missing.

Now, I doubt I will ever meet the person who thought it would
be wise to throw an error if a plurals tag is missing in a
translation, but I sure hope this person will learn to make
better decisions some day.
2023-03-01 21:36:45 +01:00
Anthony RyanandGitHub 23e0564594 Losslessly compress PNG images
Using Efficient-Compression-Tool we can reduce the size by 254.17KB (15.8405%)
without changing visual appearance.
2023-03-01 21:29:50 +01:00
Markus Fisch 0447384bea Update tools and gradle wrapper 2023-03-01 12:09:59 +01:00
Markus Fisch b4d66e28e2 Fix resolving EC level letter for recreation
While ZXing C++ reports the QR Code error correction level with four
letters (following the spec), it expects the level for encoding as an
integer in a range from 0 to 8.
2023-02-28 21:09:52 +01:00
Markus Fisch ee1c56d99f Update ZXing C++ wrapper 2023-02-23 20:03:04 +01:00
Markus Fisch 33ef78443e Advance version number to 1.59.0 2023-02-22 18:37:57 +01:00
Markus Fisch 9f1e34b06d Add setting error correction for AZTEC/PDF417 too
Because ZXing C++ supports setting an error correction level for
these formats too.
2023-02-20 20:04:01 +01:00
Markus Fisch 24766f55d4 Fix setting error correction level for QR Codes
ZXing C++ expects the error correction level to be in a range from
0 to 8, so the four possible values for QR codes need to be translated
into this range.
2023-02-19 18:59:11 +01:00
Markus Fisch 0ae7d080e3 Add missing changelogs for F-Droid 2023-02-09 22:22:05 +01:00
Markus Fisch 7d8c6016db Optimize monochrome launcher icon with avocado 2023-02-09 22:19:37 +01:00
KamaleiZestriandGitHub 3d923035e3 Follow beep settings for error beeps too 2023-02-06 10:18:52 +01:00
Markus Fisch a489f3aa22 Remove finishing string resource
And show the more generic `camera_error` message instead.

This message makes no sense anymore now that the app isn't
finished.
2023-02-05 20:30:55 +01:00
Markus Fisch 7dfd7a1303 Remove finishing activity if camera is unavailable
While the camera is the main feature of the camera acitvity,
there are other features that are still useful even if the
camera is not available.

So it's better not automatically finish the camera activity
but let the user decide.
2023-02-05 18:03:32 +01:00
Markus Fisch 9abc01fc4f Advance version number to 1.58.2 2023-01-31 12:36:32 +01:00
Markus Fisch d10a33c1b7 Check string is not empty before calling last()
Because `String.last()` will throw a NoSuchElementException when
the string is empty.
2023-01-31 10:51:18 +01:00
Markus Fisch 357b2b5d59 Advance version number to 1.58.1 2023-01-31 10:51:18 +01:00
Markus Fisch dfd64405da Fix design of monochrome launcher icon
Monochrome icons don't use any color, not even black or white.
2023-01-30 18:41:56 +01:00
Markus Fisch 045daf9deb Remove committing preferences
This made only sense when this app used RenderScript, which could
cause the app to crash before settings were saved.
2023-01-25 20:31:11 +01:00
Tom XinandGitHub 46b9ef516c Update zh-rCn translation 2023-01-21 20:52:19 +01:00
Markus Fisch 0265909fd7 Advance version number to 1.58.0 2023-01-19 20:28:25 +01:00
Markus Fisch ceef92bb7c Alternate binarizers to improve detection
By default, ZXing uses LOCAL_AVERAGE, but this does not work well
with inverted barcodes on low-contrast backgrounds.

Of course, it would be better to improve ZXing's HybridBinarizer
(which is used for LOCAL_AVERAGE), but this is not trivial.
2023-01-19 20:16:49 +01:00
Markus Fisch 46785bab01 Update ZXing C++ wrapper for DecodeHints
The latest version makes all native `DecodeHints` available
to the JVM.
2023-01-19 20:12:54 +01:00
Markus Fisch ccbb0f9e8a Fix terminating string tag in italian translation 2023-01-19 18:01:27 +01:00
bovirusandGitHub 833d8e93d3 Update italian language 2023-01-19 17:53:41 +01:00
Markus Fisch 6dff9992d8 Remove META parameter from README
Since the migration to ZXing-C++ this parameter doesn't exist anymore.
2023-01-16 20:20:44 +01:00
Markus Fisch 0b3dfe93cf Silently try openUrl() for OpenOrSearchAction
Avoid using `execShareIntent()` for OpenOrSearchAction because it
will toast a message when it fails.
2023-01-11 19:21:54 +01:00
Markus Fisch e79ad49d15 Remove converting charset for PDF417
This is handled by ZXing C++ now.

Converting the text again destroys it.
2023-01-08 17:35:57 +01:00
chreddyandGitHub 38f7ba1ec6 Add Danish translation 2023-01-08 17:35:43 +01:00
NPLandGitHub 4d268240fd Update Japanese translation 2023-01-03 09:22:56 +01:00
Markus Fisch 1131f749a9 Make database migrations extension functions
Simpler and more Kotlin idiomatic.
2023-01-02 12:12:43 +01:00
Markus Fisch 93a3cd2620 Migrate version number to version string
Because ZXing C++ did switch to a String to support versions
with letters.
2023-01-02 12:10:02 +01:00
Mystery0 MandGitHub a866a2eab3 Add fillAlpha for monochrome icon 2022-12-29 13:58:22 +01:00
Markus Fisch c5d6bfa4b2 Respect setting to ignore duplicates for bulk scan
Before this, the previously scanned code was _always_ ignored for
bulk scans to avoid scanning the same code twice. But this isn't
always desirable, and the setting to ignore duplicates should have
an effect to give the user control over this behaviour.
2022-12-21 18:24:00 +01:00
Markus Fisch 6a63bc4e06 Increase the duration of the vibration
Because 100ms is too short for some devices and the vibration
cannot be felt.

This should fix https://github.com/markusfisch/BinaryEye/issues/334
2022-12-21 18:17:03 +01:00
Markus Fisch 09ff334c4c Update link on how to write a good commit message 2022-12-21 16:09:56 +01:00
solokotandGitHub 45a2ac0647 Update Russian translation 2022-12-20 13:06:40 +01:00
Markus Fisch 425f3a7b80 Advance version number to 1.57.0 2022-12-19 20:45:36 +01:00
Markus Fisch f895b42cfe Allow removing individual network suggestions
From Android R on, because `WifiManager.getNetworkSuggestions()`
is not available on Q.
2022-12-19 20:29:04 +01:00
Markus Fisch ecd4c487e3 Update pt-br translation
Thanks to m_s_
2022-12-18 12:39:05 +01:00
Markus Fisch 750671c408 Remove carriage returns from string resource 2022-12-17 13:27:24 +01:00
Markus Fisch ead856221f Update Kotlin version 2022-12-16 10:19:28 +01:00
Markus Fisch 34f14d0ff0 Update to latest ZXing C++ version 2022-12-16 10:19:28 +01:00
motive0604andGitHub 1b21297d83 Add Korean language 2022-12-13 09:38:34 +01:00
solokotandGitHub 53cb6fe007 Update Russian translation 2022-12-11 22:44:17 +01:00
Markus Fisch f1daa19056 Add optional audio feedback for scanning
And also support a couple of signal noises.
2022-12-10 13:52:39 +01:00
Markus Fisch bd9da5889c Add a semicolon to WIFI strings if it is missing
Because many generators don't terminate the expression.
2022-12-07 12:21:22 +01:00
Markus Fisch d5949e557a Add a RequiresApi annotation
To make clear `addNetworkFromBuilder` is only ever called
on Android Q+.
2022-12-06 20:09:41 +01:00
Markus Fisch 51079e5208 Update tools version 2022-12-06 20:07:55 +01:00
Markus Fisch 09f3368bf0 Update ScalingImageView library 2022-12-06 20:06:22 +01:00
Markus Fisch 84e03e3cc8 Fix typo in german translation 2022-12-06 20:03:20 +01:00
Markus Fisch cff299771a Remove resource references from vector drawables
Resource references will not work correctly in images generated
for vector icons for API < 24.
2022-12-06 20:00:43 +01:00
Markus Fisch 7a327ab7c4 Fix transferring shared text to encode fragment 2022-12-03 21:37:18 +01:00
Markus Fisch 72b8924574 Fix parsing a WiFi network on Android Q
`WifiConnector.parse()` still returned a `WifiNetworkSuggestion`
on Android Q but `WifiConnector.addNetwork()` is now expecting a
`WifiNetworkSuggestion.Builder` :8

Anyway, this code wasn't very good to start with. Having the exact
same check in two different places with the exact same meaning is
bad. This bug is a good example of that ;)

So now, `WifiConnector.addNetwork()` checks what type of object it
got and does the right thing with it.

Thanks to @JacobKochems who found this bug and made me aware of it.
2022-12-01 19:23:17 +01:00
Markus Fisch 527b7a6a59 Use deprecated WiFi API on Android Q
Because WifiManager.getNetworkSuggestions() is only available from
Android R (API level 30) on. So added network suggestions cannot be
queried on Android Q (API level 29) which will be important to allow
removing them individually.
2022-11-30 21:07:05 +01:00
Markus Fisch e9267e4e5a Accept lower case for E, PH and T in WiFi configs
While the spec demands upper case here, it's probably best to
be liberal and accept lower case values as well.
2022-11-30 12:11:29 +01:00
Tom XinandGitHub ac18733368 Update Chinese translation 2022-11-22 12:17:05 +01:00
Markus Fisch 300c3bfd26 Advance version number to 1.56.3 2022-11-21 13:04:19 +01:00
Markus Fisch 6449d9962d Simplify RegEx to recognize URLs
Because the current expression leads to an infinite loop for some
inputs. For example, this string was reported to make the app crash:
com.taobao.arthas.boot.ProcessUtils.findJavaHome(ProcessUtils.java:222)

The problem seems to be somehow related to case insensitivity as the
expression works when insensitivity is removed. Also, the infinite
loop only occurs on an Android device - not in unit tests.

Anyway, the current expression was too complex anyway, and this
simpler one should be good enough.
2022-11-21 12:37:15 +01:00
Markus Fisch 12554e63e2 Remove deep linking intent filter
Was just added to make Lint happy but is no longer necessary.
2022-11-17 19:21:28 +01:00
Markus Fisch af60ee6edb Fix indent in chinese translation 2022-11-17 16:17:20 +01:00
grenagitandGitHub fe31fc6df2 Update french translation 2022-11-17 14:07:36 +01:00
Markus Fisch 6d4f3cafbf Update pt-br translation 2022-11-14 18:06:17 +01:00
Oğuz ErsenandGitHub fa23b8078c Update Turkish translation 2022-11-13 12:49:20 +01:00
jhih_yuandGitHub e3c0fe8857 Update zh_TW 2022-11-11 09:45:58 +01:00
Markus Fisch fa568686b6 Advance version number to 1.56.2 2022-11-09 20:34:08 +01:00
Markus Fisch 304357b43c Update to latest ZXing C++ wrapper
To fix generating text output of 1D barcodes.
2022-11-09 18:27:06 +01:00
Markus Fisch 1e76b14038 Advance version number to 1.56.1 2022-11-08 20:33:08 +01:00
Markus Fisch d0777350a2 Allow pinching to size in device pixels
To allow small codes to be small on screen.

This makes it easier to use a generated barcode in place of a small
printed barcode. There are scanners out there that expect a barcode
to be of a certain (small) size.
2022-11-08 20:28:41 +01:00
Markus Fisch c7c1e74240 Update to latest ZXing C++ wrapper
To fix handling of tab characters.
2022-11-08 20:27:23 +01:00
Markus Fisch c793e1399b Fix view/frame transformation matrix
The view offset needs to be translated first - not last, where the
matrix is no longer in view space.
2022-11-08 20:27:23 +01:00
zmniandGitHub c550a6ff51 Update indonesian translation 2022-11-08 20:27:00 +01:00
solokotandGitHub 05b0f719e0 Updated Russian translation 2022-11-07 18:22:34 +01:00
Markus Fisch 4326df5069 Advance version number to 1.56.0 2022-11-03 19:05:06 +01:00
Markus Fisch ba24287f04 Update to latest ZXing C++ wrapper
To fix getting UTF-8 strings from the JVM.
2022-11-03 19:00:49 +01:00
Markus Fisch bd8f1b17dd Remove double action item for forward/next 2022-11-02 21:57:32 +01:00
Markus Fisch 2c21aeb83a Set FAB background to @null
To silence this warning:

> I/FloatingActionButton: Setting a custom background is not supported.

Details:
https://github.com/material-components/material-components-android/issues/283
2022-11-03 12:30:05 +01:00
Markus Fisch 9ccff808bc Replace properties with functions in Barcode
We should only prefer read-only properties over of functions if the
underlying algorithm…

* does not throw
* is cheap to calculate (or cached on the first run)
* returns the same result over invocations if the object state
  hasn't changed

See:
https://kotlinlang.org/docs/coding-conventions.html#functions-vs-properties

But `ZXing.encodeAs*` may throw and may also not be that cheap to
calculate. So functions are a better fit here.

Also, because these functions will always return the same result,
it makes sense to cache their outputs.
2022-11-02 21:49:08 +01:00
Markus Fisch 32e936dd71 Optimize new drawables with avocado 2022-11-02 21:06:17 +01:00
Markus Fisch 58eebacd4f Use forward arrow for FAB in picking activity
Hopefully this makes it more clear that you have to tap on the
FAB to actually read the found barcode.
2022-11-02 21:06:17 +01:00
Markus Fisch 75b945e842 Remove unused forceCompat preference
Obsolete since we use the ZXing C++ fork.
2022-11-02 21:06:17 +01:00
Markus Fisch a9ea77f74f Add an action item to lock/unlock free rotation
When scanning a barcode from an image.

Free rotation may not always be desirable.
2022-11-02 21:06:17 +01:00
Markus Fisch 3df658165b Support setting fore and background colors
When creating AZTEC, DATA MATRIX or QR Codes.
2022-11-02 21:06:17 +01:00
Markus Fisch 40a6a77b8d Advance version number to 1.55.0 2022-10-30 14:21:01 +01:00
Markus Fisch 301a33a176 Update to latest ZXing C++ wrapper 2022-10-30 14:17:18 +01:00
GiovanniandGitHub 8d6623786c Update an Italian string 2022-10-27 22:59:07 +02:00
Markus Fisch a225eab6f2 Make recreated barcode interactive
This way the barcode can easily be exported, too.

Also live update the data views and clean up the DecodeFragment.
2022-10-26 21:45:06 +02:00
Markus Fisch 9f2efeb001 Advance version number to 1.54.1 2022-10-25 22:51:11 +02:00
Markus Fisch 105c81d409 Treat GS1 and ISO15434 content types as text
And use the HRI formatted text ZxingCpp provides.
2022-10-25 22:05:29 +02:00
Markus Fisch 4e1eb28ca4 Enable auto rotate by default
With ZXingCpp this is hardly noticeable. So enable it for new users.
2022-10-24 22:07:00 +02:00
Markus Fisch b72ed746bf Go back to VIBRATOR_SERVICE for Android 4
Use the deprecated `VIBRATOR_SERVICE` on all versions to fix a
`VerifyError` on Android 4.

For reasons beyond my interests, compiling with `VIBRATOR_MANAGER_SERVICE`
leads to a very cryptic `java.lang.VerifyError: r0/b` on Android 4.
Even though this symbol is never actually used under SDK 31.

This is probably a Proguard/R8 issue, but I don't want to waste more
time just to get rid of the deprecation warning. So let's use the old
`VIBRATOR_SERVICE` and wait for Google to fix their stuff.
2022-10-24 21:57:00 +02:00
solokotandGitHub 1aaee3c85a Update Russian translation 2022-10-24 20:49:37 +02:00
Oğuz ErsenandGitHub eb0218e733 Update Turkish translation 2022-10-23 20:42:01 +02:00
GiovanniandGitHub bef7365f28 Update Italian translation 2022-10-22 21:25:50 +02:00
Markus Fisch c72b6a2e5f Advance version number to 1.54.0 2022-10-21 23:39:30 +02:00
Markus Fisch a7e358852c Complete search engines for fa locale 2022-10-21 23:33:34 +02:00
Markus Fisch 7cf8cbe6d8 Recreate barcode on result fragment
It's sometimes very helpful to easily recover read barcodes.
2022-10-21 23:31:30 +02:00
Markus Fisch e379e55570 Use new Html.fromHtml() on Nougat+ 2022-10-21 22:41:53 +02:00
Markus Fisch a55795a7b6 Use new getParcelable() method on Tiramisu+ 2022-10-21 22:40:34 +02:00
Markus Fisch 83c0cd0293 Only use EXTRA_IS_SENSITIVE on Tiramisu+
And clean up that Pyramid of Death.
2022-10-21 21:23:30 +02:00
Markus Fisch d138148cb8 Refactor string extension functions
And put them where they belong instead of having a dump file.

According to the Kotlin Coding Conventions we should avoid creating
files just to hold extensions.
2022-10-21 21:14:52 +02:00
Markus Fisch c3c08879e0 Move ellipsize() from Toast to Data
Because it's used in more than one place now.
2022-10-21 17:25:17 +02:00
Markus Fisch d0f02faca7 Add german domains for search engines
To open the .de domains for Google, ebay, Amazon, etc.
2022-10-21 19:33:01 +02:00
Markus Fisch c9db3514d1 Add ebay, Amazon and barcodelookup.com
To the list of search engines.
2022-10-21 19:31:35 +02:00
Markus Fisch f2a0e1a392 Add changelogs for F-Droid 2022-10-20 21:39:40 +02:00
Markus Fisch f4de041407 Advance version number to 1.53.1 2022-10-20 09:38:36 +02:00
Markus Fisch 73ba2914e8 Fix proguard configuration for ZXing C++ 2022-10-20 09:37:45 +02:00
Markus Fisch 2907c8c49c Advance version number to 1.53.0 2022-10-19 22:27:21 +02:00
Markus Fisch f28f956a8d Only generate barcode output when required 2022-10-19 21:45:15 +02:00
Markus Fisch 972eb6a0b0 Update to latest ZXing C++ wrapper 2022-10-19 21:43:48 +02:00
Markus Fisch 08bb3f2127 Replace RelativeLayout with LinearLayout
In decoding fragment.

All children were layed out linearly anyway and it's simpler
and more clear this way.
2022-10-19 19:54:33 +02:00
Markus Fisch b28e939f58 Refactor resolveFormat() and make it an extension 2022-10-19 13:04:48 +02:00
solokotandGitHub 2edb8112b7 Update Russian translation 2022-10-19 13:04:06 +02:00
Markus Fisch cf5a6dc8b8 Hide setting a custom locale from API 33 on
Android 13 allows to set per-app language preferences, so this
setting is no longer required from there on.

See:
https://developer.android.com/guide/topics/resources/app-languages
2022-10-15 18:43:40 +02:00
Markus Fisch 3ec6f18fe0 Hide sensitive content from clipboard
At the moment, this affects just the WiFi password.

See:
https://developer.android.com/about/versions/13/behavior-changes-all#copy-sensitive-content
2022-10-15 18:38:14 +02:00
Markus Fisch 3a8f6cb827 Target SDK 33, Android 13 2022-10-15 18:37:49 +02:00
Markus Fisch 65c7fe52ee Fix closing Cursor's below JELLY BEAN
Unfortunately, Cursor cannot be cast to Closeable below API level 16
JELLY BEAN. So we can't just use Kotlin's ".use" extension function
because it would implicitly cast Cursor to a Closeable.

So this adds a simple drop-in replacement that does exactly what ".use"
is doing but without casting Cursor.

Of course, this should be removed as soon as minSDK is increased to at
least JELLY_BEAN.
2022-10-13 23:02:32 +02:00
Markus Fisch 5d3b3eb195 Fix generating a date time string below API 18
Before API level 18, there was no 'H' but only 'k', which was
incorrectly implemented to produce what we now know as 'H'.
2022-10-13 22:39:52 +02:00
Markus Fisch 0e4c2963a5 Catch ParseException when parsing scan dates 2022-10-13 22:38:04 +02:00
Markus Fisch 791c50cd4a Update build tools 2022-10-13 22:37:00 +02:00
Markus Fisch c04b08ab87 Update to latest ZXing C++ wrapper
Which adds a ContentType so we can distinguish between text
and binary content.
2022-10-12 21:47:54 +02:00
Markus Fisch f07c4ac0f4 Update to latest Kotlin and coroutines version 2022-10-11 23:43:30 +02:00
Markus Fisch 05d63bd73f Fix vector image fill color for API < 21
`fillColor` cannot have Android resources below API 21.
2022-10-11 23:37:29 +02:00
Markus Fisch 558fd5212d Remove double support annotation 2022-10-11 23:34:54 +02:00
Markus Fisch b918be76e4 Fix getting version number from database 2022-10-11 23:33:59 +02:00
Markus Fisch 2136a8c73e Show version code for all supported barcodes
And the module count if it's a QR Code.
2022-10-11 23:29:59 +02:00
Markus Fisch 959c6e7d4d Always show QR Code version and remove setting
This comes no longer with a cost so it can be always there.
2022-10-11 23:02:47 +02:00
Markus Fisch 50930d07a6 Show binary data placeholder in edit name dialog
To show something instead of nothing in the dialog title.
Still not perfect, of course.
2022-10-11 22:47:14 +02:00
Markus Fisch 36e7aab27c Update to latest ZXing C++ AAR
Fixes getting HRI formatted result text instead of the real thing.
2022-10-11 22:39:14 +02:00
Markus Fisch bb4fc8ed08 Enable multi-select in history listing 2022-10-11 21:53:15 +02:00
Markus Fisch 7a33ebd1a3 Remove MicroQR from list of writable codes
ZXing C++ doesn't contain a writer for this format, yet.
2022-10-11 20:41:18 +02:00
solokotandGitHub c8444b8935 Update Russian translation 2022-10-10 12:22:06 +02:00
Markus Fisch 4c6d66a4aa Migrate to ZXing-C++
Replace the ZXing Java implementation with the C++ fork.

The C++ fork is faster, actively maintained and supports the MicroQR
Code barcode format.

The original Java implementation is in "Maintenance Mode Only",
what means that no new features or barcodes will be accepted.

Because the C++ fork is much faster, we can now drop RenderScript
which has been deprecated by Google anyway. Also, this removes a lot
of complications. RenderScript was never very robust.
2022-10-09 18:46:50 +02:00
Markus Fisch 39f95a1c04 Remove shortcut extra from EncodeFragment
And make it possible to open the EncodeFragment without content.
2022-10-04 21:19:47 +02:00
Markus Fisch 9e30b108e7 Reformat code and optimize imports
Let Android Studio clean up.
2022-09-29 18:42:00 +02:00
Markus Fisch 1b6b1cefe3 Convert charset for PDF417 in an extension
And run it from PickActivity too to apply this conversion when
scanning from still images too.
2022-09-29 18:39:01 +02:00
Mladen MilinkovicandGitHub b634370a0b Fix PDF-417 UTF-8 text encoding
This fixes reading PDF-417 barcodes containing international UTF-8 characters.
2022-09-29 18:23:07 +02:00
gonandGitHub f32d44c3a1 Update spanish translation 2022-09-27 20:59:12 +02:00
Markus Fisch 2e060d1ca8 Add Persian to list of custom languages
That can be changed in the app independently from the system settings.
2022-09-11 23:01:31 +02:00
Andreas KorbandGitHub 6acdce32f2 Add multidex dependency
Required on some systems/Android Studio versions.
2022-09-10 21:33:04 +02:00
Markus Fisch 092ec694f6 Fix terminating string tag in persian translation 2022-09-10 19:12:03 +02:00
7fed7877a0 Add persian translation
Co-authored-by: eshagh79 <eshagh094@gmail.com>
2022-09-10 19:09:05 +02:00
Markus Fisch b17393d5ef Invert plain text output
Because plain text will most likely end up being black text on a
white background on a mobile device.

But with night mode we can never be sure. So there's an "inverted"
parameter now if the text is bright on a dark background.
2022-08-21 00:36:49 +02:00
Markus Fisch 319ae53b3b Make conditional an argument
To avoid the repetition of the function invocation.

Also make bt a constant variable because it can be.
2022-08-20 19:03:29 +02:00
Markus Fisch 6a47a7e477 Fix indent of new code for generating text output
We're not mixing tabs and spaces.
2022-08-20 18:56:50 +02:00
Tom XinandGitHub 19fb733182 Improve plain text output of generated barcodes
Optimize the 'save as text' function to make its results more recognizable when
printing on the console.
2022-08-20 18:53:43 +02:00
Markus Fisch ce6c6f26d2 Advance version number to 1.52.0 2022-08-10 23:25:46 +02:00
Markus Fisch 3633af5e0a Fix parsing timezone in calendar dates
And add patterns for RFC 822 and ISO 8601 formats.

Before this 'Z' was quoted and therefore just a string in the pattern.
So the time zone was actually never really applied to the resulting date.
Now, it's pattern letter and the resulting date is adjusted accordingly.

This also fixes using dates without a time zone.
2022-08-10 23:07:17 +02:00
87502f7226 Update translation (#280)
* Syntax correction (omitted point)

* Update french translation

Co-authored-by: Grena <grena@grenabox.fr>
2022-06-22 13:30:53 +02:00
Markus Fisch f4af35ad46 Advance version number to 1.51.1 2022-06-16 16:51:39 +02:00
Markus Fisch 60f0d8bd87 Convert result text with ISO_8859_1 encoding
Important to suppress UTF-8 encoding.
2022-06-16 16:45:31 +02:00
Markus Fisch 1ccfcfcb8f Advance version number to 1.51.0 2022-06-16 13:37:44 +02:00
Markus Fisch 213689e9f9 Improve syntax for DP link generation 2022-06-16 13:30:07 +02:00
Markus Fisch 6e2f2cab92 Make drawing functions extensions in DetectorView
Because it's more idiomatic.
2022-06-16 13:20:32 +02:00
Markus Fisch 4b3d745154 Add and improve a few comments 2022-06-16 13:20:12 +02:00
Markus Fisch a2bcd67568 Use logical operator instead of bitwise 2022-06-16 13:19:14 +02:00
Markus Fisch 072eec5306 Simplify setting handleActive flag
And make sure it's false if handlePos is invalid.
2022-06-16 13:17:16 +02:00
ZahnstocherandGitHub d505c6b07d Add stamp tracking number 2022-06-14 18:41:41 +02:00
GiovanniandGitHub dbfbaab030 Update Italian translation 2022-06-14 14:26:07 +02:00
Markus Fisch 3d1402add4 Fix XML for zh-rCN translation 2022-06-12 20:29:20 +02:00
yzqzssandGitHub 1d2bd8d778 Update zh-rCN translation 2022-06-12 20:22:11 +02:00
Markus Fisch 2bb413e3e8 Add tests for MATMSG format 2022-06-07 20:43:15 +02:00
Markus Fisch 75a59bc3e9 Fix setting Intent.EXTRA_EMAIL for MatMsg contents
Remember, this must be an array.
2022-06-06 20:59:03 +02:00
inkhornandGitHub 9a15bf0871 Update ptbr translation including meta data 2022-05-31 20:28:03 +02:00
Markus Fisch 53248fd23d Allow free image rotation in pick activity
To make it easy to recognize barcodes at odd angles.
2022-05-23 23:33:23 +02:00
Markus Fisch 1dde8c2817 Advance version number to 1.50.0 2022-05-18 22:48:58 +02:00
Markus Fisch 57fea95b9b Add support for MATMSG format 2022-05-18 22:37:56 +02:00
solokotandGitHub 806dafbecd Updated Russian translation 2022-05-18 12:11:14 +02:00
Markus Fisch 44b788fa74 Add a setting to show the QR Code version
Which is determined by recreating the QR Code.

Knowing the exact version of a given QR Code can be useful sometimes.
2022-05-17 19:03:03 +02:00
ss11mikandGitHub 9f167e7a2b Update Czech translation
Add Czech translation for new strings and update some old ones
2022-05-15 13:25:46 +02:00
Markus Fisch 6852b65239 Recognize URLs in colloquial, incomplete form too
So "google.com" is recognized as web action.
2022-05-14 12:50:22 +02:00
Markus Fisch 3d7c9be7ba Update Kotlin version 2022-05-12 22:40:03 +02:00
Markus Fisch f9401a9dda Migrate to lint from lintOptions 2022-05-12 22:40:03 +02:00
Markus Fisch 79dd48b07a Move package from Android manifest to build files
Declaration of a project's namespace using the package attribute
of the Android manifest is deprecated in favour of a namespace
declaration in build files.
2022-05-12 22:40:03 +02:00
Markus Fisch 6a7ab2c6e5 Update build tools and gradle wrapper 2022-05-12 22:40:03 +02:00
NickoriginalandGitHub c76d96cbe4 Update Russian translation 2022-05-12 22:39:23 +02:00
Markus Fisch e1b3935659 Add timezone offset in calendar dates
VCalendar/VEvent dates may contain a timezone that was not actually
used, as Date.getTime() returns the number of milliseconds (since
January 1, 1970, 00:00:00 GMT) without taking the timezone into
account.
2022-05-09 21:47:51 +02:00
Markus Fisch b7a4db5f4b Update to latest ZXing version 2022-05-02 18:54:30 +02:00
Markus Fisch f23414b003 Remove unused getLinks() function
No longer used.
2022-04-30 20:25:06 +02:00
Markus Fisch 282d2499a8 Shorten encoding a barcode 2022-04-25 20:17:53 +02:00
Markus Fisch a6cc8ed32f Add sample for AndroidX Activity's to README
Because `startActivityForResult()` is deprecated there.
2022-04-25 18:11:12 +02:00
Markus Fisch 7b155369fd Fix closing end tag in Japanese translation 2022-04-24 15:16:54 +02:00
NPLandGitHub 55a69db2c5 Update Japanese translation 2022-04-24 15:14:17 +02:00
Balázs ÚrandGitHub 170878a795 Update Hungarian translation 2022-04-17 11:15:11 +02:00
Markus Fisch 18ade0fe33 Update icon and feature graphic for F-Droid 2022-04-10 13:30:37 +02:00
Markus Fisch 4565848344 Add changelog for latest version for f-droid 2022-04-08 12:12:37 +02:00
Markus Fisch 353e1b5494 Update tools version 2022-04-08 12:11:25 +02:00
Markus Fisch 9986a4ffb5 Advance version number to 1.49.2 2022-04-08 12:09:43 +02:00
Markus Fisch c464b7de02 Optimize latest vector drawables with avocado 2022-04-07 22:48:46 +02:00
Markus Fisch e588405413 Change icon design
Because Google thinks my original design would "impersonate someone
else".

I have absolutely no idea.

Well, in order to make the app available again as soon as possible,
and because there have already been complaints about the icon not
being "intuitive", and because it's probably pointless to argue with
Google's bots and minions, I'm just changing the design a bit.
2022-04-07 22:47:31 +02:00
mezy sincandMarkus Fisch fdaf20fd45 Fix pt-br translation 2022-04-02 19:32:33 +02:00
mezy sincandMarkus Fisch 7c8fdb8ea1 Update pt-br translation 2022-04-02 13:53:54 +02:00
Markus Fisch bb9d556c16 Advance version number to 1.49.1 2022-03-31 20:50:50 +02:00
VixbandGitHub 9e395d1928 Update Simplified Chinese translation 2022-03-31 19:11:01 +02:00
Markus Fisch 95f12e7c31 Return directly to caller for deep links
If this app was invoked via a deep link, but without a return URI,
we never want to return to the camera screen after scanning, but
to the caller.
2022-03-30 20:11:44 +02:00
Markus Fisch 9dac0b13fb Fix getting ORIENTATION member from meta data
Was UPC_EAN_EXTENSION instead.
2022-03-30 19:57:00 +02:00
Markus Fisch 7939a728bc Make isReturnUrl() a String extension
And thereby remove Intent from the scope of the function.
2022-03-30 19:51:19 +02:00
Markus Fisch b6ca20d813 Move Cursor extensions to a separate file 2022-03-30 19:48:43 +02:00
Markus Fisch fe7e36804e Advance version number to 1.49.0 2022-03-29 19:56:31 +02:00
Markus Fisch 8cf1c35029 Enable forwarding by default
To keep forwarding intact when updating an app.

This has no effect for new installations because initially there's
no forwarding URL set. Forwarding works only when this toggle is
enabled *and* if there was a forwarding URL set.
2022-03-29 19:44:05 +02:00
Markus Fisch 62ca2299a0 Clean up preprocessor test
And move creating RenderScript out of loop.

No need to re-create this for every sample.
2022-03-25 20:10:43 +01:00
Markus Fisch 2423586c8c Make Y in encodeYUV420SP() lower case
To comply with the Kotlin style guide.

And simply use s/t for x/y.
2022-03-24 19:49:21 +01:00
Markus Fisch 29b1f44bb9 Update getting Vibrator on Android S+
VIBRATOR_SERVICE is deprecated.
2022-03-24 19:18:36 +01:00
Markus Fisch acee18e016 Replace context getter with local variable
It's there anyway and we shouldn't run a function multiple times
where it's enough to do it once and go with the result.
2022-03-21 22:39:21 +01:00
Markus Fisch f798dce832 Make setZoom() a Camera extension 2022-03-21 22:31:09 +01:00
Markus Fisch 97838ec7c4 Remove unnecessary type declarations 2022-03-22 13:51:27 +01:00
Markus Fisch 767860ab07 Remove body of decodeLuminanceSource()
And use the single expression syntax instead.
2022-03-22 13:51:27 +01:00
Markus Fisch f8fd00f21b Use apply scope function to set ContentValues
A bit more elegant.
2022-03-22 13:51:27 +01:00
solokotandGitHub 2cf6aa0812 Update Russian translation 2022-03-22 12:00:31 +01:00
Markus Fisch 197554fd1b Add a toggle to quickly enable/disable forwarding
Easier than clearing the URL, especially if you want to keep the
URL for later.
2022-03-21 21:56:06 +01:00
Markus Fisch 3dc35ac60d Only play error peep when not in silent mode
The app shouldn't play any sound when the phone is set to silent.
2022-03-21 21:33:42 +01:00
Markus Fisch fd05209f57 Enable/disable torch mode according to parameters
And show an error toast in case setting flash parameters fails.
2022-03-21 19:48:59 +01:00
Markus Fisch 6d5aed816f Break very long lines in IAction
Improves readability for my taste.
2022-03-18 20:44:55 +01:00
Markus Fisch 268c395043 Configure new Intent with apply scope function
Instead of declaring a variable beforehand.
2022-03-18 20:41:36 +01:00
Markus Fisch 867dc36811 Desugar Java 8 language features for ZXing 3.4
Add desugaring support to reverse translate Java 8 language features
in order to use the latest ZXing without having to increase minSdk.

ZXing 3.4 doesn't work on SDK levels below 24 anymore, see:
https://github.com/zxing/zxing/issues/1170

Many thanks to @TheLastProject for showing me the way:
https://github.com/CatimaLoyalty/Android/commit/cbcf1bcd998b9a5fdf7354a4287c64e95f2c3845
2022-03-16 21:44:20 +01:00
Markus Fisch e6e9b912b6 Improve german translation 2022-03-15 20:15:15 +01:00
Markus Fisch 152b4e50fc Update Kotlin version 2022-03-15 20:15:02 +01:00
Markus Fisch 93070f38c9 Update Kotlin coroutines library 2022-03-15 20:14:39 +01:00
Markus Fisch 7a162d6fb0 Update JUnit version 2022-03-15 20:14:15 +01:00
solokotandGitHub 9c03e83d3a Update Russian translation 2022-03-15 09:28:44 +01:00
Markus Fisch 4be9421b44 Advance version number to 1.48.1 2022-03-11 15:21:16 +01:00
Markus Fisch b895997967 Fix broken detection of binary content
And simplify detection and handling of binary data.
2022-03-11 15:16:43 +01:00
Markus Fisch b5bbe659db Advance version number to 1.48.0 2022-03-10 12:04:34 +01:00
Markus Fisch bb7715455a Add an item to remove the format restriction
If it is set.
2022-03-09 19:53:37 +01:00
Markus Fisch 5283acee8f Add a menu item to restrict recognized formats
Only temporarily as long as the instance is used.

This allows to quickly restrict scanning to a certain format
without having to fiddle with all the formats in settings.
2022-03-09 19:47:33 +01:00
Markus Fisch 315abfb1dd Show alnum characters in binary data
And condense all non-alnum characters to just "…".

This may give a glimpse at the readable content and is probably
better to read than the hex dump for non-technical users.
2022-03-09 18:57:58 +01:00
Markus Fisch 05c776168e Make parseAndNormalizeUri() an extension function 2022-03-09 18:46:58 +01:00
Markus Fisch 880b8e0b24 Catch unsupported encodings in urlEncode()
And just return the original string in that case.

Invalid data shouldn't crash the app.
2022-03-09 18:43:33 +01:00
Markus Fisch 1597adb284 Fix showing binary data label for history scans
A scan's (String) "content" will be an empty string when read
from the database because I don't want to save the content twice
(binary data is already saved in the "raw" field).
2022-03-09 18:39:32 +01:00
Markus Fisch 1c356aeaed Update tools version 2022-03-09 18:37:16 +01:00
Markus Fisch fe934c5d6e Use AlertDialog from base SDK
Instead of the support variant.

There's no need to use the special variant from the support library.
2022-03-09 18:34:17 +01:00
Markus Fisch 5091565ff0 Make preference constants private
Because they can be.
2022-02-26 12:48:22 +01:00
Markus Fisch c7eb664958 Add a monochome launcher icon
As required for SDK 32, Android 13.
2022-02-21 19:48:08 +01:00
Markus Fisch c763c522e7 Update to SDK 32 2022-02-21 19:47:53 +01:00
Markus Fisch dc1beb5f28 Add new data extraction rules configuration
There's a new XML format for Android 12+.
2022-02-21 19:43:07 +01:00
Markus Fisch 76ea46cea8 Split data tag for VIEW intent filter
According to lint, it's better to have multiple tags with
individual attributes because it better "communicates the
combining behavior and is clearer".
2022-02-21 19:35:00 +01:00
Markus Fisch 0991fb85f0 Remove redundant label from activities 2022-02-21 19:30:57 +01:00
Markus Fisch 09f0d2e1db Remove unused quantity translations
According to lint, these quantities are not relevant.
2022-02-21 19:29:27 +01:00
Markus Fisch bc0655788c Add "many" plural for french translation
As required by the linter.
2022-02-21 19:24:57 +01:00
Markus Fisch 739a801cb4 Add "many" plural for czech translation
As required by the linter.
2022-02-21 19:23:50 +01:00
Markus Fisch c18f1b8770 Simplify Bitmap.saveAsPng() function 2022-02-19 18:37:13 +01:00
Markus Fisch b0df09d76f Simplify the execShareIntent function 2022-02-19 18:36:14 +01:00
Markus Fisch e8b8e578cb Fix handling empty meta strings
Check if the data is empty and not just null.

And prepare WiFi info like we do it for meta info.
2022-02-10 22:20:54 +01:00
Markus Fisch 09ce14125e Use apply scope function to use ViewHolder
And thereby avoid a temporary variable.

Also make getViewHolder() a bit more compact by using the
single-expression function syntax.
2022-02-10 19:48:12 +01:00
Markus Fisch 446d1543c3 Refactor Scan.timestamp to Scan.dateTime
Because it's really just a string containing the date and time
and not a timestamp in the sense of a Unix timestamp.
2022-02-08 19:23:33 +01:00
Markus Fisch 02a360beaf Refactor getRawBytes() to getRawData()
And make it an extension of Result.
2022-02-08 19:19:49 +01:00
Markus Fisch 9742e5b790 Give signing configuration a proper name
"config" isn't a very good name for a configuration.

These is the release configuration, so we should name it accordingly.
2022-02-07 20:38:55 +01:00
Markus Fisch 9c08aa1184 Update build tools 2022-01-27 23:01:57 +01:00
Markus Fisch ce8a5f89cd Remove buildToolsVersion as it's optional now
Since Gradle 3.0, the specification of "buildToolsVersion" in
"app/build.gradle" is optional.
2022-01-27 23:01:57 +01:00
Oğuz ErsenandGitHub 50795afeb4 Update Turkish translation 2022-01-27 23:01:40 +01:00
Markus Fisch b8c941ee62 Make sure to return a String and not null
Cursor.getString(int) may return null so this case needs
to be dealt with.
2022-01-26 16:44:40 +01:00
Markus Fisch 5b1738342d Ignore lint warning about the custom splash screen
Androidx SplashScreen compat library would require minSdk 21,
make the app unnecessarily larger and Android 12 automatically
replaces our custom splash screen anyway, which is exactly what
we want. So there is no reason to complain.

The migration guide says about our kind of splash screen:

> If your existing splash screen is implemented using a custom
> theme that overrides android:windowBackground, the system replaces
> your custom splash screen with a default Android system splash
> screen on Android 12 and higher (which may not be your app’s
> intended experience).

Source:
https://developer.android.com/guide/topics/ui/splash-screen/migrate

This is not only the intended but desired experience for this app.
2022-01-26 11:28:37 +01:00
Markus Fisch 004738440c Check return value of getColumnIndex() before use
To silence the Range lint error.

getColumnIndex() can return -1 which isn't suitable for
Cursor.get[Blob|Long|String]().

IMHO this is a quite useless, maybe even dangerous, lint error.
This kind of error should only happen in development where I
want to break things to see the problem. Now, using a wrong
name or asking for a non-existent column doesn't result in an
exception and is masking the problem.
2022-01-26 11:04:05 +01:00
Markus Fisch a90aee570a Ignore lint warning about ACCESS_COARSE_LOCATION
Android 12 requires apps that request ACCESS_FINE_LOCATION
to also request ACCESS_COARSE_LOCATION. But this app doesn't
request nor requires ACCESS_FINE_LOCATION above SDK 28.

So this is a false positive and we're ignoring it.
Hopefully, this will be fixed in future updates.
2022-01-25 18:38:12 +01:00
Markus Fisch 17f2f88b7f Update to SDK 31 2022-01-25 18:35:47 +01:00
Markus Fisch 071ea1500f Replace fraction string with fraction character
Using dedicated characters makes the text more readable.
2022-01-25 18:33:36 +01:00
Markus Fisch 25b142407b Explicitly set android:exported
As of Android 12, android:exported must be set.
2022-01-25 18:33:22 +01:00
Markus Fisch 848b4bbaa8 Upgrade gradle wrapper 2022-01-18 21:37:24 +01:00
Markus Fisch c2dc8984c1 Update syntax of zxing auxiliary functions 2022-01-18 21:23:09 +01:00
Sergiy StuparandGitHub e37a4d21ea Update Ukrainian translation 2022-01-13 18:41:49 +01:00
MastiggiaandGitHub da2a20ba1f Update the French translation 2021-12-29 22:32:44 +01:00
kwiateuszandGitHub 5fe69e5a3d Update Polish translation
And fix typo in english texts.
2021-12-27 16:19:30 +01:00
solokotandGitHub f50e1dab0a Updated Russian translation 2021-12-25 19:20:44 +01:00
Markus Fisch b165192377 Advance version number to 1.47.0 2021-12-23 20:34:15 +01:00
Markus Fisch c0a4d67cc5 Add new scan type to open data directly in browser
This way Binary Eye can also be used as a front-end to your own
website that deals with the scanned content directly.

This is of course the same as adding a URL for unknown content and
picking it from the dialog. However, this requires two taps and is
therefore more suitable for unusual use.
2021-12-23 18:32:23 +01:00
Markus Fisch ef36a2f7e0 Unify URL encoding with a String extension 2021-12-23 18:26:01 +01:00
Markus Fisch 40b90e0be2 Make hasNonPrintableCharacters() an extension 2021-12-23 17:49:46 +01:00
Markus Fisch 680030e89e Simplify opening URLs in external browser
So we can use `openUrl()` from anywhere now.
2021-12-23 17:49:46 +01:00
Markus Fisch b4fefad54f Improve readability with a traditional null check
Sure, this can be expressed more briefly, but not more comprehensibly.
2021-12-23 17:49:46 +01:00
Markus Fisch f65e942100 Break long expressions
For better comprehensibility. Should've done this a long time ago.
2021-12-23 17:49:46 +01:00
Markus Fisch 95d7a84648 Reset visibility of zoom bar
It needs to be made visible again after making it invisible.

Happens when one of the cameras doesn't support zooming.
2021-12-20 19:57:14 +01:00
Markus Fisch 1e4a0fde7a Make links to permissions references
So PRIVACY can be read in the shell.
2021-12-16 22:44:33 +01:00
Markus Fisch a6785d500e Update changelogs for F-Droid 2021-12-15 21:22:03 +01:00
Markus Fisch d77e464554 Advance version number to 1.46.3 2021-12-15 21:20:49 +01:00
Markus Fisch d7198934d7 Make fragment functions extension functions 2021-12-15 19:05:51 +01:00
Markus Fisch 1a3b3f263f Make bitmap editor functions extensions 2021-12-15 10:30:22 +01:00
Markus Fisch d4c5c6a1dc Fix cropping still images
Can't use Rect.width()/.height() with negative left/top values
because these get cropped at 0/0 of course.

Before this commit, the cropped image was larger than it should be.
2021-12-15 10:27:15 +01:00
Markus Fisch 8618a5b482 Avoid modifying ROI when scanning in PickActivity
detectorView.roi was modified by Rect.intersect() so we
need to make a copy to keep the currently selected ROI.
2021-12-15 10:22:42 +01:00
Markus Fisch 6cb65635e3 Update changelogs for F-Droid 2021-12-14 21:40:30 +01:00
Markus Fisch 5e37ff41d6 Make r/w byte array functions of Scan extensions 2021-12-14 21:37:23 +01:00
Markus Fisch 03ac3ff0e9 Make export and file saving functions extensions 2021-12-14 21:36:28 +01:00
Markus Fisch 480a248e71 Make restart functions extensions 2021-12-14 21:31:01 +01:00
Markus Fisch b4060d70ce Make permission functions extensions too 2021-12-14 21:30:37 +01:00
Markus Fisch 7ceb97e942 Make sharing functions Context extensions
Makes things simpler and more clear.
2021-12-14 21:27:37 +01:00
Markus Fisch 7100f79efc Use explicit CoroutineScope instead of GlobalScope
We shouldn't use GlobalScope directly because it can't be cancelled.
2021-12-14 18:56:23 +01:00
Markus Fisch 00a1ec877b Explicitly trim margin of SQL queries
And clean up helper functions.
2021-12-14 18:55:23 +01:00
Markus Fisch 89e029687b Cancel scanning if rectangles do not overlap
When scanning from an image. In reality, the rectangles will
always overlap but Android Studio can't know that so it's better
to add a safe guard.
2021-12-14 18:53:38 +01:00
Markus Fisch 5f4f18a062 Move zoom slider up and increase spacing around it
And center it with the FAB.

This should improve the usability because the slider should
now be a bit easier to grab. Also, it should interfere less
likely with gesture navigation.
2021-12-14 18:53:17 +01:00
Klaas SwartandMarkus Fisch 69ec2cda04 Update Dutch translation 2021-12-14 18:51:50 +01:00
anenasaandGitHub 4aba885fb6 Update zh-TW translation 2021-12-13 20:30:01 +01:00
Markus Fisch 9dbb78ce67 Advance version number to 1.46.2 2021-12-10 19:52:21 +01:00
Markus Fisch 47c252ab18 Fix requesting write permissions on Q and above
Requesting WRITE_EXTERNAL_STORAGE is only required before Android Q.
2021-12-10 19:45:50 +01:00
Markus Fisch 10e02b3164 Update tools version 2021-12-10 19:45:45 +01:00
Markus Fisch 7e82dbe730 Update changelogs for F-Droid 2021-12-06 19:43:55 +01:00
Markus Fisch e91c30f7c2 Advance version number to 1.46.1 2021-12-06 19:42:38 +01:00
Markus Fisch 30a36e7e07 Update Kotlin version 2021-12-04 19:35:54 +01:00
Markus Fisch 5f91fe2f02 Fix setting number of coordinates in DetectorView
mapResultToView() already gives the number of components (in
the target array), not points. So this number doesn't need to
be doubled.
2021-12-04 19:06:12 +01:00
Markus Fisch cab8d6c038 Restore/save crop limiter settings in PickActivity
Use the same setup that the user configured (in CameraActivity)
in PickActivity, too. There's no good reason to change the
scanning experience for scanning from an image.
2021-12-04 18:58:23 +01:00
Markus Fisch 4aac5dc61b Remove extra link on result screen
Because the very same functionality is already available with
the FAB, which is the default action for all content that can
be opened or shared.

I don't like having an extra element just for URLs that doesn't
add anything over the already available default action button.

So I tried, but I just don't like it. Sorry.

This reverts commit 9fb2eb2d2b.
2021-11-27 17:45:15 +01:00
Oğuz ErsenandGitHub fbbc20d327 Update Turkish translation 2021-11-25 18:45:24 +01:00
Markus Fisch 5595b68ff4 Update changelogs for F-Droid 2021-11-13 15:46:33 +01:00
Markus Fisch c492897fa9 Advance version number to 1.46.0 2021-11-13 15:45:30 +01:00
Markus Fisch 647c08bfb8 Add documentation for Deep Links and SCAN intent 2021-11-13 15:31:39 +01:00
Markus Fisch e5025ef58c Support deep links
To open the app from web links.
2021-11-12 23:54:19 +01:00
inkhornandGitHub 74bb421b2d Update pt-br translation 2021-11-08 21:47:23 +01:00
Markus Fisch 4ed8d4614a Update tools version 2021-10-28 13:51:01 +02:00
Markus Fisch f038eb989b Remove double setting WPA passphrase
It's already set in the enterprise configuration.
2021-10-25 21:11:08 +02:00
Markus Fisch c5722a3890 Collapse setting WPA passphrases in one line 2021-10-25 21:11:08 +02:00
Sergiy StuparandGitHub 41108007ad Update Ukrainian translation 2021-10-18 12:56:11 +02:00
Markus Fisch 867f179a37 Add support for "A:" in WIFI codes
Anonymous Identity may be "A" or "AI".
2021-10-17 19:19:49 +02:00
Markus Fisch 892916b0d0 Catch exception when passphrase isn't encodeable
And ignore WiFi codes that have passphrases that aren't ASCII
encodeable.
2021-10-15 21:23:37 +02:00
Markus Fisch 3bd440fdb7 Update tools version 2021-10-07 22:53:03 +02:00
Markus Fisch a4c8551be8 Clean up new code 2021-10-07 20:38:28 +02:00
Markus Fisch 316644d3ae Allow multiple query arguments in custom URL 2021-10-07 20:28:07 +02:00
Damir RakhimulinandGitHub 9fb2eb2d2b Add visual support for links after scanning 2021-10-07 20:23:07 +02:00
solokotandGitHub dd046a5d52 Russian translation for missing Wi-Fi info support 2021-10-07 12:13:32 +02:00
Balázs ÚrandGitHub f3ddd458cb Update Hungarian translation 2021-10-06 09:39:21 +02:00
Markus Fisch 157d928620 Add missing translations for Wi-Fi info support 2021-10-05 12:22:04 +02:00
Ngô Ngọc Đức HuyandGitHub 94cb509f0b Add Vietnamese translation 2021-10-05 12:15:27 +02:00
Sylvia van OsandGitHub df18f8ebd3 Add content data section
Initially with only Wi-Fi info support, but could be extended in the
future.
2021-10-05 12:15:11 +02:00
solokotandGitHub 705095472f Update Russian language 2021-09-30 19:50:25 +02:00
Markus Fisch f897973b3f Update changelogs for F-Droid 2021-09-29 22:28:59 +02:00
Markus Fisch c88d5cf4cd Advance version number to 1.45.0 2021-09-29 22:25:18 +02:00
Markus Fisch 8ecd49731f Add a setting to set the delay for bulk mode
As requested.
2021-09-29 22:21:15 +02:00
Markus Fisch 6f3b4dbdab Update build tools and Kotlin version 2021-08-31 17:08:58 +02:00
Markus Fisch 3c8c0737c4 Add support for MECARD contact format
By silently transforming it into VCARD format.

This might be genius or a really bad idea. Let's find out ;)
2021-08-31 17:06:49 +02:00
Markus Fisch 9baf6d621a Remove unnecessary safe call operators 2021-08-31 17:04:14 +02:00
Markus Fisch f0d0ee04af Replace toUpperCase with just uppercase
And the same for toLowerCase. Following Android Studio's suggestion
for the latest release of Kotlin.
2021-08-31 17:02:36 +02:00
Markus Fisch 4d38da045a Remove unused permissions on Android Q 2021-08-24 23:15:52 +02:00
Markus Fisch af70d9507b Remove enableR8=true from gradle.properties
No longer used with Gradle 7.
2021-08-13 09:51:12 +02:00
Markus Fisch 273f38c36c Update build tools and gradle 2021-08-10 10:52:22 +02:00
Markus Fisch 210cdfc171 Get the Context only once and put in a val
Instead of (silently) invoking getters multiple times.
2021-08-10 10:41:25 +02:00
Markus Fisch 3ec8c4b5d7 Write exported barcode file on IO dispatcher 2021-08-10 10:40:45 +02:00
Markus Fisch d99f0ca039 Update changelogs for F-Droid 2021-07-29 21:51:30 +02:00
Markus Fisch 4a9e700d20 Advance version number to 1.44.1 2021-07-29 21:50:06 +02:00
Markus Fisch 40e339ce89 Use a matrix to map from frame to view
Because it's more elegant and less code.

However, this solution requires more calculations than before
because `Matrix.mapPoints()` carries out a matrix vector
multiplication which consists of more calculations than what
was required before.

But even mobile CPUs are fast enough that this won't make any
difference.

Also, this solution avoids allocating Point and List objects in
the hot path. Also not too important because ZXing still
allocates a lot of objects but that's okay too.
2021-07-29 10:35:33 +02:00
Markus Fisch 9d476b3491 Include all language resources in App Bundles
So the in-app language setting works for App Bundles too.

Normally, Google Play delivers only the language resource of
the device to minimise download size.

Another solution would have been to use the PlayCore API to
download language resources on demand, but it makes much more
sense to simply include the ~60 kb than adding fragile code
and dependencies.
2021-07-29 10:29:43 +02:00
Markus Fisch 22b58265a5 Clean up code
According to Android Studio recommendations.
2021-07-15 16:33:20 +02:00
Markus Fisch bd4576b7ac Update tools version 2021-07-15 14:05:24 +02:00
ElaborendumandGitHub a57f6d1904 Update Spanish translation 2021-07-15 09:24:42 +02:00
Markus Fisch 842b38c986 Update tools and Kotlin version 2021-06-29 21:46:50 +02:00
Markus Fisch b1fae727a9 Calculate ratio for mapping on initialization
Because the ratio is fixed for the mapping.
2021-06-20 18:01:12 +02:00
Markus Fisch db24f608d5 Update changelogs for F-Droid 2021-06-06 14:31:07 +02:00
gnuhead-chiebandGitHub 9f49a00bae Update Japanese translation
* Update app Japanese translation
* Add Japanese store description
2021-06-06 14:29:38 +02:00
Markus Fisch 947bbf3031 Advance version number to 1.44.0 2021-06-05 14:49:33 +02:00
GazandGitHub b3b57a7ba8 Update Traditional Chinese Translation 2021-06-04 15:29:00 +02:00
solokotandGitHub 1627f3ead9 Update Russian language 2021-06-03 13:53:53 +02:00
Heimen StoffelsandGitHub 4343f5da82 Update Dutch translation 2021-06-02 22:18:41 +02:00
Markus Fisch 67395a067d Add a setting to choose barcode formats to scan
This setting isn't available before Honeycomb because there is
no MultiSelectListPreference before.
2021-06-02 19:05:55 +02:00
Markus Fisch 0de571f3c1 Ask before removing network suggestions
To avoid unintentional removal.
2021-06-02 19:02:38 +02:00
Markus Fisch d83cd77a87 Update changelogs for F-Droid 2021-06-02 19:02:38 +02:00
Heimen StoffelsandGitHub 5ca7aff5df Updated Dutch translation 2021-06-02 18:58:19 +02:00
solokotandGitHub e4cc516a9b Updated & improved Russian language 2021-06-02 18:57:52 +02:00
Markus Fisch f160cf0953 Advance version number to 1.43.0 2021-06-01 22:04:17 +02:00
Markus Fisch ef5b5aa34a Add a preference to remove network suggestions
Because as it turns out, WiFi network suggestions cannot be removed
by the user. Which is pretty silly in my opinion. But anyway, now a
user can remove all the networks added by Binary Eye.
2021-06-01 21:57:20 +02:00
GazandGitHub 536ee5bc3d Update Traditional Chinese Translation 2021-05-25 12:03:51 +02:00
solokotandGitHub 0becada572 Update Russian language 2021-05-25 11:55:34 +02:00
Markus Fisch 0c773d6f05 Update changelogs for F-Droid 2021-05-24 22:19:23 +02:00
Markus Fisch f2df364840 Advance version number to 1.42.0 2021-05-24 22:18:26 +02:00
Markus Fisch 5740b43568 Add a setting to pick a default search engine
To open unknown data with.
2021-05-24 22:12:13 +02:00
GazandGitHub b384b99b01 Update zh-TW(Traditional Chinese) Translation 2021-05-23 12:21:27 +02:00
Heimen StoffelsandGitHub 6affa4ce25 Update Dutch translation 2021-05-18 18:40:05 +02:00
Markus Fisch 455d329fff Remove resolveActivity() for opening content
Because on Android 11+ resolveActivity() can no longer be used
to query if there's an app that can handle the intent for privacy
reasons.
2021-05-07 22:15:38 +02:00
Markus Fisch 792be87283 Advance version number to 1.41.1 2021-05-06 23:01:49 +02:00
Markus Fisch 381e10bddc Ignore exceptions in MultiFormatReader.decode()
Usually it's bad practice to blindly catch *all* exceptions
because this can hide problems we want to know about.

But since ZXing has some errors (like all software) and I don't
want this app to break in the hands of my users, which won't
see the stack trace anyway, it's better to just catch all
exceptions that may happen in MultiFormatReader.decode().
2021-05-06 17:19:49 +02:00
Markus Fisch 220d1b9d4c Remove useless context argument
The argument is never used except for calling the function again.
A leftover from an earlier implementation.
2021-05-06 17:10:00 +02:00
Markus Fisch 020cd2c192 Update tools and gradle version
And migrate from jcenter() back to mavenCentral().
2021-05-05 20:50:50 +02:00
OymateandGitHub e8766a0fd1 Update Bengali translation 2021-05-02 13:31:28 +02:00
yzqzssandGitHub 69c6d1324e Update Simplified Chinese (Zh-rCN) 2021-05-01 19:50:13 +02:00
Markus Fisch 2dd0c48225 Format comments like sentences
Makes reading multiline comments easier.
2021-04-27 19:59:21 +02:00
Markus Fisch faa536274b Update build tools 2021-04-27 19:58:31 +02:00
Markus Fisch 0a944f9fb8 Add latest changelog for F-Droid 2021-04-13 19:47:59 +02:00
Markus Fisch a31982646a Advance version number to 1.41.0 2021-04-10 14:19:54 +02:00
Markus Fisch 4320ee8fcc Crop by default for new installations
To increase performance on bad devices.
2021-04-10 14:13:29 +02:00
Markus Fisch d890bf28fa Fix creating Locale from resource format
Locale() requires the country part as secondary argument and
can't use the resource format "lang-country" directly.
2021-04-09 10:23:45 +02:00
Markus Fisch 6347bd568c Fix XMl of Bengali language 2021-04-07 12:15:03 +02:00
OymateandGitHub 9de11e2ae8 Add Bangla translation 2021-04-07 11:12:15 +02:00
Ryota HasegawaandGitHub 57c381e310 Add missing Japanese locale 2021-03-25 09:28:20 +01:00
Balázs ÚrandGitHub a11650eaa5 Update Hungarian language pack
* Update Hungarian translation
* Add Hungarian app description
2021-03-24 09:34:14 +01:00
solokotandGitHub e85b006e40 Update Russian app description 2021-03-20 19:59:29 +01:00
OymateandGitHub a6c25be316 Add translation for Bangla
* Create title.txt
* Create summary.txt
* Create short_description.txt
* Create full_description.txt
2021-03-20 17:44:48 +01:00
fossddandGitHub 2b011325a6 Add summary from other languages 2021-03-18 09:37:24 +01:00
Markus Fisch fb96d5ecf8 Rename fastlane locale directories
On request of F-Droid.
2021-03-17 20:28:34 +01:00
Markus Fisch 897d61a646 Truncate all toasts with strings from the outside
Ellipsize texts in Toasts after 128 characters to not clutter the UI
with too long texts.

There's at least one case where too long toast texts caused crashes:
https://github.com/markusfisch/BinaryEye/issues/166
2021-03-13 16:08:32 +01:00
Markus Fisch ac67db6491 Advance version number to 1.40.0 2021-03-09 20:09:19 +01:00
solokotandGitHub 84bc7dad30 Update Russian language 2021-03-09 20:03:32 +01:00
Markus Fisch b21af65b68 Only reset bulk mode if it's always enabled
Otherwise the current state would be lost and rotating the device
with bulk mode on would reset it.
2021-03-08 20:18:35 +01:00
Markus Fisch a7adec7177 Share hex dump if content is binary
Instead of just sharing "(binary data)" which is quite useless.
2021-03-08 20:13:25 +01:00
Markus Fisch fc6fcfa743 Only show the first 50 characters in data Toast
More is just cluttering the UI.
2021-03-08 19:58:05 +01:00
Markus Fisch 47f95fc67a Add a setting to show/hide Toast with scanned data
When scanning continuously.

If we are scanning many codes at once, this might be too
cumbersome.
2021-03-08 19:50:38 +01:00
solokotandGitHub deccc9eb36 Update Russian language 2021-03-08 19:27:02 +01:00
Markus Fisch 6505312b44 Add latest changelog for F-Droid 2021-03-02 20:07:26 +01:00
Markus Fisch cb82fc3252 Advance version number to 1.39.0 2021-03-02 20:06:15 +01:00
Markus Fisch 636ac2386a Add a setting to always start in bulk mode 2021-03-02 19:51:41 +01:00
Markus Fisch 49d32ff95c Remove trying to resolve activities on API 30+.
Avoid using `intent.resolveActivity()` at API level 30+ due to the
new package visibility restrictions. In order for `resolveActivity()`
to "see" another package, we would need to list that package/intent
in a `<queries>` block in the Manifest.

But since we used `resolveActivity()` only to avoid an exception
if the Intent cannot be resolved, it's much easier and more robust
to just try and catch that exception if necessary.

This fixes adding contacts (and other things) on API level 30+.
2021-03-02 19:12:56 +01:00
ElaborendumandGitHub fed7d561c5 Update Spanish translation 2021-02-27 11:34:59 +01:00
Markus Fisch 8e22290c5f Refactor settings label to change language
"Custom locale" is a bit too cumbersome.
2021-02-18 16:38:17 +01:00
ss11mikandGitHub b33e474d12 Update Czech translation
* Fix screwed indentation
* Add missing plural
* Add short_description.txt
* Add full_description.txt
2021-02-18 16:37:02 +01:00
ss11mikandGitHub 40a05a1fc0 Add Czech translation
* Add Czech translation
* Add Czech strings
2021-02-18 09:58:46 +01:00
Markus Fisch d947764882 Add latest changelog for F-Droid 2021-02-13 18:00:51 +01:00
456 changed files with 21174 additions and 6528 deletions
+487
View File
@@ -1,5 +1,492 @@
# Change Log
## 1.72.1
* Fix migrating DATA_BAR entries
* Italian language update
## 1.72.0
* Improve result screen
* Update vdstools
* Fix camera initialization
## 1.71.0
* Parse VDS and IDB barcodes
* Restrict scanning to horizontal crosshair if set
* Include barcode format in history search
* Add a dedicated barcode icon for PDF417
* Add barcode format descriptions
* Fix handling deep links
* Fix detecting web URLs
## 1.70.0
* Add barcode format icons in history
* Add beep audio stream preference
* Parse EPC-QR codes and show the data
* Improve layout of decode screen
* Fix parsing first field of subfile in IDLParser
* Use quiet zone from ZXingCpp
* Italian language update
## 1.69.1
* Update translations
## 1.69.0
* Add an option to show crosshairs
* Add preference for codes that should not be saved
* Add option to restrict searching to a specific format
* Pin history items
* Improve preference icons
* Optimize vector drawables
* Fix beeping when phone is set to Vibrate mode
## 1.68.7
* Add icons to preferences screen
* Update history listing on resume
* Fix quiet zone for recreated barcodes
* Fix automatic screen brightening
* Migrate to CameraX
## 1.68.6
* Update ZXingCpp
* Ask for confirmation before deleting a scan from the result screen
## 1.68.5
* Downgrade ZXingCpp for compatibilty
## 1.68.4
* Fix generating 1D barcodes
## 1.68.3
* Stability improvement
## 1.68.2
* Fix barcode regeneration
## 1.68.1
* Improve UI of search barcode dialog
* Stability improvements
* Update ZXingCpp
* Update Russian translation
## 1.68.0
* Add automated actions
* Improve managing profiles
## 1.67.1
* Fix opening file:// Uris
* Fix auto-return/immediate opening
* Improve Bluetooth stability
## 1.67.0
* Add preference profiles
* Support regex when searching for a barcode
* Improve feedback when searching for a barcode
* Update translations
## 1.66.2
* Remove forcing `?content=` on forwarding URL
* Update Spanish translation
## 1.66.1
* Show elements of invalid Wifi configurations too
* Update translations
## 1.66.0
* Support deep links to encode content via web links
* Parse International Driver Licenses (IDL) in PDF417 barcodes
* Add WiFis from system settings
* Show parsed data items
* Update translations
## 1.65.2
* Sanity check ROI metrics
## 1.65.1
* Improve simple mode
* Remember quiet zone settings
* Reduce height for 1D barcodes
* Add execute argument for binaryeye://encode
* Update Russian translation
## 1.65.0
* Add a welcome screen to choose a mode
* Add a deep link to encode a barcode
* Remember zoom level of generated barcodes
* Remove Human Readable Interpretation (HRI) decoration
* Update Italian translation
## 1.64.2
* Separate crop window settings for image scanning
* Fix initializing dataMask
* Update Russian translation
## 1.64.1
* Handle empty input for recreation
* Fix setting up database
## 1.64.0
* Find barcode by content
* Immediately replace toasts
* Use detected barcode for recreation
* Show data mask of QR Codes
* Fix deep linking
* Replace margin with quiet zone switch when generating barcodes
* Update Russian translation
* Update Portuguese (Brazil) translation
## 1.63.13
* Fix UTF-8 conversion of binary escape sequences when creating barcodes
* Fix scan order for intervals under one second
* Add arabic translation
* Update French translation
## 1.63.12
* Fix magnifying barcode recreation
## 1.63.11
* Update parcel tracking URL
* Update multiple translations
* Only ask for barcode size when exporting/sharing
## 1.63.10
* Use maximum brightness when showing a generated barcode
* Allow file input from share menu
* Update multiple translations
## 1.63.9
* Export/share as JPEG
* Ignore "URL:" before URLs in barcode content
* Fix exporting/sharing multiple history items
* Update multiple translations
## 1.63.8
* Add an option to show a checksum for the decoded content
* Add support for encoding escape sequences for non-printable characters
* Update Italian translation
## 1.63.7
* Update ZXingCpp for Aztec Runes
* Update Italian translation
## 1.63.6
* Add history shortcut
* Return Codabar start/stop codes
* Update French, Russian, Spanish and Ukrainian translations
## 1.63.5
* Add an option to ignore any duplicates
* Fix invalid bluetooth connection
* Update Russian translation
* Update Ukrainian translation
## 1.63.4
* Update Chinese translation
* Improve support for old devices
## 1.63.3
* Fix SCAN Intent
## 1.63.2
* Add DX Film Edge barcode format
* Update Turkish translation
* Update Ukrainian translation
## 1.63.1
* Include scan label in exports/shares
* Update Russian translation
## 1.63.0
* Edit scan label in decoding screen
* Add a button to add generated codes to the history
* Improve scanning from images
* Improve asking for camera permission
* Fix margin for recreated barcodes
* Limit duration of error beep to 1s
* Update Ukrainian translation
* Update Spanish translation
## 1.62.3
* Extend selection with single taps in history listing
* Update Brazilian Portuguese translation
## 1.62.2
* Include rMQR Code for updates
## 1.62.1
* Make rMQR Code selectable
## 1.62.0
* Add support for rMQR (rectangular Micro QR) Code
* Share history as a file
* Only share selected scans from history
## 1.61.2
* Fix quick settings tile for Android 14
* Fix Xiaomi MIUI lockscreen barcode shortcut
* Update French translation
* Update Czech translation
* Update Russian translation
## 1.61.1
* Share scanned contents as a file
* Recreate binary barcodes too
* Add Bulgarian translation and Brave search engine
* Update Russian translation
* Fix general format restriction from preferences
## 1.61.0
* Support encoding binary data
* Add margin parameter for encoding
* Add copying binary data as hex dump
* Fix parsing TYPE argument in VCARDs
* Update Russian translation
* Update Brazilian Portuguese translation
* Update Ukrainian translation
* Update Chinese translation
## 1.60.3
* Fix saving custom language
* Update Brazilian Portuguese translation
* Update Chinese translation
* Update Czech localisation
* Update Russian translation
* Update Italian language
## 1.60.2
* Expand escape sequences in encoding input
* Update Taiwan translation
## 1.60.1
* Support sending scans via bluetooth
* Fix resolving error correction level for recreation
* Improve asset image compression
* Update ZXing C++
* Update Italian translation
* Update Russian translation
## 1.59.0
* Add setting error correction for AZTEC/PDF417
* Fix setting error correction level for QR Codes
* Make error beeps follow beep settings too
* Don't close the app when cameras is unavailable
## 1.58.2
* Fix parsing WiFi network suggestions
## 1.58.1
* Update zh-rCn translation
* Fix monochrome launcher icon
## 1.58.0
* Improve detection of inverted barcodes
* Optionally allow duplicates in bulk scan
* Add Danish translation
* Update Italian translation
* Update Japanese translation
* Update Russian translation
* Fix charset decoding for PDF 417
* Fix monochrome icon
## 1.57.0
* Add optional audio feedback for scanning
* Allow removing individual WiFi network suggestions
* Recognize incomplete and malformed WiFi barcodes
* Fix using shared text for encoding
* Add Korean language
* Update Chinese translation
* Update Português/Brasil translation
* Update Russian translation
## 1.56.3
* Fix parsing URLs in barcodes
* Update French, Portuguese, Turkish and Taiwan translation
## 1.56.2
* Fix generating 1D barcode text output
## 1.56.1
* Allow pinching a barcode to its generated size
* Fix view/frame transformation matrix
* Fix handling of tab characters
* Update Indonesian translation
* Update Russian translation
## 1.56.0
* Add an action item to lock/unlock free rotation
* Support setting fore and background colors when creating barcodes
* Fix creating barcodes with UTF-8 content
## 1.55.0
* Make recreated barcode interactive
* Update to latest ZXing C++
* Update Italian translation
## 1.54.1
* Update Russian translation
* Update Turkish translation
* Update Italian translation
* Fix handling GS1 and ISO15434 content types
* Fix VerifyError on Android 4
## 1.54.0
* Recreate and show barcode from read contents if possible
* Add ebay, Amazon and barcodelookup.com to search engines
## 1.53.1
* Fix proguard configuration
## 1.53.0
* Migrate to ZXing-C++ and add support for Micro QR Codes
* Multi-select scans in history listing
* Remove preset content for Encode shortcut
* Always show QR Code version and remove setting
* Fix PDF-417 UTF-8 text encoding
* Hide sensitive content from clipboard
* Remove setting a custom language on Android 13+
* Condense text output of generated barcodes
* Update Russian translation
* Update Spanish translation
* Add Persian translation
## 1.52.0
* Fix parsing timezone in calendar dates
* Update French translation
## 1.51.1
* Fix extraction of raw bytes for some barcodes
## 1.51.0
* Add support for Deutsche Post Matrixcode stamp
* Allow free image rotation for scanning from images
* Fix setting TO field in MATMSG format
* Update Italian translation
* Update zh-rCN translation
* Update pt-br translation
## 1.50.0
* Add support for MATMSG format
* Add a setting to show the QR Code version
* Add timezone offset in calendar dates
* Recognize colloquial incomplete URLs
* Update ZXing library to latest version
* Update Czech translation
* Update Russian translation
* Update Japanese translation
* Update Hungarian translation
## 1.49.2
* Update design of app icon
* Update pt-br translation
## 1.49.1
* Update Simplified Chinese translation
* Return directly to caller for deep links
* Fix metadata for deep links
## 1.49.0
* Add a setting to quickly enable/disable forwarding
* Stop playing error beep when in silent mode
* Improve enabling/disabling torch mode
* Update to latest ZXing version
* Update German translation
* Update Russian translation
## 1.48.1
* Fix broken detection of binary content
## 1.48.0
* Add a menu item to temporarily scan a certain format only
* Add a monochome launcher icon for Android 13
* Show alpha numeric characters in binary data
* Fix showing binary data label for scans from the history
* Fix handling empty meta strings
* Update Turkish translation
* Update Ukrainian translation
* Update French translation
* Update Polish translation
* Update Russian translation
## 1.47.0
* Add forwarding into external browser
* Fix visibility of zoom slider when switching cameras
## 1.46.3
* Fix cropping still images
* Improve usability of zoom slider
* Update Dutch translation
* Update Chinese translation
## 1.46.2
* Fix saving external files on Android Q and newer
## 1.46.1
* Use cropping limiter settings for image picking too
* Remove extra link on result screen
* Update Turkish translation
## 1.46.0
* Support deep links
* Support "A:" in WIFI codes
* Allow multiple query arguments in custom URL
* Add Wi-Fi info data section
* Add Vietnamese translation
* Update Brazilian Portuguese translation
* Update Hungarian translation
* Update Ukrainian translation
* Update Russian translation
## 1.45.0
* Add a setting to set the delay for bulk mode
* Add support for MECARD contact format
* Remove unused permissions on Android Q
## 1.44.1
* Update Spanish translation
* Update Japanese translation
* Fix in-app language switching for App Bundles
## 1.44.0
* Add a setting to choose barcode formats to scan
* Ask before removing network suggestions
* Update Traditional Chinese Translation
* Update Russian language
* Update Dutch translation
## 1.43.0
* Add a preference item to remove WiFi network suggestions
* Update Traditional Chinese Translation
* Update Russian language
## 1.42.0
* Add a setting to pick a default search engine
* Update Traditional Chinese
* Update Dutch translation
## 1.41.1
* Update Bengali translation
* Update Simplified Chinese
## 1.41.0
* Use cropping limiter by default for new installations
* Truncate all toasts with strings from the outside
* Add Bangla translation
* Add missing Japanese locale
* Update Hungarian translation
* Update Russian app description
## 1.40.0
* Add a setting to show/hide scanned data when scanning continuously
* Only show the first 50 characters when scanning continuously
* Share binary data as hex dump
* Update Russian language
## 1.39.0
* Fix adding contacts and calendar entries on Android 11+
* Add a setting to always start in bulk mode
* Add Czech translation
* Update Spanish translation
* Update Czech translation
## 1.38.0
* Add a quick settings tile to scan from settings
* Make custom background requests time out after 5 seconds
+6 -1
View File
@@ -16,5 +16,10 @@ to squash when merging into master:
Then write a [good commit message][commit_messages] to keep the history
meaningful and useful. One feature, one commit.
## Translations
For translations use [Toolate][toolate].
[android_best_practices]: https://developer.android.com/distribute/best-practices/develop/
[commit_messages]: https://juffalow.com/other/write-good-git-commit-message
[commit_messages]: https://git-scm.com/book/en/v2/Distributed-Git-Contributing-to-a-Project#_commit_guidelines
[toolate]: https://toolate.othing.xyz/projects/binaryeye/
+37 -2
View File
@@ -20,8 +20,43 @@ infer: clean
test:
./gradlew test
cat:
./gradlew test cAT
testview:
adb shell am start -W -a android.intent.action.VIEW -d 'binaryeye://scan'
testscan:
adb shell am start -a android.intent.action.VIEW \
-c android.intent.category.BROWSABLE \
-d 'binaryeye://scan/?ret=http%3A%2F%2Fmarkusfisch.de%2F%3Fresult%3D{RESULT}'
testencode:
adb shell am start -a android.intent.action.VIEW \
-c android.intent.category.BROWSABLE \
-d 'binaryeye://encode?content=Test\&format=QR_CODE'
testencodenotqr:
adb shell am start -a android.intent.action.VIEW \
-c android.intent.category.BROWSABLE \
-d 'binaryeye://encode?content=Test\&format=DATA_MATRIX'
testencodeexec:
adb shell am start -a android.intent.action.VIEW \
-c android.intent.category.BROWSABLE \
-d 'binaryeye://encode?content=Test\&format=QR_CODE\&execute'
testencodeurl:
adb shell am start -a android.intent.action.VIEW \
-c android.intent.category.BROWSABLE \
-d 'http://markusfisch.de/encode?content=Test\&format=QR_CODE'
testurl:
adb shell am start -a android.intent.action.VIEW \
-c android.intent.category.BROWSABLE \
-d 'http://markusfisch.de/BinaryEye?ret=http%3A%2F%2Fmarkusfisch.de%2F%3Fresult%3D{RESULT}'
testxiaomi:
adb shell am start -a android.intent.action.VIEW \
-c android.intent.category.BROWSABLE \
-d 'market://details?id=com.xiaomi.scanner'
install:
adb $(TARGET) install -r app/build/outputs/apk/debug/app-debug.apk
+33 -11
View File
@@ -7,33 +7,40 @@ hesitate to contact me.
## Permissions
### [ACCESS_FINE_LOCATION](https://developer.android.com/reference/android/Manifest.permission#ACCESS_FINE_LOCATION)
### [ACCESS_FINE_LOCATION][ACCESS_FINE_LOCATION]
Required to add a WiFi network from a barcode (usually a QR Code).
Before Android Q, this feature requires using
[WifiManager.getConfiguredNetworks][configuredNetworks]
[WifiManager.getConfiguredNetworks][getConfiguredNetworks]
which requires `ACCESS_FINE_LOCATION`.
On Android Q an better, this permission is not requested nor required.
On Android Q and better, this permission is not requested nor required.
### [CAMERA](https://developer.android.com/reference/android/Manifest.permission#CAMERA)
### [BLUETOOTH][BLUETOOTH], [BLUETOOTH_ADMIN][BLUETOOTH_ADMIN] and [BLUETOOTH_CONNECT][BLUETOOTH_CONNECT]
Required to optionally forward scans to a Bluetooth device.
[BLUETOOTH][BLUETOOTH] and [BLUETOOTH_ADMIN][BLUETOOTH_ADMIN] are required
before Android S. [BLUETOOTH_CONNECT][BLUETOOTH_CONNECT] from Android S on.
### [CAMERA][CAMERA]
Required to read a barcode from the camera image.
### [INTERNET](https://developer.android.com/reference/android/Manifest.permission#INTERNET)
### [INTERNET][INTERNET]
Required to send a scanned code to a custom URL you can specify in settings.
### [VIBRATE](https://developer.android.com/reference/android/Manifest.permission#VIBRATE)
### [VIBRATE][VIBRATE]
Required to vibrate on detection.
### [WRITE_EXTERNAL_STORAGE](https://developer.android.com/reference/android/Manifest.permission#WRITE_EXTERNAL_STORAGE)
### [WRITE_EXTERNAL_STORAGE][WRITE_EXTERNAL_STORAGE]
Required to save generated barcodes as files before Android Q.
### [CHANGE_WIFI_STATE](https://developer.android.com/reference/android/Manifest.permission#CHANGE_WIFI_STATE)
### [CHANGE_WIFI_STATE][CHANGE_WIFI_STATE]
Required to add a WiFi network from a barcode (usually a QR Code).
@@ -41,13 +48,28 @@ On Android Q and better, this feature requires using
[WifiManager.addNetworkSuggestions][addNetworkSuggestions]
which requires `CHANGE_WIFI_STATE`.
### [ACCESS_WIFI_STATE](https://developer.android.com/reference/android/Manifest.permission#ACCESS_FINE_LOCATION)
### [ACCESS_WIFI_STATE][ACCESS_FINE_LOCATION]
Required to add a WiFi network from a barcode (usually a QR Code).
Before Android Q, this feature requires using
[WifiManager.getConfiguredNetworks][configuredNetworks]
[WifiManager.getConfiguredNetworks][getConfiguredNetworks]
which requires `ACCESS_WIFI_STATE`.
[configuredNetworks]: https://developer.android.com/reference/android/net/wifi/WifiManager#getConfiguredNetworks()
From Android R, `ACCESS_WIFI_STATE` is required for
[WifiManager.getNetworkSuggestions][getNetworkSuggestions]
which is used to remove individual network suggestions.
[ACCESS_FINE_LOCATION]: https://developer.android.com/reference/android/Manifest.permission#ACCESS_FINE_LOCATION
[BLUETOOTH]: https://developer.android.com/reference/android/Manifest.permission#BLUETOOTH
[BLUETOOTH_ADMIN]: https://developer.android.com/reference/android/Manifest.permission#BLUETOOTH_ADMIN
[BLUETOOTH_CONNECT]: https://developer.android.com/reference/android/Manifest.permission#BLUETOOTH_CONNECT
[CAMERA]: https://developer.android.com/reference/android/Manifest.permission#CAMERA
[INTERNET]: https://developer.android.com/reference/android/Manifest.permission#INTERNET
[VIBRATE]: https://developer.android.com/reference/android/Manifest.permission#VIBRATE
[WRITE_EXTERNAL_STORAGE]: https://developer.android.com/reference/android/Manifest.permission#WRITE_EXTERNAL_STORAGE
[CHANGE_WIFI_STATE]: https://developer.android.com/reference/android/Manifest.permission#CHANGE_WIFI_STATE
[ACCESS_WIFI_STATE]: https://developer.android.com/reference/android/Manifest.permission#ACCESS_FINE_LOCATION
[getConfiguredNetworks]: https://developer.android.com/reference/android/net/wifi/WifiManager#getConfiguredNetworks()
[addNetworkSuggestions]: https://developer.android.com/reference/android/net/wifi/WifiManager#addNetworkSuggestions(java.util.List%3Candroid.net.wifi.WifiNetworkSuggestion%3E)
[getNetworkSuggestions]: https://developer.android.com/reference/android/net/wifi/WifiManager#getNetworkSuggestions()
+133 -27
View File
@@ -2,13 +2,30 @@
Yet another barcode scanner for Android. As if there weren't [enough][play].
This one is free, without any ads and open source.
This one is free, without any ads, and open source.
Works in portrait and landscape orientation, can read inverted codes,
comes in Material Design and can also generate barcodes.
Binary Eye uses the [ZXing][zxing] ("Zebra Crossing") barcode scanning
library.
Binary Eye uses the [ZXing-C++][zxing_cpp] ("Zebra Crossing") barcode
scanning library.
If you find this app useful and wish to support its continued development,
you can [buy me a coffee](https://www.buymeacoffee.com/markusfisch) or
send some Bitcoin decimals to `bc1q2guk2rpll587aymrfadkdtpq32448x5khk5j8z`.
<a href="https://www.buymeacoffee.com/markusfisch" target="_blank"><img
src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png"
alt="Buy Me A Coffee"
style="height: 60px !important;width: 217px !important;"/></a>&nbsp;<a
href="https://liberapay.com/markusfisch/" target="_blank"><img
src="https://liberapay.com/assets/widgets/donate.svg"
alt="Liberapay"
style="height: 60px !important"/></a>&nbsp;<a
href="https://ko-fi.com/markusfisch" target="_blank"><img
src="https://storage.ko-fi.com/cdn/brandasset/kofi_s_tag_dark.png"
alt="Ko-fi"
style="height: 60px !important"/></a>
## Screenshots
@@ -36,13 +53,15 @@ ZXing can read the following barcode formats:
* [CODE 93][code_93]
* [CODE 128][code_128]
* [DATA MATRIX][data_matrix]
* [DX FILM EDGE][dx_film_edge]
* [EAN 8][ean_8]
* [EAN 13][ean_13]
* [ITF][itf]
* [MAXICODE][maxicode] (only when unrotated and unskewed, see [77][77],
because of which Binary Eye *cannot* read this barcode)
* [MAXICODE][maxicode] (partial)
* [PDF417][pdf417]
* [QR CODE][qr_code]
* [Micro QR Code][micro_qr_code]
* [rMQR Code][rmqr_code]
* [RSS 14][rss]
* [RSS EXPANDED][rss]
* [UPC A][upc_a]
@@ -64,37 +83,117 @@ ZXing can generate the following barcode formats:
* [QR CODE][qr_code]
* [UPC A][upc_a]
## RenderScript
## Deep Links
This app uses [RenderScript][rs] to resize and rotate the camera image.
Unfortunately, RenderScript has some nasty gotchas.
You can invoke Binary Eye with a web URI intent from anything that can
open URIs.
### RenderScript.forceCompat()
### Decoding
It's necessary to call `RenderScript.forceCompat()` on some devices/roms.
1. [binaryeye://scan](binaryeye://scan) (note: GitHub does not render this as clickable link)
2. [http(s)://markusfisch.de/BinaryEye](http://markusfisch.de/BinaryEye)
`RenderScript.forceCompat()` needs to be run before any other RenderScript
function and unfortunately there is no way to know if invoking `forceCompat()`
is necessary or not.
If you want to get the scanned contents, you can add a `ret` query
argument with a (URL encoded) URI template. For example:
If `RenderScript.forceCompat()` is necessary, a `RSRuntimeException` will
be thrown and the only option is to restart the app, this time with calling
`forceCompat()` first.
[http://markusfisch.de/BinaryEye?ret=http%3A%2F%2Fexample.com%2F%3Fresult%3D{RESULT}](http://markusfisch.de/BinaryEye?ret=http%3A%2F%2Fexample.com%2F%3Fresult%3D{RESULT})
Calling `RenderScript.forceCompat()` means the processing is done in
software so you probably don't want to enable it by default.
Supported symbols are:
### 2D barcodes
* `RESULT` - scanned content
* `RESULT_BYTES` - raw result as a hex string
* `FORMAT` - barcode format
If you want to fork this and are only interested in reading 2D barcodes
(like QR or Aztec), you may want to remove the custom rotation kernel
altogether as ZXing can read 2D barcodes in any orientation.
### Encoding
This will make your app a bit simpler and saves you from compiling a
custom RenderScript kernel for each architecture you want to support.
1. [binaryeye://encode](binaryeye://encode)
You can use the URL arguments `content` and `format` to automatically
preset this data. For example:
1. [binaryeye://encode?content=Test&format=QR_CODE](binaryeye://encode?content=Test&format=QR_CODE)
2. [http(s)://markusfisch.de/encode?content=Test&format=QR_CODE](http://markusfisch.de/encode?content=Test&format=QR_CODE)
3. [http(s)://markusfisch.de/encode?content=Test&format=DATA_MATRIX](http://markusfisch.de/encode?content=Test2&format=DATA_MATRIX&execute)
If you want the code to be generated immediately, add `execute=true` (or
just `execute`).
## Intents
You can also use Binary Eye from other apps by using an [Intent][intent].
If you prefer to integrate a barcode scanner into your app, take a look at
[BarcodeScannerView][barcode_scanner_view] (if you also want to use
[ZXing-C++][zxing_cpp]) or read how to
[scan barcodes with ML Kit on Android][mlkit_barcode_scanning].
### SCAN Intent
Use the `com.google.zxing.client.android.SCAN` `Intent` with
[startActivityForResult()][start_activity] like this:
```kotlin
startActivityForResult(
Intent("com.google.zxing.client.android.SCAN"),
SOME_NUMBER
)
```
And process the result in [onActivityResult()][on_activity_result] of your
`Activity`:
```kotlin
override fun onActivityResult(
requestCode: Int,
resultCode: Int,
data: Intent?
) {
when (requestCode) {
SOME_NUMBER -> if (resultCode == RESULT_OK) {
val result = data.getStringExtra("SCAN_RESULT")
}
}
}
```
If you're using AndroidX, this would be the new,
[recommended way][intent_result]:
```kotlin
class YourActivity : AppCompatActivity() {
private val resultLauncher = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) { result ->
if (result.resultCode == RESULT_OK) {
val content = result.data?.getStringExtra("SCAN_RESULT")
}
}
fun openScanner() {
resultLauncher.launch(Intent("com.google.zxing.client.android.SCAN"))
}
}
```
## Forwarding scans via Bluetooth
**Note:** The companion apps aren't developed nor maintained by the
author of Binary Eye.
In order to set up Bluetooth forwarding to a computer:
1. Pair your devices (phone and pc) if not paired already
2. Download and run a companion app:
- Windows: https://github.com/KamaleiZestri/BinaryReceptorWindows
- Linux: https://github.com/sean666888/bin_eye_bt_receiver
3. In the settings of Binary Eye, enable "Forward scans with Bluetooth"
and select the appropriate target host device that is running the
companion application.
[play]: https://play.google.com/store/search?q=barcode%20scanner&c=apps
[zxing]: https://github.com/zxing/zxing
[zxing_cpp]: https://github.com/zxing-cpp/zxing-cpp
[kotlin]: http://kotlinlang.org/
[aztec]: https://en.wikipedia.org/wiki/Aztec_Code
[codabar]: https://en.wikipedia.org/wiki/Codabar
@@ -102,15 +201,22 @@ custom RenderScript kernel for each architecture you want to support.
[code_93]: https://en.wikipedia.org/wiki/Code_93
[code_128]: https://en.wikipedia.org/wiki/Code_128
[data_matrix]: https://en.wikipedia.org/wiki/Data_Matrix
[dx_film_edge]: https://en.wikipedia.org/wiki/DX_encoding
[ean_8]: https://en.wikipedia.org/wiki/EAN-8
[ean_13]: https://en.wikipedia.org/wiki/International_Article_Number
[itf]: https://en.wikipedia.org/wiki/Interleaved_2_of_5
[maxicode]: https://en.wikipedia.org/wiki/MaxiCode
[pdf417]: https://en.wikipedia.org/wiki/PDF417
[qr_code]: https://en.wikipedia.org/wiki/QR_code
[micro_qr_code]: https://en.wikipedia.org/wiki/QR_code#Micro_QR_code
[rmqr_code]: https://www.qrcode.com/en/codes/rmqr.html
[rss]: https://en.wikipedia.org/wiki/GS1_DataBar
[upc_a]: https://en.wikipedia.org/wiki/Universal_Product_Code
[upc_e]: https://en.wikipedia.org/wiki/Universal_Product_Code#UPC-E
[upc_ean]: https://en.wikipedia.org/wiki/Universal_Product_Code#EAN-13
[77]: https://github.com/markusfisch/BinaryEye/issues/77
[rs]: https://developer.android.com/guide/topics/renderscript/compute
[intent]: https://developer.android.com/reference/android/content/Intent
[barcode_scanner_view]: https://github.com/markusfisch/BarcodeScannerView
[mlkit_barcode_scanning]: https://developers.google.com/ml-kit/vision/barcode-scanning/android
[start_activity]: https://developer.android.com/reference/android/app/Activity#startActivityForResult(android.content.Intent,%20int)
[on_activity_result]: https://developer.android.com/reference/android/app/Activity#onActivityResult(int,%20int,%20android.content.Intent)
[intent_result]: https://developer.android.com/training/basics/intents/result
+55 -41
View File
@@ -1,28 +1,19 @@
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
android {
compileSdkVersion sdk_version
buildToolsVersion build_tools_version
namespace "de.markusfisch.android.binaryeye"
compileSdk sdk_version
defaultConfig {
minSdkVersion 9
targetSdkVersion sdk_version
minSdk 21
targetSdk sdk_version
versionCode 77
versionName '1.38.0'
// it's recommended to set this value to the lowest API level
// able to provide all the functionality
renderscriptTargetApi 24
renderscriptSupportModeEnabled true
renderscriptSupportModeBlasEnabled true
testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner'
versionCode 167
versionName '1.72.1'
}
signingConfigs {
config {
release {
keyAlias System.getenv('ANDROID_KEY_ALIAS')
keyPassword System.getenv('ANDROID_KEY_PASSWORD')
storePassword System.getenv('ANDROID_STORE_PASSWORD')
@@ -43,39 +34,62 @@ android {
}
release {
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
minifyEnabled true
shrinkResources true
signingConfig signingConfigs.config
signingConfig signingConfigs.release
}
}
lintOptions {
// because at the time of writing, even the latest version
// of RenderScript is raising this error no matter if
// renderscriptTargetApi matches targetSdkVersion
disable 'GradleCompatible'
buildFeatures {
buildConfig true
}
bundle {
language {
// To make the app bundle contain all language resources
// so the in-app language setting works. Another solution
// would be to use the PlayCore API to download language
// resources on demand, but it makes much more sense to
// simply include the ~60 kb than adding fragile code and
// dependencies.
enableSplit = false
}
}
// Required since Gradle 8.
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
}
dependencies {
androidTestImplementation('com.android.support.test:runner:1.0.2') {
exclude module: 'support-annotations'
}
androidTestImplementation('com.android.support.test:rules:1.0.2') {
exclude module: 'support-annotations'
}
testImplementation 'junit:junit:4.12'
// Kotlin
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.2"
implementation "com.android.support:appcompat-v7:$support_version"
implementation "com.android.support:design:$support_version"
implementation "com.android.support:preference-v7:$support_version"
implementation "com.android.support:preference-v14:$support_version"
// Do NOT upgrade ZXing because newer versions won't work on API < 24
// https://github.com/zxing/zxing/issues/1170
implementation 'com.google.zxing:core:3.3.3'
implementation 'com.github.markusfisch:CameraView:1.9.1'
implementation 'com.github.markusfisch:ScalingImageView:1.3.0'
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2"
implementation 'org.jetbrains.kotlinx:kotlinx-datetime:0.7.1'
implementation "androidx.core:core-ktx:1.17.0"
// Support
implementation "androidx.appcompat:appcompat:1.7.1"
implementation "com.google.android.material:material:1.13.0"
implementation "androidx.preference:preference:1.2.1"
// External
implementation 'androidx.camera:camera-core:1.4.2'
implementation 'androidx.camera:camera-camera2:1.4.2'
implementation 'androidx.camera:camera-lifecycle:1.4.2'
implementation 'androidx.camera:camera-view:1.4.2'
implementation 'com.github.markusfisch:ScalingImageView:1.4.3'
implementation 'com.github.markusfisch:zxing-cpp:v3.0.2.3'
implementation 'de.tsenger:vdstools:0.16.0-SNAPSHOT'
implementation 'org.bouncycastle:bcpkix-jdk15to18:1.83'
// Testing
testImplementation 'junit:junit:4.13.2'
testImplementation 'org.robolectric:robolectric:4.16.1'
// Debugging
debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.14'
}
Binary file not shown.
+10
View File
@@ -9,4 +9,14 @@
<issue id="UnusedResources">
<ignore path="*/res/rs/debug/raw/bc*" />
</issue>
<!-- Android 12 requires apps that request ACCESS_FINE_LOCATION
to also request ACCESS_COARSE_LOCATION. But this app doesn't
request nor requires ACCESS_FINE_LOCATION above SDK 28. So
this is a false positive. -->
<issue id="CoarseFineLocation" severity="ignore"/>
<!-- Androidx SplashScreen compat library would require minSdk 21,
make the app unnecessarily larger and Android 12 automatically
replaces our custom splash screen anyway, which is exactly what
we want. So there is no reason to complain. -->
<issue id="CustomSplashScreen" severity="ignore"/>
</lint>
+2 -1
View File
@@ -3,4 +3,5 @@
-dontwarn android.support.v8.**
-keep class android.support.v7.widget.SearchView { *; }
-keep class android.support.v8.renderscript.** { *; }
-keep class de.tsenger.vdstools.** { *; }
Binary file not shown.

Before

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

@@ -1,108 +0,0 @@
package de.markusfisch.android.binaryeye
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import android.support.v8.renderscript.RenderScript
import de.markusfisch.android.binaryeye.rs.Preprocessor
import de.markusfisch.android.binaryeye.zxing.Zxing
import org.junit.Assert.fail;
import org.junit.Test
import org.junit.runner.RunWith
import java.util.regex.Pattern
@RunWith(AndroidJUnit4::class)
class PreprocessorTest {
@Test
fun processSamples() {
val zxing = Zxing()
val assets = InstrumentationRegistry.getInstrumentation()
.context.assets
val pattern = Pattern.compile(
"[0-9]+-([0-9]+)deg.jpg"
)
val samples = assets.list("samples")
checkNotNull(samples) { "no samples found" }
for (sample in samples) {
val m = pattern.matcher(sample)
if (!m.find() || m.groupCount() < 1) {
fail("invalid sample: $sample")
}
val bitmap = BitmapFactory.decodeStream(
assets.open("samples/$sample")
)
val frameData = getNV21(bitmap)
val frameWidth = bitmap.width
val frameHeight = bitmap.height
val frameOrientation = m.group(1) ?: return
val rs = RenderScript.create(
InstrumentationRegistry.getTargetContext(),
)
val preprocessor = Preprocessor(
rs,
frameWidth,
frameHeight,
null
)
val outWidth: Int
val outHeight: Int
val orientation = frameOrientation.toInt()
if (orientation == 90 || orientation == 270) {
preprocessor.resizeAndRotate(frameData)
outWidth = preprocessor.outHeight
outHeight = preprocessor.outWidth
} else {
preprocessor.resizeOnly(frameData)
outWidth = preprocessor.outWidth
outHeight = preprocessor.outHeight
}
val result = zxing.decode(frameData, outWidth, outHeight)
preprocessor.destroy()
rs.destroy()
checkNotNull(result) { "no barcode found in $sample" }
}
}
}
fun getNV21(bitmap: Bitmap): ByteArray {
val width = bitmap.width
val height = bitmap.height
val argb = IntArray(width * height)
bitmap.getPixels(argb, 0, width, 0, 0, width, height)
return encodeYUV420SP(argb, width, height)
}
private fun encodeYUV420SP(argb: IntArray, width: Int, height: Int): ByteArray {
val yuv = ByteArray(ceilIfUneven(width) * ceilIfUneven(height) * 3 / 2)
var yIndex = 0
var uvIndex = width * height
var r: Int
var g: Int
var b: Int
var Y: Int
var u: Int
var v: Int
var index = 0
for (y in 0 until height) {
for (x in 0 until width) {
val pixel = argb[index]
r = pixel and 0xff0000 shr 16
g = pixel and 0xff00 shr 8
b = pixel and 0xff
Y = (66 * r + 129 * g + 25 * b + 128 shr 8) + 16
u = (-38 * r - 74 * g + 112 * b + 128 shr 8) + 128
v = (112 * r - 94 * g - 18 * b + 128 shr 8) + 128
yuv[yIndex++] = (if (Y < 0) 0 else if (Y > 255) 255 else Y).toByte()
if (y % 2 == 0 && index % 2 == 0) {
yuv[uvIndex++] = (if (v < 0) 0 else if (v > 255) 255 else v).toByte()
yuv[uvIndex++] = (if (u < 0) 0 else if (u > 255) 255 else u).toByte()
}
++index
}
}
return yuv
}
private fun ceilIfUneven(n: Int) = if (n and 1 == 1) n + 1 else n
@@ -4,35 +4,7 @@
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillColor="#FF000000"
android:pathData="M52,-884.362h29v71h-29z"/>
<path
android:fillColor="#FF000000"
android:pathData="M52,-884.362h29v71h-29z"/>
<path
android:fillColor="#FF000000"
android:pathData="M52,-884.362h29v71h-29z"/>
<path
android:fillColor="#FF000000"
android:pathData="M32.002,-24.974h3.127v7.656h-3.127z"/>
<path
android:fillColor="#FF000000"
android:pathData="M52,-884.362h29v71h-29z"/>
<path
android:fillColor="#FF000000"
android:pathData="M52,-884.362h29v71h-29z"/>
<path
android:fillColor="#FF000000"
android:pathData="M52,-884.362h29v71h-29z"/>
<path
android:fillColor="#FF000000"
android:pathData="M52,-884.362h29v71h-29z"/>
<path
android:fillColor="#FF000000"
android:pathData="M52,-884.362h29v71h-29z"/>
<path
android:pathData="m54.826,27.893c-6.851,0 -13.701,2.581 -18.924,7.745 -10.445,10.328 -10.413,27.062 0,37.423l36.218,36.036 37.879,0.902 -0.07,-38.363 -36.18,-35.998c-5.207,-5.18 -12.073,-7.745 -18.924,-7.745z"
android:strokeAlpha="1"
android:pathData="M54.826,27.894C47.976,27.894 41.125,30.475 35.903,35.639C25.457,45.967 25.489,62.701 35.903,73.062L72.121,109.098L108,108L109.93,71.637L73.75,35.639C68.543,30.459 61.677,27.894 54.826,27.894Z"
android:strokeLineJoin="miter"
android:strokeWidth="8.60725021"
android:fillColor="#000000"
@@ -41,43 +13,25 @@
android:fillAlpha="0.1254902"
android:strokeLineCap="butt"/>
<path
android:pathData="M28.001,54.118a26.525,26.227 0,1 0,53.049 0a26.525,26.227 0,1 0,-53.049 0z"
android:strokeAlpha="1"
android:pathData="M27.475,54a26.525,26.5 0,1 0,53.05 0a26.525,26.5 0,1 0,-53.05 0z"
android:strokeLineJoin="miter"
android:strokeWidth="4"
android:fillColor="#ffffff"
android:strokeColor="#00000000"
android:fillAlpha="1"
android:strokeLineCap="butt"/>
<path
android:pathData="M39.26,54.988a14.509,14.346 0,1 0,29.019 0a14.509,14.346 0,1 0,-29.019 0z"
android:strokeAlpha="1"
android:pathData="M72.745,54.001C72.745,58.588 71.099,62.791 68.362,66.049L68.362,41.953C71.099,45.21 72.745,49.412 72.745,54.001ZM54.001,72.745C53.463,72.745 52.931,72.723 52.406,72.679L52.406,35.322C52.931,35.278 53.463,35.255 54.001,35.255C54.538,35.255 55.071,35.278 55.596,35.322L55.596,72.679C55.071,72.723 54.538,72.745 54.001,72.745ZM35.255,54.001C35.255,49.412 36.903,45.21 39.638,41.953L39.638,66.049C36.903,62.791 35.255,58.588 35.255,54.001ZM61.98,70.969C60.961,71.447 59.895,71.838 58.789,72.13L58.789,35.873C59.895,36.164 60.961,36.553 61.98,37.032L61.98,70.969ZM49.213,72.13C46.877,71.514 44.717,70.458 42.831,69.056L42.831,38.945C44.717,37.543 46.877,36.487 49.213,35.873L49.213,72.13Z"
android:strokeLineJoin="miter"
android:strokeWidth="4"
android:fillColor="#000000"
android:strokeColor="#00000000"
android:fillAlpha="1"
android:strokeLineCap="butt"/>
<path
android:pathData="M54.034,44.513a9.535,9.428 0,1 0,19.07 0a9.535,9.428 0,1 0,-19.07 0z"
android:strokeAlpha="1"
android:strokeLineJoin="miter"
android:strokeWidth="10"
android:fillColor="#ffffff"
android:strokeColor="#00000000"
android:fillAlpha="1"
android:strokeLineCap="butt"/>
<path
android:fillColor="#FF000000"
android:pathData="M52,-884.362h29v71h-29z"/>
<path
android:pathData="m62.745,24.783c-2.055,1.011 -2.87,3.415 -1.847,5.446 0.588,1.168 1.642,1.916 2.839,2.168 -0.564,0.884 -0.835,1.972 -0.925,3.156 -1.782,-0.45 -3.735,-0.191 -5.25,0.639a0.799,0.808 90,0 0,-0.132 0.172,0.799 0.808,90 0,0 -0.132,0.172 0.799,0.808 90,0 0,-0.132 0.39,0.799 0.808,90 0,0 0.044,0.304 0.799,0.808 90,0 0,0.437 0.433,0.799 0.808,90 0,0 0.131,0.043 0.799,0.808 90,0 0,0.131 0.043,0.799 0.808,90 0,0 0.218,-0 0.799,0.808 90,0 0,0.263 -0.129c1.29,-0.707 2.97,-0.892 4.375,-0.425 0.096,0.882 0.341,1.782 0.695,2.683 -0.456,0.072 -0.936,0.177 -1.357,0.343 -1.207,0.48 -2.245,1.302 -3.022,2.244a0.799,0.808 90,0 0,-0.044 0.129,0.799 0.808,90 0,0 -0.088,0.258 0.799,0.808 90,0 0,0.044 0.304,0.799 0.808,90 0,0 0.393,0.563 0.799,0.808 90,0 0,0.394 0.131,0.799 0.808,90 0,0 0.175,-0.086 0.799,0.808 90,0 0,0.175 -0.086,0.799 0.808,90 0,0 0.219,-0.215c0.922,-1.115 2.409,-1.925 3.897,-2.025 0.494,0.845 1.016,1.575 1.658,2.209 -1.232,1.149 -2.043,2.664 -2.239,4.234a0.799,0.808 90,0 0,-0.001 0.215,0.799 0.808,90 0,0 0.174,0.346 0.799,0.808 90,0 0,0.043 0.086,0.799 0.808,90 0,0 0.219,0.217 0.799,0.808 90,0 0,0.131 0.043,0.799 0.808,90 0,0 0.131,0.043 0.799,0.808 90,0 0,0.218 -0,0.799 0.808,90 0,0 0.218,-0 0.799,0.808 90,0 0,0.132 -0.172,0.799 0.808,90 0,0 0.175,-0.086 0.799,0.808 90,0 0,0.044 -0.129,0.799 0.808,90 0,0 0.088,-0.258 0.799,0.808 90,0 0,0.044 -0.129c0.159,-1.272 0.816,-2.493 1.799,-3.371 1.966,1.394 4.252,1.797 6.122,0.876 1.892,-0.931 2.903,-3.018 2.941,-5.444 1.327,-0.259 2.813,0.014 3.936,0.656a0.799,0.808 90,0 0,0.174 0.129,0.799 0.808,90 0,0 0.131,0.043 0.799,0.808 90,0 0,0.088 -0.043,0.799 0.808,90 0,0 0.218,-0 0.799,0.808 90,0 0,0.087 -0.043,0.799 0.808,90 0,0 0.175,-0.086 0.799,0.808 90,0 0,0.132 -0.172,0.799 0.808,90 0,0 0.132,-0.172 0.799,0.808 90,0 0,0.045 -0.562,0.799 0.808,90 0,0 -0.043,-0.086 0.799,0.808 90,0 0,-0.262 -0.303,0.799 0.808,90 0,0 -0.131,-0.043c-1.386,-0.792 -3.097,-1.066 -4.766,-0.787 -0.125,-0.89 -0.309,-1.783 -0.695,-2.683 0.982,-1.073 2.47,-1.756 3.896,-1.81a0.799,0.808 90,0 0,0.131 0.043,0.799 0.808,90 0,0 0.087,-0.043 0.799,0.808 90,0 0,0.482 -0.345,0.799 0.808,90 0,0 0.044,-0.129 0.799,0.808 90,0 0,0.088 -0.476,0.799 0.808,90 0,0 -0.043,-0.086 0.799,0.808 90,0 0,-0.262 -0.303,0.799 0.808,90 0,0 -0.043,-0.086 0.799,0.808 90,0 0,-0.394 -0.131,0.799 0.808,90 0,0 -0.131,-0.043c-1.227,0.048 -2.518,0.369 -3.633,1.031 -0.388,0.233 -0.762,0.548 -1.095,0.864 -0.513,-0.821 -1.093,-1.559 -1.746,-2.166 0.47,-1.39 1.632,-2.605 2.98,-3.195a0.799,0.808 90,0 0,0.175 -0.086,0.799 0.808,90 0,0 0.132,-0.172 0.799,0.808 90,0 0,0.132 -0.172,0.799 0.808,90 0,0 0.132,-0.39 0.799,0.808 90,0 0,-0.043 -0.086,0.799 0.808,90 0,0 -0.174,-0.346 0.799,0.808 90,0 0,-0.043 -0.086,0.799 0.808,90 0,0 -0.437,-0.217 0.799,0.808 90,0 0,-0.175 0.086,0.799 0.808,90 0,0 -0.131,-0.043 0.799,0.808 90,0 0,-0.087 0.043,0.799 0.808,90 0,0 -0.131,-0.043c-1.584,0.694 -2.97,2.079 -3.681,3.756 -1.012,-0.644 -2.048,-1.087 -3.104,-1.173 0.53,-1.101 0.642,-2.414 0.05,-3.59 -1.023,-2.031 -3.541,-2.795 -5.596,-1.783z"
android:pathData="m62.745,28.783c-2.055,1.011 -2.87,3.415 -1.847,5.446 0.588,1.168 1.642,1.916 2.839,2.168 -0.564,0.884 -0.835,1.972 -0.925,3.156 -1.782,-0.45 -3.735,-0.191 -5.25,0.639a0.799,0.808 90.001,0 0,-0.132 0.172,0.799 0.808,90.001 0,0 -0.132,0.172 0.799,0.808 90.001,0 0,-0.132 0.39,0.799 0.808,90.001 0,0 0.044,0.304 0.799,0.808 90.001,0 0,0.437 0.433,0.799 0.808,90.001 0,0 0.131,0.043 0.799,0.808 90.001,0 0,0.131 0.043,0.799 0.808,90.001 0,0 0.218,-0 0.799,0.808 90.001,0 0,0.263 -0.129c1.29,-0.707 2.97,-0.892 4.375,-0.425 0.096,0.882 0.341,1.782 0.695,2.683 -0.456,0.072 -0.936,0.177 -1.357,0.343 -1.207,0.48 -2.245,1.302 -3.022,2.244a0.799,0.808 90.001,0 0,-0.044 0.129,0.799 0.808,90.001 0,0 -0.088,0.258 0.799,0.808 90.001,0 0,0.044 0.304,0.799 0.808,90.001 0,0 0.393,0.563 0.799,0.808 90.001,0 0,0.394 0.131,0.799 0.808,90.001 0,0 0.175,-0.086 0.799,0.808 90.001,0 0,0.175 -0.086,0.799 0.808,90.001 0,0 0.219,-0.215c0.922,-1.115 2.409,-1.925 3.897,-2.025 0.494,0.845 1.016,1.575 1.658,2.209 -1.232,1.149 -2.043,2.664 -2.239,4.234a0.799,0.808 90.001,0 0,-0.001 0.215,0.799 0.808,90.001 0,0 0.174,0.346 0.799,0.808 90.001,0 0,0.043 0.086,0.799 0.808,90.001 0,0 0.219,0.217 0.799,0.808 90.001,0 0,0.131 0.043,0.799 0.808,90.001 0,0 0.131,0.043 0.799,0.808 90.001,0 0,0.218 -0,0.799 0.808,90.001 0,0 0.218,-0 0.799,0.808 90.001,0 0,0.132 -0.172,0.799 0.808,90.001 0,0 0.175,-0.086 0.799,0.808 90.001,0 0,0.044 -0.129,0.799 0.808,90.001 0,0 0.088,-0.258 0.799,0.808 90.001,0 0,0.044 -0.129c0.159,-1.272 0.816,-2.493 1.799,-3.371 1.966,1.394 4.252,1.797 6.122,0.876 1.892,-0.931 2.903,-3.018 2.941,-5.444 1.327,-0.259 2.813,0.014 3.936,0.656a0.799,0.808 90.001,0 0,0.174 0.129,0.799 0.808,90.001 0,0 0.131,0.043 0.799,0.808 90.001,0 0,0.088 -0.043,0.799 0.808,90.001 0,0 0.218,-0 0.799,0.808 90.001,0 0,0.087 -0.043,0.799 0.808,90.001 0,0 0.175,-0.086 0.799,0.808 90.001,0 0,0.132 -0.172,0.799 0.808,90.001 0,0 0.132,-0.172 0.799,0.808 90.001,0 0,0.045 -0.562,0.799 0.808,90.001 0,0 -0.043,-0.086 0.799,0.808 90.001,0 0,-0.262 -0.303,0.799 0.808,90.001 0,0 -0.131,-0.043c-1.386,-0.792 -3.097,-1.066 -4.766,-0.787 -0.125,-0.89 -0.309,-1.783 -0.695,-2.683 0.982,-1.073 2.47,-1.756 3.896,-1.81a0.799,0.808 90.001,0 0,0.131 0.043,0.799 0.808,90.001 0,0 0.087,-0.043 0.799,0.808 90.001,0 0,0.482 -0.345,0.799 0.808,90.001 0,0 0.044,-0.129 0.799,0.808 90.001,0 0,0.088 -0.476,0.799 0.808,90.001 0,0 -0.043,-0.086 0.799,0.808 90.001,0 0,-0.262 -0.303,0.799 0.808,90.001 0,0 -0.043,-0.086 0.799,0.808 90.001,0 0,-0.394 -0.131,0.799 0.808,90.001 0,0 -0.131,-0.043c-1.227,0.048 -2.518,0.369 -3.633,1.031 -0.388,0.233 -0.762,0.548 -1.095,0.864 -0.513,-0.821 -1.093,-1.559 -1.746,-2.166 0.47,-1.39 1.632,-2.605 2.98,-3.195a0.799,0.808 90.001,0 0,0.175 -0.086,0.799 0.808,90.001 0,0 0.132,-0.172 0.799,0.808 90.001,0 0,0.132 -0.172,0.799 0.808,90.001 0,0 0.132,-0.39 0.799,0.808 90.001,0 0,-0.043 -0.086,0.799 0.808,90.001 0,0 -0.174,-0.346 0.799,0.808 90.001,0 0,-0.043 -0.086,0.799 0.808,90.001 0,0 -0.437,-0.217 0.799,0.808 90.001,0 0,-0.175 0.086,0.799 0.808,90.001 0,0 -0.131,-0.043 0.799,0.808 90.001,0 0,-0.087 0.043,0.799 0.808,90.001 0,0 -0.131,-0.043c-1.584,0.694 -2.97,2.079 -3.681,3.756 -1.012,-0.644 -2.048,-1.087 -3.104,-1.173 0.53,-1.101 0.642,-2.414 0.05,-3.59 -1.023,-2.031 -3.541,-2.795 -5.596,-1.783z"
android:fillColor="#ff2a2a"
android:strokeColor="#00000000"
android:fillAlpha="1"/>
android:strokeColor="#00000000"/>
<path
android:pathData="m66.624,32.489c0.281,-0.138 1.896,2.465 3.62,5.889 1.724,3.424 2.893,6.354 2.613,6.492 -0.281,0.138 -1.94,-2.551 -3.663,-5.975 -1.724,-3.424 -2.85,-6.268 -2.569,-6.406z"
android:pathData="m66.624,36.489c0.281,-0.138 1.896,2.465 3.62,5.889 1.724,3.424 2.893,6.354 2.613,6.492 -0.281,0.138 -1.94,-2.551 -3.663,-5.975 -1.724,-3.424 -2.85,-6.268 -2.569,-6.406z"
android:fillColor="#d40000"
android:strokeColor="#00000000"
android:fillAlpha="1"/>
android:strokeColor="#00000000"/>
</vector>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.1 KiB

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.5 KiB

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.5 KiB

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 8.2 KiB

+84 -17
View File
@@ -1,20 +1,27 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="de.markusfisch.android.binaryeye"
android:installLocation="auto">
<supports-screens
android:largeScreens="true"
android:xlargeScreens="true"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
android:maxSdkVersion="28"/>
<uses-permission android:name="android.permission.BLUETOOTH"
android:maxSdkVersion="30"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"
android:maxSdkVersion="30"/>
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="28"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-feature android:name="android.hardware.camera"/>
<uses-feature android:name="android.hardware.camera.autofocus"/>
<uses-sdk tools:overrideLibrary="android.support.v14.preference"/>
<uses-feature android:name="android.hardware.camera.autofocus"
android:required="false" />
<uses-sdk tools:overrideLibrary="androidx.preference"/>
<queries>
<intent>
<action android:name="android.intent.action.VIEW"/>
@@ -31,6 +38,7 @@
android:usesCleartextTraffic="true"
android:allowBackup="true"
android:fullBackupContent="@xml/backup_rules"
android:dataExtractionRules="@xml/extraction_rules"
android:supportsRtl="true"
android:resizeableActivity="true"
android:label="@string/app_name"
@@ -38,8 +46,8 @@
android:theme="@style/AppTheme">
<activity
android:name=".activity.SplashActivity"
android:label="@string/app_name"
android:theme="@style/SplashTheme">
android:theme="@style/SplashTheme"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
@@ -50,11 +58,12 @@
</activity>
<activity
android:name=".activity.CameraActivity"
android:label="@string/scan_code">
android:label="@string/scan_code"
android:exported="true">
<intent-filter android:label="@string/compose_barcode">
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
<data android:mimeType="text/*"/>
</intent-filter>
<intent-filter>
<action android:name="com.google.zxing.client.android.SCAN"/>
@@ -64,15 +73,29 @@
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data
android:host="www.markusfisch.de"
android:pathPrefix="/BinaryEye"
android:scheme="http"/>
<data android:host="details" android:scheme="market"
android:pathSuffix="id=com.xiaomi.scanner"/>
</intent-filter>
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:host="markusfisch.de"/>
<data android:pathPrefix="/BinaryEye"/>
<data android:scheme="http"/>
<data android:scheme="https"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="binaryeye" android:host="scan"/>
</intent-filter>
</activity>
<activity
android:name=".activity.PickActivity"
android:label="@string/pick_code_to_scan"
android:exported="true"
tools:ignore="AppLinkUrlError">
<intent-filter android:label="@string/decode_barcode">
<action android:name="android.intent.action.SEND"/>
@@ -86,20 +109,64 @@
</intent-filter>
</activity>
<activity
android:name=".activity.MainActivity"
android:label="@string/app_name"
android:name=".activity.WelcomeActivity"
android:exported="true"/>
<activity
android:name=".activity.PreferencesActivity"
android:exported="true"/>
<activity
android:name=".activity.HistoryActivity"
android:exported="true"/>
<activity
android:name=".activity.EncodeActivity"
android:exported="true">
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:host="markusfisch.de"/>
<data android:pathPrefix="/encode"/>
<data android:scheme="http"/>
<data android:scheme="https"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="binaryeye" android:host="encode"/>
</intent-filter>
</activity>
<activity
android:name=".activity.DecodeActivity"
android:exported="false"/>
<activity
android:name=".activity.BarcodeActivity"
android:exported="false"/>
<activity
android:name=".activity.ProfilesActivity"
android:exported="false"/>
<activity
android:name=".activity.AutomatedActionsActivity"
android:exported="false"/>
<activity
android:name=".activity.IgnoreCodesActivity"
android:exported="false"/>
<activity
android:name=".activity.NetworkSuggestionsActivity"
android:exported="false"/>
<service
android:name=".service.ScanTileService"
android:icon="@drawable/ic_action_scan"
android:label="@string/scan_code"
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
android:exported="true"
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE"
tools:targetApi="n">
<intent-filter>
<action android:name="android.service.quicksettings.action.QS_TILE"/>
</intent-filter>
</service>
<provider
android:name="android.support.v4.content.FileProvider"
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
Binary file not shown.
@@ -0,0 +1,57 @@
package de.markusfisch.android.binaryeye.actions
import android.content.Context
import android.content.Intent
import de.markusfisch.android.binaryeye.content.execShareIntent
import de.markusfisch.android.binaryeye.content.openUrl
import de.markusfisch.android.binaryeye.widget.toast
abstract class Action {
abstract val iconResId: Int
abstract val titleResId: Int
var fired: Boolean = false
abstract fun canExecuteOn(data: ByteArray): Boolean
abstract suspend fun execute(context: Context, data: ByteArray)
}
abstract class IntentAction : Action() {
abstract val errorMsg: Int
final override suspend fun execute(context: Context, data: ByteArray) {
val intent = createIntent(context, data)
if (intent == null) {
context.toast(errorMsg)
} else {
fired = context.execShareIntent(intent)
}
}
abstract suspend fun createIntent(
context: Context,
data: ByteArray
): Intent?
}
abstract class SchemeAction : Action() {
abstract val scheme: String
open val buildRegex: Boolean = false
final override fun canExecuteOn(data: ByteArray): Boolean {
val content = String(data)
return if (buildRegex) {
content.matches(
"""^$scheme://[\w\W]+$""".toRegex(
RegexOption.IGNORE_CASE
)
)
} else {
content.startsWith("$scheme://", ignoreCase = true)
}
}
final override suspend fun execute(context: Context, data: ByteArray) {
fired = context.openUrl(String(data))
}
}
@@ -1,6 +1,7 @@
package de.markusfisch.android.binaryeye.actions
import de.markusfisch.android.binaryeye.actions.mail.MailAction
import de.markusfisch.android.binaryeye.actions.mail.MatMsgAction
import de.markusfisch.android.binaryeye.actions.otpauth.OtpauthAction
import de.markusfisch.android.binaryeye.actions.search.OpenOrSearchAction
import de.markusfisch.android.binaryeye.actions.sms.SmsAction
@@ -11,20 +12,23 @@ import de.markusfisch.android.binaryeye.actions.web.WebAction
import de.markusfisch.android.binaryeye.actions.wifi.WifiAction
object ActionRegistry {
val DEFAULT_ACTION: IAction = OpenOrSearchAction
val DEFAULT_ACTION: Action = OpenOrSearchAction
private val REGISTRY: Set<IAction> = setOf(
private val REGISTRY: Set<Action> = setOf(
MailAction,
MatMsgAction,
OtpauthAction,
SmsAction,
TelAction,
VCardAction,
VEventAction,
WebAction,
WifiAction
WifiAction,
// Try WebAction last because recognizing colloquial URLs is
// very aggressive.
WebAction
)
fun getAction(data: ByteArray): IAction = REGISTRY.find {
fun getAction(data: ByteArray): Action = REGISTRY.find {
it.canExecuteOn(data)
} ?: DEFAULT_ACTION
}
@@ -1,48 +0,0 @@
package de.markusfisch.android.binaryeye.actions
import android.content.Context
import android.content.Intent
import de.markusfisch.android.binaryeye.app.parseAndNormalizeUri
import de.markusfisch.android.binaryeye.content.execShareIntent
import de.markusfisch.android.binaryeye.widget.toast
interface IAction {
val iconResId: Int
val titleResId: Int
fun canExecuteOn(data: ByteArray): Boolean
suspend fun execute(context: Context, data: ByteArray)
}
abstract class IntentAction : IAction {
abstract val errorMsg: Int
final override suspend fun execute(context: Context, data: ByteArray) {
val intent = createIntent(context, data) ?: return context.toast(
errorMsg
)
execShareIntent(context, intent)
}
abstract suspend fun createIntent(context: Context, data: ByteArray): Intent?
}
abstract class SchemeAction : IAction {
abstract val scheme: String
open val intentAction: String = Intent.ACTION_VIEW
open val buildRegex: Boolean = false
final override fun canExecuteOn(data: ByteArray): Boolean {
val content = String(data)
return if (buildRegex) {
content.matches("""^$scheme://[\w\W]+$""".toRegex(RegexOption.IGNORE_CASE))
} else {
content.startsWith("$scheme://", ignoreCase = true)
}
}
final override suspend fun execute(context: Context, data: ByteArray) {
val uri = parseAndNormalizeUri(String(data))
execShareIntent(context, Intent(intentAction, uri))
}
}
@@ -2,7 +2,7 @@ package de.markusfisch.android.binaryeye.actions.mail
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.core.net.toUri
import de.markusfisch.android.binaryeye.R
import de.markusfisch.android.binaryeye.actions.IntentAction
@@ -24,7 +24,7 @@ object MailAction : IntentAction() {
)?.groupValues?.get(1) ?: return null
return Intent(
Intent.ACTION_SENDTO,
Uri.parse("mailto:$mailWithMessage")
"mailto:$mailWithMessage".toUri()
)
}
}
@@ -0,0 +1,55 @@
package de.markusfisch.android.binaryeye.actions.mail
import android.content.Context
import android.content.Intent
import androidx.core.net.toUri
import de.markusfisch.android.binaryeye.R
import de.markusfisch.android.binaryeye.actions.IntentAction
object MatMsgAction : IntentAction() {
override val iconResId: Int = R.drawable.ic_action_mail
override val titleResId: Int = R.string.mail_send
override val errorMsg: Int = R.string.mail_error
override fun canExecuteOn(data: ByteArray): Boolean {
return String(data).startsWith("MATMSG:")
}
override suspend fun createIntent(
context: Context,
data: ByteArray
): Intent? {
val mm = MatMsg(String(data))
// Allow incomplete but not completely missing data.
if (mm.isEmpty()) {
return null
}
return Intent(
Intent.ACTION_SENDTO,
"mailto:".toUri()
).apply {
mm.to?.let {
putExtra(Intent.EXTRA_EMAIL, arrayOf(mm.to))
}
mm.sub?.let {
putExtra(Intent.EXTRA_SUBJECT, mm.sub)
}
mm.body?.let {
putExtra(Intent.EXTRA_TEXT, mm.body)
}
}
}
}
// Public so this can be tested.
class MatMsg(encoded: String) {
// Allow arbitrary order.
val to = encoded.extractFirst("""[:;]TO:([\w.%@+-]+);""")
val sub = encoded.extractFirst("""[:;]SUB:([^;]+);""")
val body = encoded.extractFirst("""[:;]BODY:([^;]+);""")
fun isEmpty() = to == null && sub == null && body == null
}
private fun String.extractFirst(regex: String) =
regex.toRegex().find(this)?.groupValues?.get(1)
@@ -1,55 +1,66 @@
package de.markusfisch.android.binaryeye.actions.search
import android.content.Context
import android.content.Intent
import de.markusfisch.android.binaryeye.R
import de.markusfisch.android.binaryeye.actions.IAction
import de.markusfisch.android.binaryeye.actions.Action
import de.markusfisch.android.binaryeye.app.alertDialog
import de.markusfisch.android.binaryeye.app.parseAndNormalizeUri
import de.markusfisch.android.binaryeye.app.prefs
import de.markusfisch.android.binaryeye.content.execShareIntent
import de.markusfisch.android.binaryeye.widget.toast
import java.net.URLEncoder
import de.markusfisch.android.binaryeye.content.openUrl
import de.markusfisch.android.binaryeye.net.urlEncode
object OpenOrSearchAction : IAction {
object OpenOrSearchAction : Action() {
override val iconResId: Int = R.drawable.ic_action_search
override val titleResId: Int = R.string.search_web
override fun canExecuteOn(data: ByteArray): Boolean = false
override suspend fun execute(context: Context, data: ByteArray) {
val intent = openUri(context, String(data)) ?: return
execShareIntent(context, intent)
}
private suspend fun openUri(context: Context, data: String, search: Boolean = true): Intent? {
val uri = parseAndNormalizeUri(data)
val intent = Intent(Intent.ACTION_VIEW, uri)
when {
intent.resolveActivity(context.packageManager) != null -> return intent
search -> return getSearchIntent(context, data)
else -> context.toast(R.string.cannot_resolve_action)
}
return null
}
private suspend fun getSearchIntent(context: Context, query: String): Intent? {
val names = context.resources.getStringArray(
R.array.search_engines_names
).toMutableList()
val urls = context.resources.getStringArray(
R.array.search_engines_values
).toMutableList()
if (prefs.openWithUrl.isNotEmpty()) {
names.add(prefs.openWithUrl)
urls.add(prefs.openWithUrl)
}
val queryUri = alertDialog<String>(context) { resume ->
setTitle(R.string.pick_search_engine)
setItems(names.toTypedArray()) { _, which ->
resume(urls[which] + URLEncoder.encode(query, "utf-8"))
}
} ?: return null
return openUri(context, queryUri, false)
fired = openUrlOrSearch(context, String(data))
}
}
private suspend fun openUrlOrSearch(
context: Context,
url: String,
search: Boolean = true
): Boolean {
if (context.openUrl(url, silent = true)) {
return true
}
if (search) {
return prependSearchUrl(context, url)?.let {
openUrlOrSearch(context, it, false)
} ?: false
}
return false
}
private suspend fun prependSearchUrl(
context: Context,
query: String
): String? {
val defaultSearchUrl = prefs.defaultSearchUrl
if (defaultSearchUrl.isNotEmpty()) {
return defaultSearchUrl + query.urlEncode()
}
val names = context.resources.getStringArray(
R.array.search_engines_names
).toMutableList()
val urls = context.resources.getStringArray(
R.array.search_engines_values
).toMutableList()
// Remove the "Always ask" entry. The arrays search_engines_*
// are used in the preferences too.
names.removeAt(0)
urls.removeAt(0)
if (prefs.openWithUrl.isNotEmpty()) {
names.add(prefs.openWithUrl)
urls.add(prefs.openWithUrl)
}
return alertDialog(context) { resume ->
setTitle(R.string.pick_search_engine)
setItems(names.toTypedArray()) { _, which ->
resume(urls[which] + query.urlEncode())
}
}
}
@@ -2,13 +2,14 @@ package de.markusfisch.android.binaryeye.actions.sms
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.core.net.toUri
import de.markusfisch.android.binaryeye.R
import de.markusfisch.android.binaryeye.actions.IntentAction
object SmsAction : IntentAction() {
private val smsRegex =
"""^sms(?:to)?:(\+?[0-9]+)(?::([\S\s]*))?$""".toRegex(RegexOption.IGNORE_CASE)
private val smsRegex = """^sms(?:to)?:(\+?[0-9]+)(?::([\S\s]*))?$""".toRegex(
RegexOption.IGNORE_CASE
)
override val iconResId: Int = R.drawable.ic_action_sms
override val titleResId: Int = R.string.sms_send
@@ -26,9 +27,11 @@ object SmsAction : IntentAction() {
} ?: return null
return Intent(
Intent.ACTION_SENDTO,
Uri.parse("smsto:$number")
"smsto:$number".toUri()
).apply {
if (message.isNotEmpty()) putExtra("sms_body", message)
if (message.isNotEmpty()) {
putExtra("sms_body", message)
}
}
}
}
@@ -4,10 +4,12 @@ import android.content.Context
import android.content.Intent
import de.markusfisch.android.binaryeye.R
import de.markusfisch.android.binaryeye.actions.IntentAction
import de.markusfisch.android.binaryeye.app.parseAndNormalizeUri
import de.markusfisch.android.binaryeye.content.parseAndNormalizeUri
object TelAction : IntentAction() {
private val telRegex = """^tel:(\+?[0-9]+)$""".toRegex(RegexOption.IGNORE_CASE)
private val telRegex = """^tel:(\+?[0-9]+)$""".toRegex(
RegexOption.IGNORE_CASE
)
override val iconResId: Int = R.drawable.ic_action_tel
override val titleResId: Int = R.string.tel_dial
@@ -17,7 +19,11 @@ object TelAction : IntentAction() {
return String(data).matches(telRegex)
}
override suspend fun createIntent(context: Context, data: ByteArray): Intent {
return Intent(Intent.ACTION_DIAL, parseAndNormalizeUri(String(data)))
}
override suspend fun createIntent(
context: Context,
data: ByteArray
): Intent = Intent(
Intent.ACTION_DIAL,
String(data).parseAndNormalizeUri()
)
}
@@ -1,6 +1,6 @@
package de.markusfisch.android.binaryeye.actions.vtype
import java.util.*
import java.util.Locale
object VTypeParser {
private const val BACKSLASH_R_LEGACY =
@@ -15,7 +15,7 @@ object VTypeParser {
fun parseVType(data: String): String? = vTypeRegex.matchEntire(
data
)?.groupValues?.get(1)?.toUpperCase(Locale.US)
)?.groupValues?.get(1)?.uppercase(Locale.US)
fun parseMap(
data: String
@@ -26,7 +26,7 @@ object VTypeParser {
it.groupValues[2]
)
}
}.groupBy({ it.first.toUpperCase(Locale.US) }) { it.second }
}.groupBy({ it.first.uppercase(Locale.US) }) { it.second }
}
data class VTypeProperty(
@@ -39,6 +39,6 @@ data class VTypeProperty(
} ?: this.info.firstOrNull()
companion object {
private val typeRegex = """^(?:TYPE=)(.+?)[:;]?.*$""".toRegex(RegexOption.IGNORE_CASE)
private val typeRegex = """^TYPE=([A-Z_]+)[:;]?.*$""".toRegex(RegexOption.IGNORE_CASE)
}
}
@@ -3,13 +3,11 @@ package de.markusfisch.android.binaryeye.actions.vtype.vcard
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.os.Build
import android.provider.ContactsContract
import de.markusfisch.android.binaryeye.R
import de.markusfisch.android.binaryeye.actions.IntentAction
import de.markusfisch.android.binaryeye.actions.vtype.VTypeParser
import java.util.*
import kotlin.collections.ArrayList
import java.util.Locale
object VCardAction : IntentAction() {
override val iconResId: Int
@@ -20,10 +18,19 @@ object VCardAction : IntentAction() {
get() = R.string.vcard_failed
override fun canExecuteOn(data: ByteArray): Boolean {
return VTypeParser.parseVType(String(data)) == "VCARD"
var stringData = String(data)
// Quick & dirty MECARD support: simply make it a VCARD.
if (stringData.startsWith("MECARD:")) {
stringData = stringData
.trim()
.replace("MECARD:", "BEGIN:VCARD\n")
.replace(";;", "\nEND:VCARD\n")
.replace(";", "\n")
}
return VTypeParser.parseVType(stringData) == "VCARD"
}
override suspend fun createIntent(context: Context, data: ByteArray): Intent? {
override suspend fun createIntent(context: Context, data: ByteArray): Intent {
val info = VTypeParser.parseMap(String(data))
return Intent(Intent.ACTION_INSERT_OR_EDIT).apply {
@@ -37,10 +44,13 @@ object VCardAction : IntentAction() {
val (extraPhoneType, extraPhone) = when (index) {
0 -> ContactsContract.Intents.Insert.PHONE_TYPE to
ContactsContract.Intents.Insert.PHONE
1 -> ContactsContract.Intents.Insert.SECONDARY_PHONE_TYPE to
ContactsContract.Intents.Insert.SECONDARY_PHONE
2 -> ContactsContract.Intents.Insert.TERTIARY_PHONE_TYPE to
ContactsContract.Intents.Insert.TERTIARY_PHONE_TYPE
else -> return@forEachIndexed
}
phoneProperty.firstTypeOrFirstInfo?.also {
@@ -50,17 +60,20 @@ object VCardAction : IntentAction() {
}
putExtra(
extraPhone,
phoneProperty.value.toLowerCase(Locale.US).removePrefix("tel:")
phoneProperty.value.lowercase(Locale.US).removePrefix("tel:")
)
}
info["EMAIL"]?.forEachIndexed { index, mailProperty ->
val (extraMailType, extraMail) = when (index) {
0 -> ContactsContract.Intents.Insert.EMAIL_TYPE to
ContactsContract.Intents.Insert.EMAIL
1 -> ContactsContract.Intents.Insert.SECONDARY_EMAIL_TYPE to
ContactsContract.Intents.Insert.SECONDARY_EMAIL
2 -> ContactsContract.Intents.Insert.TERTIARY_EMAIL_TYPE to
ContactsContract.Intents.Insert.TERTIARY_EMAIL
else -> return@forEachIndexed
}
mailProperty.firstTypeOrFirstInfo?.also {
@@ -84,38 +97,36 @@ object VCardAction : IntentAction() {
}
putExtra(ContactsContract.Intents.Insert.POSTAL, addr.value.locationFormat)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
val urls = info["URL"]?.mapNotNull {
it.value.takeIf { url -> url.isNotBlank() }?.let { url ->
ContentValues(2).apply {
put(
ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE
)
put(ContactsContract.CommonDataKinds.Website.URL, url)
}
val urls = info["URL"]?.mapNotNull {
it.value.takeIf { url -> url.isNotBlank() }?.let { url ->
ContentValues(2).apply {
put(
ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE
)
put(ContactsContract.CommonDataKinds.Website.URL, url)
}
}
val bDays = info["BDAY"]?.mapNotNull {
it.value.takeIf { day -> day.isNotBlank() }?.let { day ->
ContentValues(3).apply {
put(
ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE
)
put(
ContactsContract.CommonDataKinds.Event.TYPE,
ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY
)
put(ContactsContract.CommonDataKinds.Event.START_DATE, day)
}
}
}
putParcelableArrayListExtra(
ContactsContract.Intents.Insert.DATA,
ArrayList(listOfNotNull(urls, bDays).flatten())
)
}
val bDays = info["BDAY"]?.mapNotNull {
it.value.takeIf { day -> day.isNotBlank() }?.let { day ->
ContentValues(3).apply {
put(
ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE
)
put(
ContactsContract.CommonDataKinds.Event.TYPE,
ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY
)
put(ContactsContract.CommonDataKinds.Event.START_DATE, day)
}
}
}
putParcelableArrayListExtra(
ContactsContract.Intents.Insert.DATA,
ArrayList(listOfNotNull(urls, bDays).flatten())
)
}
}
@@ -142,7 +153,7 @@ object VCardAction : IntentAction() {
} ?: this
private val String.mailType: Int?
get() = when (this.toUpperCase(Locale.US)) {
get() = when (this.uppercase(Locale.US)) {
"HOME" -> ContactsContract.CommonDataKinds.Email.TYPE_HOME
"WORK" -> ContactsContract.CommonDataKinds.Email.TYPE_WORK
"OTHER" -> ContactsContract.CommonDataKinds.Email.TYPE_OTHER
@@ -151,7 +162,7 @@ object VCardAction : IntentAction() {
}
private val String.phoneType: Int?
get() = when (this.toUpperCase(Locale.US)) {
get() = when (this.uppercase(Locale.US)) {
"HOME" -> ContactsContract.CommonDataKinds.Phone.TYPE_HOME
"MOBILE", "CELL" -> ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE
"WORK" -> ContactsContract.CommonDataKinds.Phone.TYPE_WORK
@@ -176,7 +187,7 @@ object VCardAction : IntentAction() {
}
private val String.addressType: Int?
get() = when (this.toUpperCase(Locale.US)) {
get() = when (this.uppercase()) {
"HOME" -> ContactsContract.CommonDataKinds.StructuredPostal.TYPE_HOME
"WORK" -> ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK
"OTHER" -> ContactsContract.CommonDataKinds.StructuredPostal.TYPE_OTHER
@@ -1,16 +1,14 @@
package de.markusfisch.android.binaryeye.actions.vtype.vevent
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Build
import android.provider.CalendarContract
import android.support.annotation.RequiresApi
import de.markusfisch.android.binaryeye.R
import de.markusfisch.android.binaryeye.actions.IntentAction
import de.markusfisch.android.binaryeye.actions.vtype.VTypeParser
import java.text.SimpleDateFormat
import java.util.*
import java.util.Date
import java.util.Locale
object VEventAction : IntentAction() {
override val iconResId: Int
@@ -21,14 +19,10 @@ object VEventAction : IntentAction() {
get() = R.string.vevent_failed
override fun canExecuteOn(data: ByteArray): Boolean {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
return false
}
val type = VTypeParser.parseVType(String(data))
return type == "VEVENT" || type == "VCALENDAR"
}
@RequiresApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
override suspend fun createIntent(context: Context, data: ByteArray): Intent? {
val info = VTypeParser.parseMap(String(data))
@@ -45,37 +39,49 @@ object VEventAction : IntentAction() {
}
info["DTSTART"]?.singleOrNull()?.also { eventStart ->
dateFormats.simpleFindParse(eventStart.value)?.also {
putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, it.time)
putExtra(
CalendarContract.EXTRA_EVENT_BEGIN_TIME,
it.time
)
}
}
info["DTEND"]?.singleOrNull()?.also { eventEnd ->
dateFormats.simpleFindParse(eventEnd.value)?.also {
putExtra(CalendarContract.EXTRA_EVENT_END_TIME, it.time)
putExtra(
CalendarContract.EXTRA_EVENT_END_TIME,
it.time
)
}
}
}
}
@SuppressLint("SimpleDateFormat") // we definitely don't wan't the local format
private val dateFormats = listOf(
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"),
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"),
SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'"),
SimpleDateFormat("yyyyMMdd'T'HHmmss"),
SimpleDateFormat("yyyy-MM-dd"),
SimpleDateFormat("yyyyMMdd")
)
private fun List<SimpleDateFormat>.simpleFindParse(data: String): Date? {
for (simpleDataFormat in this) {
return simpleDataFormat.simpleParse(data) ?: continue
}
return null
}
private fun SimpleDateFormat.simpleParse(data: String): Date? = try {
this.parse(data)
} catch (e: Exception) {
null
}
}
private val dateFormats = listOf(
"yyyy-MM-dd'T'HH:mm:ssXXX",
"yyyy-MM-dd'T'HH:mm:ssZ",
"yyyy-MM-dd'T'HH:mm:ssz",
"yyyy-MM-dd'T'HH:mm:ss",
"yyyyMMdd'T'HHmmssXXX",
"yyyyMMdd'T'HHmmssZ",
"yyyyMMdd'T'HHmmssz",
"yyyyMMdd'T'HHmmss",
"yyyy-MM-dd",
"yyyyMMdd"
)
private fun List<String>.simpleFindParse(date: String): Date? {
for (pattern in this) {
return SimpleDateFormat(
pattern,
Locale.getDefault()
).simpleParse(date) ?: continue
}
return null
}
private fun SimpleDateFormat.simpleParse(date: String): Date? = try {
parse(date)
} catch (_: Exception) {
null
}
@@ -1,11 +1,29 @@
package de.markusfisch.android.binaryeye.actions.web
import android.content.Context
import de.markusfisch.android.binaryeye.R
import de.markusfisch.android.binaryeye.actions.SchemeAction
import de.markusfisch.android.binaryeye.actions.Action
import de.markusfisch.android.binaryeye.content.openUrl
object WebAction : Action() {
private val colloquialRegex =
"^(URL:[ ]*)*(http[s]*://)*[A-Za-z0-9.-]{3,}\\.[A-Za-z]{2,}[^ \t\r\n]*$".toRegex()
object WebAction : SchemeAction() {
override val iconResId: Int = R.drawable.ic_action_open
override val titleResId: Int = R.string.open_url
override val scheme: String = "https?"
override val buildRegex: Boolean = true
override fun canExecuteOn(data: ByteArray): Boolean {
return String(data).trim().matches(colloquialRegex)
}
override suspend fun execute(context: Context, data: ByteArray) {
var url = String(data).trim()
if (url.startsWith("URL:")) {
url = url.substring(4).trim()
}
if (!url.startsWith("http") && !url.startsWith("ftp")) {
url = "http://${url}"
}
fired = context.openUrl(url)
}
}
@@ -2,32 +2,39 @@ package de.markusfisch.android.binaryeye.actions.wifi
import android.content.Context
import de.markusfisch.android.binaryeye.R
import de.markusfisch.android.binaryeye.actions.IAction
import de.markusfisch.android.binaryeye.actions.Action
import de.markusfisch.android.binaryeye.widget.toast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
object WifiAction : IAction {
object WifiAction : Action() {
override val iconResId = R.drawable.ic_action_wifi
override val titleResId = R.string.connect_to_wifi
var password: String? = null
override fun canExecuteOn(data: ByteArray): Boolean =
WifiConnector.parse(String(data)) {
password = it
} != null
override fun canExecuteOn(data: ByteArray): Boolean {
// Just check if the data can be parsed as the app should also
// show invalid configurations so users can still access them.
val inputMap = WifiConnector.parseMap(String(data)) ?: return false
password = inputMap["P"]
return !inputMap["S"].isNullOrEmpty()
}
override suspend fun execute(
context: Context,
data: ByteArray
) = withContext(Dispatchers.IO) {
val wifiConfig = WifiConnector.parse(
String(data)
) ?: return@withContext
val message = WifiConnector.addNetwork(context, wifiConfig)
withContext(Dispatchers.Main) {
context.toast(message)
override suspend fun execute(context: Context, data: ByteArray) {
withContext(Dispatchers.IO) {
fired = WifiConnector.parse(String(data))?.let {
WifiConnector.addNetwork(context, it)
} ?: false
withContext(Dispatchers.Main) {
context.toast(
if (fired) {
R.string.wifi_added
} else {
R.string.wifi_config_failed
}
)
}
}
}
}
@@ -1,14 +1,15 @@
package de.markusfisch.android.binaryeye.actions.wifi
import android.content.Context
import android.content.Intent
import android.net.wifi.WifiConfiguration
import android.net.wifi.WifiEnterpriseConfig
import android.net.wifi.WifiManager
import android.net.wifi.WifiNetworkSuggestion
import android.os.Build
import android.support.annotation.RequiresApi
import de.markusfisch.android.binaryeye.R
import java.util.*
import android.provider.Settings
import androidx.annotation.RequiresApi
import java.util.Locale
/**
* Normal:
@@ -35,66 +36,61 @@ import java.util.*
* The fields can appear in any order. Only "S:" is required.
*/
object WifiConnector {
fun parse(
input: String,
passwordBlock: ((password: String?) -> Unit)? = null
): Any? {
fun parse(input: String): Any? {
val inputMap = parseMap(input) ?: return null
val parsedData = SimpleDataAccessor.of(inputMap) ?: return null
passwordBlock?.apply {
invoke(parsedData.password)
}
return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
// WifiConfiguration is deprecated in Android Q
@Suppress("DEPRECATION")
WifiConfiguration().apply(parsedData)
} else {
WifiNetworkSuggestion.Builder().apply(parsedData)
return try {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.Q) {
// WifiConfiguration is deprecated in Android Q but
// because it's only possible in R to query network
// suggestions, we still use the deprecated API on Q.
@Suppress("DEPRECATION")
WifiConfiguration().apply(parsedData)
} else {
WifiNetworkSuggestion.Builder().apply(parsedData)
}
} catch (_: IllegalArgumentException) {
// Some arguments may be out of range, e.g. SSIDs cannot
// be longer than 32 characters in some versions of Android.
// See: https://github.com/markusfisch/BinaryEye/issues/402
null
}
}
fun addNetwork(context: Context, config: Any): Int {
fun addNetwork(context: Context, config: Any): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R &&
config is WifiNetworkSuggestion.Builder
) {
context.suggestNetworkFromBuilder(config)
return true
}
val wifiManager = context.applicationContext.getSystemService(
Context.WIFI_SERVICE
) as WifiManager
return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
// WifiConfiguration is deprecated in Android Q
@Suppress("DEPRECATION")
val wifiConfig = config as WifiConfiguration
if (wifiManager.enableWifi() &&
wifiManager.removeOldNetwork(wifiConfig) &&
wifiManager.enableNewNetwork(wifiConfig)
) {
R.string.wifi_added
} else {
R.string.wifi_config_failed
}
} else {
val suggestion = (config as WifiNetworkSuggestion.Builder).build()
val suggestions = listOf(suggestion)
// remove previous conflicting network suggestion
wifiManager.removeNetworkSuggestions(suggestions)
val result = wifiManager.addNetworkSuggestions(suggestions)
if (result == WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS) {
R.string.wifi_added
} else {
R.string.wifi_config_failed
}
}
// WifiConfiguration is deprecated in Android Q.
@Suppress("DEPRECATION")
return (config is WifiConfiguration &&
wifiManager.enableWifi() &&
wifiManager.removeOldNetwork(config) &&
wifiManager.enableNewNetwork(config)) ||
(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q &&
config is WifiNetworkSuggestion.Builder &&
wifiManager.addNetworkFromBuilder(config))
}
internal fun parseMap(string: String): Map<String, String>? {
// normally those codes should have the last semicolon, but many
// generators don't add it
internal fun parseMap(input: String): Map<String, String>? {
// Normally those codes should have the last semicolon, but many
// generators don't add it.
val wifiRegex = """^WIFI:((?:.+?:(?:[^\\;]|\\.)*;)+);?$""".toRegex()
// should be: ^(.+):((?:[^\\;,":]|\\.)*);$ but allows unescaped , "
// and : because many QR Code creators don't escape properly
// Should be: ^(.+):((?:[^\\;,":]|\\.)*);$ but allows unescaped , "
// and : because many QR Code creators don't escape properly.
val pairRegex = """(.+?):((?:[^\\;]|\\.)*);""".toRegex()
return wifiRegex.matchEntire(
string
input.trimAndTerminate()
)?.groupValues?.get(1)?.let { pairs ->
pairRegex.findAll(pairs).map { pair ->
pair.groupValues[1].toUpperCase(Locale.US) to pair.groupValues[2]
pair.groupValues[1].uppercase(Locale.US) to pair.groupValues[2].unescape
}.toMap()
}
}
@@ -102,49 +98,45 @@ object WifiConnector {
internal class SimpleDataAccessor private constructor(
private val inputMap: Map<String, String>
) {
// this should be private but because of testing it isn't possible
// This should be private but because of testing it isn't possible.
internal val ssid: String
get() = inputMap.getValue("S").unescape
get() = inputMap.getValue("S")
internal val securityType: String
get() = inputMap["T"]?.unescape ?: ""
get() = inputMap["T"] ?: ""
internal val password: String?
get() = inputMap["P"]?.unescape
get() = inputMap["P"]
internal val hidden: Boolean
get() = inputMap["H"]?.unescape == "true"
get() = inputMap["H"] == "true"
internal val anonymousIdentity: String
get() = inputMap["AI"]?.unescape ?: ""
get() = inputMap["AI"] ?: inputMap["A"] ?: ""
internal val identity: String
get() = inputMap["I"]?.unescape ?: ""
get() = inputMap["I"] ?: ""
internal val eapMethod: Int?
get() = if (inputMap["E"].isNullOrEmpty()) {
requireSdk(Build.VERSION_CODES.JELLY_BEAN_MR2) {
WifiEnterpriseConfig.Eap.NONE
}
} else when (inputMap["E"]) {
"AKA" -> requireSdk(Build.VERSION_CODES.LOLLIPOP) { WifiEnterpriseConfig.Eap.AKA }
WifiEnterpriseConfig.Eap.NONE
} else when (inputMap["E"]?.uppercase()) {
"AKA" -> WifiEnterpriseConfig.Eap.AKA
"AKA_PRIME" -> requireSdk(Build.VERSION_CODES.M) { WifiEnterpriseConfig.Eap.AKA_PRIME }
"NONE" -> requireSdk(Build.VERSION_CODES.JELLY_BEAN_MR2) { WifiEnterpriseConfig.Eap.NONE }
"PEAP" -> requireSdk(Build.VERSION_CODES.JELLY_BEAN_MR2) { WifiEnterpriseConfig.Eap.PEAP }
"PWD" -> requireSdk(Build.VERSION_CODES.JELLY_BEAN_MR2) { WifiEnterpriseConfig.Eap.PWD }
"SIM" -> requireSdk(Build.VERSION_CODES.LOLLIPOP) { WifiEnterpriseConfig.Eap.SIM }
"TLS" -> requireSdk(Build.VERSION_CODES.JELLY_BEAN_MR2) { WifiEnterpriseConfig.Eap.TLS }
"TTLS" -> requireSdk(Build.VERSION_CODES.JELLY_BEAN_MR2) { WifiEnterpriseConfig.Eap.TTLS }
"NONE" -> WifiEnterpriseConfig.Eap.NONE
"PEAP" -> WifiEnterpriseConfig.Eap.PEAP
"PWD" -> WifiEnterpriseConfig.Eap.PWD
"SIM" -> WifiEnterpriseConfig.Eap.SIM
"TLS" -> WifiEnterpriseConfig.Eap.TLS
"TTLS" -> WifiEnterpriseConfig.Eap.TTLS
"UNAUTH_TLS" -> requireSdk(Build.VERSION_CODES.N) { WifiEnterpriseConfig.Eap.UNAUTH_TLS }
else -> null
}
internal val phase2Method: Int?
get() = if (inputMap["PH2"].isNullOrEmpty()) {
requireSdk(Build.VERSION_CODES.JELLY_BEAN_MR2) {
WifiEnterpriseConfig.Phase2.NONE
}
} else when (inputMap["PH2"]) {
WifiEnterpriseConfig.Phase2.NONE
} else when (inputMap["PH2"]?.uppercase()) {
"AKA" -> requireSdk(Build.VERSION_CODES.O) { WifiEnterpriseConfig.Phase2.AKA }
"AKA_PRIME" -> requireSdk(Build.VERSION_CODES.O) { WifiEnterpriseConfig.Phase2.AKA_PRIME }
"GTC" -> requireSdk(Build.VERSION_CODES.JELLY_BEAN_MR2) { WifiEnterpriseConfig.Phase2.GTC }
"MSCHAP" -> requireSdk(Build.VERSION_CODES.JELLY_BEAN_MR2) { WifiEnterpriseConfig.Phase2.MSCHAP }
"MSCHAPV2" -> requireSdk(Build.VERSION_CODES.JELLY_BEAN_MR2) { WifiEnterpriseConfig.Phase2.MSCHAPV2 }
"NONE" -> requireSdk(Build.VERSION_CODES.JELLY_BEAN_MR2) { WifiEnterpriseConfig.Phase2.NONE }
"PAP" -> requireSdk(Build.VERSION_CODES.JELLY_BEAN_MR2) { WifiEnterpriseConfig.Phase2.PAP }
"GTC" -> WifiEnterpriseConfig.Phase2.GTC
"MSCHAP" -> WifiEnterpriseConfig.Phase2.MSCHAP
"MSCHAPV2" -> WifiEnterpriseConfig.Phase2.MSCHAPV2
"NONE" -> WifiEnterpriseConfig.Phase2.NONE
"PAP" -> WifiEnterpriseConfig.Phase2.PAP
"SIM" -> requireSdk(Build.VERSION_CODES.O) { WifiEnterpriseConfig.Phase2.SIM }
else -> null
}
@@ -164,7 +156,7 @@ object WifiConnector {
): WifiNetworkSuggestion.Builder? {
fun WifiNetworkSuggestion.Builder.applyCommon(
data: SimpleDataAccessor
): WifiNetworkSuggestion.Builder? {
): WifiNetworkSuggestion.Builder {
setSsid(data.ssid)
return this
}
@@ -172,47 +164,47 @@ object WifiConnector {
fun WifiNetworkSuggestion.Builder.applySecurity(
data: SimpleDataAccessor
): WifiNetworkSuggestion.Builder? {
when (data.securityType) {
"WPA", "WPA2" -> {
data.password?.let {
setWpa2Passphrase(it)
try {
when (data.securityType.uppercase()) {
"WPA", "WPA2" -> {
data.password?.let { setWpa2Passphrase(it) }
}
"WPA2-EAP" -> {
setWpa2EnterpriseConfig(WifiEnterpriseConfig().apply {
identity = data.identity
anonymousIdentity = data.anonymousIdentity
password = data.password
data.eapMethod?.let { eapMethod = it }
data.phase2Method?.let { phase2Method = it }
})
}
"WPA3" -> {
data.password?.let { setWpa3Passphrase(it) }
}
"WPA3-EAP" -> {
setWpa3EnterpriseConfig(WifiEnterpriseConfig().apply {
identity = data.identity
anonymousIdentity = data.anonymousIdentity
password = data.password
data.eapMethod?.let { eapMethod = it }
data.phase2Method?.let { phase2Method = it }
})
}
}
"WPA2-EAP" -> {
data.password?.let {
setWpa2Passphrase(it)
}
setWpa2EnterpriseConfig(WifiEnterpriseConfig().apply {
identity = data.identity
anonymousIdentity = data.anonymousIdentity
password = data.password
data.eapMethod?.let { eapMethod = it }
data.phase2Method?.let { phase2Method = it }
})
}
"WPA3" -> {
data.password?.let {
setWpa3Passphrase(it)
}
}
"WPA3-EAP" -> {
data.password?.let { setWpa3Passphrase(it) }
setWpa3EnterpriseConfig(WifiEnterpriseConfig().apply {
identity = data.identity
anonymousIdentity = data.anonymousIdentity
password = data.password
data.eapMethod?.let { eapMethod = it }
data.phase2Method?.let { phase2Method = it }
})
}
} catch (_: IllegalArgumentException) {
// Don't accept passphrases that aren't ASCII encodeable.
return null
}
return this
}
return this.applyCommon(data)?.applySecurity(data)
return this.applyCommon(data).applySecurity(data)
}
// WifiConfiguration is deprecated in Android Q
// WifiConfiguration is deprecated in Android Q.
@Suppress("DEPRECATION")
private fun WifiConfiguration.apply(
data: SimpleDataAccessor
@@ -222,7 +214,7 @@ object WifiConnector {
fun WifiConfiguration.applyCommon(
data: SimpleDataAccessor
): WifiConfiguration? {
): WifiConfiguration {
allowedAuthAlgorithms.clear()
allowedGroupCiphers.clear()
allowedKeyManagement.clear()
@@ -237,8 +229,8 @@ object WifiConnector {
fun WifiConfiguration.applySecurity(
data: SimpleDataAccessor
): WifiConfiguration? {
when (data.securityType) {
"", "nopass" -> allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE)
when (data.securityType.uppercase()) {
"", "NOPASS" -> allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE)
"WEP" -> @Suppress("DEPRECATION") /* WEP as insecure */ {
passwordWithQuotes?.let {
wepKeys[0] = it
@@ -251,6 +243,7 @@ object WifiConnector {
allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40)
allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104)
}
"WPA" -> {
passwordWithQuotes?.let {
preSharedKey = it
@@ -267,14 +260,15 @@ object WifiConnector {
allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP)
allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP)
}
"WPA2-EAP" -> requireSdk(Build.VERSION_CODES.JELLY_BEAN_MR2) {
"WPA2-EAP" -> {
passwordWithQuotes?.let {
preSharedKey = it
} ?: return null
allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN)
allowedProtocols.set(WifiConfiguration.Protocol.RSN) // WPA2
allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP)
@Suppress("DEPRECATION") // TKIP is insecure and has bad performance
@Suppress("DEPRECATION") // TKIP is insecure and has bad performance.
allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP)
allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP)
allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP)
@@ -287,12 +281,12 @@ object WifiConnector {
data.eapMethod ?: return null // non valid eapMethod
enterpriseConfig.phase2Method =
data.phase2Method ?: return null // non valid phase2Method
} ?: return null // api isn't high enough
}
}
return this
}
return this.applyCommon(data)?.applySecurity(data)
return this.applyCommon(data).applySecurity(data)
}
private inline fun <T> requireSdk(version: Int, block: () -> T): T? {
@@ -300,11 +294,47 @@ object WifiConnector {
}
}
// keep possibility of wrongly unescaped \ by explicitly searching
// for special chars
@RequiresApi(Build.VERSION_CODES.Q)
private fun WifiManager.addNetworkFromBuilder(
builder: WifiNetworkSuggestion.Builder
): Boolean {
val suggestion = builder.build()
val suggestions = listOf(suggestion)
// Remove previous conflicting network suggestion.
removeNetworkSuggestions(suggestions)
val result = addNetworkSuggestions(suggestions)
return result == WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS
}
@RequiresApi(Build.VERSION_CODES.R)
private fun Context.suggestNetworkFromBuilder(
builder: WifiNetworkSuggestion.Builder
) {
val suggestion = builder.build()
startActivity(
Intent(Settings.ACTION_WIFI_ADD_NETWORKS).apply {
putParcelableArrayListExtra(
Settings.EXTRA_WIFI_NETWORK_LIST,
arrayListOf(suggestion)
)
}
)
}
// Make sure the string ends with a semicolon.
private fun String.trimAndTerminate(): String {
var trimmed = trim()
if (trimmed.isNotEmpty() && trimmed.last() != ';') {
trimmed += ";"
}
return trimmed
}
// Keep possibility of wrongly unescaped \ by explicitly searching
// for special chars.
private val escapedRegex = """\\([\\;,":])""".toRegex()
private val String.unescape: String
get() = this.replace(escapedRegex) { escaped ->
get() = replace(escapedRegex) { escaped ->
escaped.groupValues[1]
}
@@ -327,12 +357,12 @@ private fun String.isHex() = length == 64 && matches(hexRegex)
private fun WifiManager.enableWifi(): Boolean {
// setWifiEnabled() will always return false for Android Q
// because Q doesn't allow apps to enable/disable Wi-Fi anymore
// because Q doesn't allow apps to enable/disable Wi-Fi anymore.
@Suppress("DEPRECATION")
return isWifiEnabled || setWifiEnabled(true)
}
// WifiConfiguration is deprecated in Android Q
// WifiConfiguration is deprecated in Android Q.
@Suppress("DEPRECATION")
private fun WifiManager.removeOldNetwork(
wifiConfig: WifiConfiguration
@@ -344,14 +374,14 @@ private fun WifiManager.removeOldNetwork(
}?.networkId?.also {
removeNetwork(it)
}
} catch (e: SecurityException) {
// the user didn't allow ACCESS_FINE_LOCATION which is
// required to access configuredNetworks and that's fine
} catch (_: SecurityException) {
// The user didn't allow ACCESS_FINE_LOCATION which is
// required to access configuredNetworks and that's fine.
}
return true
}
// WifiConfiguration is deprecated in Android Q
// WifiConfiguration is deprecated in Android Q.
@Suppress("DEPRECATION")
private fun WifiManager.enableNewNetwork(
wifiConfig: WifiConfiguration
@@ -0,0 +1,65 @@
package de.markusfisch.android.binaryeye.activity
import android.content.Context
import android.content.pm.PackageManager
import android.view.Menu
import android.view.MenuInflater
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isNotEmpty
import de.markusfisch.android.binaryeye.app.PERMISSION_LOCATION
import de.markusfisch.android.binaryeye.app.PERMISSION_WRITE
import de.markusfisch.android.binaryeye.app.applyLocale
import de.markusfisch.android.binaryeye.app.permissionGrantedCallback
import de.markusfisch.android.binaryeye.app.prefs
import de.markusfisch.android.binaryeye.view.initBars
abstract class AbstractBaseActivity : AppCompatActivity() {
override fun attachBaseContext(base: Context?) {
base?.applyLocale(prefs.customLocale)
super.attachBaseContext(base)
}
protected fun setScreenContentView(@LayoutRes layoutId: Int) {
setContentView(layoutId)
initBars()
supportActionBar?.setDisplayHomeAsUpEnabled(true)
}
override fun onSupportNavigateUp(): Boolean {
finish()
return true
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(
requestCode,
permissions,
grantResults
)
when (requestCode) {
PERMISSION_LOCATION, PERMISSION_WRITE -> {
if (grantResults.isNotEmpty() &&
grantResults[0] == PackageManager.PERMISSION_GRANTED
) {
permissionGrantedCallback?.invoke()
permissionGrantedCallback = null
}
}
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
onCreateOptionsMenu(menu, menuInflater)
return menu.isNotEmpty() || super.onCreateOptionsMenu(menu)
}
protected open fun onCreateOptionsMenu(
menu: Menu,
inflater: MenuInflater
) = Unit
}
@@ -0,0 +1,304 @@
package de.markusfisch.android.binaryeye.activity
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.EditText
import android.widget.ListView
import android.widget.RadioGroup
import android.widget.Spinner
import android.widget.TextView
import de.markusfisch.android.binaryeye.R
import de.markusfisch.android.binaryeye.adapter.prettifyFormatName
import de.markusfisch.android.binaryeye.app.prefs
import de.markusfisch.android.binaryeye.automation.AutomatedAction
import de.markusfisch.android.binaryeye.view.setPaddingFromWindowInsets
import de.markusfisch.android.binaryeye.view.systemBarListViewScrollListener
class AutomatedActionsActivity : AbstractBaseActivity() {
private val actions = ArrayList<AutomatedAction>()
private lateinit var adapter: ActionsAdapter
override fun onCreate(state: Bundle?) {
super.onCreate(state)
setScreenContentView(R.layout.activity_automated_actions)
setTitle(R.string.automated_actions)
actions.clear()
actions.addAll(prefs.automatedActions)
val listView = findViewById<ListView>(R.id.actions)
listView.emptyView = findViewById(R.id.no_actions)
adapter = ActionsAdapter(this, actions)
listView.adapter = adapter
listView.setOnScrollListener(systemBarListViewScrollListener)
listView.setOnItemClickListener { _, _, position, _ ->
editAction(position)
}
listView.setOnItemLongClickListener { _, _, position, _ ->
confirmRemoveAction(position)
true
}
findViewById<View>(R.id.add).setOnClickListener {
editAction(null)
}
findViewById<View>(R.id.inset_layout).setPaddingFromWindowInsets()
listView.setPaddingFromWindowInsets()
}
private fun editAction(position: Int?) {
val action = position?.let { actions[it] }
val view = layoutInflater.inflate(
R.layout.dialog_automated_action,
null
)
val regexView = view.findViewById<EditText>(R.id.regex)
val formatView = view.findViewById<Spinner>(R.id.format)
val urlView = view.findViewById<EditText>(R.id.url_template)
val typeGroup = view.findViewById<RadioGroup>(R.id.action_type)
val urlSection = view.findViewById<View>(R.id.url_section)
val intentSection = view.findViewById<View>(R.id.intent_section)
val intentUriView = view.findViewById<EditText>(
R.id.intent_uri_template
)
val names = resources.getStringArray(
R.array.barcode_formats_names
).toMutableList().apply {
add(0, getString(R.string.all_formats))
}
val values = resources.getStringArray(
R.array.barcode_formats_values
).toMutableList().apply {
add(0, "")
}
formatView.adapter = ArrayAdapter(
this,
android.R.layout.simple_spinner_item,
names
).apply {
setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item
)
}
if (action != null) {
regexView.setText(action.pattern)
formatView.setSelection(
values.indexOf(action.format ?: "").coerceAtLeast(0)
)
when (action.type) {
AutomatedAction.Type.Intent -> {
urlView.setText(action.urlTemplate ?: "")
}
AutomatedAction.Type.CustomIntent -> {
intentUriView.setText(action.intentUriTemplate ?: "")
}
}
} else {
formatView.setSelection(0)
}
fun updateTypeSections(checkedId: Int) {
val isIntent = checkedId == R.id.action_type_intent
urlSection.visibility = if (isIntent) View.VISIBLE else View.GONE
intentSection.visibility = if (isIntent) View.GONE else View.VISIBLE
}
typeGroup.setOnCheckedChangeListener { _, checkedId ->
updateTypeSections(checkedId)
}
val initialTypeId = if (
action?.type == AutomatedAction.Type.CustomIntent
) {
R.id.action_type_custom_intent
} else {
R.id.action_type_intent
}
typeGroup.check(initialTypeId)
updateTypeSections(initialTypeId)
val dialog = AlertDialog.Builder(this)
.setTitle(
if (action == null) {
R.string.automated_action_add
} else {
R.string.automated_action_edit
}
)
.setView(view)
.setPositiveButton(android.R.string.ok, null)
.setNegativeButton(android.R.string.cancel) { _, _ -> }
.create()
dialog.setOnShowListener {
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
addOrUpdateAction(
position,
regexView,
formatView,
values,
urlView,
typeGroup,
intentUriView,
dialog
)
}
}
dialog.show()
}
private fun addOrUpdateAction(
position: Int?,
regexView: EditText,
formatView: Spinner,
values: List<String>,
urlView: EditText,
typeGroup: RadioGroup,
intentUriView: EditText,
dialog: Dialog,
) {
val pattern = regexView.text.toString().trim()
if (pattern.isEmpty()) {
regexView.error = getString(R.string.automated_action_regex_required)
return
}
try {
Regex(pattern)
} catch (_: Exception) {
regexView.error = getString(R.string.automated_action_regex_invalid)
return
}
val isIntent = typeGroup.checkedRadioButtonId == R.id.action_type_intent
val format = formatView.selectedItemPosition.let {
values[it].ifEmpty { null }
}
val newAction = if (isIntent) {
val urlTemplate = urlView.text.toString().trim()
if (urlTemplate.isEmpty()) {
urlView.error = getString(R.string.automated_action_url_required)
return
}
AutomatedAction(
pattern = pattern,
type = AutomatedAction.Type.Intent,
format = format,
urlTemplate = urlTemplate
)
} else {
val intentUriTemplate = intentUriView.text.toString().trim()
if (intentUriTemplate.isEmpty()) {
intentUriView.error = getString(
R.string.automated_action_intent_uri_required
)
return
}
if (!intentUriTemplate.startsWith(
"intent:",
ignoreCase = true
)
) {
intentUriView.error = getString(
R.string.automated_action_intent_uri_invalid
)
return
}
AutomatedAction(
pattern = pattern,
type = AutomatedAction.Type.CustomIntent,
format = format,
intentUriTemplate = intentUriTemplate
)
}
if (position == null) {
actions.add(newAction)
} else {
actions[position] = newAction
}
prefs.setAutomatedActions(actions)
adapter.notifyDataSetChanged()
dialog.dismiss()
}
private fun confirmRemoveAction(position: Int) {
AlertDialog.Builder(this)
.setMessage(R.string.automated_action_remove_confirm)
.setPositiveButton(android.R.string.ok) { _, _ ->
actions.removeAt(position)
prefs.setAutomatedActions(actions)
adapter.notifyDataSetChanged()
}
.setNegativeButton(android.R.string.cancel) { _, _ -> }
.show()
}
private class ActionsAdapter(
context: Context,
private val items: List<AutomatedAction>
) : ArrayAdapter<AutomatedAction>(
context,
android.R.layout.simple_list_item_2,
android.R.id.text1,
items
) {
override fun getView(
position: Int,
convertView: View?,
parent: ViewGroup
): View {
val view = super.getView(position, convertView, parent)
val action = items[position]
getViewHolder(view).apply {
title.text = action.pattern
subtitle.text = when (action.type) {
AutomatedAction.Type.Intent -> if (!action.urlTemplate.isNullOrEmpty()) {
context.getString(
R.string.automated_action_list_intent,
action.urlTemplate
)
} else {
context.getString(R.string.automated_action_list_intent_empty)
}
AutomatedAction.Type.CustomIntent ->
if (!action.intentUriTemplate.isNullOrEmpty()) {
context.getString(
R.string.automated_action_list_custom_intent,
action.intentUriTemplate
)
} else {
context.getString(
R.string.automated_action_list_custom_intent_empty
)
}
}
action.format?.let { format ->
subtitle.text = "${subtitle.text} (${format.prettifyFormatName()})"
}
}
return view
}
private fun getViewHolder(
view: View
): ViewHolder = view.tag as ViewHolder? ?: ViewHolder(
view.findViewById(android.R.id.text1),
view.findViewById(android.R.id.text2),
).also {
view.tag = it
}
private data class ViewHolder(
val title: TextView,
val subtitle: TextView,
)
}
}
@@ -0,0 +1,594 @@
package de.markusfisch.android.binaryeye.activity
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Matrix
import android.os.Build
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.SeekBar
import android.widget.TextView
import de.markusfisch.android.binaryeye.R
import de.markusfisch.android.binaryeye.app.db
import de.markusfisch.android.binaryeye.app.hasWritePermission
import de.markusfisch.android.binaryeye.app.prefs
import de.markusfisch.android.binaryeye.content.Barcode
import de.markusfisch.android.binaryeye.content.BarcodeColors
import de.markusfisch.android.binaryeye.content.BitMatrixBarcode
import de.markusfisch.android.binaryeye.content.ContentBarcode
import de.markusfisch.android.binaryeye.content.copyToClipboard
import de.markusfisch.android.binaryeye.content.shareFile
import de.markusfisch.android.binaryeye.content.shareText
import de.markusfisch.android.binaryeye.database.toScan
import de.markusfisch.android.binaryeye.io.addSuffixIfNotGiven
import de.markusfisch.android.binaryeye.io.toSaveResult
import de.markusfisch.android.binaryeye.io.writeExternalFile
import de.markusfisch.android.binaryeye.net.createEncodeDeeplink
import de.markusfisch.android.binaryeye.os.getScreenBrightness
import de.markusfisch.android.binaryeye.os.setScreenBrightness
import de.markusfisch.android.binaryeye.view.doOnApplyWindowInsets
import de.markusfisch.android.binaryeye.view.setPaddingFromWindowInsets
import de.markusfisch.android.binaryeye.widget.ConfinedScalingImageView
import de.markusfisch.android.binaryeye.widget.toast
import de.markusfisch.android.zxingcpp.ZxingCpp
import de.markusfisch.android.zxingcpp.ZxingCpp.BarcodeFormat
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStream
import java.util.Locale
import kotlin.math.max
import kotlin.math.min
class BarcodeActivity : AbstractBaseActivity() {
private enum class FileType {
PNG, JPG, SVG, TXT
}
private val parentJob = Job()
private val scope = CoroutineScope(Dispatchers.IO + parentJob)
private lateinit var imageView: ConfinedScalingImageView
private lateinit var barcode: Barcode<*>
private var contentView: View? = null
private var addToHistoryItem: MenuItem? = null
private var brightenScreenItem: MenuItem? = null
private var currentBrightness = -1f
override fun onCreate(state: Bundle?) {
super.onCreate(state)
setScreenContentView(R.layout.activity_barcode)
setTitle(R.string.view_barcode)
contentView = findViewById(android.R.id.content)
// Make `imageView` available for `onPause()`.
imageView = findViewById(R.id.barcode)
val bitmap: Bitmap
try {
barcode = intent?.extras?.toBarcode() ?: throw IllegalArgumentException(
"Illegal arguments"
)
// Catch exceptions from encoding.
bitmap = barcode.bitmap()
} catch (e: Exception) {
var message = e.message
if (message.isNullOrEmpty()) {
message = getString(R.string.error_encoding_barcode)
}
toast(message)
finish()
return
}
imageView.setImageBitmap(bitmap)
imageView.runAfterLayout = {
val scale = prefs.previewScale
if (scale > 0) {
imageView.setScale(
scale,
bitmap.width / 2f,
bitmap.height / 2f
)
}
imageView.minWidth = min(
imageView.minWidth / 2f,
max(bitmap.width, bitmap.height).toFloat()
)
}
findViewById<View>(R.id.share).setOnClickListener {
it.context?.apply {
pickFileType(R.string.share_as) { fileType ->
shareAs(fileType)
}
}
}
findViewById<View>(R.id.inset_layout).setPaddingFromWindowInsets()
imageView.doOnApplyWindowInsets { _, insets ->
imageView.insets.set(insets)
}
}
private fun Bundle.toBarcode(): Barcode<*> {
val content =
getString(CONTENT_TEXT) ?: getByteArray(CONTENT_RAW) ?: throw IllegalArgumentException(
"content cannot be null"
)
val barcodeFormat = BarcodeFormat.valueOf(
getString(FORMAT) ?: throw IllegalArgumentException(
"format cannot be null"
)
)
val colors = BarcodeColors.entries[getInt(COLORS)]
val data = getByteArray(BIT_MATRIX_DATA)
return if (data != null) {
BitMatrixBarcode(
ZxingCpp.BitMatrix(
getInt(BIT_MATRIX_WIDTH),
getInt(BIT_MATRIX_HEIGHT),
data
),
content,
barcodeFormat,
colors
)
} else {
ContentBarcode(
content,
barcodeFormat,
getInt(EC_LEVEL),
getBoolean(ADD_QUIET_ZONE),
colors
)
}
}
override fun onResume() {
super.onResume()
if (prefs.brightenScreen) {
// Post to make sure brightenScreenItem is initialized.
contentView?.postDelayed({
brightenScreen()
}, 500)
}
}
override fun onPause() {
super.onPause()
if (currentBrightness > -1f) {
restoreScreenBrightness()
}
if (imageView.isInBounds()) {
prefs.previewScale = imageView.getScale()
}
}
override fun onDestroy() {
super.onDestroy()
parentJob.cancel()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.fragment_barcode, menu)
addToHistoryItem = menu.findItem(R.id.add_to_history)
brightenScreenItem = menu.findItem(R.id.brighten_screen)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.add_to_history -> {
readAndAddToHistory(
barcode.bitmap(),
barcode.format
)
addToHistoryItem?.isVisible = false
toast(R.string.added_to_history)
true
}
R.id.copy_to_clipboard -> {
copyToClipboard(barcode.text())
true
}
R.id.copy_as_deeplink -> {
copyToClipboard(deeplinkToCopy())
true
}
R.id.export_to_file -> {
pickFileType(R.string.export_as) { fileType ->
when (fileType) {
FileType.PNG,
FileType.JPG -> askForSize { size ->
askForFileNameAndSave(fileType, size)
}
else -> askForFileNameAndSave(fileType, 0)
}
}
true
}
R.id.brighten_screen -> {
prefs.brightenScreen = if (currentBrightness > -1f) {
restoreScreenBrightness()
false
} else {
brightenScreen()
true
}
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun copyToClipboard(text: String, isSensitive: Boolean = false) {
(this as android.content.Context).copyToClipboard(text, isSensitive)
toast(R.string.copied_to_clipboard)
}
private fun deeplinkToCopy() = createEncodeDeeplink(
format = barcode.format.name,
content = barcode.textOrHex(),
)
private fun Context.pickFileType(
title: Int,
action: (FileType) -> Unit
) {
val fileTypes = FileType.entries.toTypedArray()
AlertDialog.Builder(this)
.setTitle(title)
.setItems(fileTypes.map { it.name }.toTypedArray()) { _, which ->
action(fileTypes[which])
}
.show()
}
// Dialogs do not have a parent view.
@SuppressLint("InflateParams")
private fun askForFileNameAndSave(fileType: FileType, bitmapSize: Int) {
// Write permission is only required before Android Q.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q &&
!hasWritePermission {
askForFileNameAndSave(fileType, bitmapSize)
}
) {
return
}
val view = layoutInflater.inflate(R.layout.dialog_save_file, null)
val editText = view.findViewById<EditText>(R.id.file_name)
editText.setText(
encodeFileName("${barcode.format}_${barcode.content}")
)
AlertDialog.Builder(this)
.setView(view)
.setPositiveButton(android.R.string.ok) { _, _ ->
val fileName = editText.text.toString()
when (fileType) {
FileType.PNG -> saveAs(
addSuffixIfNotGiven(fileName, ".png"),
MIME_PNG
) {
barcode.bitmap(bitmapSize).saveAsPng(it)
}
FileType.JPG -> saveAs(
addSuffixIfNotGiven(fileName, ".jpg"),
MIME_JPG
) {
barcode.bitmap(bitmapSize).saveAsJpg(it)
}
FileType.SVG -> saveAs(
addSuffixIfNotGiven(fileName, ".svg"),
MIME_SVG
) {
it.write(barcode.svg().toByteArray())
}
FileType.TXT -> saveAs(
addSuffixIfNotGiven(fileName, ".txt"),
MIME_TXT
) {
it.write(barcode.text().toByteArray())
}
}
}
.setNegativeButton(android.R.string.cancel) { _, _ ->
}
.show()
}
// Dialogs do not have a parent view.
@SuppressLint("InflateParams")
private fun askForSize(write: (size: Int) -> Unit) {
val view = layoutInflater.inflate(R.layout.dialog_size, null)
val sizeView = view.findViewById<TextView>(R.id.size_display)
val sizeBarView = view.findViewById<SeekBar>(R.id.size_bar)
sizeBarView.initSizeBar(sizeView)
AlertDialog.Builder(this)
.setView(view)
.setPositiveButton(android.R.string.ok) { _, _ ->
write(getSize(sizeBarView.progress))
}
.setNegativeButton(android.R.string.cancel) { _, _ ->
}
.show()
}
private fun SeekBar.initSizeBar(sizeView: TextView) {
sizeView.updateSize(progress)
setOnSeekBarChangeListener(
object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(
seekBar: SeekBar,
progressValue: Int,
fromUser: Boolean
) {
sizeView.updateSize(progressValue)
}
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onStopTrackingTouch(seekBar: SeekBar) {}
}
)
}
private fun TextView.updateSize(power: Int) {
val size = getSize(power)
text = if (size > 0) {
getString(R.string.size_width_by_height, size, size)
} else {
getString(R.string.size_no_magnification)
}
}
private fun saveAs(
fileName: String,
mimeType: String,
write: (outputStream: OutputStream) -> Unit
) {
scope.launch(Dispatchers.IO) {
val message = writeExternalFile(
fileName, mimeType, write
).toSaveResult()
withContext(Dispatchers.Main) {
toast(message)
}
}
}
private fun Context.shareAs(fileType: FileType) {
when (fileType) {
FileType.PNG -> askForSize {
share(barcode.bitmap(it), MIME_PNG, "png")
}
FileType.JPG -> askForSize {
share(barcode.bitmap(it), MIME_JPG, "jpg")
}
FileType.SVG -> shareText(barcode.svg(), MIME_SVG)
FileType.TXT -> shareText(barcode.text())
}
}
private fun Context.share(bitmap: Bitmap, mimeType: String, ext: String) {
scope.launch(Dispatchers.IO) {
val file = File(
externalCacheDir,
"shared_barcode.$ext"
)
val success = try {
FileOutputStream(file).use {
when (mimeType) {
MIME_PNG -> bitmap.saveAsPng(it)
MIME_JPG -> bitmap.saveAsJpg(it)
else -> throw IllegalArgumentException(
"Invalid mime type"
)
}
}
true
} catch (_: IOException) {
false
}
withContext(Dispatchers.Main) {
if (success) {
shareFile(file, mimeType)
} else {
toast(R.string.error_saving_file)
}
}
}
}
private fun brightenScreen() {
if (isFinishing || isDestroyed) {
return
}
currentBrightness = getScreenBrightness()
setScreenBrightness(1f)
brightenScreenItem?.isChecked = true
}
private fun restoreScreenBrightness() {
if (currentBrightness > -1f) {
setScreenBrightness(currentBrightness)
currentBrightness = -1f
brightenScreenItem?.isChecked = false
}
}
companion object {
private const val BIT_MATRIX_WIDTH = "bit_matrix_width"
private const val BIT_MATRIX_HEIGHT = "bit_matrix_height"
private const val BIT_MATRIX_DATA = "bit_matrix_data"
private const val CONTENT_TEXT = "content_text"
private const val CONTENT_RAW = "content_raw"
private const val FORMAT = "format"
private const val EC_LEVEL = "ec_level"
private const val ADD_QUIET_ZONE = "add_quiet_zone"
private const val COLORS = "colors"
private const val MIME_PNG = "image/png"
private const val MIME_JPG = "image/jpeg"
private const val MIME_SVG = "image/svg+xmg"
private const val MIME_TXT = "text/plain"
fun newIntent(
context: Context,
barcode: Barcode<*>,
colors: Int = 0
): Intent {
val args = Bundle()
when (barcode) {
is ContentBarcode -> args.putEcLevelQuietZone(
barcode.ecLevel,
barcode.addQuietZone
)
is BitMatrixBarcode -> {
args.putInt(BIT_MATRIX_WIDTH, barcode.bitMatrix.width)
args.putInt(BIT_MATRIX_HEIGHT, barcode.bitMatrix.height)
args.putByteArray(BIT_MATRIX_DATA, barcode.bitMatrix.data)
}
}
args.putContentFormatColors(
barcode.content,
barcode.format,
colors
)
return Intent(context, BarcodeActivity::class.java).apply {
putExtras(args)
}
}
fun <T> newIntent(
context: Context,
content: T,
format: BarcodeFormat,
ecLevel: Int = -1,
addQuietZone: Boolean = false,
colors: Int = 0
): Intent {
val args = Bundle()
args.putContentFormatColors(content, format, colors)
args.putEcLevelQuietZone(ecLevel, addQuietZone)
return Intent(context, BarcodeActivity::class.java).apply {
putExtras(args)
}
}
private fun <T> Bundle.putContentFormatColors(
content: T,
format: BarcodeFormat,
colors: Int
) {
when (content) {
is String -> {
putString(CONTENT_TEXT, content)
}
is ByteArray -> {
putByteArray(CONTENT_RAW, content)
}
else -> {
throw IllegalArgumentException(
"content must be a String of a ByteArray"
)
}
}
putString(FORMAT, format.name)
putInt(COLORS, colors)
}
private fun Bundle.putEcLevelQuietZone(
ecLevel: Int,
addQuietZone: Boolean
) {
putInt(EC_LEVEL, ecLevel)
putBoolean(ADD_QUIET_ZONE, addQuietZone)
}
}
}
private fun ImageView.setScale(scale: Float, x: Float, y: Float) {
imageMatrix = Matrix().apply {
setTranslate(-x, -y)
postScale(scale, scale)
postTranslate(x, y)
}
}
private fun ImageView.getScale(): Float {
val values = FloatArray(9)
imageMatrix.getValues(values)
return values[Matrix.MSCALE_X]
}
private fun Bitmap.saveAsPng(outputStream: OutputStream, quality: Int = 90) =
compress(Bitmap.CompressFormat.PNG, quality, outputStream)
private fun Bitmap.saveAsJpg(outputStream: OutputStream, quality: Int = 90) =
compress(Bitmap.CompressFormat.JPEG, quality, outputStream)
private val fileNameCharacters = "[^A-Za-z0-9]".toRegex()
private fun encodeFileName(name: String): String = fileNameCharacters
.replace(name, "_")
.take(16)
.trim('_')
.lowercase(Locale.getDefault())
private fun getSize(step: Int) = when (step) {
0 -> 0
else -> 128 shl (step - 1)
}
private fun readAndAddToHistory(
bitmap: Bitmap,
format: BarcodeFormat
) {
ZxingCpp.readBitmap(
bitmap,
0, 0,
bitmap.width, bitmap.height,
0,
ZxingCpp.ReaderOptions(
tryHarder = true,
tryRotate = true,
tryInvert = true,
tryDownscale = true,
maxNumberOfSymbols = 1,
formats = setOf(format)
)
)?.first {
val scan = it.toScan()
if (!prefs.shouldIgnoreHistoryContent(scan.text, scan.format.name)) {
db.insertScan(scan)
}
true
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,467 @@
package de.markusfisch.android.binaryeye.activity
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.CheckBox
import android.widget.EditText
import android.widget.Spinner
import android.widget.TextView
import androidx.appcompat.widget.SwitchCompat
import androidx.core.net.toUri
import de.markusfisch.android.binaryeye.R
import de.markusfisch.android.binaryeye.adapter.prettifyFormatName
import de.markusfisch.android.binaryeye.adapter.toFormatDescriptionResId
import de.markusfisch.android.binaryeye.app.prefs
import de.markusfisch.android.binaryeye.net.isEncodeDeeplink
import de.markusfisch.android.binaryeye.text.unescape
import de.markusfisch.android.binaryeye.view.hideSoftKeyboard
import de.markusfisch.android.binaryeye.view.setPaddingFromWindowInsets
import de.markusfisch.android.binaryeye.widget.toast
import de.markusfisch.android.zxingcpp.ZxingCpp.BarcodeFormat
import java.io.InputStream
import kotlin.math.min
class EncodeActivity : AbstractBaseActivity() {
private lateinit var formatView: Spinner
private lateinit var formatDescriptionView: TextView
private lateinit var ecLabel: TextView
private lateinit var ecSpinner: Spinner
private lateinit var colorsLabel: TextView
private lateinit var colorsSpinner: Spinner
private lateinit var addQuietZoneSwitch: SwitchCompat
private lateinit var contentView: EditText
private lateinit var unescapeCheckBox: CheckBox
private val writeableFormats = arrayListOf(
BarcodeFormat.Aztec,
BarcodeFormat.Codabar,
BarcodeFormat.Code39Std,
BarcodeFormat.Code39Ext,
BarcodeFormat.Code32,
BarcodeFormat.PZN,
BarcodeFormat.Code93,
BarcodeFormat.Code128,
BarcodeFormat.DataBar,
BarcodeFormat.DataBarOmni,
BarcodeFormat.DataBarStk,
BarcodeFormat.DataBarLtd,
BarcodeFormat.DataBarExp,
BarcodeFormat.DataBarExpStk,
BarcodeFormat.DataMatrix,
BarcodeFormat.DXFilmEdge,
BarcodeFormat.EAN8,
BarcodeFormat.EAN13,
BarcodeFormat.ITF,
BarcodeFormat.MaxiCode,
BarcodeFormat.PDF417,
BarcodeFormat.QRCode,
BarcodeFormat.MicroQRCode,
BarcodeFormat.RMQRCode,
BarcodeFormat.UPCA,
BarcodeFormat.UPCE,
)
private var bytes: ByteArray? = null
override fun onActivityResult(
requestCode: Int,
resultCode: Int,
resultData: Intent?
) {
super.onActivityResult(requestCode, resultCode, resultData)
when (requestCode) {
PICK_FILE_RESULT_CODE -> {
if (resultCode == Activity.RESULT_OK &&
resultData != null &&
resultData.data != null
) {
hideSoftKeyboard(contentView)
val uri = resultData.data ?: return
bytes = contentResolver?.openInputStream(uri)?.use {
it.readBytesMax(4096)
} ?: return
setEncodeByteArray()
}
}
}
}
override fun onCreate(state: Bundle?) {
super.onCreate(state)
setScreenContentView(R.layout.activity_encode)
setTitle(R.string.compose_barcode)
formatView = findViewById(R.id.format)
formatDescriptionView = findViewById(R.id.format_description)
val formatAdapter = ArrayAdapter(
this,
android.R.layout.simple_spinner_item,
writeableFormats.map { it.name.prettifyFormatName() }
)
formatAdapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item
)
formatView.adapter = formatAdapter
formatView.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parentView: AdapterView<*>?,
selectedItemView: View?,
position: Int,
id: Long
) {
val format = writeableFormats[position]
val descResId = format.name.toFormatDescriptionResId()
if (descResId != 0) {
formatDescriptionView.setText(descResId)
formatDescriptionView.visibility = View.VISIBLE
} else {
formatDescriptionView.visibility = View.GONE
}
val arrayId = when (format) {
BarcodeFormat.Aztec -> R.array.aztec_error_correction_levels
BarcodeFormat.QRCode -> R.array.qr_error_correction_levels
BarcodeFormat.MicroQRCode -> R.array.mqr_error_correction_levels
BarcodeFormat.RMQRCode -> R.array.rmqr_error_correction_levels
BarcodeFormat.PDF417 -> R.array.pdf417_error_correction_levels
else -> 0
}
if (arrayId > 0) {
ecSpinner.setEntries(arrayId)
val idx = format.unpackEcLevel(
prefs.indexOfLastSelectedEcLevel
)
if (idx < ecSpinner.adapter.count) {
ecSpinner.setSelection(idx)
}
true
} else {
false
}.setVisibilityFor(ecLabel, ecSpinner)
format.canBeInverted().setVisibilityFor(
colorsLabel, colorsSpinner
)
}
override fun onNothingSelected(parentView: AdapterView<*>?) {}
}
ecLabel = findViewById(R.id.error_correction_label)
ecSpinner = findViewById(R.id.error_correction_level)
ecSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parentView: AdapterView<*>?,
selectedItemView: View?,
position: Int,
id: Long
) {
val format = writeableFormats[formatView.selectedItemPosition]
prefs.indexOfLastSelectedEcLevel = format.packEcLevel(
prefs.indexOfLastSelectedEcLevel,
position
)
}
override fun onNothingSelected(parentView: AdapterView<*>?) {}
}
colorsLabel = findViewById(R.id.colors_label)
colorsSpinner = findViewById(R.id.colors)
addQuietZoneSwitch = findViewById(R.id.add_quiet_zone)
addQuietZoneSwitch.isChecked = prefs.addQuietZone
contentView = findViewById(R.id.content)
unescapeCheckBox = findViewById(R.id.unescape)
unescapeCheckBox.isChecked = prefs.expandEscapeSequences
applyIntent(state == null)
findViewById<View>(R.id.encode).setOnClickListener {
it.context.encode()
}
findViewById<View>(R.id.inset_layout).setPaddingFromWindowInsets()
findViewById<View>(R.id.scroll_view).setPaddingFromWindowInsets()
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
applyIntent(true)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.fragment_encode, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.pick_file -> {
startActivityForResult(
Intent.createChooser(
Intent(Intent.ACTION_GET_CONTENT).apply {
type = "*/*"
},
getString(R.string.pick_file)
),
PICK_FILE_RESULT_CODE
)
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onPause() {
super.onPause()
prefs.indexOfLastSelectedFormat = formatView.selectedItemPosition
prefs.expandEscapeSequences = unescapeCheckBox.isChecked
prefs.addQuietZone = addQuietZoneSwitch.isChecked
}
private fun applyIntent(applyDefaultFormat: Boolean) {
val args = intent?.extras ?: getExtrasFromDeeplink()
val hasTextContent = args?.containsKey(CONTENT_TEXT) == true
val hasRawContent = args?.containsKey(CONTENT_RAW) == true
var complete = bytes?.isNotEmpty() == true ||
contentView.text?.isNotEmpty() == true
if (hasTextContent || hasRawContent) {
bytes = null
contentView.isEnabled = true
contentView.hint = null
unescapeCheckBox.isEnabled = true
}
if (hasTextContent) {
args.getString(CONTENT_TEXT)?.let {
contentView.setText(it)
complete = it.isNotEmpty()
}
}
if (hasRawContent) {
args.getByteArray(CONTENT_RAW)?.let {
bytes = it
complete = it.isNotEmpty()
setEncodeByteArray()
}
}
val barcodeFormat = args?.getString(FORMAT)
if (barcodeFormat != null) {
formatView.setSelection(
writeableFormats.indexOf(barcodeFormat.toFormat())
)
} else if (applyDefaultFormat) {
formatView.post {
formatView.setSelection(prefs.indexOfLastSelectedFormat)
}
}
if (complete &&
args?.getBoolean(EXECUTE, false) == true
) {
contentView.post {
val content = contentView.context.getContent() ?: return@post
startActivity(newBarcodeIntent(content))
finish()
}
}
}
private fun Context.encode() {
hideSoftKeyboard(contentView)
val content = getContent() ?: return
contentView.post {
startActivity(newBarcodeIntent(content))
}
}
private fun newBarcodeIntent(content: Any): Intent {
val format = writeableFormats[formatView.selectedItemPosition]
return BarcodeActivity.newIntent(
this,
content,
format,
format.getErrorCorrectionLevel(ecSpinner.selectedItemPosition),
addQuietZoneSwitch.isChecked,
if (format.canBeInverted()) {
colorsSpinner.selectedItemPosition
} else 0
)
}
private fun Context.getContent(): Any? {
if (bytes != null) {
return bytes
}
var text = contentView.text.toString()
if (text.isEmpty()) {
toast(R.string.error_no_content)
return null
}
if (!unescapeCheckBox.isChecked) {
return text
}
try {
text = text.unescape()
} catch (e: IllegalArgumentException) {
toast(e.message ?: "Invalid escape sequence")
return null
}
// Return a ByteArray if there were escape sequences for
// non-printable characters.
return if (text.any { it.code < 32 && it.code !in setOf(9, 10, 13) }) {
// Do not expand UTF-8 sequences in binary data.
text.toByteArray(Charsets.ISO_8859_1)
} else {
text
}
}
private fun setEncodeByteArray() {
contentView.text = null
contentView.hint = getString(R.string.binary_data)
contentView.isEnabled = false
unescapeCheckBox.isEnabled = false
}
private fun getExtrasFromDeeplink(): Bundle? {
val data = intent?.dataString ?: return null
if (!isEncodeDeeplink(data)) {
return null
}
val uri = data.toUri()
return Bundle().apply {
uri.getQueryParameter("content")?.let {
putString(CONTENT_TEXT, it)
}
uri.getQueryParameter("format")?.let {
putString(FORMAT, it)
}
putBoolean(
EXECUTE,
uri.getQueryParameter("execute").let {
it == "" || it?.toBoolean() == true
}
)
}
}
companion object {
private const val CONTENT_TEXT = "content_text"
private const val CONTENT_RAW = "content_raw"
private const val FORMAT = "format"
private const val EXECUTE = "execute"
private const val PICK_FILE_RESULT_CODE = 1
fun <T> newIntent(
context: Context,
content: T? = null,
format: String? = null,
execute: Boolean = false
): Intent {
val args = Bundle()
content?.let {
when (content) {
is String -> args.putString(CONTENT_TEXT, content)
is ByteArray -> args.putByteArray(CONTENT_RAW, content)
else -> throw IllegalArgumentException(
"content must be a String or a ByteArray"
)
}
args.putBoolean(EXECUTE, execute)
}
format?.let { args.putString(FORMAT, it) }
return Intent(context, EncodeActivity::class.java).apply {
putExtras(args)
}
}
}
}
private fun Boolean.setVisibilityFor(vararg views: View) {
val visibility = if (this) View.VISIBLE else View.GONE
for (view in views) {
view.visibility = visibility
}
}
private fun BarcodeFormat.packEcLevel(packed: Int, level: Int): Int {
val s = ecLevelShift()
return (level shl s) or (packed and (15 shl s).inv())
}
private fun BarcodeFormat.unpackEcLevel(packed: Int) =
(packed shr ecLevelShift()) and 15
private fun BarcodeFormat.ecLevelShift() = when (this) {
BarcodeFormat.Aztec -> 0
BarcodeFormat.QRCode -> 4
BarcodeFormat.MicroQRCode -> 3
BarcodeFormat.RMQRCode -> 2
BarcodeFormat.PDF417 -> 8
else -> throw IllegalArgumentException("$this does not have error levels")
}
private fun BarcodeFormat.canBeInverted() = when (this) {
BarcodeFormat.Aztec,
BarcodeFormat.DataMatrix,
BarcodeFormat.QRCode,
BarcodeFormat.MicroQRCode,
BarcodeFormat.RMQRCode -> true
else -> false
}
private fun String.toFormat(
default: BarcodeFormat = BarcodeFormat.QRCode
): BarcodeFormat = try {
BarcodeFormat.valueOf(this)
} catch (_: IllegalArgumentException) {
default
}
private fun BarcodeFormat.getErrorCorrectionLevel(position: Int) = when (this) {
BarcodeFormat.Aztec -> position
BarcodeFormat.QRCode,
BarcodeFormat.MicroQRCode -> (position + 1) * 2
BarcodeFormat.RMQRCode -> (position + 1) * 4
BarcodeFormat.PDF417 -> position
else -> 0
}.coerceIn(0, 8)
private fun Spinner.setEntries(resId: Int) = ArrayAdapter.createFromResource(
this.context,
resId,
android.R.layout.simple_spinner_item
).also { aa ->
aa.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item
)
adapter = aa
}
private fun InputStream.readBytesMax(max: Int): ByteArray {
var offset = 0
var remaining = min(available(), max)
val result = ByteArray(remaining)
while (remaining > 0) {
val read = read(result, offset, remaining)
if (read < 0) {
break
}
remaining -= read
offset += read
}
return result
}
@@ -1,4 +1,4 @@
package de.markusfisch.android.binaryeye.fragment
package de.markusfisch.android.binaryeye.activity
import android.annotation.SuppressLint
import android.app.AlertDialog
@@ -8,32 +8,46 @@ import android.database.Cursor
import android.os.Build
import android.os.Bundle
import android.os.Parcelable
import android.support.v4.app.ActivityCompat
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.support.v7.view.ActionMode
import android.support.v7.widget.SearchView
import android.support.v7.widget.SwitchCompat
import android.view.*
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.widget.EditText
import android.widget.ListView
import androidx.appcompat.view.ActionMode
import androidx.appcompat.widget.SearchView
import androidx.appcompat.widget.SwitchCompat
import androidx.core.content.ContextCompat
import de.markusfisch.android.binaryeye.R
import de.markusfisch.android.binaryeye.adapter.ScansAdapter
import de.markusfisch.android.binaryeye.app.*
import de.markusfisch.android.binaryeye.app.alertDialog
import de.markusfisch.android.binaryeye.app.db
import de.markusfisch.android.binaryeye.app.hasWritePermission
import de.markusfisch.android.binaryeye.app.prefs
import de.markusfisch.android.binaryeye.content.copyToClipboard
import de.markusfisch.android.binaryeye.content.shareAsFile
import de.markusfisch.android.binaryeye.content.shareText
import de.markusfisch.android.binaryeye.content.wipeLastShareFile
import de.markusfisch.android.binaryeye.database.Database
import de.markusfisch.android.binaryeye.database.exportCsv
import de.markusfisch.android.binaryeye.database.exportDatabase
import de.markusfisch.android.binaryeye.database.exportJson
import de.markusfisch.android.binaryeye.io.askForFileName
import de.markusfisch.android.binaryeye.io.toSaveResult
import de.markusfisch.android.binaryeye.view.*
import de.markusfisch.android.binaryeye.view.lockStatusBarColor
import de.markusfisch.android.binaryeye.view.setPaddingFromWindowInsets
import de.markusfisch.android.binaryeye.view.systemBarListViewScrollListener
import de.markusfisch.android.binaryeye.view.unlockStatusBarColor
import de.markusfisch.android.binaryeye.view.useVisibility
import de.markusfisch.android.binaryeye.widget.toast
import kotlinx.coroutines.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class HistoryFragment : Fragment() {
class HistoryActivity : AbstractBaseActivity() {
private lateinit var useHistorySwitch: SwitchCompat
private lateinit var listView: ListView
private lateinit var fab: View
@@ -50,9 +64,11 @@ class HistoryFragment : Fragment() {
R.menu.fragment_history_edit,
menu
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// SDK35+ doesn't draw a status bar background anymore.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.VANILLA_ICE_CREAM) {
lockStatusBarColor()
val ac = activity ?: return false
val ac = this@HistoryActivity
@Suppress("DEPRECATION")
ac.window.statusBarColor = ContextCompat.getColor(
ac,
R.color.accent_dark
@@ -72,34 +88,39 @@ class HistoryFragment : Fragment() {
mode: ActionMode,
item: MenuItem
): Boolean {
val ac = activity ?: return false
val ac = this@HistoryActivity
return when (item.itemId) {
R.id.copy_scan -> {
scansAdapter?.getSelectedContent()?.let {
scansAdapter?.getSelectedContent("\n")?.let {
ac.copyToClipboard(it)
ac.toast(R.string.copied_to_clipboard)
}
closeActionMode()
true
}
R.id.edit_scan -> {
scansAdapter?.let {
askForName(
ac,
it.selectedScanId,
getScanName(it.selectedScanPosition)
R.id.edit_label -> {
scansAdapter?.forSelection { id, position ->
ac.askForName(
id,
scansAdapter?.getName(position),
scansAdapter?.getContent(position)
)
}
closeActionMode()
true
}
R.id.remove_scan -> {
scansAdapter?.let {
askToRemoveScan(ac, it.selectedScanId)
scansAdapter?.getSelectedIds()?.let {
if (it.isNotEmpty()) {
ac.askToRemoveScans(it)
}
}
closeActionMode()
true
}
else -> false
}
}
@@ -115,40 +136,30 @@ class HistoryFragment : Fragment() {
private var filter: String? = null
private var clearListMenuItem: MenuItem? = null
private var exportHistoryMenuItem: MenuItem? = null
private var shareAsFileMenuItem: MenuItem? = null
override fun onCreate(state: Bundle?) {
super.onCreate(state)
setHasOptionsMenu(true)
}
setScreenContentView(R.layout.activity_history)
setTitle(R.string.history)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
state: Bundle?
): View? {
val ac = activity ?: return null
ac.setTitle(R.string.history)
val view = inflater.inflate(
R.layout.fragment_history,
container,
false
)
useHistorySwitch = view.findViewById(
useHistorySwitch = findViewById(
R.id.use_history
) as SwitchCompat
)
initHistorySwitch(useHistorySwitch)
listView = view.findViewById(R.id.scans)
listView.setOnItemClickListener { _, _, _, id ->
showScan(id)
listView = findViewById(R.id.scans)
listView.setOnItemClickListener { _, v, position, id ->
if (actionMode != null) {
scansAdapter?.select(v, id, position)
} else {
showScan(id)
}
}
listView.setOnItemLongClickListener { _, v, position, id ->
v.isSelected = true
scansAdapter?.select(id, position)
if (actionMode == null && ac is AppCompatActivity) {
actionMode = ac.delegate.startSupportActionMode(
scansAdapter?.select(v, id, position)
if (actionMode == null) {
actionMode = delegate.startSupportActionMode(
actionModeCallback
)
}
@@ -156,25 +167,27 @@ class HistoryFragment : Fragment() {
}
listView.setOnScrollListener(systemBarListViewScrollListener)
fab = view.findViewById(R.id.share)
fab = findViewById(R.id.share)
fab.setOnClickListener { v ->
pickListSeparatorAndShare(v.context)
v.context.pickListSeparatorAndShare(false)
}
progressView = view.findViewById(R.id.progress_view)
progressView = findViewById(R.id.progress_view)
(view.findViewById(R.id.inset_layout) as View).setPaddingFromWindowInsets()
findViewById<View>(R.id.inset_layout).setPaddingFromWindowInsets()
listView.setPaddingFromWindowInsets()
update()
return view
}
override fun onDestroy() {
super.onDestroy()
scansAdapter?.changeCursor(null)
parentJob.cancel()
wipeLastShareFile()
}
override fun onResume() {
super.onResume()
update()
}
override fun onPause() {
@@ -184,49 +197,61 @@ class HistoryFragment : Fragment() {
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.fragment_history, menu)
initSearchView(menu.findItem(R.id.search))
menu.setGroupVisible(R.id.scans_available, scansAdapter?.count != 0)
clearListMenuItem = menu.findItem(R.id.clear)
exportHistoryMenuItem = menu.findItem(R.id.export_history)
val searchMenuItem = menu.findItem(R.id.search)
initSearchView(searchMenuItem)
val visible = scansAdapter?.count != 0
searchMenuItem?.isVisible = visible
exportHistoryMenuItem = menu.findItem(R.id.export_history)?.apply {
isVisible = visible
}
shareAsFileMenuItem = menu.findItem(R.id.share_as_file)?.apply {
isVisible = visible
}
clearListMenuItem = menu.findItem(R.id.clear)?.apply {
isVisible = visible
}
}
private fun initSearchView(item: MenuItem?) {
item ?: return
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
item.isVisible = false
} else {
val ac = activity ?: return
val searchView = item.actionView as SearchView
val searchManager = ac.getSystemService(
Context.SEARCH_SERVICE
) as SearchManager
searchView.setSearchableInfo(
searchManager.getSearchableInfo(ac.componentName)
)
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
update(query)
return false
}
val ac = this
val searchView = item.actionView as SearchView
val searchManager = ac.getSystemService(
Context.SEARCH_SERVICE
) as SearchManager
searchView.setSearchableInfo(
searchManager.getSearchableInfo(ac.componentName)
)
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
update(query)
return false
}
override fun onQueryTextChange(query: String): Boolean {
update(query)
return false
}
})
}
override fun onQueryTextChange(query: String): Boolean {
update(query)
return false
}
})
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.clear -> {
askToRemoveScans(context)
this.askToRemoveScans()
true
}
R.id.export_history -> {
askToExportToFile(context)
askToExportToFile()
true
}
R.id.share_as_file -> {
this.pickListSeparatorAndShare(true)
true
}
else -> super.onOptionsItemSelected(item)
}
}
@@ -250,13 +275,13 @@ class HistoryFragment : Fragment() {
scope.launch {
val cursor = db.getScans(filter)
withContext(Dispatchers.Main) {
val ac = activity ?: return@withContext
val hasScans = cursor != null && cursor.count > 0
val ac = this@HistoryActivity
val hasScans = cursor.count > 0
if (filter == null) {
if (!hasScans) {
listView.emptyView = useHistorySwitch
}
ActivityCompat.invalidateOptionsMenu(ac)
ac.invalidateOptionsMenu()
}
enableMenuItems(hasScans)
fab.visibility = if (hasScans) {
@@ -264,10 +289,19 @@ class HistoryFragment : Fragment() {
} else {
View.GONE
}
cursor?.let { cursor ->
// close previous cursor
cursor.let { cursor ->
// Close previous cursor.
scansAdapter?.also { it.changeCursor(null) }
scansAdapter = ScansAdapter(ac, cursor)
scansAdapter = ScansAdapter(ac, cursor) { id, pinned ->
if (actionMode == null) {
scope.launch {
db.setPinned(id, pinned)
withContext(Dispatchers.Main) {
update()
}
}
}
}
listView.adapter = scansAdapter
listViewState?.also {
listView.onRestoreInstanceState(it)
@@ -280,6 +314,7 @@ class HistoryFragment : Fragment() {
private fun enableMenuItems(enabled: Boolean) {
clearListMenuItem?.isEnabled = enabled
exportHistoryMenuItem?.isEnabled = enabled
shareAsFileMenuItem?.isEnabled = enabled
}
private fun closeActionMode() {
@@ -293,29 +328,28 @@ class HistoryFragment : Fragment() {
private fun showScan(id: Long) = db.getScan(id)?.also { scan ->
closeActionMode()
try {
addFragment(
fragmentManager,
DecodeFragment.newInstance(scan)
)
} catch (e: IllegalArgumentException) {
// ignore, can never happen
startActivity(DecodeActivity.newIntent(this, scan))
} catch (_: IllegalArgumentException) {
// Ignore, can never happen.
}
}
private fun getScanName(position: Int): String? {
val cursor = scansAdapter?.getItem(position) as Cursor?
return cursor?.getString(cursor.getColumnIndex(Database.SCANS_NAME))
}
// dialogs don't have a parent layout
// Dialogs don't have a parent layout.
@SuppressLint("InflateParams")
private fun askForName(context: Context, id: Long, text: String?) {
val view = LayoutInflater.from(context).inflate(
private fun Context.askForName(id: Long, text: String?, content: String?) {
val view = LayoutInflater.from(this).inflate(
R.layout.dialog_enter_name, null
)
val nameView = view.findViewById<EditText>(R.id.name)
nameView.setText(text)
AlertDialog.Builder(context)
AlertDialog.Builder(this)
.setTitle(
if (content.isNullOrEmpty()) {
getString(R.string.binary_data)
} else {
content
}
)
.setView(view)
.setPositiveButton(android.R.string.ok) { _, _ ->
val name = nameView.text.toString()
@@ -326,11 +360,17 @@ class HistoryFragment : Fragment() {
.show()
}
private fun askToRemoveScan(context: Context, id: Long) {
AlertDialog.Builder(context)
.setMessage(R.string.really_remove_scan)
private fun Context.askToRemoveScans(ids: List<Long>) {
AlertDialog.Builder(this)
.setMessage(
if (ids.size > 1) {
R.string.really_remove_selected_scans
} else {
R.string.really_remove_scan
}
)
.setPositiveButton(android.R.string.ok) { _, _ ->
db.removeScan(id)
ids.forEach { db.removeScan(it) }
if (scansAdapter?.count == 1) {
updateAndClearFilter()
} else {
@@ -342,8 +382,8 @@ class HistoryFragment : Fragment() {
.show()
}
private fun askToRemoveScans(context: Context) {
AlertDialog.Builder(context)
private fun Context.askToRemoveScans() {
AlertDialog.Builder(this)
.setMessage(
if (filter == null) {
R.string.really_remove_all_scans
@@ -360,17 +400,20 @@ class HistoryFragment : Fragment() {
.show()
}
private fun askToExportToFile(context: Context) {
private fun askToExportToFile() {
scope.launch {
val ac = activity ?: return@launch
val ac = this@HistoryActivity
progressView.useVisibility {
if (!hasWritePermission(ac) { askToExportToFile(context) }) {
// Write permission is only required before Android Q.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q &&
!ac.hasWritePermission { askToExportToFile() }
) {
return@useVisibility
}
val options = context.resources.getStringArray(
val options = ac.resources.getStringArray(
R.array.export_options_values
)
val delimiter = alertDialog<String>(context) { resume ->
val delimiter = alertDialog<String>(ac) { resume ->
setTitle(R.string.export_as)
setItems(R.array.export_options_names) { _, which ->
resume(options[which])
@@ -386,13 +429,13 @@ class HistoryFragment : Fragment() {
)
} ?: return@useVisibility
val message = when (delimiter) {
"db" -> exportDatabase(ac, name)
else -> db.getScansDetailed(filter)?.use {
"db" -> ac.exportDatabase(name)
else -> db.getScansDetailed(filter).use {
when (delimiter) {
"json" -> exportJson(context, name, it)
else -> exportCsv(context, name, it, delimiter)
"json" -> ac.exportJson(name, it)
else -> ac.exportCsv(name, it, delimiter)
}
} ?: false
}
}.toSaveResult()
withContext(Dispatchers.Main) {
ac.toast(message)
@@ -401,49 +444,61 @@ class HistoryFragment : Fragment() {
}
}
private fun pickListSeparatorAndShare(context: Context) {
val separators = context.resources.getStringArray(
private fun Context.pickListSeparatorAndShare(asFile: Boolean) {
val separators = resources.getStringArray(
R.array.list_separators_values
)
AlertDialog.Builder(context)
AlertDialog.Builder(this)
.setTitle(R.string.pick_list_separator)
.setItems(R.array.list_separators_names) { _, which ->
shareScans(separators[which])
shareScans(separators[which], asFile)
}
.show()
}
private fun shareScans(format: String) = scope.launch {
private fun shareScans(format: String, asFile: Boolean) = scope.launch {
progressView.useVisibility {
var text: String? = null
db.getScansDetailed(filter)?.use { cursor ->
val selectedIds = scansAdapter?.getSelectedIds()
if (selectedIds?.isNotEmpty() == true) {
db.getScansDetailed(selectedIds.toLongArray())
} else {
db.getScansDetailed(filter)
}.use { cursor ->
val details = format.split(":")
text = when (details[0]) {
"text" -> exportText(cursor, details[1])
"csv" -> exportCsv(cursor, details[1])
else -> exportJson(cursor)
when (details[0]) {
"text" -> Pair(cursor.exportText(details[1]), "txt")
"csv" -> Pair(cursor.exportCsv(details[1]), "csv")
else -> Pair(cursor.exportJson(), "json")
}
}
text?.let {
withContext(Dispatchers.Main) {
shareText(context, it)
}.let { (text, ext) ->
text?.let {
withContext(Dispatchers.Main) {
if (asFile) {
this@HistoryActivity.shareAsFile(
it,
String.format("scans.%s", ext)
)
} else {
this@HistoryActivity.shareText(it)
}
}
}
}
}
}
}
private fun exportText(cursor: Cursor, separator: String): String {
private fun Cursor.exportText(separator: String): String {
val sb = StringBuilder()
val contentIndex = cursor.getColumnIndex(Database.SCANS_CONTENT)
if (cursor.moveToFirst()) {
val contentIndex = getColumnIndex(Database.SCANS_TEXT)
if (contentIndex > -1 && moveToFirst()) {
do {
val content = cursor.getString(contentIndex)
val content = getString(contentIndex)
if (content?.isNotEmpty() == true) {
sb.append(content)
sb.append(separator)
}
} while (cursor.moveToNext())
} while (moveToNext())
}
return sb.toString()
}
@@ -0,0 +1,171 @@
package de.markusfisch.android.binaryeye.activity
import android.app.AlertDialog
import android.app.Dialog
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.EditText
import android.widget.ListView
import android.widget.Spinner
import android.widget.TextView
import de.markusfisch.android.binaryeye.R
import de.markusfisch.android.binaryeye.adapter.prettifyFormatName
import de.markusfisch.android.binaryeye.adapter.setupFormatSpinner
import de.markusfisch.android.binaryeye.app.prefs
import de.markusfisch.android.binaryeye.preference.IgnoreCode
import de.markusfisch.android.binaryeye.view.setPaddingFromWindowInsets
import de.markusfisch.android.binaryeye.view.systemBarListViewScrollListener
import de.markusfisch.android.binaryeye.widget.toast
class IgnoreCodesActivity : AbstractBaseActivity() {
private val patterns = ArrayList<IgnoreCode>()
private lateinit var adapter: PatternsAdapter
override fun onCreate(state: Bundle?) {
super.onCreate(state)
setScreenContentView(R.layout.activity_ignore_codes)
setTitle(R.string.ignore_codes)
patterns.addAll(prefs.ignoreCodes)
val listView = findViewById<ListView>(R.id.actions)
listView.emptyView = findViewById(R.id.no_actions)
findViewById<TextView>(R.id.no_actions).setText(
R.string.ignore_codes_empty
)
adapter = PatternsAdapter(patterns)
listView.adapter = adapter
listView.setOnScrollListener(systemBarListViewScrollListener)
listView.setOnItemClickListener { _, _, position, _ ->
editPattern(position)
}
listView.setOnItemLongClickListener { _, _, position, _ ->
confirmRemovePattern(position)
true
}
findViewById<View>(R.id.add).apply {
contentDescription = getString(R.string.ignore_code_add)
setOnClickListener {
editPattern(null)
}
}
findViewById<View>(R.id.inset_layout).setPaddingFromWindowInsets()
listView.setPaddingFromWindowInsets()
}
private fun editPattern(position: Int?) {
val pattern = position?.let { patterns[it] }
val view = layoutInflater.inflate(R.layout.dialog_ignore_code, null)
val regexView = view.findViewById<EditText>(R.id.regex)
val formatView = view.findViewById<Spinner>(R.id.format)
val values = setupFormatSpinner(formatView)
if (pattern != null) {
regexView.setText(pattern.pattern)
regexView.setSelection(pattern.pattern.length)
formatView.setSelection(
values.indexOf(pattern.format ?: "").coerceAtLeast(0)
)
} else {
formatView.setSelection(0)
}
val dialog = AlertDialog.Builder(this)
.setTitle(
if (pattern == null) {
R.string.ignore_code_add
} else {
R.string.ignore_code_edit
}
)
.setView(view)
.setPositiveButton(android.R.string.ok, null)
.setNegativeButton(android.R.string.cancel) { _, _ -> }
.create()
dialog.setOnShowListener {
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
addOrUpdatePattern(position, regexView, formatView, values, dialog)
}
}
dialog.show()
}
private fun addOrUpdatePattern(
position: Int?,
regexView: EditText,
formatView: Spinner,
values: List<String>,
dialog: Dialog,
) {
val pattern = regexView.text.toString().trim()
if (pattern.isEmpty()) {
regexView.error = getString(R.string.ignore_code_regex_required)
return
}
try {
Regex(pattern)
} catch (e: Exception) {
val message = e.message ?: getString(
R.string.ignore_code_regex_invalid
)
regexView.error = message
toast(message)
return
}
val item = IgnoreCode(
pattern = pattern,
format = values[formatView.selectedItemPosition].ifEmpty { null }
)
if (position == null) {
patterns.add(item)
} else {
patterns[position] = item
}
prefs.setIgnoreCodes(patterns)
adapter.notifyDataSetChanged()
dialog.dismiss()
}
private fun confirmRemovePattern(position: Int) {
AlertDialog.Builder(this)
.setMessage(R.string.ignore_code_remove_confirm)
.setPositiveButton(android.R.string.ok) { _, _ ->
patterns.removeAt(position)
prefs.setIgnoreCodes(patterns)
adapter.notifyDataSetChanged()
}
.setNegativeButton(android.R.string.cancel) { _, _ -> }
.show()
}
private inner class PatternsAdapter(
items: List<IgnoreCode>
) : ArrayAdapter<IgnoreCode>(
this,
android.R.layout.simple_list_item_2,
android.R.id.text1,
items
) {
override fun getView(
position: Int,
convertView: View?,
parent: ViewGroup
): View {
val view = super.getView(position, convertView, parent)
val item = patterns[position]
val title = view.findViewById<TextView>(android.R.id.text1)
val subtitle = view.findViewById<TextView>(android.R.id.text2)
title.text = item.pattern
subtitle.text = item.format?.prettifyFormatName() ?: getString(
R.string.all_formats
)
return view
}
}
}
@@ -1,132 +0,0 @@
package de.markusfisch.android.binaryeye.activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import de.markusfisch.android.binaryeye.R
import de.markusfisch.android.binaryeye.app.*
import de.markusfisch.android.binaryeye.database.Scan
import de.markusfisch.android.binaryeye.fragment.DecodeFragment
import de.markusfisch.android.binaryeye.fragment.EncodeFragment
import de.markusfisch.android.binaryeye.fragment.HistoryFragment
import de.markusfisch.android.binaryeye.fragment.PreferencesFragment
import de.markusfisch.android.binaryeye.view.colorSystemAndToolBars
import de.markusfisch.android.binaryeye.view.initSystemBars
import de.markusfisch.android.binaryeye.view.recordToolbarHeight
class MainActivity : AppCompatActivity() {
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
when (requestCode) {
PERMISSION_LOCATION, PERMISSION_WRITE -> if (grantResults.isNotEmpty() &&
grantResults[0] == PackageManager.PERMISSION_GRANTED
) {
permissionGrantedCallback?.invoke()
permissionGrantedCallback = null
}
}
}
override fun onSupportNavigateUp(): Boolean {
val fm = supportFragmentManager
if (fm != null && fm.backStackEntryCount > 0) {
fm.popBackStack()
} else {
finish()
}
return true
}
override fun attachBaseContext(base: Context?) {
base?.applyLocale(prefs.customLocale)
super.attachBaseContext(base)
}
override fun onCreate(state: Bundle?) {
super.onCreate(state)
setContentView(R.layout.activity_main)
initSystemBars(this)
val toolbar = findViewById(R.id.toolbar) as Toolbar
recordToolbarHeight(toolbar)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportFragmentManager.addOnBackStackChangedListener {
colorSystemAndToolBars(this@MainActivity)
}
if (state == null) {
setFragment(supportFragmentManager, getFragmentForIntent(intent))
}
}
companion object {
private const val PREFERENCES = "preferences"
private const val HISTORY = "history"
private const val ENCODE = "encode"
const val DECODED = "decoded"
private fun getFragmentForIntent(intent: Intent?): Fragment {
intent ?: return PreferencesFragment()
return when {
intent.hasExtra(PREFERENCES) -> PreferencesFragment()
intent.hasExtra(HISTORY) -> HistoryFragment()
intent.hasExtra(ENCODE) -> EncodeFragment.newInstance(
intent.getStringExtra(ENCODE)!!
)
intent.hasExtra(DECODED) -> DecodeFragment.newInstance(
intent.getParcelableExtra(DECODED)!!
)
else -> PreferencesFragment()
}
}
fun getPreferencesIntent(context: Context): Intent {
val intent = Intent(context, MainActivity::class.java)
intent.putExtra(PREFERENCES, true)
return intent
}
fun getHistoryIntent(context: Context): Intent {
val intent = Intent(context, MainActivity::class.java)
intent.putExtra(HISTORY, true)
return intent
}
fun getEncodeIntent(
context: Context,
text: String? = "",
isExternal: Boolean = false
): Intent {
val intent = Intent(context, MainActivity::class.java)
intent.putExtra(ENCODE, text)
if (isExternal) {
val flagActivityClearTask =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
Intent.FLAG_ACTIVITY_CLEAR_TASK
} else 0
intent.addFlags(
Intent.FLAG_ACTIVITY_NO_HISTORY or
flagActivityClearTask or
Intent.FLAG_ACTIVITY_NEW_TASK
)
}
return intent
}
fun getDecodeIntent(context: Context, scan: Scan): Intent {
val intent = Intent(context, MainActivity::class.java)
intent.putExtra(DECODED, scan)
return intent
}
}
}
@@ -0,0 +1,81 @@
package de.markusfisch.android.binaryeye.activity
import android.content.Context
import android.net.wifi.WifiManager
import android.net.wifi.WifiNetworkSuggestion
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.ArrayAdapter
import android.widget.ListView
import androidx.annotation.RequiresApi
import androidx.core.util.size
import de.markusfisch.android.binaryeye.R
import de.markusfisch.android.binaryeye.view.setPaddingFromWindowInsets
import de.markusfisch.android.binaryeye.view.systemBarListViewScrollListener
import de.markusfisch.android.binaryeye.widget.toast
class NetworkSuggestionsActivity : AbstractBaseActivity() {
@RequiresApi(Build.VERSION_CODES.R)
override fun onCreate(state: Bundle?) {
super.onCreate(state)
setScreenContentView(R.layout.activity_network_suggestions)
setTitle(R.string.network_suggestions)
val wm = applicationContext.getSystemService(
Context.WIFI_SERVICE
) as WifiManager
val suggestionArrayAdapter = ArrayAdapter(
this,
android.R.layout.simple_list_item_checked,
wm.networkSuggestions.map {
Suggestion(
it.ssid ?: it.toString(),
it
)
}
)
val listView = findViewById<ListView>(R.id.suggestions)
listView.emptyView = findViewById(R.id.no_suggestions)
listView.adapter = suggestionArrayAdapter
listView.setOnScrollListener(systemBarListViewScrollListener)
findViewById<View>(R.id.inset_layout).setPaddingFromWindowInsets()
listView.setPaddingFromWindowInsets()
findViewById<View>(R.id.remove).setOnClickListener {
val removeList = ArrayList<WifiNetworkSuggestion>()
val removeFromAdapter = ArrayList<Suggestion>()
val checked = listView.checkedItemPositions
val size = checked.size
for (i in 0 until size) {
if (checked.valueAt(i)) {
val pos = checked.keyAt(i)
listView.setItemChecked(pos, false)
val suggestion = listView.getItemAtPosition(
pos
) as Suggestion
removeList.add(suggestion.suggestion)
removeFromAdapter.add(suggestion)
}
}
if (removeList.isNotEmpty()) {
removeFromAdapter.forEach {
suggestionArrayAdapter.remove(it)
}
wm.removeNetworkSuggestions(removeList)
} else {
toast(
R.string.clear_network_suggestions_nothing_to_remove
)
}
}
}
}
private data class Suggestion(
val label: String,
val suggestion: WifiNetworkSuggestion
) {
override fun toString() = label
}
@@ -3,46 +3,60 @@ package de.markusfisch.android.binaryeye.activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Matrix
import android.graphics.Rect
import android.graphics.RectF
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Parcelable
import android.os.Vibrator
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.support.v8.renderscript.RenderScript
import android.view.Menu
import android.view.MenuItem
import com.google.zxing.Result
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import de.markusfisch.android.binaryeye.R
import de.markusfisch.android.binaryeye.app.*
import de.markusfisch.android.binaryeye.app.applyLocale
import de.markusfisch.android.binaryeye.app.prefs
import de.markusfisch.android.binaryeye.graphics.crop
import de.markusfisch.android.binaryeye.graphics.fixTransparency
import de.markusfisch.android.binaryeye.graphics.loadImageUri
import de.markusfisch.android.binaryeye.graphics.mapResult
import de.markusfisch.android.binaryeye.os.vibrate
import de.markusfisch.android.binaryeye.rs.fixTransparency
import de.markusfisch.android.binaryeye.graphics.mapPosition
import de.markusfisch.android.binaryeye.media.releaseToneGenerators
import de.markusfisch.android.binaryeye.view.colorSystemAndToolBars
import de.markusfisch.android.binaryeye.view.initSystemBars
import de.markusfisch.android.binaryeye.view.recordToolbarHeight
import de.markusfisch.android.binaryeye.view.initBars
import de.markusfisch.android.binaryeye.view.scanFeedback
import de.markusfisch.android.binaryeye.view.setPaddingFromWindowInsets
import de.markusfisch.android.binaryeye.widget.CropImageView
import de.markusfisch.android.binaryeye.widget.DetectorView
import de.markusfisch.android.binaryeye.widget.toast
import de.markusfisch.android.binaryeye.zxing.Zxing
import de.markusfisch.android.zxingcpp.ZxingCpp
import de.markusfisch.android.zxingcpp.ZxingCpp.Binarizer
import de.markusfisch.android.zxingcpp.ZxingCpp.ReaderOptions
import de.markusfisch.android.zxingcpp.ZxingCpp.Result
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
class PickActivity : AppCompatActivity() {
private val zxing = Zxing()
private lateinit var rs: RenderScript
private lateinit var vibrator: Vibrator
private lateinit var cropImageView: CropImageView
private lateinit var detectorView: DetectorView
private val matrix = Matrix()
private val parentJob = Job()
private val scope = CoroutineScope(Dispatchers.IO + parentJob)
private val options = ReaderOptions(
tryHarder = true,
tryRotate = true,
tryInvert = true,
tryDownscale = true,
maxNumberOfSymbols = 1,
formats = prefs.barcodeFormats.toFormatSet()
)
private var cropImageView: CropImageView? = null
private var detectorView: DetectorView? = null
private var freeRotationItem: MenuItem? = null
private var result: Result? = null
override fun attachBaseContext(base: Context?) {
@@ -54,47 +68,49 @@ class PickActivity : AppCompatActivity() {
super.onCreate(state)
setContentView(R.layout.activity_pick)
// necessary to get the right translation after setting a custom locale
// Necessary to get the right translation after setting a custom
// locale.
setTitle(R.string.pick_code_to_scan)
zxing.updateHints(true)
rs = RenderScript.create(this)
vibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
initSystemBars(this)
val toolbar = findViewById(R.id.toolbar) as Toolbar
recordToolbarHeight(toolbar)
setSupportActionBar(toolbar)
initBars()
supportFragmentManager.addOnBackStackChangedListener {
colorSystemAndToolBars(this@PickActivity)
}
val bitmap = fixTransparency(
rs,
getBitmapFromIntent()
)
val bitmap = getBitmapFromIntent()?.fixTransparency()
if (bitmap == null) {
applicationContext.toast(R.string.error_no_content)
finish()
// This is why cropImageView and detectorView aren't lateinit.
// If they were, a kotlin.UninitializedPropertyAccessException
// would happen here.
return
}
cropImageView = findViewById(R.id.image) as CropImageView
cropImageView.restrictTranslation = false
cropImageView.setImageBitmap(bitmap)
cropImageView.onScan = {
scanWithinBounds(bitmap)
cropImageView = (findViewById(R.id.image) as CropImageView).apply {
restrictTranslation = false
freeRotation = prefs.freeRotation
setImageBitmap(bitmap)
onScan = {
scanWithinBounds(bitmap)
}
runAfterLayout = {
minWidth = min(
minWidth / 2f,
max(bitmap.width, bitmap.height).toFloat()
)
}
}
detectorView = findViewById(R.id.detector_view) as DetectorView
detectorView.onRoiChanged = {
scanWithinBounds(bitmap)
detectorView = (findViewById(R.id.detector_view) as DetectorView).apply {
onRoiChanged = {
scanWithinBounds(bitmap)
}
setPaddingFromWindowInsets()
cropHandleName = "picker_crop_handle"
}
detectorView.setPaddingFromWindowInsets()
findViewById(R.id.scan).setOnClickListener {
findViewById<View>(R.id.scan).setOnClickListener {
showResult()
}
}
@@ -114,36 +130,53 @@ class PickActivity : AppCompatActivity() {
}
private fun scanWithinBounds(bitmap: Bitmap) {
val roi = detectorView.roi
val rectInView = if (roi.width() < 1) {
cropImageView.getBoundsRect()
} else {
roi
}
val imageRect = cropImageView.mappedRect
val rectInImage = normalizeRoi(imageRect, rectInView)
val cropped = crop(
bitmap,
rectInImage,
cropImageView.imageRotation
) ?: return
CoroutineScope(Dispatchers.IO).launch(Dispatchers.IO) {
result = zxing.decodePositiveNegative(cropped)
result?.let {
val dv = detectorView ?: return
val civ = cropImageView ?: return
val viewRoi = Rect(
if (dv.roi.width() < 1) {
civ.getBoundsRect()
} else {
dv.roi
}
)
val mappedRect = RectF(civ.mappedRect)
val imageRotation = civ.imageRotation
val pivotX = civ.pivotX
val pivotY = civ.pivotY
scope.launch {
val cropped = bitmap.crop(
getNormalizedRoi(mappedRect, viewRoi),
imageRotation,
pivotX,
pivotY
) ?: return@launch
val croppedInView = Rect(
max(viewRoi.left, mappedRect.left.roundToInt()),
max(viewRoi.top, mappedRect.top.roundToInt()),
min(viewRoi.right, mappedRect.right.roundToInt()),
min(viewRoi.bottom, mappedRect.bottom.roundToInt())
)
matrix.apply {
setScale(
croppedInView.width().toFloat() / cropped.width,
croppedInView.height().toFloat() / cropped.height
)
postTranslate(
croppedInView.left.toFloat(),
croppedInView.top.toFloat()
)
}
cropped.decode()?.first()?.let {
withContext(Dispatchers.Main) {
if (!isFinishing) {
vibrator.vibrate()
if (isFinishing) {
return@withContext
}
val rc = Rect()
imageRect.round(rc)
rectInView.intersect(rc)
detectorView.mark(
mapResult(
cropped.width,
cropped.height,
0,
rectInView,
it
result = it
scanFeedback()
dv.update(
matrix.mapPosition(
it.position,
dv.coordinates
)
)
}
@@ -151,13 +184,38 @@ class PickActivity : AppCompatActivity() {
}
}
// By default, ZXing uses LOCAL_AVERAGE, but this does not work
// well with inverted barcodes on low-contrast backgrounds.
private fun Bitmap.decode() = ZxingCpp.readBitmap(
this,
0, 0,
width, height,
0,
options.apply {
binarizer = Binarizer.LOCAL_AVERAGE
}
) ?: ZxingCpp.readBitmap(
this,
0, 0,
width, height,
0,
options.apply {
binarizer = Binarizer.GLOBAL_HISTOGRAM
}
)
override fun onDestroy() {
super.onDestroy()
rs.destroy()
detectorView?.storeCropHandlePos()
parentJob.cancel()
releaseToneGenerators()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.activity_pick, menu)
freeRotationItem = menu.findItem(R.id.toggle_free).apply {
updateFreeRotationIcon()
}
return true
}
@@ -167,37 +225,55 @@ class PickActivity : AppCompatActivity() {
rotateClockwise()
true
}
R.id.toggle_free -> {
prefs.freeRotation = prefs.freeRotation xor true
cropImageView?.freeRotation = prefs.freeRotation
freeRotationItem?.updateFreeRotationIcon()
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun MenuItem.updateFreeRotationIcon() {
setIcon(
if (prefs.freeRotation) {
R.drawable.ic_action_rotation_unlocked
} else {
R.drawable.ic_action_rotation_locked
}
)
}
private fun rotateClockwise() {
cropImageView.imageRotation = cropImageView.imageRotation + 90 % 360
val civ = cropImageView ?: return
civ.imageRotation = (civ.imageRotation + 90) % 360
}
private fun loadSentImage(intent: Intent): Bitmap? {
val uri = intent.getParcelableExtra<Parcelable>(
Intent.EXTRA_STREAM
) as? Uri ?: return null
return loadImageUri(contentResolver, uri)
val uri = intent.getUriExtra() ?: return null
return contentResolver.loadImageUri(uri)
}
private fun loadImageToOpen(intent: Intent): Bitmap? {
val uri = intent.data ?: return null
return loadImageUri(contentResolver, uri)
return contentResolver.loadImageUri(uri)
}
private fun showResult() {
result?.let {
showResult(this, it, vibrator)
val r = result
if (r != null) {
showResult(r)
finish()
return
} else {
applicationContext.toast(R.string.no_barcode_found)
}
applicationContext.toast(R.string.no_barcode_found)
}
}
private fun normalizeRoi(imageRect: RectF, roi: Rect): RectF {
private fun getNormalizedRoi(imageRect: RectF, roi: Rect): RectF {
val w = imageRect.width()
val h = imageRect.height()
return RectF(
@@ -207,3 +283,12 @@ private fun normalizeRoi(imageRect: RectF, roi: Rect): RectF {
(roi.bottom - imageRect.top) / h
)
}
private fun Intent.getUriExtra(): Uri? = if (
Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU
) {
@Suppress("DEPRECATION")
getParcelableExtra(Intent.EXTRA_STREAM)
} else {
getParcelableExtra(Intent.EXTRA_STREAM, Uri::class.java)
}
@@ -0,0 +1,34 @@
package de.markusfisch.android.binaryeye.activity
import android.content.Context
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import de.markusfisch.android.binaryeye.R
import de.markusfisch.android.binaryeye.app.applyLocale
import de.markusfisch.android.binaryeye.app.prefs
import de.markusfisch.android.binaryeye.fragment.PreferencesFragment
import de.markusfisch.android.binaryeye.view.initBars
class PreferencesActivity : AppCompatActivity() {
override fun attachBaseContext(base: Context?) {
base?.applyLocale(prefs.customLocale)
super.attachBaseContext(base)
}
override fun onCreate(state: Bundle?) {
super.onCreate(state)
setContentView(R.layout.activity_main)
initBars()
supportActionBar?.setDisplayHomeAsUpEnabled(true)
if (state == null) {
supportFragmentManager.beginTransaction()
.replace(R.id.content_frame, PreferencesFragment())
.commit()
}
}
override fun onSupportNavigateUp(): Boolean {
finish()
return true
}
}
@@ -0,0 +1,163 @@
package de.markusfisch.android.binaryeye.activity
import android.app.AlertDialog
import android.content.Context
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.EditText
import android.widget.ListView
import android.widget.TextView
import de.markusfisch.android.binaryeye.R
import de.markusfisch.android.binaryeye.app.prefs
import de.markusfisch.android.binaryeye.view.setPaddingFromWindowInsets
import de.markusfisch.android.binaryeye.view.systemBarListViewScrollListener
import de.markusfisch.android.binaryeye.widget.toast
class ProfilesActivity : AbstractBaseActivity() {
private val profiles = ArrayList<ProfileItem>()
private lateinit var adapter: ProfilesAdapter
override fun onCreate(state: Bundle?) {
super.onCreate(state)
setScreenContentView(R.layout.activity_profiles)
setTitle(R.string.profile)
refreshProfiles()
val listView = findViewById<ListView>(R.id.profiles)
listView.emptyView = findViewById(R.id.no_profiles)
adapter = ProfilesAdapter(this, profiles)
listView.adapter = adapter
listView.setOnScrollListener(systemBarListViewScrollListener)
listView.setOnItemClickListener { _, _, position, _ ->
selectProfile(position)
}
listView.setOnItemLongClickListener { _, _, position, _ ->
confirmRemoveProfile(position)
true
}
findViewById<View>(R.id.add).setOnClickListener {
addProfile()
}
findViewById<View>(R.id.inset_layout).setPaddingFromWindowInsets()
listView.setPaddingFromWindowInsets()
}
private fun refreshProfiles() {
profiles.clear()
profiles.add(
ProfileItem(
null,
getString(R.string.profile_default)
)
)
prefs.profiles.forEach { name ->
profiles.add(ProfileItem(name, name))
}
if (this::adapter.isInitialized) {
adapter.notifyDataSetChanged()
}
}
private fun selectProfile(position: Int) {
val profile = profiles[position].name
if (prefs.profile == profile) {
return
}
prefs.load(this, profile)
adapter.notifyDataSetChanged()
}
// Dialogs do not have a parent view.
@Suppress("InflateParams")
private fun addProfile() {
val view = layoutInflater.inflate(
R.layout.dialog_profile_name, null
)
val editText = view.findViewById<EditText>(R.id.name)
AlertDialog.Builder(this)
.setView(view)
.setPositiveButton(android.R.string.ok) { _, _ ->
val name = editText.text.toString().trim()
if (name.isNotEmpty() && prefs.addProfile(name)) {
prefs.load(this, name)
refreshProfiles()
} else {
toast(R.string.profile_invalid_name)
}
}
.show()
}
private fun confirmRemoveProfile(position: Int) {
val profile = profiles[position]
val profileName = profile.name ?: return
AlertDialog.Builder(this)
.setMessage(R.string.profile_remove_confirm)
.setPositiveButton(android.R.string.ok) { _, _ ->
val isCurrent = prefs.profile == profileName
prefs.removeProfile(profileName)
if (isCurrent) {
prefs.load(this, null)
}
refreshProfiles()
}
.setNegativeButton(android.R.string.cancel) { _, _ -> }
.show()
}
private class ProfilesAdapter(
context: Context,
private val items: List<ProfileItem>
) : ArrayAdapter<ProfileItem>(
context,
android.R.layout.simple_list_item_2,
android.R.id.text1,
items
) {
override fun getView(
position: Int,
convertView: View?,
parent: ViewGroup
): View {
val view = super.getView(position, convertView, parent)
val item = items[position]
val isCurrent = item.name == prefs.profile
getViewHolder(view).apply {
title.text = item.label
if (isCurrent) {
subtitle.text = context.getString(R.string.profile_current)
subtitle.visibility = View.VISIBLE
} else {
subtitle.text = ""
subtitle.visibility = View.GONE
}
}
return view
}
private fun getViewHolder(
view: View
): ViewHolder = view.tag as ViewHolder? ?: ViewHolder(
view.findViewById(android.R.id.text1),
view.findViewById(android.R.id.text2),
).also {
view.tag = it
}
private data class ViewHolder(
val title: TextView,
val subtitle: TextView,
)
}
}
private data class ProfileItem(
val name: String?,
val label: String
)
@@ -2,18 +2,16 @@ package de.markusfisch.android.binaryeye.activity
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import de.markusfisch.android.binaryeye.app.setRestartCount
import androidx.appcompat.app.AppCompatActivity
class SplashActivity : AppCompatActivity() {
override fun onCreate(state: Bundle?) {
super.onCreate(state)
// it's important _not_ to inflate a layout file here
// It's important _not_ to inflate a layout file here
// because that would happen after the app is fully
// initialized what is too late
// initialized what is too late.
setRestartCount(intent)
startActivity(Intent(applicationContext, CameraActivity::class.java))
finish()
}
@@ -0,0 +1,33 @@
package de.markusfisch.android.binaryeye.activity
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import de.markusfisch.android.binaryeye.R
import de.markusfisch.android.binaryeye.app.prefs
class WelcomeActivity : AppCompatActivity() {
override fun onCreate(state: Bundle?) {
super.onCreate(state)
setContentView(R.layout.activity_welcome)
findViewById<View>(R.id.expert).setOnClickListener {
finish()
}
findViewById<View>(R.id.simple).setOnClickListener {
prefs.apply {
showCropHandle = false
zoomBySwiping = false
beep = true
copyImmediately = true
openImmediately = true
showMetaData = false
showHexDump = false
defaultSearchUrl = "https://www.google.com/search?q="
openWithUrl = defaultSearchUrl
expandEscapeSequences = false
brightenScreen = true
}
finish()
}
}
}
@@ -5,46 +5,86 @@ import android.database.Cursor
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.CursorAdapter
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.Spinner
import android.widget.TextView
import androidx.core.content.ContextCompat
import de.markusfisch.android.binaryeye.R
import de.markusfisch.android.binaryeye.database.Database
import java.text.DateFormat
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
import java.util.Locale
class ScansAdapter(context: Context, cursor: Cursor) :
class ScansAdapter(
context: Context,
cursor: Cursor,
private val onPinClick: (Long, Boolean) -> Unit
) :
CursorAdapter(context, cursor, false) {
var selectedScanId = 0L
var selectedScanPosition = -1
private val idIndex = cursor.getColumnIndex(Database.SCANS_ID)
private val pinnedIndex = cursor.getColumnIndex(Database.SCANS_PINNED)
private val timeIndex = cursor.getColumnIndex(Database.SCANS_DATETIME)
private val nameIndex = cursor.getColumnIndex(Database.SCANS_NAME)
private val contentIndex = cursor.getColumnIndex(Database.SCANS_CONTENT)
private val textIndex = cursor.getColumnIndex(Database.SCANS_TEXT)
private val formatIndex = cursor.getColumnIndex(Database.SCANS_FORMAT)
private val selections = mutableMapOf<Long, Int>()
private val selectedColor = ContextCompat.getColor(
context, R.color.selected_row
)
fun select(id: Long, position: Int) {
selectedScanId = id
selectedScanPosition = position
fun select(view: View, id: Long, position: Int) {
view.select(
if (selections[id] == null) {
selections[id] = position
true
} else {
selections.remove(id)
false
}
)
}
fun clearSelection() {
selectedScanId = 0L
selectedScanPosition = -1
selections.clear()
}
fun getSelectedContent() = if (selectedScanPosition < 0) {
null
} else {
val cursor = getItem(selectedScanPosition)
if (cursor is Cursor) {
cursor.getString(contentIndex)
} else {
null
fun forSelection(callback: (Long, Int) -> Unit) {
selections.forEach {
callback.invoke(it.key, it.value)
}
}
fun getSelectedIds(): List<Long> = mutableListOf<Long>().apply {
forSelection { id, _ ->
add(id)
}
}
fun getSelectedContent(separator: String): String {
val sb = StringBuilder()
forSelection { _, position ->
getContent(position)?.let {
if (sb.isNotEmpty()) {
sb.append(separator)
}
sb.append(it)
}
}
return sb.toString()
}
fun getName(
position: Int
) = (getItem(position) as Cursor?)?.getString(nameIndex)
fun getContent(
position: Int
) = (getItem(position) as Cursor?)?.getString(textIndex)
override fun newView(
context: Context,
cursor: Cursor,
@@ -58,55 +98,170 @@ class ScansAdapter(context: Context, cursor: Cursor) :
context: Context,
cursor: Cursor
) {
val holder = getViewHolder(view)
holder.timeView.text = formatDateTime(cursor.getString(timeIndex))
val name = cursor.getString(nameIndex)
val content = cursor.getString(contentIndex)
var icon = 0
holder.contentView.text = when {
name?.isNotEmpty() == true -> {
icon = R.drawable.ic_label
name
val id = cursor.getLong(idIndex)
val pinned = cursor.getInt(pinnedIndex) != 0
val format = cursor.getString(formatIndex)
getViewHolder(view).apply {
metaView.text = context.getString(
R.string.scan_meta_data,
formatDateTime(cursor.getString(timeIndex)),
format.prettifyFormatName()
)
formatIconView.setImageResource(format.toBarcodeIcon())
val name = cursor.getString(nameIndex)
val text = cursor.getString(textIndex)
var icon = 0
contentView.text = when {
name?.isNotEmpty() == true -> {
icon = R.drawable.ic_label
name
}
text.isNullOrEmpty() -> context.getString(
R.string.binary_data
)
else -> text
}
contentView.setCompoundDrawablesWithIntrinsicBounds(
icon, 0, 0, 0
)
pinView.apply {
setImageResource(
if (pinned) {
R.drawable.ic_action_pin
} else {
R.drawable.ic_action_pin_outline
}
)
contentDescription = context.getString(
if (pinned) {
R.string.unpin_item
} else {
R.string.pin_item
}
)
setOnClickListener {
onPinClick(id, !pinned)
}
}
content?.isEmpty() == true -> context.getString(R.string.binary_data)
else -> content
}
holder.contentView.setCompoundDrawablesWithIntrinsicBounds(
icon, 0, 0, 0
)
holder.formatView.text = prettifyFormatName(cursor.getString(formatIndex))
// view.isSelected needs to be put on the queue to work
val selected = cursor.getLong(idIndex) == selectedScanId
val selected = selections[id] != null
view.post {
view.isSelected = selected
// Needs to be put on the queue to work.
view.select(selected)
}
}
private fun getViewHolder(view: View): ViewHolder {
return view.tag as ViewHolder? ?: ViewHolder(
view.findViewById(R.id.time),
view.findViewById(R.id.content),
view.findViewById(R.id.format)
).also {
view.tag = it
}
private fun View.select(selected: Boolean) {
setBackgroundColor(if (selected) selectedColor else 0)
}
private fun getViewHolder(
view: View
): ViewHolder = view.tag as ViewHolder? ?: ViewHolder(
view.findViewById(R.id.format_icon),
view.findViewById(R.id.meta),
view.findViewById(R.id.content),
view.findViewById(R.id.pin)
).also {
view.tag = it
}
private data class ViewHolder(
val timeView: TextView,
val formatIconView: ImageView,
val metaView: TextView,
val contentView: TextView,
val formatView: TextView
val pinView: ImageButton
)
}
fun prettifyFormatName(format: String) = format.replace("_", " ")
private val formatWordBoundary =
"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|(?<=[A-Za-z])(?=\\d)|(?<=\\d)(?=[A-Za-z])".toRegex()
fun Context.setupFormatSpinner(spinner: Spinner): List<String> {
val names = resources.getStringArray(
R.array.barcode_formats_names
).toMutableList().apply {
add(0, getString(R.string.all_formats))
}
val values = resources.getStringArray(
R.array.barcode_formats_values
).toMutableList().apply {
add(0, "")
}
spinner.adapter = ArrayAdapter(
this,
android.R.layout.simple_spinner_item,
names
).apply {
setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item
)
}
return values
}
fun String.prettifyFormatName() = replace("_", " ")
.replace(formatWordBoundary, " ")
fun String.toFormatDescriptionResId(): Int = when (this) {
"Aztec" -> R.string.format_description_aztec
"Codabar" -> R.string.format_description_codabar
"Code39",
"Code39Std" -> R.string.format_description_code39
"Code39Ext" -> R.string.format_description_code39ext
"Code32" -> R.string.format_description_code32
"PZN" -> R.string.format_description_pzn
"Code93" -> R.string.format_description_code93
"Code128" -> R.string.format_description_code128
"DataBar" -> R.string.format_description_databar
"DataBarOmni" -> R.string.format_description_databar_omni
"DataBarStk" -> R.string.format_description_databar_stk
"DataBarLtd" -> R.string.format_description_databar_ltd
"DataBarExp" -> R.string.format_description_databar_exp
"DataBarExpStk" -> R.string.format_description_databar_exp_stk
"DataMatrix" -> R.string.format_description_data_matrix
"DXFilmEdge" -> R.string.format_description_dx_film_edge
"EAN8" -> R.string.format_description_ean8
"EAN13" -> R.string.format_description_ean13
"ITF" -> R.string.format_description_itf
"MaxiCode" -> R.string.format_description_maxicode
"PDF417" -> R.string.format_description_pdf417
"QRCode" -> R.string.format_description_qr_code
"MicroQRCode" -> R.string.format_description_micro_qr_code
"RMQRCode" -> R.string.format_description_rmqr_code
"UPCA" -> R.string.format_description_upca
"UPCE" -> R.string.format_description_upce
else -> 0
}
private fun String?.toBarcodeIcon(): Int = when (this) {
"QRCode",
"RMQRCode" -> R.drawable.ic_barcode_qr_code
"MicroQRCode" -> R.drawable.ic_barcode_micro_qr
"Aztec" -> R.drawable.ic_barcode_aztec
"DataMatrix",
"MaxiCode" -> R.drawable.ic_barcode_data_matrix
"PDF417" -> R.drawable.ic_barcode_pdf417
else -> R.drawable.ic_barcode_linear
}
private fun formatDateTime(rfc: String): String {
SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).parse(rfc)?.let {
return DateFormat.getDateTimeInstance(
DateFormat.LONG,
DateFormat.SHORT
).format(it)
try {
SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).parse(rfc)?.let {
return DateFormat.getDateTimeInstance(
DateFormat.LONG,
DateFormat.SHORT
).format(it)
}
} catch (_: ParseException) {
// Ignore and fall through.
}
return rfc
}
@@ -1,7 +1,7 @@
package de.markusfisch.android.binaryeye.app
import android.app.AlertDialog
import android.content.Context
import android.support.v7.app.AlertDialog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlin.coroutines.resume
@@ -11,7 +11,7 @@ suspend inline fun <T : Any> alertDialog(
context: Context,
crossinline build: AlertDialog.Builder.(resume: (T?) -> Unit) -> Unit
): T? = withContext(Dispatchers.Main) {
suspendCoroutine<T?> { continuation ->
suspendCoroutine { continuation ->
AlertDialog.Builder(context).apply {
setOnCancelListener {
continuation.resume(null)
@@ -1,7 +1,6 @@
package de.markusfisch.android.binaryeye.app
import android.app.Application
import android.support.v8.renderscript.RenderScript
import de.markusfisch.android.binaryeye.database.Database
import de.markusfisch.android.binaryeye.preference.Preferences
@@ -13,9 +12,5 @@ class BinaryEyeApp : Application() {
super.onCreate()
db.open(this)
prefs.init(this)
if (prefs.forceCompat) {
RenderScript.forceCompat()
}
}
}
@@ -1,14 +0,0 @@
package de.markusfisch.android.binaryeye.app
import android.net.Uri
import android.os.Build
private val nonPrintable = "[\\x00-\\x08\\x0e-\\x1f]".toRegex()
fun hasNonPrintableCharacters(s: String) = nonPrintable.containsMatchIn(s)
fun parseAndNormalizeUri(input: String): Uri = Uri.parse(input).let {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) it.normalizeScheme() else it
}
fun ByteArray.toHexString() = joinToString("") { "%02X".format(it) }
@@ -1,20 +0,0 @@
package de.markusfisch.android.binaryeye.app
import android.annotation.SuppressLint
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import de.markusfisch.android.binaryeye.R
fun setFragment(fm: FragmentManager?, fragment: Fragment) {
fm?.let { getTransaction(fm, fragment).commit() }
}
fun addFragment(fm: FragmentManager?, fragment: Fragment) {
fm?.let { getTransaction(fm, fragment).addToBackStack(null).commit() }
}
@SuppressLint("CommitTransaction")
private fun getTransaction(
fm: FragmentManager,
fragment: Fragment
) = fm.beginTransaction().replace(R.id.content_frame, fragment)
@@ -2,19 +2,25 @@ package de.markusfisch.android.binaryeye.app
import android.content.Context
import android.os.Build
import java.util.*
import java.util.Locale
fun Context.applyLocale(localeName: String) {
if (localeName.isNotEmpty()) {
val locale = Locale(localeName)
Locale.setDefault(locale)
val conf = resources.configuration
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
@Suppress("DEPRECATION")
conf.locale = locale
} else {
conf.setLocale(locale)
}
resources.updateConfiguration(conf, resources.displayMetrics)
if (localeName.isEmpty()) {
return
}
val localeParts = localeName.split("-")
val locale = if (localeParts.size == 2) {
Locale(localeParts[0], localeParts[1])
} else {
Locale(localeName)
}
Locale.setDefault(locale)
val conf = resources.configuration
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
@Suppress("DEPRECATION")
conf.locale = locale
} else {
conf.setLocale(locale)
}
resources.updateConfiguration(conf, resources.displayMetrics)
}
@@ -3,52 +3,63 @@ package de.markusfisch.android.binaryeye.app
import android.Manifest
import android.app.Activity
import android.content.pm.PackageManager
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.os.Build
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
var permissionGrantedCallback: (() -> Any)? = null
const val PERMISSION_CAMERA = 1
fun hasCameraPermission(activity: Activity) = hasPermission(
activity,
fun Activity.hasCameraPermission(request: Boolean = true) = hasPermission(
Manifest.permission.CAMERA,
PERMISSION_CAMERA
if (request) PERMISSION_CAMERA else 0
)
const val PERMISSION_WRITE = 2
fun hasWritePermission(activity: Activity, callback: () -> Any): Boolean {
fun Activity.hasWritePermission(callback: () -> Any): Boolean {
permissionGrantedCallback = callback
return hasPermission(
activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
PERMISSION_WRITE
)
}
const val PERMISSION_LOCATION = 3
fun hasLocationPermission(activity: Activity, callback: () -> Any): Boolean {
fun Activity.hasLocationPermission(callback: () -> Any): Boolean {
permissionGrantedCallback = callback
return hasPermission(
activity,
Manifest.permission.ACCESS_FINE_LOCATION,
PERMISSION_LOCATION
)
}
private fun hasPermission(
activity: Activity,
const val PERMISSION_BLUETOOTH = 4
fun Activity.hasBluetoothPermission() = if (
Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
) {
hasPermission(
Manifest.permission.BLUETOOTH_CONNECT,
PERMISSION_BLUETOOTH
)
} else {
false
}
private fun Activity.hasPermission(
permission: String,
requestCode: Int
) = if (ContextCompat.checkSelfPermission(
activity,
this,
permission
) != PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(
activity,
arrayOf(permission),
requestCode
)
if (requestCode > 0) {
ActivityCompat.requestPermissions(
this,
arrayOf(permission),
requestCode
)
}
false
} else {
true
@@ -1,26 +0,0 @@
package de.markusfisch.android.binaryeye.app
import android.app.Activity
import android.content.Intent
import de.markusfisch.android.binaryeye.activity.SplashActivity
private const val RESTART_COUNT = "restart_count"
private var restartCount = 0
fun setRestartCount(intent: Intent?) {
intent?.let {
restartCount = intent.getIntExtra(RESTART_COUNT, restartCount)
}
}
fun restartApp(activity: Activity? = null) {
if (activity != null && restartCount < 3) {
val intent = Intent(activity, SplashActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.putExtra(RESTART_COUNT, ++restartCount)
activity.startActivity(intent)
activity.finish()
}
Runtime.getRuntime().exit(0)
}
@@ -0,0 +1,111 @@
package de.markusfisch.android.binaryeye.automation
import de.markusfisch.android.binaryeye.database.Scan
import de.markusfisch.android.binaryeye.net.urlEncode
import org.json.JSONArray
import org.json.JSONObject
import java.util.Locale
data class AutomatedAction(
val pattern: String,
val type: Type,
val format: String? = null,
val urlTemplate: String? = null,
val intentUriTemplate: String? = null
) {
enum class Type {
Intent, CustomIntent
}
fun matches(content: String, format: String): Boolean = try {
(this.format == null || this.format == format) &&
Regex(pattern).matches(content)
} catch (_: Exception) {
false
}
fun toJson(): JSONObject = JSONObject().apply {
put(KEY_PATTERN, pattern)
put(KEY_TYPE, type.name.lowercase(Locale.ROOT))
put(KEY_FORMAT, format ?: "")
put(KEY_URL_TEMPLATE, urlTemplate ?: "")
put(KEY_INTENT_URI_TEMPLATE, intentUriTemplate ?: "")
}
companion object {
private const val KEY_PATTERN = "pattern"
private const val KEY_TYPE = "type"
private const val KEY_FORMAT = "format"
private const val KEY_URL_TEMPLATE = "url_template"
private const val KEY_INTENT_URI_TEMPLATE = "intent_uri_template"
fun fromJson(obj: JSONObject): AutomatedAction? {
val pattern = obj.optString(KEY_PATTERN, "").trim()
if (pattern.isEmpty()) {
return null
}
val type = when (obj.optString(KEY_TYPE, "")) {
"custom_intent" -> Type.CustomIntent
"intent" -> Type.Intent
"html" -> return null
else -> Type.Intent
}
val format = obj.optString(KEY_FORMAT, "").trim()
val urlTemplate = obj.optString(KEY_URL_TEMPLATE, "").trim()
val intentUriTemplate = obj.optString(
KEY_INTENT_URI_TEMPLATE,
""
).trim()
return AutomatedAction(
pattern = pattern,
type = type,
format = format.ifEmpty { null },
urlTemplate = urlTemplate.ifEmpty { null },
intentUriTemplate = intentUriTemplate.ifEmpty { null }
)
}
fun fromJsonArray(json: String): MutableList<AutomatedAction> {
val actions = ArrayList<AutomatedAction>()
val array = try {
JSONArray(json)
} catch (_: Exception) {
JSONArray()
}
for (i in 0 until array.length()) {
val obj = array.optJSONObject(i) ?: continue
fromJson(obj)?.let { actions.add(it) }
}
return actions
}
fun toJsonArray(actions: List<AutomatedAction>): String {
val array = JSONArray()
actions.forEach { array.put(it.toJson()) }
return array.toString()
}
}
}
fun String.buildUrl(scan: Scan): String {
return buildTemplate(scan, encodeResult = true)
}
fun String.buildTemplate(scan: Scan, encodeResult: Boolean): String {
val text = scan.text
val raw = scan.raw ?: text.toByteArray()
val result = if (encodeResult) {
text.urlEncode()
} else {
text
}
val format = if (encodeResult) {
scan.format.name.urlEncode()
} else {
scan.format.name
}
return this
.replace("{RESULT}", result)
.replace("{RESULT_BYTES}", raw.toHexString())
.replace("{FORMAT}", format)
}
@@ -0,0 +1,59 @@
package de.markusfisch.android.binaryeye.automation
import android.content.Context
import android.content.Intent
import de.markusfisch.android.binaryeye.R
import de.markusfisch.android.binaryeye.app.prefs
import de.markusfisch.android.binaryeye.content.execShareIntent
import de.markusfisch.android.binaryeye.content.openUrl
import de.markusfisch.android.binaryeye.database.Scan
import de.markusfisch.android.binaryeye.widget.toast
fun Context.runAutomatedActions(scan: Scan): Boolean {
val content = scan.text
if (content.isEmpty()) {
return false
}
val actions = prefs.automatedActions
if (actions.isEmpty()) {
return false
}
for (action in actions) {
if (action.matches(content, scan.format.name)) {
return when (action.type) {
AutomatedAction.Type.Intent -> {
val url = action.urlTemplate?.buildUrl(scan)
if (url.isNullOrEmpty()) {
toast(R.string.automated_action_invalid_url)
false
} else {
openUrl(url)
}
}
AutomatedAction.Type.CustomIntent ->
execCustomIntent(action, scan)
}
}
}
return false
}
private fun Context.execCustomIntent(
action: AutomatedAction,
scan: Scan
): Boolean {
val template = action.intentUriTemplate
if (template.isNullOrEmpty()) {
toast(R.string.automated_action_intent_uri_required)
return false
}
val intentUri = template.buildTemplate(scan, encodeResult = false)
val intent = try {
Intent.parseUri(intentUri, Intent.URI_INTENT_SCHEME)
} catch (_: Exception) {
toast(R.string.automated_action_intent_uri_invalid)
return false
}
return execShareIntent(intent)
}
@@ -0,0 +1,128 @@
package de.markusfisch.android.binaryeye.bluetooth
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import androidx.preference.ListPreference
import de.markusfisch.android.binaryeye.database.Scan
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.IOException
import java.io.OutputStreamWriter
import java.util.UUID
fun Scan.sendBluetoothAsync(
host: String,
callback: (Boolean, Boolean) -> Unit
) {
CoroutineScope(Dispatchers.IO).launch(Dispatchers.IO) {
val connected = if (isConnected) {
true
} else {
connect(host, true)
}
val sent = if (connected) {
send(text, host)
} else {
false
}
withContext(Dispatchers.Main) {
callback(connected, sent)
}
}
}
fun setBluetoothHosts(listPref: ListPreference) {
try {
val devices = blue.bondedDevices ?: return
listPref.entries = devices.map {
it.name
}.toTypedArray()
listPref.entryValues = devices.map {
it.address
}.toTypedArray()
listPref.callChangeListener(listPref.value)
} catch (_: SecurityException) {
// Do nothing, either the user has denied Bluetooth access
// or the permission was removed by the system. We're catching
// the exception to keep the app from crashing.
}
}
private var socket: BluetoothSocket? = null
private var writer: OutputStreamWriter? = null
private val blue = BluetoothAdapter.getDefaultAdapter()
private val uuid = UUID.fromString(
"8a8478c9-2ca8-404b-a0de-101f34ab71ae"
)
private var isConnected = false
private fun connect(deviceName: String, onceMore: Boolean): Boolean = try {
val device = findByName(deviceName) ?: throw RuntimeException(
"Bluetooth device not found"
)
socket = device.createRfcommSocketToServiceRecord(uuid)
socket?.connect()
writer = socket?.outputStream?.writer()
isConnected = true
true
} catch (_: Exception) {
if (onceMore) {
connect(deviceName, false)
} else {
close()
}
false
}
private fun send(message: String, host: String): Boolean = try {
writer?.apply {
write(message)
write("\n")
flush()
}
true
} catch (_: Exception) {
close()
if (connect(host, false)) {
send(message, host)
} else {
false
}
}
private fun close() {
try {
writer?.close()
} catch (_: IOException) {
// Catch exception if writer wasn't initialized.
}
try {
socket?.close()
} catch (_: IOException) {
// Nothing we can do about this but keep
// the app from crashing.
}
writer = null
socket = null
isConnected = false
}
private fun findByName(findableName: String): BluetoothDevice? {
try {
val deviceList = blue.bondedDevices
for (device in deviceList) {
if (device.address == findableName) {
return device
}
}
} catch (_: SecurityException) {
// Fall through.
}
return null
}
@@ -0,0 +1,218 @@
package de.markusfisch.android.binaryeye.content
import android.graphics.Bitmap
import android.util.Size
import de.markusfisch.android.binaryeye.database.Scan
import de.markusfisch.android.binaryeye.graphics.COLOR_BLACK
import de.markusfisch.android.binaryeye.graphics.COLOR_WHITE
import de.markusfisch.android.zxingcpp.ZxingCpp
import de.markusfisch.android.zxingcpp.ZxingCpp.BarcodeFormat
import de.markusfisch.android.zxingcpp.ZxingCpp.BitMatrix
import de.markusfisch.android.zxingcpp.ZxingCpp.toBitmap
import de.markusfisch.android.zxingcpp.ZxingCpp.toSvg
import de.markusfisch.android.zxingcpp.ZxingCpp.toText
import java.util.Arrays
enum class BarcodeColors {
BLACK_ON_WHITE,
WHITE_ON_BLACK,
BLACK_ON_TRANSPARENT,
WHITE_ON_TRANSPARENT;
fun foregroundColor(): Int = when (this) {
BLACK_ON_WHITE,
BLACK_ON_TRANSPARENT -> COLOR_BLACK
WHITE_ON_BLACK,
WHITE_ON_TRANSPARENT -> COLOR_WHITE
}
fun backgroundColor(): Int = when (this) {
BLACK_ON_WHITE -> COLOR_WHITE
WHITE_ON_BLACK -> COLOR_BLACK
BLACK_ON_TRANSPARENT,
WHITE_ON_TRANSPARENT -> 0
}
}
fun Scan.toBarcode(): Barcode<*> {
val content = text.ifEmpty {
raw
}
return if (symbol != null) {
BitMatrixBarcode(
symbol,
content,
format
)
} else {
ContentBarcode(
content,
format,
errorCorrectionLevel.toErrorCorrectionInt(),
addQuietZone = true
)
}
}
fun String?.toErrorCorrectionInt() = when (this) {
"L" -> 0
"M" -> 4
"Q" -> 6
"H" -> 8
else -> -1
}
sealed class Barcode<T>(
val content: T,
val format: BarcodeFormat,
val colors: BarcodeColors
) {
private var _bitmap: Bitmap? = null
fun bitmap(): Bitmap {
val b = _bitmap ?: bitmap(512)
_bitmap = b
return b
}
fun bitmap(size: Int): Bitmap {
return toBitmap(size)
}
protected abstract fun toBitmap(size: Int): Bitmap
private var _svg: String? = null
fun svg(): String {
val s = _svg ?: toSvg()
_svg = s
return s
}
protected abstract fun toSvg(): String
private var _text: String? = null
fun text(): String {
val t = _text ?: toText()
_text = t
return t
}
protected abstract fun toText(): String
fun textOrHex(): String = when (content) {
is String -> content
is ByteArray -> content.toHexString()
else -> throw IllegalArgumentException("Illegal arguments")
}
}
class ContentBarcode<T>(
content: T,
format: BarcodeFormat,
val ecLevel: Int = -1,
val addQuietZone: Boolean = false,
colors: BarcodeColors = BarcodeColors.BLACK_ON_WHITE
) : Barcode<T>(content, format, colors) {
override fun toBitmap(size: Int): Bitmap {
val s = format.resolveSize(size)
return ZxingCpp.encodeAsBitmap(
content, format, s.width, s.height, addQuietZone, ecLevel,
setColor = colors.foregroundColor(),
unsetColor = colors.backgroundColor()
)
}
override fun toSvg() = ZxingCpp.encodeAsSvg(
content, format, addQuietZone, ecLevel
)
override fun toText() = ZxingCpp.encodeAsText(
content, format, addQuietZone, ecLevel,
inverted = colors == BarcodeColors.BLACK_ON_WHITE
)
}
class BitMatrixBarcode<T>(
val bitMatrix: BitMatrix,
content: T,
format: BarcodeFormat,
colors: BarcodeColors = BarcodeColors.BLACK_ON_WHITE
) : Barcode<T>(content, format, colors) {
override fun toBitmap(size: Int) = bitMatrix.inflate(size).toBitmap(
setColor = colors.foregroundColor(),
unsetColor = colors.backgroundColor()
)
override fun toSvg() = bitMatrix.inflate().toSvg()
override fun toText() = bitMatrix.inflate().toText(
inverted = colors == BarcodeColors.BLACK_ON_WHITE
)
}
private fun BitMatrix.inflate(
size: Int = 0,
quietZone: Boolean = true
): BitMatrix {
val extraModules = if (quietZone) 2 else 0
val codeWidth = width + extraModules
val codeHeight = height + extraModules
var scale = size / codeWidth
if (scale < 1) {
if (size > 0 && !quietZone) {
return this
}
scale = 1
}
val outWidth = codeWidth * scale
val outHeight = codeHeight * scale
val scaled = BitMatrix(
outWidth,
outHeight,
ByteArray(outWidth * outHeight)
)
Arrays.fill(scaled.data, 1)
val padding = extraModules / 2
val left = padding * scale
val top = padding * scale
val right = outWidth - left
val bottom = outHeight - top
for (y in top until bottom) {
var dst = y * outWidth + left
val offset = (y - top) / scale * width
for (x in left until right) {
scaled.data[dst++] = data[
offset + (x - left) / scale
]
}
}
return scaled
}
private fun BarcodeFormat.resolveSize(size: Int): Size = when (this) {
// 1D barcodes don't need as much vertical space.
BarcodeFormat.Codabar,
BarcodeFormat.Code39,
BarcodeFormat.Code39Std,
BarcodeFormat.Code39Ext,
BarcodeFormat.Code32,
BarcodeFormat.PZN,
BarcodeFormat.Code93,
BarcodeFormat.Code128,
BarcodeFormat.DataBarOmni,
BarcodeFormat.DataBarStk,
BarcodeFormat.DataBarLtd,
BarcodeFormat.DataBarExp,
BarcodeFormat.DataBarExpStk,
BarcodeFormat.DXFilmEdge,
BarcodeFormat.EAN8,
BarcodeFormat.EAN13,
BarcodeFormat.ITF,
BarcodeFormat.UPCA,
BarcodeFormat.UPCE -> Size(size, size / 3)
// PDF417 requires more horizontal space.
BarcodeFormat.PDF417 -> Size(size * 3, size / 2)
else -> Size(size, size)
}
@@ -1,17 +1,32 @@
package de.markusfisch.android.binaryeye.content
import android.content.ClipData
import android.content.ClipDescription
import android.content.Context
import android.os.Build
import android.os.PersistableBundle
fun Context.copyToClipboard(text: String) {
fun Context.copyToClipboard(text: String, isSensitive: Boolean = false) {
val service = getSystemService(Context.CLIPBOARD_SERVICE)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
@Suppress("DEPRECATION")
(service as android.text.ClipboardManager).text = text
} else {
(service as android.content.ClipboardManager).setPrimaryClip(
ClipData.newPlainText("plain text", text)
)
(service as android.content.ClipboardManager).setPrimaryClip(
ClipData.newPlainText("plain text", text).apply {
setSensitive(isSensitive)
}
)
}
private fun ClipData.setSensitive(isSensitive: Boolean) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
description.extras = PersistableBundle().apply {
putBoolean(EXTRA_IS_SENSITIVE, isSensitive)
}
}
}
}
private val EXTRA_IS_SENSITIVE = if (
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU
) {
ClipDescription.EXTRA_IS_SENSITIVE
} else {
"android.content.extra.IS_SENSITIVE"
}
@@ -0,0 +1,23 @@
package de.markusfisch.android.binaryeye.content
import android.content.Context
import de.markusfisch.android.binaryeye.R
private val elementToLabel = mapOf(
EpcQrElement.SERVICE_TAG to R.string.epc_service_tag,
EpcQrElement.VERSION to R.string.epc_version,
EpcQrElement.CHARSET to R.string.epc_charset,
EpcQrElement.IDENTIFICATION to R.string.epc_identification,
EpcQrElement.BIC to R.string.epc_bic,
EpcQrElement.NAME to R.string.epc_name,
EpcQrElement.IBAN to R.string.epc_iban,
EpcQrElement.AMOUNT to R.string.epc_amount,
EpcQrElement.PURPOSE to R.string.epc_purpose,
EpcQrElement.REFERENCE to R.string.epc_reference,
EpcQrElement.TEXT to R.string.epc_text,
EpcQrElement.INFORMATION to R.string.epc_information
)
fun Context.epcQrToRes(element: EpcQrElement): String {
return elementToLabel[element]?.let { getString(it) } ?: element.name
}
@@ -0,0 +1,141 @@
package de.markusfisch.android.binaryeye.content
enum class EpcQrElement {
SERVICE_TAG, VERSION, CHARSET, IDENTIFICATION,
BIC, NAME, IBAN, AMOUNT, PURPOSE, REFERENCE, TEXT, INFORMATION
}
object EpcQrParser {
private val BIC_REGEX = Regex("[A-Z0-9]{8}([A-Z0-9]{3})?")
private val IBAN_REGEX = Regex("[A-Z]{2}[0-9A-Z]{13,32}")
private val AMOUNT_REGEX = Regex("EUR\\d{1,10}(\\.\\d{2})?")
private val PURPOSE_REGEX = Regex("[A-Z]{4}")
private val charsetMap = mapOf(
"1" to "UTF-8",
"2" to "ISO 8859-1",
"3" to "ISO 8859-2",
"4" to "ISO 8859-4",
"5" to "ISO 8859-5",
"6" to "ISO 8859-7",
"7" to "ISO 8859-10",
"8" to "ISO 8859-15"
)
private fun splitLines(s: String): List<String>? {
val normalized = s
.replace("\r\n", "\n")
.replace('\r', '\n')
.removeSuffix("\n")
if (normalized.isEmpty()) {
return null
}
return normalized.split('\n')
}
private fun isValidVersion(value: String): Boolean {
return value == "001" || value == "002"
}
private fun isValidCharset(value: String): Boolean {
return charsetMap.containsKey(value)
}
private fun isValidIdentification(value: String): Boolean {
return value == "SCT"
}
private fun isValidBic(value: String): Boolean {
return value.matches(BIC_REGEX)
}
private fun isValidIban(value: String): Boolean {
return value.matches(IBAN_REGEX)
}
private fun isValidAmount(value: String): Boolean {
return value.matches(AMOUNT_REGEX)
}
fun parse(s: String?): Map<EpcQrElement, String>? {
if (s.isNullOrEmpty()) {
return null
}
val lines = splitLines(s) ?: return null
if (lines.size !in 7..12) {
return null
}
if (lines[0] != "BCD") {
return null
}
if (!isValidVersion(lines[1])) {
return null
}
if (!isValidCharset(lines[2])) {
return null
}
if (!isValidIdentification(lines[3])) {
return null
}
val bic = lines.getOrElse(4) { "" }
if ((lines[1] == "001" || bic.isNotEmpty()) && !isValidBic(bic)) {
return null
}
val recipient = lines.getOrElse(5) { "" }
if (recipient.isBlank() || recipient.length > 70) {
return null
}
val iban = lines.getOrElse(6) { "" }
if (!isValidIban(iban)) {
return null
}
val amount = lines.getOrElse(7) { "" }
if (amount.isNotEmpty() && !isValidAmount(amount)) {
return null
}
val purpose = lines.getOrElse(8) { "" }
if (purpose.isNotEmpty() && !purpose.matches(PURPOSE_REGEX)) {
return null
}
val remittanceReference = lines.getOrElse(9) { "" }
if (remittanceReference.length > 25) {
return null
}
val remittanceText = lines.getOrElse(10) { "" }
if (remittanceText.length > 140) {
return null
}
if (remittanceReference.isNotEmpty() && remittanceText.isNotEmpty()) {
return null
}
val information = lines.getOrElse(11) { "" }
if (information.length > 70) {
return null
}
return linkedMapOf(
EpcQrElement.SERVICE_TAG to lines[0],
EpcQrElement.VERSION to lines[1],
EpcQrElement.CHARSET to (charsetMap[lines[2]] ?: lines[2]),
EpcQrElement.IDENTIFICATION to lines[3],
EpcQrElement.BIC to bic,
EpcQrElement.NAME to recipient,
EpcQrElement.IBAN to iban,
EpcQrElement.AMOUNT to amount.removePrefix("EUR"),
EpcQrElement.PURPOSE to purpose,
EpcQrElement.REFERENCE to remittanceReference,
EpcQrElement.TEXT to remittanceText,
EpcQrElement.INFORMATION to information
)
}
}
@@ -0,0 +1,191 @@
package de.markusfisch.android.binaryeye.content
import android.content.Context
import de.markusfisch.android.binaryeye.R
import de.tsenger.vdstools.DataEncoder
import de.tsenger.vdstools.Verifier
import de.tsenger.vdstools.idb.IdbSeal
import org.bouncycastle.asn1.ASN1ObjectIdentifier
import org.bouncycastle.asn1.icao.CscaMasterList
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo
import org.bouncycastle.asn1.x9.ECNamedCurveTable
import org.bouncycastle.asn1.x9.X962Parameters
import org.bouncycastle.cert.X509CertificateHolder
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter
import org.bouncycastle.cms.CMSSignedData
import org.bouncycastle.jce.provider.BouncyCastleProvider
import java.security.Provider
import java.security.Security
import java.security.cert.X509Certificate
import java.util.Date
object IdbVerifier {
private const val MASTER_LIST_ASSET = "DE_ML_2026-01-08-12-20-54.ml"
private val provider: Provider by lazy {
BouncyCastleProvider().also { bcProvider ->
if (Security.getProvider(bcProvider.name) == null) {
Security.addProvider(bcProvider)
}
}
}
@Volatile
private var cachedMasterListCertificates: List<X509Certificate>? = null
fun verify(context: Context, seal: IdbSeal): List<SealField> {
val signatureInfo = seal.signatureInfo
?: return listOf(
SealField(
R.string.idb_verification,
context.getString(R.string.idb_verification_unsigned)
)
)
val headerCertificateReference = seal.signerCertReference
?.hexToByteArrayOrNull()
val signerCertificate = context.findCertificateByReference(
headerCertificateReference
)
val curveName = signerCertificate?.let {
curveNameFrom(it)
}
val signedBytes = seal.signedBytes
val signatureResult = if (
signerCertificate == null ||
curveName.isNullOrBlank() ||
signedBytes == null
) {
Verifier.Result.VerifyError
} else {
Verifier(
signedBytes,
signatureInfo.plainSignatureBytes,
signerCertificate.publicKey.encoded,
curveName
).verify()
}
val referenceMatches = signerCertificate != null &&
headerCertificateReference != null &&
DataEncoder.buildCertificateReference(signerCertificate.encoded)
.contentEquals(headerCertificateReference)
val certificateValidNow = signerCertificate != null && runCatching {
signerCertificate.checkValidity(Date())
true
}.getOrElse {
false
}
val verification = context.getString(
when {
signerCertificate == null ->
R.string.idb_verification_signer_certificate_issuer_not_found_in_master_list
!referenceMatches ->
R.string.idb_verification_signature_invalid
!certificateValidNow ->
R.string.idb_verification_signature_invalid
signatureResult == Verifier.Result.SignatureValid ->
R.string.idb_verification_verified
signatureResult == Verifier.Result.SignatureInvalid ->
R.string.idb_verification_signature_invalid
else -> R.string.idb_verification_error
}
)
val fields = mutableListOf(
SealField(R.string.idb_verification, verification),
SealField(
R.string.idb_certificate_reference,
signatureInfo.signerCertificateReference
),
SealField(
R.string.vds_signing_date,
signatureInfo.signingDate.toString()
),
SealField(
R.string.idb_signature_verification,
signatureResult.name
),
)
if (signerCertificate != null) {
fields.add(
SealField(
R.string.idb_signer_certificate_subject,
signerCertificate.subjectX500Principal.name
)
)
fields.add(
SealField(
R.string.idb_signer_certificate_issuer,
signerCertificate.issuerX500Principal.name
)
)
}
return fields
}
private fun String.hexToByteArrayOrNull(): ByteArray? {
if (length % 2 != 0) {
return null
}
return runCatching {
ByteArray(length / 2) { index ->
substring(index * 2, index * 2 + 2).toInt(16).toByte()
}
}.getOrNull()
}
private fun Context.loadMasterListCertificates(): List<X509Certificate> {
cachedMasterListCertificates?.let {
return it
}
synchronized(this) {
cachedMasterListCertificates?.let {
return it
}
val cmsSignedData = assets.open(MASTER_LIST_ASSET).use { input ->
CMSSignedData(input.readBytes())
}
val signedContent = cmsSignedData.signedContent?.content as? ByteArray
?: throw IllegalArgumentException("Master list does not contain signed content")
val masterList = CscaMasterList.getInstance(signedContent)
val certificates = masterList.certStructs.map { cert ->
JcaX509CertificateConverter()
.setProvider(provider)
.getCertificate(X509CertificateHolder(cert))
}
cachedMasterListCertificates = certificates
return certificates
}
}
private fun Context.findCertificateByReference(
certificateReference: ByteArray?
): X509Certificate? {
if (certificateReference == null || certificateReference.size != 5) {
return null
}
return runCatching {
loadMasterListCertificates().firstOrNull { certificate ->
DataEncoder.buildCertificateReference(certificate.encoded)
.contentEquals(certificateReference)
}
}.getOrNull()
}
private fun curveNameFrom(certificate: X509Certificate): String? {
return runCatching {
val subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(
certificate.publicKey.encoded
)
val params = X962Parameters.getInstance(subjectPublicKeyInfo.algorithm.parameters)
val oid = params.parameters as? ASN1ObjectIdentifier
oid?.let {
ECNamedCurveTable.getName(it)
}
}.getOrNull()
}
}
@@ -0,0 +1,67 @@
package de.markusfisch.android.binaryeye.content
import android.content.Context
import de.markusfisch.android.binaryeye.R
private val idToLabel = hashMapOf(
"DCA" to R.string.idl_vehicle_class,
"DCB" to R.string.idl_restriction_codes,
"DCD" to R.string.idl_endorsement_codes,
"DBA" to R.string.idl_date_of_expiry,
"DCS" to R.string.idl_customer_family_name,
"DAC" to R.string.idl_customer_first_name,
"DCT" to R.string.idl_customer_first_name_alt,
"DAD" to R.string.idl_customer_middle_name,
"DBD" to R.string.idl_date_of_issue,
"DBB" to R.string.idl_date_of_birth,
"DBC" to R.string.idl_sex,
"DAY" to R.string.idl_eye_color,
"DAU" to R.string.idl_body_height,
"DAG" to R.string.idl_address_street,
"DAI" to R.string.idl_address_city,
"DAJ" to R.string.idl_address_jurisdiction_code,
"DAK" to R.string.idl_address_postal_code,
"DAQ" to R.string.idl_customer_id_number,
"DCF" to R.string.idl_document_discriminator,
"DCG" to R.string.idl_country,
"DDE" to R.string.idl_family_name_truncation,
"DDF" to R.string.idl_first_name_truncation,
"DDG" to R.string.idl_middle_name_truncation,
"DAH" to R.string.idl_address_street_2,
"DAZ" to R.string.idl_hair_color,
"DCI" to R.string.idl_place_of_birth,
"DCJ" to R.string.idl_audit_information,
"DCK" to R.string.idl_inventory_control_number,
"DBN" to R.string.idl_alias_family_name,
"DBG" to R.string.idl_alias_given_name,
"DBS" to R.string.idl_alias_suffix_name,
"DCU" to R.string.idl_name_suffix,
"DCE" to R.string.idl_weight_range,
"DCL" to R.string.idl_ethnicity,
"DCM" to R.string.idl_standard_vehicle_classification,
"DCN" to R.string.idl_standard_endorsement_code,
"DCO" to R.string.idl_standard_restriction_code,
"DCP" to R.string.idl_vehicle_classification_description,
"DCQ" to R.string.idl_endorsement_code_description,
"DCR" to R.string.idl_restriction_code_description,
"DDA" to R.string.idl_compliance_type,
"DDB" to R.string.idl_card_revision_date,
"DDC" to R.string.idl_hazmat_endorsement_expiration_date,
"DDD" to R.string.idl_limited_duration_document_indicator,
"DAW" to R.string.idl_weight_pounds,
"DAX" to R.string.idl_weight_kilograms,
"DDH" to R.string.idl_under_18_until_date,
"DDI" to R.string.idl_under_19_until_date,
"DDJ" to R.string.idl_under_21_until_date,
"DDK" to R.string.idl_organ_donor_indicator,
"DDL" to R.string.idl_veteran_indicator
)
fun Context.idlToRes(id: String): String {
val resId = idToLabel[id]
return if (resId != null) {
getString(resId)
} else {
id
}
}
@@ -0,0 +1,138 @@
package de.markusfisch.android.binaryeye.content
data class IdlInfo(
var iin: String? = null,
val elements: MutableMap<String, String> = linkedMapOf()
)
object IdlParser {
private fun resolveSex(value: String): String = when (value.firstOrNull()) {
'1' -> "M"
'2' -> "F"
'9' -> "X"
else -> value
}
private fun skipWhitespace(s: String, p: Int): Int {
var i = p
while (i < s.length && s[i].isWhitespace()) {
++i;
}
return i
}
private fun findSubType(s: String, idlInfo: IdlInfo): String {
val len = s.length
var p = skipWhitespace(s, 0)
if (p < len && s[p] == '@') {
while (p < len) {
if (!s[p].isDigit()) {
++p
continue
}
var d = p
while (d < len && s[d].isDigit()) {
++d
}
if (d - p < 8 || len - d < 3) {
p = d
continue
}
val code = s.substring(d, d + 2)
if (code != "DL" && code != "ID") {
p = d + 2
continue
}
idlInfo.elements["DL"] = code
d += 2
while (d < len) {
while (d < len && s[d] !in "DI") {
++d
}
if (len - d < 2) break
val sec = s.substring(d, d + 2)
if (sec == "DL" || sec == "ID") {
return s.substring(d + 2)
}
++d
}
break
}
}
return s
}
private fun findIIN(s: String): String? {
val ansi = s.indexOf("ANSI").takeIf { it >= 0 } ?: return null
var p = ansi + 4
val len = s.length
val whitespaceSkipped = skipWhitespace(s, p)
if (whitespaceSkipped == p) {
return null
}
p = whitespaceSkipped
val iinStart = p
var digits = 0
while (digits < 6 && p < len && s[p].isDigit()) {
++p
++digits
}
return s.substring(iinStart, p)
}
fun parse(s: String?): IdlInfo? {
if (s.isNullOrEmpty()) {
return null
}
val idlInfo = IdlInfo().apply {
iin = findIIN(s)
}
val data = findSubType(s, idlInfo)
val len = data.length
var start = 0
var skipSubtype = false
for (p in 0..len) {
if (p < len && data[p] > '\u001f') {
continue
}
// Per spec, CR (0x0d) is the subfile boundary marker. The segment
// immediately following a CR may begin with a 2-char subfile type
// identifier (e.g. "ZV", "ZI") prepended to the first field.
// Detect this by checking that the marker matches the key prefix
// (jurisdiction fields always share their 2-char subfile prefix).
val seg = if (skipSubtype && p - start >= 4 &&
data[start] == data[start + 2] &&
data[start + 1] == data[start + 3]
) {
start + 2
} else {
start
}
if (p - seg > 3) {
val vp = seg + 3
val key = data.substring(seg, vp)
if (key.matches(Regex("[DZ][A-Z]{2}"))) {
var value = data.substring(vp, p)
if (key == "DBC") {
value = resolveSex(value)
}
idlInfo.elements[key] = value.trim()
}
}
skipSubtype = p < len && data[p] == '\r'
start = p + 1
}
return if (idlInfo.elements.isEmpty()) null else idlInfo
}
}
@@ -0,0 +1,142 @@
package de.markusfisch.android.binaryeye.content
import android.content.Context
import de.markusfisch.android.binaryeye.R
import de.tsenger.vdstools.asn1.DerTlv
import de.tsenger.vdstools.generic.Message
import de.tsenger.vdstools.generic.MessageCoding
import de.tsenger.vdstools.generic.MessageValue
import de.tsenger.vdstools.generic.Seal
import de.tsenger.vdstools.idb.IdbSeal
import org.json.JSONArray
import org.json.JSONObject
import de.tsenger.vdstools.generic.SealParser as VdsSealParser
data class SealField(val name: Any, val value: String)
private data class IdbChildMessageDefinition(
val name: String,
val coding: MessageCoding
)
object SealParser {
private val idbChildMessagesByName: Map<String, Map<Int, IdbChildMessageDefinition>> by lazy {
loadIdbChildMessagesByName()
}
fun parse(
context: Context,
bytes: ByteArray
): List<SealField>? = try {
context.buildFields(
VdsSealParser().parse(bytes.toString(Charsets.ISO_8859_1))
)
} catch (_: Exception) {
null
}
private fun Context.buildFields(seal: Seal): List<SealField> = buildList {
add(SealField(R.string.vds_document_type, seal.documentType))
add(SealField(R.string.vds_issuing_country, seal.issuingCountry))
if (seal is IdbSeal) {
addAll(IdbVerifier.verify(this@buildFields, seal))
}
for (message in seal.messageList) {
addAll(message.toFields())
}
}
private fun Message.toFields(): List<SealField> = buildList {
add(
if (value is MessageValue.BytesValue) {
SealField(
"$name (${value.rawBytes.size} bytes)",
value.rawBytes.toHexString().uppercase()
)
} else {
SealField(name, value.toString())
}
)
for (child in childMessages()) {
addAll(child.toFields())
}
}
private fun Message.childMessages(): List<Message> {
val childDefinitionsByTag = idbChildMessagesByName[name] ?: return emptyList()
return runCatching {
DerTlv.parseAll(value.rawBytes).mapNotNull { derTlv ->
val childTag = derTlv.tag.toInt() and 0xff
val childDefinition = childDefinitionsByTag[childTag]
?: return@mapNotNull null
Message(
childTag,
childDefinition.name,
childDefinition.coding,
MessageValue.fromBytes(
derTlv.value,
childDefinition.coding
)
)
}
}.getOrElse {
emptyList()
}
}
private fun loadIdbChildMessagesByName(): Map<String, Map<Int, IdbChildMessageDefinition>> {
val resourceConstantsClass = runCatching {
Class.forName("de.tsenger.vdstools.generated.ResourceConstants")
}.getOrElse {
return emptyMap()
}
val json = runCatching {
resourceConstantsClass.getField(
"IDB_MESSAGE_TYPES_JSON"
).get(null) as String
}.getOrElse {
return emptyMap()
}
val childMessagesByName =
mutableMapOf<String, Map<Int, IdbChildMessageDefinition>>()
val messageTypes = JSONArray(json)
for (i in 0 until messageTypes.length()) {
val messageType = messageTypes.getJSONObject(i)
val messages = messageType.optJSONArray("messages") ?: continue
collectChildMessages(
messageType.getString("name"),
messages,
childMessagesByName
)
}
return childMessagesByName
}
private fun collectChildMessages(
parentName: String,
messages: JSONArray,
childMessagesByName: MutableMap<String, Map<Int, IdbChildMessageDefinition>>
) {
val childMessages = mutableMapOf<Int, IdbChildMessageDefinition>()
for (i in 0 until messages.length()) {
val message = messages.getJSONObject(i)
val childDefinition = message.toChildMessageDefinition()
childMessages[message.getInt("tag")] = childDefinition
val nestedMessages = message.optJSONArray("messages") ?: continue
collectChildMessages(
childDefinition.name,
nestedMessages,
childMessagesByName
)
}
if (childMessages.isNotEmpty()) {
childMessagesByName[parentName] = childMessages
}
}
private fun JSONObject.toChildMessageDefinition(): IdbChildMessageDefinition {
return IdbChildMessageDefinition(
getString("name"),
MessageCoding.valueOf(getString("coding"))
)
}
}
@@ -1,52 +1,131 @@
package de.markusfisch.android.binaryeye.content
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.support.v4.content.FileProvider
import androidx.core.content.FileProvider
import androidx.core.net.toUri
import de.markusfisch.android.binaryeye.BuildConfig
import de.markusfisch.android.binaryeye.R
import de.markusfisch.android.binaryeye.widget.toast
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
fun shareText(context: Context, text: String, type: String = "text/plain") {
val intent = Intent(Intent.ACTION_SEND)
intent.putExtra(Intent.EXTRA_TEXT, text)
intent.type = type
execShareIntent(context, intent)
fun Context.execShareIntent(intent: Intent): Boolean = if (
!startIntent(intent)
) {
toast(R.string.cannot_resolve_action)
false
} else {
true
}
fun shareUri(context: Context, uri: Uri, type: String) {
val intent = Intent(Intent.ACTION_SEND)
intent.putExtra(Intent.EXTRA_STREAM, uri)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.type = type
execShareIntent(context, intent)
fun Context.startIntent(intent: Intent): Boolean = try {
// Avoid using `intent.resolveActivity()` at API level 30+ due
// to the new package visibility restrictions. In order for
// `resolveActivity()` to "see" another package, we would need
// to list that package/intent in a `<queries>` block in the
// Manifest. But since we used `resolveActivity()` only to avoid
// an exception if the Intent cannot be resolved, it's much easier
// and more robust to just try and catch that exception if
// necessary.
startActivity(intent)
true
} catch (_: ActivityNotFoundException) {
false
}
fun execShareIntent(context: Context, intent: Intent) {
if (intent.resolveActivity(context.packageManager) != null) {
context.startActivity(intent)
fun Context.openUrl(url: String, silent: Boolean = false): Boolean {
return openUri(url.parseAndNormalizeUri(), silent)
}
fun Context.openUri(uri: Uri, silent: Boolean = false): Boolean {
val intent = Intent(Intent.ACTION_VIEW, uri).apply {
if (uri.scheme == "content") {
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
}
return if (silent) {
startIntent(intent)
} else {
context.toast(R.string.cannot_resolve_action)
execShareIntent(intent)
}
}
fun shareFile(context: Context, file: File, type: String) {
getUriForFile(context, file)?.let {
shareUri(context, it, type)
fun String.parseAndNormalizeUri(): Uri = toUri().let {
it.normalizeScheme()
}
fun Context.shareText(text: String, mimeType: String = "text/plain") {
execShareIntent(Intent(Intent.ACTION_SEND).apply {
putExtra(Intent.EXTRA_TEXT, text)
type = mimeType
})
}
private var lastShareFile: File? = null
fun wipeLastShareFile() {
lastShareFile?.let {
it.delete()
lastShareFile = null
}
}
fun getUriForFile(context: Context, file: File): Uri? {
return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
Uri.fromFile(file)
} else {
FileProvider.getUriForFile(
context,
BuildConfig.APPLICATION_ID + ".provider",
file
fun <T> Context.shareAsFile(content: T, fileName: String) {
val (bytes, mimeType) = when (content) {
is ByteArray -> Pair(
content,
"text/plain"
)
is String -> Pair(
content.toByteArray(),
"application/octet-stream"
)
else -> throw IllegalArgumentException(
"Unsupported content text for shareAsFile()"
)
}
wipeLastShareFile()
val file = File(externalCacheDir, fileName)
try {
FileOutputStream(file).use {
it.write(bytes)
}
} catch (_: IOException) {
toast(R.string.error_saving_file)
return
}
lastShareFile = file
shareFile(file, mimeType)
}
fun Context.shareFile(file: File, mimeType: String) {
getUriForFile(file)?.let {
shareUri(it, mimeType)
}
}
private fun Context.getUriForFile(file: File): Uri? = if (
Build.VERSION.SDK_INT < Build.VERSION_CODES.N
) {
Uri.fromFile(file)
} else {
FileProvider.getUriForFile(
this,
BuildConfig.APPLICATION_ID + ".provider",
file
)
}
private fun Context.shareUri(uri: Uri, mimeType: String) {
execShareIntent(Intent(Intent.ACTION_SEND).apply {
putExtra(Intent.EXTRA_STREAM, uri)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
type = mimeType
})
}
@@ -2,23 +2,21 @@ package de.markusfisch.android.binaryeye.database
import android.content.Context
import android.database.Cursor
import de.markusfisch.android.binaryeye.app.toHexString
import de.markusfisch.android.binaryeye.io.writeExternalFile
import java.io.ByteArrayOutputStream
import java.io.OutputStream
fun exportCsv(
context: Context,
fun Context.exportCsv(
name: String,
cursor: Cursor,
delimiter: String
) = writeExternalFile(context, name, "text/csv") { outputStream ->
) = writeExternalFile(name, "text/csv") { outputStream ->
exportCsv(outputStream, cursor, delimiter)
}
fun exportCsv(cursor: Cursor, delimiter: String): String? {
fun Cursor.exportCsv(delimiter: String): String {
val outputStream = ByteArrayOutputStream()
exportCsv(outputStream, cursor, delimiter)
exportCsv(outputStream, this, delimiter)
return outputStream.toString()
}
@@ -31,22 +29,25 @@ private fun exportCsv(
return
}
val columns = arrayOf(
Database.SCANS_PINNED,
Database.SCANS_DATETIME,
Database.SCANS_FORMAT,
Database.SCANS_CONTENT,
Database.SCANS_NAME,
Database.SCANS_TEXT,
Database.SCANS_ERROR_CORRECTION_LEVEL,
Database.SCANS_ISSUE_NUMBER,
Database.SCANS_ORIENTATION,
Database.SCANS_OTHER_META_DATA,
Database.SCANS_PDF417_EXTRA_METADATA,
Database.SCANS_POSSIBLE_COUNTRY,
Database.SCANS_SUGGESTED_PRICE,
Database.SCANS_UPC_EAN_EXTENSION
Database.SCANS_VERSION,
Database.SCANS_SEQUENCE_SIZE,
Database.SCANS_SEQUENCE_INDEX,
Database.SCANS_SEQUENCE_ID,
Database.SCANS_GTIN_COUNTRY,
Database.SCANS_GTIN_ADD_ON,
Database.SCANS_GTIN_PRICE,
Database.SCANS_GTIN_ISSUE_NUMBER
)
val indices = columns.map {
cursor.getColumnIndex(it)
}
val contentIndex = cursor.getColumnIndex(Database.SCANS_CONTENT)
val contentIndex = cursor.getColumnIndex(Database.SCANS_TEXT)
val rawIndex = cursor.getColumnIndex(Database.SCANS_RAW)
outputStream.write(
columns.joinToString(
@@ -0,0 +1,39 @@
package de.markusfisch.android.binaryeye.database
import android.database.Cursor
import de.markusfisch.android.zxingcpp.ZxingCpp
fun Cursor.getInt(name: String): Int {
val idx = getColumnIndex(name)
return if (idx < 0) 0 else getInt(idx)
}
fun Cursor.getLong(name: String): Long {
val idx = getColumnIndex(name)
return if (idx < 0) 0L else getLong(idx)
}
fun Cursor.getString(name: String): String {
val idx = getColumnIndex(name)
return if (idx < 0) "" else getString(idx) ?: ""
}
fun Cursor.getBlob(name: String): ByteArray? {
val idx = getColumnIndex(name)
return if (idx < 0) null else getBlob(idx)
}
fun Cursor.getBitMatrix(
widthName: String,
heightName: String,
dataName: String
): ZxingCpp.BitMatrix? {
val width = getInt(widthName)
val height = getInt(heightName)
val data = getBlob(dataName)
return if (width > 0 && height > 0 && data != null) {
ZxingCpp.BitMatrix(width, height, data)
} else {
null
}
}
@@ -5,8 +5,11 @@ import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import de.markusfisch.android.binaryeye.app.hasNonPrintableCharacters
import de.markusfisch.android.binaryeye.app.prefs
import de.markusfisch.android.binaryeye.preference.Preferences
import de.markusfisch.android.binaryeye.zxingcpp.migrateBarcodeFormatName
import de.markusfisch.android.binaryeye.zxingcpp.oldToNewFormatNames
import de.markusfisch.android.zxingcpp.ZxingCpp.BarcodeFormat
class Database {
private lateinit var db: SQLiteDatabase
@@ -15,47 +18,51 @@ class Database {
db = OpenHelper(context).writableDatabase
}
fun getScans(query: String? = null): Cursor? = db.rawQuery(
fun getScans(query: String? = null): Cursor = db.rawQuery(
"""SELECT
$SCANS_ID,
$SCANS_PINNED,
$SCANS_DATETIME,
$SCANS_NAME,
$SCANS_CONTENT,
$SCANS_TEXT,
$SCANS_FORMAT
FROM $SCANS
${getWhereClause(query)}
ORDER BY $SCANS_DATETIME DESC
""", getWhereArguments(query)
ORDER BY $SCANS_PINNED DESC, $SCANS_DATETIME DESC
""".trimMargin(), getWhereArguments(query)
)
fun getScansDetailed(query: String? = null): Cursor? = db.rawQuery(
fun getScansDetailed(query: String? = null): Cursor = db.rawQuery(
"""SELECT
$SCANS_ID,
$SCANS_PINNED,
$SCANS_DATETIME,
$SCANS_NAME,
$SCANS_CONTENT,
$SCANS_TEXT,
$SCANS_RAW,
$SCANS_FORMAT,
$SCANS_ERROR_CORRECTION_LEVEL,
$SCANS_ISSUE_NUMBER,
$SCANS_ORIENTATION,
$SCANS_OTHER_META_DATA,
$SCANS_PDF417_EXTRA_METADATA,
$SCANS_POSSIBLE_COUNTRY,
$SCANS_SUGGESTED_PRICE,
$SCANS_UPC_EAN_EXTENSION
$SCANS_VERSION,
$SCANS_SEQUENCE_SIZE,
$SCANS_SEQUENCE_INDEX,
$SCANS_SEQUENCE_ID,
$SCANS_GTIN_COUNTRY,
$SCANS_GTIN_ADD_ON,
$SCANS_GTIN_PRICE,
$SCANS_GTIN_ISSUE_NUMBER
FROM $SCANS
${getWhereClause(query)}
ORDER BY $SCANS_DATETIME DESC
""", getWhereArguments(query)
ORDER BY $SCANS_PINNED DESC, $SCANS_DATETIME DESC
""".trimMargin(), getWhereArguments(query)
)
private fun getWhereClause(
query: String?,
prefix: String = "WHERE"
) = if (query?.isNotEmpty() == true) {
"""$prefix $SCANS_CONTENT LIKE ?
OR $SCANS_NAME LIKE ?"""
"""$prefix $SCANS_TEXT LIKE ?
OR $SCANS_NAME LIKE ?
OR $SCANS_FORMAT LIKE ?"""
} else {
""
}
@@ -64,46 +71,87 @@ class Database {
query: String?
) = if (query?.isNotEmpty() == true) {
val instr = "%$query%"
arrayOf(instr, instr)
arrayOf(instr, instr, instr)
} else {
null
}
fun getScan(id: Long): Scan? = db.rawQuery(
fun getScansDetailed(ids: LongArray): Cursor = db.rawQuery(
"""SELECT
$SCANS_ID,
$SCANS_PINNED,
$SCANS_DATETIME,
$SCANS_NAME,
$SCANS_CONTENT,
$SCANS_TEXT,
$SCANS_RAW,
$SCANS_FORMAT,
$SCANS_ERROR_CORRECTION_LEVEL,
$SCANS_ISSUE_NUMBER,
$SCANS_ORIENTATION,
$SCANS_OTHER_META_DATA,
$SCANS_PDF417_EXTRA_METADATA,
$SCANS_POSSIBLE_COUNTRY,
$SCANS_SUGGESTED_PRICE,
$SCANS_UPC_EAN_EXTENSION
$SCANS_VERSION,
$SCANS_SEQUENCE_SIZE,
$SCANS_SEQUENCE_INDEX,
$SCANS_SEQUENCE_ID,
$SCANS_GTIN_COUNTRY,
$SCANS_GTIN_ADD_ON,
$SCANS_GTIN_PRICE,
$SCANS_GTIN_ISSUE_NUMBER
FROM $SCANS
WHERE $SCANS_ID IN (${ids.joinToString(",")})
ORDER BY $SCANS_PINNED DESC, $SCANS_DATETIME DESC
""".trimMargin(), null
)
fun getScan(id: Long): Scan? = db.rawQuery(
"""SELECT
$SCANS_ID,
$SCANS_PINNED,
$SCANS_DATETIME,
$SCANS_NAME,
$SCANS_TEXT,
$SCANS_RAW,
$SCANS_FORMAT,
$SCANS_ERROR_CORRECTION_LEVEL,
$SCANS_VERSION,
$SCANS_DATA_MASK,
$SCANS_SYMBOL_WIDTH,
$SCANS_SYMBOL_HEIGHT,
$SCANS_SYMBOL_DATA,
$SCANS_SEQUENCE_SIZE,
$SCANS_SEQUENCE_INDEX,
$SCANS_SEQUENCE_ID,
$SCANS_GTIN_COUNTRY,
$SCANS_GTIN_ADD_ON,
$SCANS_GTIN_PRICE,
$SCANS_GTIN_ISSUE_NUMBER
FROM $SCANS
WHERE $SCANS_ID = ?
""", arrayOf("$id")
)?.use {
""".trimMargin(), arrayOf("$id")
).use {
if (it.moveToFirst()) {
Scan(
it.getString(SCANS_CONTENT),
it.getString(SCANS_TEXT),
it.getBlob(SCANS_RAW),
it.getString(SCANS_FORMAT),
BarcodeFormat.valueOf(
it.getString(SCANS_FORMAT).migrateBarcodeFormatName()
),
it.getString(SCANS_ERROR_CORRECTION_LEVEL),
it.getString(SCANS_ISSUE_NUMBER),
it.getString(SCANS_ORIENTATION),
it.getString(SCANS_OTHER_META_DATA),
it.getString(SCANS_PDF417_EXTRA_METADATA),
it.getString(SCANS_POSSIBLE_COUNTRY),
it.getString(SCANS_SUGGESTED_PRICE),
it.getString(SCANS_UPC_EAN_EXTENSION),
it.getString(SCANS_VERSION),
it.getInt(SCANS_DATA_MASK),
it.getBitMatrix(
SCANS_SYMBOL_WIDTH,
SCANS_SYMBOL_HEIGHT,
SCANS_SYMBOL_DATA
),
it.getInt(SCANS_SEQUENCE_SIZE),
it.getInt(SCANS_SEQUENCE_INDEX),
it.getString(SCANS_SEQUENCE_ID),
it.getString(SCANS_GTIN_COUNTRY),
it.getString(SCANS_GTIN_ADD_ON),
it.getString(SCANS_GTIN_PRICE),
it.getString(SCANS_GTIN_ISSUE_NUMBER),
it.getString(SCANS_DATETIME),
it.getLong(SCANS_ID)
it.getLong(SCANS_ID),
it.getString(SCANS_NAME),
it.getInt(SCANS_PINNED) != 0
)
} else {
null
@@ -111,67 +159,104 @@ class Database {
}
fun insertScan(scan: Scan): Long {
val cv = ContentValues()
cv.put(SCANS_DATETIME, scan.timestamp)
val isRaw = hasNonPrintableCharacters(scan.content)
if (isRaw) {
cv.put(SCANS_CONTENT, "")
cv.put(SCANS_RAW, scan.raw ?: scan.content.toByteArray())
} else {
cv.put(SCANS_CONTENT, scan.content)
}
cv.put(SCANS_FORMAT, scan.format)
scan.errorCorrectionLevel?.let {
cv.put(SCANS_ERROR_CORRECTION_LEVEL, it)
}
scan.issueNumber?.let { cv.put(SCANS_ISSUE_NUMBER, it) }
scan.orientation?.let { cv.put(SCANS_ORIENTATION, it) }
scan.otherMetaData?.let { cv.put(SCANS_OTHER_META_DATA, it) }
scan.pdf417ExtraMetaData?.let { cv.put(SCANS_PDF417_EXTRA_METADATA, it) }
scan.possibleCountry?.let { cv.put(SCANS_POSSIBLE_COUNTRY, it) }
scan.suggestedPrice?.let { cv.put(SCANS_SUGGESTED_PRICE, it) }
scan.upcEanExtension?.let { cv.put(SCANS_UPC_EAN_EXTENSION, it) }
if (prefs.ignoreConsecutiveDuplicates) {
val id = getIdOfLastScan(
cv.get(SCANS_CONTENT) as String,
if (isRaw) cv.get(SCANS_RAW) as ByteArray else null,
scan.format
)
if (id > 0L) {
return id
when (prefs.ignoreDuplicates()) {
Preferences.Companion.IgnoreDuplicates.Consecutive -> {
val id = getIdOfLastScan(
scan.text,
scan.raw,
scan.format
)
if (id > 0L) {
return id
}
}
Preferences.Companion.IgnoreDuplicates.Any -> {
val id = getIdOfScanByContent(scan.text, scan.format)
if (id > 0L) {
return id
}
}
else -> Unit
}
return db.insert(SCANS, null, cv)
return db.insert(
SCANS,
null,
ContentValues().apply {
put(SCANS_DATETIME, scan.dateTime)
put(SCANS_TEXT, scan.text)
if (scan.raw != null) {
put(SCANS_RAW, scan.raw)
}
put(SCANS_FORMAT, scan.format.name)
scan.errorCorrectionLevel?.let {
put(SCANS_ERROR_CORRECTION_LEVEL, it)
}
put(SCANS_VERSION, scan.version)
put(SCANS_DATA_MASK, scan.dataMask)
if (scan.symbol != null) {
put(SCANS_SYMBOL_WIDTH, scan.symbol.width)
put(SCANS_SYMBOL_HEIGHT, scan.symbol.height)
put(SCANS_SYMBOL_DATA, scan.symbol.data)
}
put(SCANS_SEQUENCE_SIZE, scan.sequenceSize)
put(SCANS_SEQUENCE_INDEX, scan.sequenceIndex)
put(SCANS_SEQUENCE_ID, scan.sequenceId)
scan.country?.let { put(SCANS_GTIN_COUNTRY, it) }
scan.addOn?.let { put(SCANS_GTIN_ADD_ON, it) }
scan.price?.let { put(SCANS_GTIN_PRICE, it) }
scan.issueNumber?.let { put(SCANS_GTIN_ISSUE_NUMBER, it) }
put(SCANS_PINNED, if (scan.pinned) 1 else 0)
}
)
}
private fun getIdOfLastScan(
content: String,
raw: ByteArray?,
format: String
): Long {
return db.rawQuery(
"""SELECT
format: BarcodeFormat
): Long = db.rawQuery(
"""SELECT
$SCANS_ID,
$SCANS_CONTENT,
$SCANS_TEXT,
$SCANS_RAW,
$SCANS_FORMAT
FROM $SCANS
ORDER BY $SCANS_ID DESC
LIMIT 1
""", null
)?.use {
if (it.count > 0 &&
it.moveToFirst() &&
it.getString(it.getColumnIndex(SCANS_CONTENT)) == content &&
(raw == null || it.getBlob(it.getColumnIndex(SCANS_RAW))
?.contentEquals(raw) == true) &&
it.getString(it.getColumnIndex(SCANS_FORMAT)) == format
) {
it.getLong(it.getColumnIndex(SCANS_ID))
} else {
0L
}
} ?: 0L
""".trimMargin(), null
).use {
if (it.count > 0 &&
it.moveToFirst() &&
it.getString(SCANS_TEXT) == content &&
(raw == null || it.getBlob(SCANS_RAW)
?.contentEquals(raw) == true) &&
it.getString(SCANS_FORMAT) == format.name
) {
it.getLong(SCANS_ID)
} else {
0L
}
}
private fun getIdOfScanByContent(
content: String,
format: BarcodeFormat
): Long = db.rawQuery(
"""SELECT
$SCANS_ID
FROM $SCANS
WHERE $SCANS_TEXT = ?
AND $SCANS_FORMAT = ?
LIMIT 1
""".trimMargin(), arrayOf(content, format.name)
).use {
if (it.moveToFirst()) {
it.getLong(SCANS_ID)
} else {
0L
}
}
fun removeScan(id: Long) {
@@ -188,10 +273,16 @@ class Database {
db.update(SCANS, cv, "$SCANS_ID = ?", arrayOf("$id"))
}
fun setPinned(id: Long, pinned: Boolean) {
val cv = ContentValues()
cv.put(SCANS_PINNED, if (pinned) 1 else 0)
db.update(SCANS, cv, "$SCANS_ID = ?", arrayOf("$id"))
}
private class OpenHelper(context: Context) :
SQLiteOpenHelper(context, FILE_NAME, null, 4) {
SQLiteOpenHelper(context, FILE_NAME, null, 10) {
override fun onCreate(db: SQLiteDatabase) {
createScans(db)
db.createScans()
}
override fun onUpgrade(
@@ -200,13 +291,31 @@ class Database {
newVersion: Int
) {
if (oldVersion < 2) {
addRawColumn(db)
db.addRawColumn()
}
if (oldVersion < 3) {
addMetaDataColumns(db)
db.addMetaDataColumns()
}
if (oldVersion < 4) {
addNameColumn(db)
db.addNameColumn()
}
if (oldVersion < 5) {
db.migrateToZxingCpp()
}
if (oldVersion < 6) {
db.migrateToVersionString()
}
if (oldVersion < 7) {
db.addDataMaskColumn()
}
if (oldVersion < 8) {
db.addSymbolColumns()
}
if (oldVersion < 9) {
db.migrateToNativeFormatNames()
}
if (oldVersion < 10) {
db.addPinnedColumn()
}
}
}
@@ -217,10 +326,16 @@ class Database {
const val SCANS_ID = "_id"
const val SCANS_DATETIME = "_datetime"
const val SCANS_NAME = "name"
const val SCANS_CONTENT = "content"
const val SCANS_TEXT = "content"
const val SCANS_RAW = "raw"
const val SCANS_FORMAT = "format"
const val SCANS_ERROR_CORRECTION_LEVEL = "error_correction_level"
const val SCANS_VERSION_NUMBER = "version_number"
const val SCANS_VERSION = "version"
const val SCANS_DATA_MASK = "data_mask"
const val SCANS_SYMBOL_WIDTH = "symbol_width"
const val SCANS_SYMBOL_HEIGHT = "symbol_height"
const val SCANS_SYMBOL_DATA = "symbol_data"
const val SCANS_ISSUE_NUMBER = "issue_number"
const val SCANS_ORIENTATION = "orientation"
const val SCANS_OTHER_META_DATA = "other_meta_data"
@@ -228,58 +343,108 @@ class Database {
const val SCANS_POSSIBLE_COUNTRY = "possible_country"
const val SCANS_SUGGESTED_PRICE = "suggested_price"
const val SCANS_UPC_EAN_EXTENSION = "upc_ean_extension"
const val SCANS_SEQUENCE_SIZE = "sequence_size"
const val SCANS_SEQUENCE_INDEX = "sequence_index"
const val SCANS_SEQUENCE_ID = "sequence_id"
const val SCANS_GTIN_COUNTRY = "gtin_country"
const val SCANS_GTIN_ADD_ON = "gtin_add_on"
const val SCANS_GTIN_PRICE = "gtin_price"
const val SCANS_GTIN_ISSUE_NUMBER = "gtin_issue_number"
const val SCANS_PINNED = "pinned"
private fun createScans(db: SQLiteDatabase) {
db.execSQL("DROP TABLE IF EXISTS $SCANS")
db.execSQL(
private fun SQLiteDatabase.createScans() {
execSQL("DROP TABLE IF EXISTS $SCANS".trimMargin())
execSQL(
"""CREATE TABLE $SCANS (
$SCANS_ID INTEGER PRIMARY KEY AUTOINCREMENT,
$SCANS_DATETIME DATETIME NOT NULL,
$SCANS_NAME TEXT,
$SCANS_CONTENT TEXT NOT NULL,
$SCANS_TEXT TEXT NOT NULL,
$SCANS_RAW BLOB,
$SCANS_FORMAT TEXT NOT NULL,
$SCANS_ERROR_CORRECTION_LEVEL TEXT,
$SCANS_ISSUE_NUMBER INT,
$SCANS_ORIENTATION INT,
$SCANS_OTHER_META_DATA TEXT,
$SCANS_PDF417_EXTRA_METADATA TEXT,
$SCANS_POSSIBLE_COUNTRY TEXT,
$SCANS_SUGGESTED_PRICE TEXT,
$SCANS_UPC_EAN_EXTENSION TEXT
)"""
$SCANS_VERSION TEXT,
$SCANS_DATA_MASK INTEGER,
$SCANS_SYMBOL_WIDTH INTEGER,
$SCANS_SYMBOL_HEIGHT INTEGER,
$SCANS_SYMBOL_DATA BLOB,
$SCANS_SEQUENCE_SIZE INTEGER,
$SCANS_SEQUENCE_INDEX INTEGER,
$SCANS_SEQUENCE_ID TEXT,
$SCANS_GTIN_COUNTRY TEXT,
$SCANS_GTIN_ADD_ON TEXT,
$SCANS_GTIN_PRICE TEXT,
$SCANS_GTIN_ISSUE_NUMBER TEXT,
$SCANS_PINNED INTEGER NOT NULL DEFAULT 0
)""".trimMargin()
)
}
private fun addRawColumn(db: SQLiteDatabase) {
db.execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_RAW BLOB")
private fun SQLiteDatabase.addRawColumn() {
execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_RAW BLOB".trimMargin())
}
private fun addMetaDataColumns(db: SQLiteDatabase) {
db.execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_ERROR_CORRECTION_LEVEL TEXT")
db.execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_ISSUE_NUMBER INT")
db.execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_ORIENTATION INT")
db.execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_OTHER_META_DATA TEXT")
db.execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_PDF417_EXTRA_METADATA TEXT")
db.execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_POSSIBLE_COUNTRY TEXT")
db.execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_SUGGESTED_PRICE TEXT")
db.execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_UPC_EAN_EXTENSION TEXT")
private fun SQLiteDatabase.addMetaDataColumns() {
execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_ERROR_CORRECTION_LEVEL TEXT".trimMargin())
execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_ISSUE_NUMBER INT".trimMargin())
execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_ORIENTATION INT".trimMargin())
execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_OTHER_META_DATA TEXT".trimMargin())
execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_PDF417_EXTRA_METADATA TEXT".trimMargin())
execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_POSSIBLE_COUNTRY TEXT".trimMargin())
execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_SUGGESTED_PRICE TEXT".trimMargin())
execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_UPC_EAN_EXTENSION TEXT".trimMargin())
}
private fun addNameColumn(db: SQLiteDatabase) {
db.execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_NAME TEXT")
private fun SQLiteDatabase.addNameColumn() {
execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_NAME TEXT")
}
private fun SQLiteDatabase.migrateToZxingCpp() {
execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_VERSION_NUMBER INTEGER".trimMargin())
execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_SEQUENCE_SIZE INTEGER".trimMargin())
execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_SEQUENCE_INDEX INTEGER".trimMargin())
execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_SEQUENCE_ID TEXT".trimMargin())
execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_GTIN_COUNTRY TEXT".trimMargin())
execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_GTIN_ADD_ON TEXT".trimMargin())
execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_GTIN_PRICE TEXT".trimMargin())
execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_GTIN_ISSUE_NUMBER TEXT".trimMargin())
execSQL("UPDATE $SCANS SET $SCANS_SEQUENCE_SIZE = -1")
execSQL("UPDATE $SCANS SET $SCANS_SEQUENCE_INDEX = -1")
execSQL("UPDATE $SCANS SET $SCANS_GTIN_COUNTRY = $SCANS_POSSIBLE_COUNTRY")
execSQL("UPDATE $SCANS SET $SCANS_GTIN_ADD_ON = $SCANS_UPC_EAN_EXTENSION")
execSQL("UPDATE $SCANS SET $SCANS_GTIN_PRICE = $SCANS_SUGGESTED_PRICE")
execSQL("UPDATE $SCANS SET $SCANS_GTIN_ISSUE_NUMBER = $SCANS_ISSUE_NUMBER")
}
private fun SQLiteDatabase.migrateToNativeFormatNames() {
for ((oldName, newName) in oldToNewFormatNames) {
execSQL(
"UPDATE $SCANS SET $SCANS_FORMAT = ? WHERE $SCANS_FORMAT = ?",
arrayOf(newName, oldName)
)
}
}
private fun SQLiteDatabase.migrateToVersionString() {
execSQL("ALTER TABLE $SCANS ADD $SCANS_VERSION TEXT")
execSQL("UPDATE $SCANS SET $SCANS_VERSION = $SCANS_VERSION_NUMBER")
}
private fun SQLiteDatabase.addDataMaskColumn() {
execSQL("ALTER TABLE $SCANS ADD $SCANS_DATA_MASK INTEGER")
execSQL("UPDATE $SCANS SET $SCANS_DATA_MASK = -1")
}
private fun SQLiteDatabase.addSymbolColumns() {
execSQL("ALTER TABLE $SCANS ADD $SCANS_SYMBOL_WIDTH INTEGER")
execSQL("ALTER TABLE $SCANS ADD $SCANS_SYMBOL_HEIGHT INTEGER")
execSQL("ALTER TABLE $SCANS ADD $SCANS_SYMBOL_DATA BLOB")
}
private fun SQLiteDatabase.addPinnedColumn() {
execSQL(
"ALTER TABLE $SCANS ADD COLUMN $SCANS_PINNED INTEGER NOT NULL DEFAULT 0"
)
}
}
}
private fun Cursor.getString(name: String) = this.getString(
this.getColumnIndex(name)
)
private fun Cursor.getBlob(name: String) = this.getBlob(
this.getColumnIndex(name)
)
private fun Cursor.getLong(name: String) = this.getLong(
this.getColumnIndex(name)
)
@@ -6,16 +6,15 @@ import de.markusfisch.android.binaryeye.io.writeExternalFile
import java.io.File
import java.io.FileInputStream
fun exportDatabase(activity: Activity, fileName: String): Boolean {
fun Activity.exportDatabase(fileName: String): Boolean {
val dbFile = File(
Environment.getDataDirectory(),
"//data//${activity.packageName}//databases//${Database.FILE_NAME}"
"//data//${packageName}//databases//${Database.FILE_NAME}"
)
if (!dbFile.exists()) {
return false
}
return writeExternalFile(
activity,
fileName,
"application/vnd.sqlite3"
) {
@@ -2,55 +2,56 @@ package de.markusfisch.android.binaryeye.database
import android.content.Context
import android.database.Cursor
import de.markusfisch.android.binaryeye.app.toHexString
import de.markusfisch.android.binaryeye.io.writeExternalFile
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
fun exportJson(
context: Context,
fun Context.exportJson(
name: String,
cursor: Cursor
) = writeExternalFile(context, name, "application/json") { outputStream ->
exportJson(cursor)?.let {
) = writeExternalFile(name, "application/json") { outputStream ->
cursor.exportJson()?.let {
outputStream.write(it.toByteArray())
}
}
fun exportJson(cursor: Cursor): String? {
if (!cursor.moveToFirst()) {
fun Cursor.exportJson(): String? {
if (!moveToFirst()) {
return null
}
val columns = arrayOf(
Database.SCANS_PINNED,
Database.SCANS_DATETIME,
Database.SCANS_FORMAT,
Database.SCANS_CONTENT,
Database.SCANS_NAME,
Database.SCANS_TEXT,
Database.SCANS_ERROR_CORRECTION_LEVEL,
Database.SCANS_ISSUE_NUMBER,
Database.SCANS_ORIENTATION,
Database.SCANS_OTHER_META_DATA,
Database.SCANS_PDF417_EXTRA_METADATA,
Database.SCANS_POSSIBLE_COUNTRY,
Database.SCANS_SUGGESTED_PRICE,
Database.SCANS_UPC_EAN_EXTENSION
Database.SCANS_VERSION,
Database.SCANS_SEQUENCE_SIZE,
Database.SCANS_SEQUENCE_INDEX,
Database.SCANS_SEQUENCE_ID,
Database.SCANS_GTIN_COUNTRY,
Database.SCANS_GTIN_ADD_ON,
Database.SCANS_GTIN_PRICE,
Database.SCANS_GTIN_ISSUE_NUMBER
)
val indices = columns.map {
Pair(cursor.getColumnIndex(it), it)
Pair(getColumnIndex(it), it)
}
val contentIndex = cursor.getColumnIndex(Database.SCANS_CONTENT)
val rawIndex = cursor.getColumnIndex(Database.SCANS_RAW)
val contentIndex = getColumnIndex(Database.SCANS_TEXT)
val rawIndex = getColumnIndex(Database.SCANS_RAW)
val root = JSONArray()
do {
var deviation: Pair<Int, String>? = null
if (cursor.getString(contentIndex)?.isEmpty() == true) {
if (getString(contentIndex)?.isEmpty() == true) {
deviation = Pair(
contentIndex,
cursor.getBlob(rawIndex).toHexString()
getBlob(rawIndex).toHexString()
)
}
root.put(cursor.toJsonObject(indices, deviation))
} while (cursor.moveToNext())
root.put(toJsonObject(indices, deviation))
} while (moveToNext())
return root.toString()
}
@@ -69,7 +70,7 @@ private fun Cursor.toJsonObject(
obj.put(it.second, value ?: "")
}
obj
} catch (e: JSONException) {
} catch (_: JSONException) {
obj
}
}
@@ -1,42 +1,36 @@
package de.markusfisch.android.binaryeye.database
import android.os.Parcel
import android.os.Parcelable
import android.os.Bundle
import android.text.format.DateFormat
import com.google.zxing.Result
import com.google.zxing.ResultMetadataType
import de.markusfisch.android.binaryeye.zxingcpp.migrateBarcodeFormatName
import de.markusfisch.android.zxingcpp.ZxingCpp.BarcodeFormat
import de.markusfisch.android.zxingcpp.ZxingCpp.BitMatrix
import de.markusfisch.android.zxingcpp.ZxingCpp.ContentType
import de.markusfisch.android.zxingcpp.ZxingCpp.Result
import java.util.Locale
data class Scan(
val content: String,
val text: String,
val raw: ByteArray?,
val format: String,
val errorCorrectionLevel: String?,
val issueNumber: String?,
val orientation: String?,
val otherMetaData: String?,
val pdf417ExtraMetaData: String?,
val possibleCountry: String?,
val suggestedPrice: String?,
val upcEanExtension: String?,
val timestamp: String = getDateTime(),
var id: Long = 0L
) : Parcelable {
constructor(result: Result) : this(
result.text,
getRawBytes(result),
result.barcodeFormat.toString(),
result.getMetaString(ResultMetadataType.ERROR_CORRECTION_LEVEL),
result.getMetaString(ResultMetadataType.ISSUE_NUMBER),
result.getMetaString(ResultMetadataType.ORIENTATION),
result.getMetaString(ResultMetadataType.OTHER),
result.getMetaString(ResultMetadataType.PDF417_EXTRA_METADATA),
result.getMetaString(ResultMetadataType.POSSIBLE_COUNTRY),
result.getMetaString(ResultMetadataType.SUGGESTED_PRICE),
result.getMetaString(ResultMetadataType.UPC_EAN_EXTENSION)
)
val format: BarcodeFormat,
val errorCorrectionLevel: String? = null,
val version: String? = null,
val dataMask: Int = -1,
val symbol: BitMatrix? = null,
val sequenceSize: Int = -1,
val sequenceIndex: Int = -1,
val sequenceId: String = "",
val country: String? = null,
val addOn: String? = null,
val price: String? = null,
val issueNumber: String? = null,
val dateTime: String = getDateTime(),
var id: Long = 0L,
val label: String? = null,
val pinned: Boolean = false
) {
// Needs to be overwritten manually, as ByteArray is an array and
// this isn't handled well by Kotlin
// this isn't handled well by Kotlin.
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
@@ -48,122 +42,168 @@ data class Scan(
other as Scan
return id == other.id &&
timestamp == other.timestamp &&
content == other.content &&
dateTime == other.dateTime &&
text == other.text &&
((raw == null && other.raw == null) ||
(raw != null && other.raw != null && raw.contentEquals(other.raw))) &&
(raw != null && other.raw != null &&
raw.contentEquals(other.raw))) &&
format == other.format &&
errorCorrectionLevel == other.errorCorrectionLevel &&
version == other.version &&
dataMask == other.dataMask &&
sequenceSize == other.sequenceSize &&
sequenceIndex == other.sequenceIndex &&
sequenceId == other.sequenceId &&
country == other.country &&
addOn == other.addOn &&
price == other.price &&
issueNumber == other.issueNumber &&
orientation == other.orientation &&
otherMetaData == other.otherMetaData &&
pdf417ExtraMetaData == other.pdf417ExtraMetaData &&
possibleCountry == other.possibleCountry &&
suggestedPrice == other.suggestedPrice &&
upcEanExtension == other.upcEanExtension
label == other.label &&
pinned == other.pinned
}
// Needs to be overwritten manually, as ByteArray is an array and
// this isn't handled well by Kotlin
// this isn't handled well by Kotlin.
override fun hashCode(): Int {
var result = id.hashCode()
result = 31 * result + timestamp.hashCode()
result = 31 * result + content.hashCode()
result = 31 * result + dateTime.hashCode()
result = 31 * result + text.hashCode()
result = 31 * result + (raw?.contentHashCode() ?: 0)
result = 31 * result + format.hashCode()
result = 31 * result + (errorCorrectionLevel?.hashCode() ?: 0)
result = 31 * result + version.hashCode()
result = 31 * result + dataMask
result = 31 * result + sequenceSize
result = 31 * result + sequenceIndex
result = 31 * result + sequenceId.hashCode()
result = 31 * result + (country?.hashCode() ?: 0)
result = 31 * result + (addOn?.hashCode() ?: 0)
result = 31 * result + (price?.hashCode() ?: 0)
result = 31 * result + (issueNumber?.hashCode() ?: 0)
result = 31 * result + (orientation?.hashCode() ?: 0)
result = 31 * result + (otherMetaData?.hashCode() ?: 0)
result = 31 * result + (pdf417ExtraMetaData?.hashCode() ?: 0)
result = 31 * result + (possibleCountry?.hashCode() ?: 0)
result = 31 * result + (suggestedPrice?.hashCode() ?: 0)
result = 31 * result + (upcEanExtension?.hashCode() ?: 0)
result = 31 * result + (label?.hashCode() ?: 0)
result = 31 * result + pinned.hashCode()
return result
}
private constructor(parcel: Parcel) : this(
content = parcel.readString() ?: "",
raw = readByteArray(parcel),
format = parcel.readString() ?: "",
errorCorrectionLevel = parcel.readString(),
issueNumber = parcel.readString(),
orientation = parcel.readString(),
otherMetaData = parcel.readString(),
pdf417ExtraMetaData = parcel.readString(),
possibleCountry = parcel.readString(),
suggestedPrice = parcel.readString(),
upcEanExtension = parcel.readString(),
timestamp = parcel.readString() ?: "",
id = parcel.readLong()
}
fun Result.toScan(): Scan {
return Scan(
when (contentType) {
ContentType.GS1,
ContentType.ISO15434,
ContentType.TEXT -> text
else -> "" // Show as binary.
},
rawBytes,
format,
ecLevel,
version,
dataMask,
symbol,
sequenceSize,
sequenceIndex,
sequenceId,
gtin?.country,
gtin?.addOn,
gtin?.price,
gtin?.issueNumber
)
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(content)
writeByteArray(parcel, raw)
parcel.writeString(format)
parcel.writeString(errorCorrectionLevel)
parcel.writeString(issueNumber)
parcel.writeString(orientation)
parcel.writeString(otherMetaData)
parcel.writeString(pdf417ExtraMetaData)
parcel.writeString(possibleCountry)
parcel.writeString(suggestedPrice)
parcel.writeString(upcEanExtension)
parcel.writeString(timestamp)
parcel.writeLong(id)
}
override fun describeContents() = 0
companion object {
@JvmField
val CREATOR = object : Parcelable.Creator<Scan> {
override fun createFromParcel(parcel: Parcel) = Scan(parcel)
override fun newArray(size: Int) = arrayOfNulls<Scan>(size)
}
}
}
private fun getDateTime(time: Long = System.currentTimeMillis()) = DateFormat.format(
"yyyy-MM-dd HH:mm:ss",
time
).toString()
fun Scan.toBundle() = Bundle().apply {
putString(SCAN_TEXT, text)
putByteArray(SCAN_RAW, raw)
putString(SCAN_FORMAT, format.name)
putString(SCAN_ERROR_CORRECTION_LEVEL, errorCorrectionLevel)
putString(SCAN_VERSION, version)
putInt(SCAN_DATA_MASK, dataMask)
putInt(SCAN_SYMBOL_WIDTH, symbol?.width ?: 0)
putInt(SCAN_SYMBOL_HEIGHT, symbol?.height ?: 0)
putByteArray(SCAN_SYMBOL_DATA, symbol?.data)
putInt(SCAN_SEQUENCE_SIZE, sequenceSize)
putInt(SCAN_SEQUENCE_INDEX, sequenceIndex)
putString(SCAN_SEQUENCE_ID, sequenceId)
putString(SCAN_COUNTRY, country)
putString(SCAN_ADD_ON, addOn)
putString(SCAN_PRICE, price)
putString(SCAN_ISSUE_NUMBER, issueNumber)
putString(SCAN_DATE_TIME, dateTime)
putLong(SCAN_ID, id)
putString(SCAN_LABEL, label)
putBoolean(SCAN_PINNED, pinned)
}
private fun getRawBytes(result: Result): ByteArray? {
val metadata = result.resultMetadata ?: return null
val segments = metadata[ResultMetadataType.BYTE_SEGMENTS] ?: return null
var bytes = ByteArray(0)
@Suppress("UNCHECKED_CAST")
for (seg in segments as Iterable<ByteArray>) {
bytes += seg
fun Bundle.toScan(): Scan? {
val formatName = getString(SCAN_FORMAT)?.migrateBarcodeFormatName()
if (formatName.isNullOrEmpty()) {
return null
}
// byte segments can never be shorter than the text.
// Zxing cuts off content prefixes like "WIFI:"
return if (bytes.size >= result.text.length) bytes else null
}
private fun Result.getMetaString(
key: ResultMetadataType
): String? = this.resultMetadata?.let {
it[key]?.toString()
}
private fun writeByteArray(parcel: Parcel, array: ByteArray?) {
val size = array?.size ?: 0
parcel.writeInt(size)
if (size > 0) {
parcel.writeByteArray(array)
}
}
private fun readByteArray(parcel: Parcel): ByteArray? {
val size = parcel.readInt()
return if (size > 0) {
val array = ByteArray(size)
parcel.readByteArray(array)
array
} else {
return try {
Scan(
text = getString(SCAN_TEXT) ?: "",
raw = getByteArray(SCAN_RAW),
format = BarcodeFormat.valueOf(formatName),
errorCorrectionLevel = getString(SCAN_ERROR_CORRECTION_LEVEL),
version = getString(SCAN_VERSION),
dataMask = getInt(SCAN_DATA_MASK, -1),
symbol = getBitMatrix(),
sequenceSize = getInt(SCAN_SEQUENCE_SIZE, -1),
sequenceIndex = getInt(SCAN_SEQUENCE_INDEX, -1),
sequenceId = getString(SCAN_SEQUENCE_ID) ?: "",
country = getString(SCAN_COUNTRY),
addOn = getString(SCAN_ADD_ON),
price = getString(SCAN_PRICE),
issueNumber = getString(SCAN_ISSUE_NUMBER),
dateTime = getString(SCAN_DATE_TIME) ?: getDateTime(),
id = getLong(SCAN_ID, 0L),
label = getString(SCAN_LABEL),
pinned = getBoolean(SCAN_PINNED, false)
)
} catch (_: IllegalArgumentException) {
null
}
}
private fun getDateTime(
time: Long = System.currentTimeMillis()
) = DateFormat.format(
"yyyy-MM-dd HH:mm:ss",
time
).toString() + String.format(
Locale.getDefault(),
":%03d",
time % 1000
)
private fun Bundle.getBitMatrix(): BitMatrix? {
val width = getInt(SCAN_SYMBOL_WIDTH, 0)
val height = getInt(SCAN_SYMBOL_HEIGHT, 0)
val data = getByteArray(SCAN_SYMBOL_DATA)
if (width < 1 || height < 1 || data == null) {
return null
}
return BitMatrix(width, height, data)
}
private const val SCAN_TEXT = "text"
private const val SCAN_RAW = "raw"
private const val SCAN_FORMAT = "format"
private const val SCAN_ERROR_CORRECTION_LEVEL = "error_correction_level"
private const val SCAN_VERSION = "version"
private const val SCAN_DATA_MASK = "data_mask"
private const val SCAN_SYMBOL_WIDTH = "symbol_width"
private const val SCAN_SYMBOL_HEIGHT = "symbol_height"
private const val SCAN_SYMBOL_DATA = "symbol_data"
private const val SCAN_SEQUENCE_SIZE = "sequence_size"
private const val SCAN_SEQUENCE_INDEX = "sequence_index"
private const val SCAN_SEQUENCE_ID = "sequence_id"
private const val SCAN_COUNTRY = "country"
private const val SCAN_ADD_ON = "add_on"
private const val SCAN_PRICE = "price"
private const val SCAN_ISSUE_NUMBER = "issue_number"
private const val SCAN_DATE_TIME = "date_time"
private const val SCAN_ID = "id"
private const val SCAN_LABEL = "label"
private const val SCAN_PINNED = "pinned"
@@ -1,276 +0,0 @@
package de.markusfisch.android.binaryeye.fragment
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Context
import android.graphics.Bitmap
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.*
import android.widget.EditText
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import de.markusfisch.android.binaryeye.R
import de.markusfisch.android.binaryeye.app.hasWritePermission
import de.markusfisch.android.binaryeye.content.copyToClipboard
import de.markusfisch.android.binaryeye.content.shareFile
import de.markusfisch.android.binaryeye.content.shareText
import de.markusfisch.android.binaryeye.io.addSuffixIfNotGiven
import de.markusfisch.android.binaryeye.io.toSaveResult
import de.markusfisch.android.binaryeye.io.writeExternalFile
import de.markusfisch.android.binaryeye.view.doOnApplyWindowInsets
import de.markusfisch.android.binaryeye.view.setPaddingFromWindowInsets
import de.markusfisch.android.binaryeye.widget.ConfinedScalingImageView
import de.markusfisch.android.binaryeye.widget.toast
import de.markusfisch.android.binaryeye.zxing.encodeAsBitmap
import de.markusfisch.android.binaryeye.zxing.encodeAsSvg
import de.markusfisch.android.binaryeye.zxing.encodeAsText
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStream
import java.util.*
class BarcodeFragment : Fragment() {
private enum class FileType {
PNG, SVG, TXT
}
private var barcodeBitmap: Bitmap? = null
private var barcodeSvg: String? = null
private var barcodeTxt: String? = null
private var content: String = ""
private var format: BarcodeFormat? = null
override fun onCreate(state: Bundle?) {
super.onCreate(state)
setHasOptionsMenu(true)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
state: Bundle?
): View? {
val ac = activity ?: return null
ac.setTitle(R.string.view_barcode)
val view = inflater.inflate(
R.layout.fragment_barcode,
container,
false
)
val args = arguments ?: return view
val content = args.getString(CONTENT) ?: return view
val format = args.getSerializable(FORMAT) as BarcodeFormat? ?: return view
val hints = args.getSerializable(HINTS) as EnumMap<EncodeHintType, Any>?
val size = args.getInt(SIZE)
try {
barcodeBitmap = encodeAsBitmap(content, format, size, size, hints)
barcodeSvg = encodeAsSvg(content, format, hints)
barcodeTxt = encodeAsText(content, format, hints)
} catch (e: Exception) {
var message = e.message
if (message == null || message.isEmpty()) {
message = getString(R.string.error_encoding_barcode)
}
message?.let {
ac.toast(message)
}
fragmentManager.popBackStack()
return null
}
this.content = content
this.format = format
val imageView = view.findViewById<ConfinedScalingImageView>(
R.id.barcode
)
imageView.setImageBitmap(barcodeBitmap)
imageView.post {
// make sure to invoke this after ScalingImageView.onLayout()
imageView.minWidth /= 2f
}
view.findViewById<View>(R.id.share).setOnClickListener {
pickFileType(context, R.string.share_as) {
shareAs(it)
}
}
(view.findViewById(R.id.inset_layout) as View).setPaddingFromWindowInsets()
imageView.doOnApplyWindowInsets { v, insets ->
(v as ConfinedScalingImageView).insets.set(insets)
}
return view
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.fragment_barcode, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.copy_to_clipboard -> {
barcodeTxt?.let {
context.copyToClipboard(it)
context.toast(R.string.copied_to_clipboard)
}
true
}
R.id.export_to_file -> {
pickFileType(context, R.string.export_as) {
askForFileNameAndSave(it)
}
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun pickFileType(
context: Context,
title: Int,
action: (FileType) -> Unit
) {
val fileTypes = FileType.values()
AlertDialog.Builder(context)
.setTitle(title)
.setItems(fileTypes.map { it.name }.toTypedArray()) { _, which ->
action(fileTypes[which])
}
.show()
}
// dialogs do not have a parent view
@SuppressLint("InflateParams")
private fun askForFileNameAndSave(fileType: FileType) {
val ac = activity ?: return
if (!hasWritePermission(ac) { askForFileNameAndSave(fileType) }) {
return
}
val view = ac.layoutInflater.inflate(R.layout.dialog_save_file, null)
val editText = view.findViewById<EditText>(R.id.file_name)
editText.setText(encodeFileName("${format.toString()}_$content"))
AlertDialog.Builder(ac)
.setView(view)
.setPositiveButton(android.R.string.ok) { _, _ ->
val fileName = editText.text.toString()
when (fileType) {
FileType.PNG -> saveAs(
addSuffixIfNotGiven(fileName, ".png"),
MIME_PNG
) {
barcodeBitmap?.saveAsPng(it)
}
FileType.SVG -> saveAs(
addSuffixIfNotGiven(fileName, ".svg"),
MIME_SVG
) { outputStream ->
barcodeSvg?.let {
outputStream.write(it.toByteArray())
}
}
FileType.TXT -> saveAs(
addSuffixIfNotGiven(fileName, ".txt"),
MIME_TXT
) { outputStream ->
barcodeTxt?.let {
outputStream.write(it.toByteArray())
}
}
}
}
.setNegativeButton(android.R.string.cancel) { _, _ ->
}
.show()
}
private fun saveAs(
fileName: String,
mimeType: String,
write: (outputStream: OutputStream) -> Unit
) {
val ac = activity ?: return
GlobalScope.launch {
val message = writeExternalFile(ac, fileName, mimeType, write).toSaveResult()
GlobalScope.launch(Main) {
ac.toast(message)
}
}
}
private fun shareAs(fileType: FileType) {
when (fileType) {
FileType.PNG -> barcodeBitmap?.let { share(it) }
FileType.SVG -> barcodeSvg?.let { shareText(context, it, MIME_SVG) }
FileType.TXT -> barcodeTxt?.let { shareText(context, it) }
}
}
private fun share(bitmap: Bitmap) {
GlobalScope.launch(Dispatchers.IO) {
val file = File(
context.externalCacheDir,
"shared_barcode.png"
)
val success = try {
FileOutputStream(file).use {
bitmap.saveAsPng(it)
}
true
} catch (e: IOException) {
false
}
GlobalScope.launch(Main) {
if (success) {
shareFile(context, file, "image/png")
} else {
activity?.toast(R.string.error_saving_file)
}
}
}
}
companion object {
private const val CONTENT = "content"
private const val FORMAT = "format"
private const val HINTS = "hints"
private const val SIZE = "size"
private const val MIME_PNG = "image/png"
private const val MIME_SVG = "image/svg+xmg"
private const val MIME_TXT = "text/plain"
fun newInstance(
content: String,
format: BarcodeFormat,
size: Int,
hints: EnumMap<EncodeHintType, Any>? = null
): Fragment {
val args = Bundle()
args.putString(CONTENT, content)
args.putSerializable(FORMAT, format)
hints?.let {
args.putSerializable(HINTS, it)
}
args.putInt(SIZE, size)
val fragment = BarcodeFragment()
fragment.arguments = args
return fragment
}
}
}
private fun Bitmap.saveAsPng(outputStream: OutputStream, quality: Int = 90) {
this.compress(Bitmap.CompressFormat.PNG, quality, outputStream)
}
private val fileNameCharacters = "[^A-Za-z0-9]".toRegex()
private fun encodeFileName(name: String): String =
fileNameCharacters.replace(name, "_").take(16).trim('_').toLowerCase(Locale.getDefault())
@@ -1,369 +0,0 @@
package de.markusfisch.android.binaryeye.fragment
import android.os.Build
import android.os.Bundle
import android.support.design.widget.FloatingActionButton
import android.support.v4.app.Fragment
import android.text.Editable
import android.text.TextWatcher
import android.view.*
import android.widget.EditText
import android.widget.TableLayout
import android.widget.TableRow
import android.widget.TextView
import de.markusfisch.android.binaryeye.R
import de.markusfisch.android.binaryeye.actions.ActionRegistry
import de.markusfisch.android.binaryeye.actions.wifi.WifiAction
import de.markusfisch.android.binaryeye.activity.MainActivity
import de.markusfisch.android.binaryeye.adapter.prettifyFormatName
import de.markusfisch.android.binaryeye.app.*
import de.markusfisch.android.binaryeye.content.copyToClipboard
import de.markusfisch.android.binaryeye.content.shareText
import de.markusfisch.android.binaryeye.database.Scan
import de.markusfisch.android.binaryeye.io.askForFileName
import de.markusfisch.android.binaryeye.io.toSaveResult
import de.markusfisch.android.binaryeye.io.writeExternalFile
import de.markusfisch.android.binaryeye.view.setPaddingFromWindowInsets
import de.markusfisch.android.binaryeye.widget.toast
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
class DecodeFragment : Fragment() {
private lateinit var contentView: EditText
private lateinit var formatView: TextView
private lateinit var metaView: TableLayout
private lateinit var hexView: TextView
private lateinit var format: String
private lateinit var fab: FloatingActionButton
private val parentJob = Job()
private val scope: CoroutineScope = CoroutineScope(Dispatchers.Main + parentJob)
private val content: String
get() = contentView.text.toString()
private var closeAutomatically = false
private var action = ActionRegistry.DEFAULT_ACTION
private var isBinary = false
private var id = 0L
override fun onCreate(state: Bundle?) {
super.onCreate(state)
setHasOptionsMenu(true)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
state: Bundle?
): View {
activity?.setTitle(R.string.content)
val view = inflater.inflate(
R.layout.fragment_decode,
container,
false
)
closeAutomatically = prefs.closeAutomatically &&
activity?.intent?.hasExtra(MainActivity.DECODED) == true
val scan = arguments?.getParcelable(SCAN) as Scan?
?: throw IllegalArgumentException("DecodeFragment needs a Scan")
id = scan.id
val inputContent = scan.content
isBinary = hasNonPrintableCharacters(
inputContent
) or inputContent.isEmpty()
val raw = scan.raw ?: inputContent.toByteArray()
format = scan.format
contentView = view.findViewById(R.id.content)
fab = view.findViewById(R.id.open)
if (!isBinary) {
contentView.setText(inputContent)
contentView.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
updateViewsAndAction(content.toByteArray())
}
override fun beforeTextChanged(
s: CharSequence?,
start: Int,
count: Int,
after: Int
) {
}
override fun onTextChanged(
s: CharSequence?,
start: Int,
before: Int,
count: Int
) {
}
})
fab.setOnClickListener {
executeAction(content.toByteArray())
}
if (prefs.openImmediately) {
executeAction(content.toByteArray())
}
} else {
contentView.setText(R.string.binary_data)
contentView.isEnabled = false
fab.setImageResource(R.drawable.ic_action_save)
fab.setOnClickListener {
askForFileNameAndSave(raw)
}
}
formatView = view.findViewById(R.id.format)
metaView = view.findViewById(R.id.meta)
hexView = view.findViewById(R.id.hex)
updateViewsAndAction(raw)
if (prefs.showMetaData) {
fillMetaView(metaView, scan)
}
(view.findViewById(R.id.inset_layout) as View).setPaddingFromWindowInsets()
(view.findViewById(R.id.scroll_view) as View).setPaddingFromWindowInsets()
return view
}
override fun onDestroy() {
super.onDestroy()
parentJob.cancel()
}
private fun updateViewsAndAction(bytes: ByteArray) {
val prevAction = action
if (!prevAction.canExecuteOn(bytes)) {
action = ActionRegistry.getAction(bytes)
}
formatView.text = resources.getQuantityString(
R.plurals.barcode_info,
bytes.size,
prettifyFormatName(format),
bytes.size
)
hexView.text = if (prefs.showHexDump) hexDump(bytes) else ""
if (prevAction !== action) {
fab.setImageResource(action.iconResId)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
fab.setOnLongClickListener { v ->
v.context.toast(action.titleResId)
true
}
} else {
fab.tooltipText = getString(action.titleResId)
}
}
}
private fun fillMetaView(tableLayout: TableLayout, scan: Scan) {
val ctx = tableLayout.context
val spaceBetween = (16f * ctx.resources.displayMetrics.density).toInt()
var hasMeta = false
sortedMapOf(
R.string.error_correction_level to scan.errorCorrectionLevel,
R.string.issue_number to scan.issueNumber,
R.string.orientation to scan.orientation,
R.string.other_meta_data to scan.otherMetaData,
R.string.pdf417_extra_metadata to scan.pdf417ExtraMetaData,
R.string.possible_country to scan.possibleCountry,
R.string.suggested_price to scan.suggestedPrice,
R.string.upc_ean_extension to scan.upcEanExtension
).forEach { item ->
item.value?.let {
val tr = TableRow(ctx)
val keyView = TextView(ctx)
keyView.setText(item.key)
val valueView = TextView(ctx)
valueView.setPadding(spaceBetween, 0, 0, 0)
valueView.text = it
tr.addView(keyView)
tr.addView(valueView)
tableLayout.addView(tr)
hasMeta = true
}
}
if (hasMeta) {
tableLayout.setPadding(0, 0, 0, spaceBetween)
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.fragment_decode, menu)
if (isBinary) {
menu.findItem(R.id.copy_to_clipboard).isVisible = false
menu.findItem(R.id.create).isVisible = false
}
if (id > 0L) {
menu.findItem(R.id.remove).isVisible = true
}
if (action is WifiAction) {
menu.findItem(R.id.copy_password).isVisible = true
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.copy_password -> {
copyPasswordToClipboard()
maybeBackOrFinish()
true
}
R.id.copy_to_clipboard -> {
copyToClipboard(content)
maybeBackOrFinish()
true
}
R.id.share -> {
context?.also {
shareText(it, content)
maybeBackOrFinish()
}
true
}
R.id.create -> {
addFragment(
fragmentManager,
EncodeFragment.newInstance(content, format)
)
true
}
R.id.remove -> {
db.removeScan(id)
backOrFinish()
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun copyPasswordToClipboard() {
val ac = action
if (ac is WifiAction) {
ac.password?.let { password ->
activity?.apply {
copyToClipboard(password)
toast(R.string.copied_password_to_clipboard)
}
}
}
}
private fun copyToClipboard(text: String) {
activity?.apply {
copyToClipboard(text)
toast(R.string.copied_to_clipboard)
}
}
private fun maybeBackOrFinish() {
if (closeAutomatically) {
backOrFinish()
}
}
private fun backOrFinish() {
val fm = fragmentManager
if (fm != null && fm.backStackEntryCount > 0) {
fm.popBackStack()
} else {
activity?.finish()
}
}
private fun executeAction(content: ByteArray) {
val ac = activity ?: return
if (content.isNotEmpty()) {
if (action is WifiAction &&
Build.VERSION.SDK_INT < Build.VERSION_CODES.Q &&
!hasLocationPermission(ac) { executeAction(content) }
) {
return
}
scope.launch {
action.execute(ac, content)
maybeBackOrFinish()
}
}
}
private fun askForFileNameAndSave(raw: ByteArray) {
val ac = activity ?: return
if (!hasWritePermission(ac) { askForFileNameAndSave(raw) }) {
return
}
scope.launch(Dispatchers.Main) {
val name = ac.askForFileName() ?: return@launch
val message = writeExternalFile(
ac,
name,
"application/octet-stream"
) {
it.write(raw)
}.toSaveResult()
ac.toast(message)
}
}
companion object {
private const val SCAN = "scan"
fun newInstance(scan: Scan): Fragment {
val args = Bundle()
args.putParcelable(SCAN, scan)
val fragment = DecodeFragment()
fragment.arguments = args
return fragment
}
}
}
private fun hexDump(bytes: ByteArray, charsPerLine: Int = 33): String {
if (charsPerLine < 4 || bytes.isEmpty()) {
return ""
}
val dump = StringBuilder()
val hex = StringBuilder()
val ascii = StringBuilder()
val itemsPerLine = (charsPerLine - 1) / 4
val len = bytes.size
var i = 0
while (true) {
val ord = bytes[i]
hex.append(String.format("%02X ", ord))
ascii.append(if (ord > 31) ord.toChar() else " ")
++i
val posInLine = i % itemsPerLine
val atEnd = i >= len
var atLineEnd = posInLine == 0
if (atEnd && !atLineEnd) {
for (j in posInLine until itemsPerLine) {
hex.append(" ")
}
atLineEnd = true
}
if (atLineEnd) {
dump.append(hex.toString())
dump.append(" ")
dump.append(ascii.toString())
dump.append("\n")
hex.setLength(0)
ascii.setLength(0)
}
if (atEnd) {
break
}
}
return dump.toString()
}
@@ -1,202 +0,0 @@
package de.markusfisch.android.binaryeye.fragment
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel
import de.markusfisch.android.binaryeye.R
import de.markusfisch.android.binaryeye.adapter.prettifyFormatName
import de.markusfisch.android.binaryeye.app.addFragment
import de.markusfisch.android.binaryeye.app.prefs
import de.markusfisch.android.binaryeye.view.hideSoftKeyboard
import de.markusfisch.android.binaryeye.view.setPaddingFromWindowInsets
import java.util.*
class EncodeFragment : Fragment() {
private lateinit var formatView: Spinner
private lateinit var errorCorrectionLabel: TextView
private lateinit var errorCorrectionLevel: Spinner
private lateinit var sizeView: TextView
private lateinit var sizeBarView: SeekBar
private lateinit var contentView: EditText
private val writers = arrayListOf(
BarcodeFormat.AZTEC,
BarcodeFormat.CODABAR,
BarcodeFormat.CODE_39,
BarcodeFormat.CODE_128,
BarcodeFormat.DATA_MATRIX,
BarcodeFormat.EAN_8,
BarcodeFormat.EAN_13,
BarcodeFormat.ITF,
BarcodeFormat.PDF_417,
BarcodeFormat.QR_CODE,
BarcodeFormat.UPC_A
)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
state: Bundle?
): View? {
val ac = activity ?: return null
ac.setTitle(R.string.compose_barcode)
val view = inflater.inflate(
R.layout.fragment_encode,
container,
false
)
formatView = view.findViewById(R.id.format)
val formatAdapter = ArrayAdapter(
ac,
android.R.layout.simple_spinner_item,
writers.map { prettifyFormatName(it.name) }
)
formatAdapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item
)
formatView.adapter = formatAdapter
formatView.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parentView: AdapterView<*>?,
selectedItemView: View?,
position: Int,
id: Long
) {
val visibility = if (
writers[position] == BarcodeFormat.QR_CODE
) {
View.VISIBLE
} else {
View.GONE
}
errorCorrectionLabel.visibility = visibility
errorCorrectionLevel.visibility = visibility
}
override fun onNothingSelected(parentView: AdapterView<*>?) {}
}
errorCorrectionLabel = view.findViewById(R.id.error_correction_label)
errorCorrectionLevel = view.findViewById(R.id.error_correction_level)
sizeView = view.findViewById(R.id.size_display)
sizeBarView = view.findViewById(R.id.size_bar)
initSizeBar()
contentView = view.findViewById(R.id.content)
val args = arguments
args?.also {
contentView.setText(it.getString(CONTENT))
}
val barcodeFormat = args?.getString(FORMAT)
if (barcodeFormat != null) {
formatView.setSelection(
writers.indexOf(resolveFormat(barcodeFormat))
)
} else if (state == null) {
formatView.post {
formatView.setSelection(prefs.indexOfLastSelectedFormat)
}
}
view.findViewById<View>(R.id.encode).setOnClickListener {
encode()
}
(view.findViewById(R.id.inset_layout) as View).setPaddingFromWindowInsets()
(view.findViewById(R.id.scroll_view) as View).setPaddingFromWindowInsets()
return view
}
override fun onPause() {
super.onPause()
prefs.indexOfLastSelectedFormat = formatView.selectedItemPosition
}
private fun encode() {
val hints = EnumMap<EncodeHintType, Any>(EncodeHintType::class.java)
val format = writers[formatView.selectedItemPosition]
if (format == BarcodeFormat.QR_CODE) {
hints[EncodeHintType.ERROR_CORRECTION] = arrayListOf(
ErrorCorrectionLevel.L,
ErrorCorrectionLevel.M,
ErrorCorrectionLevel.Q,
ErrorCorrectionLevel.H
)[errorCorrectionLevel.selectedItemPosition]
}
val size = getSize(sizeBarView.progress)
val content = contentView.text.toString()
if (content.isEmpty()) {
Toast.makeText(
context,
R.string.error_no_content,
Toast.LENGTH_SHORT
).show()
} else {
activity?.hideSoftKeyboard(contentView)
addFragment(
fragmentManager,
BarcodeFragment.newInstance(content, format, size, hints)
)
}
}
private fun initSizeBar() {
updateSize(sizeBarView.progress)
sizeBarView.setOnSeekBarChangeListener(
object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(
seekBar: SeekBar,
progressValue: Int,
fromUser: Boolean
) {
updateSize(progressValue)
}
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onStopTrackingTouch(seekBar: SeekBar) {}
})
}
private fun updateSize(power: Int) {
val size = getSize(power)
sizeView.text = getString(R.string.width_by_height, size, size)
}
private fun getSize(power: Int) = 128 * (power + 1)
companion object {
private const val CONTENT = "content"
private const val FORMAT = "format"
fun newInstance(
content: String,
format: String? = null
): Fragment {
val args = Bundle()
args.putString(CONTENT, content)
format?.let { args.putString(FORMAT, it) }
val fragment = EncodeFragment()
fragment.arguments = args
return fragment
}
}
}
private fun resolveFormat(name: String): BarcodeFormat = try {
BarcodeFormat.valueOf(name)
} catch (_: IllegalArgumentException) {
BarcodeFormat.QR_CODE
}
@@ -1,66 +1,231 @@
package de.markusfisch.android.binaryeye.fragment
import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.content.SharedPreferences.OnSharedPreferenceChangeListener
import android.net.wifi.WifiManager
import android.os.Build
import android.os.Bundle
import android.support.v7.preference.ListPreference
import android.support.v7.preference.Preference
import android.support.v7.preference.PreferenceFragmentCompat
import android.support.v7.preference.PreferenceGroup
import androidx.annotation.RequiresApi
import androidx.preference.ListPreference
import androidx.preference.MultiSelectListPreference
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.PreferenceGroup
import de.markusfisch.android.binaryeye.R
import de.markusfisch.android.binaryeye.activity.AutomatedActionsActivity
import de.markusfisch.android.binaryeye.activity.IgnoreCodesActivity
import de.markusfisch.android.binaryeye.activity.NetworkSuggestionsActivity
import de.markusfisch.android.binaryeye.activity.ProfilesActivity
import de.markusfisch.android.binaryeye.activity.SplashActivity
import de.markusfisch.android.binaryeye.adapter.prettifyFormatName
import de.markusfisch.android.binaryeye.app.hasBluetoothPermission
import de.markusfisch.android.binaryeye.app.prefs
import de.markusfisch.android.binaryeye.bluetooth.setBluetoothHosts
import de.markusfisch.android.binaryeye.media.beepConfirm
import de.markusfisch.android.binaryeye.preference.UrlPreference
import de.markusfisch.android.binaryeye.view.setPaddingFromWindowInsets
import de.markusfisch.android.binaryeye.view.systemBarRecyclerViewScrollListener
import de.markusfisch.android.binaryeye.widget.toast
class PreferencesFragment : PreferenceFragmentCompat() {
private var lastProfile: String? = null
private val changeListener = object : OnSharedPreferenceChangeListener {
override fun onSharedPreferenceChanged(
sharedPreferences: SharedPreferences,
key: String
sharedPreferences: SharedPreferences?,
key: String?
) {
val preference = findPreference(key) ?: return
prefs.update()
if (preference.key == "custom_locale") {
activity?.restartApp()
} else {
setSummary(preference)
key ?: return
val preference = findPreference<Preference>(key) ?: return
if (preference.key != PROFILE) {
prefs.update()
}
when (preference.key) {
"custom_locale" -> {
activity?.restartApp()
return
}
"beep_tone_name",
"beep_stream_name" -> beepConfirm()
"send_scan_bluetooth" -> if (
prefs.sendScanBluetooth &&
activity?.hasBluetoothPermission() == false
) {
prefs.sendScanBluetooth = false
}
}
setSummary(preference)
}
}
override fun onCreatePreferences(state: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.preferences)
activity?.setTitle(R.string.preferences)
loadPreferences(rootKey)
}
private fun loadPreferences(rootKey: String? = null) {
preferenceScreen?.sharedPreferences
?.unregisterOnSharedPreferenceChangeListener(changeListener)
preferenceManager.apply {
sharedPreferencesName = prefs.profile ?: "${context.packageName}_preferences"
sharedPreferencesMode = Context.MODE_PRIVATE
}
// Refresh the preferences.
preferenceScreen = null
setPreferencesFromResource(R.xml.preferences, rootKey)
preferenceScreen.sharedPreferences
?.registerOnSharedPreferenceChangeListener(changeListener)
setSummaries(preferenceScreen)
setIcons()
wireProfiles()
wireAutomatedActions()
wireIgnoreCodes()
setBluetoothResources()
wireClearNetworkPreferences()
}
private fun wireProfiles() {
findPreference<Preference>(PROFILE)?.apply {
updateProfileSummary(this)
onPreferenceClickListener = Preference.OnPreferenceClickListener {
startActivity(Intent(activity, ProfilesActivity::class.java))
true
}
}
}
private fun wireAutomatedActions() {
findPreference<Preference>(AUTOMATED_ACTIONS)?.apply {
updateAutomatedActionsSummary(this)
onPreferenceClickListener = Preference.OnPreferenceClickListener {
startActivity(
Intent(activity, AutomatedActionsActivity::class.java)
)
true
}
}
}
private fun wireIgnoreCodes() {
findPreference<Preference>(IGNORE_CODES)?.apply {
updateIgnoreCodesSummary(this)
onPreferenceClickListener = Preference.OnPreferenceClickListener {
startActivity(
Intent(activity, IgnoreCodesActivity::class.java)
)
true
}
}
}
private fun setBluetoothResources() {
if (prefs.sendScanBluetooth &&
activity?.hasBluetoothPermission() == true
) {
findPreference<ListPreference>("send_scan_bluetooth_host")?.let {
setBluetoothHosts(it)
}
}
}
private fun wireClearNetworkPreferences() {
findPreference<Preference>("clear_network_suggestions")?.apply {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {
// From R+ we can query past network suggestions and
// make them editable.
setOnPreferenceClickListener {
startActivity(
Intent(activity, NetworkSuggestionsActivity::class.java)
)
true
}
} else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.Q) {
// On Q, we can only clear *all* suggestions.
// Note that previous versions of this app allowed
// adding network suggestions on Q as well, so we
// need to keep this option.
setOnPreferenceClickListener {
context?.askToClearNetworkSuggestions()
true
}
} else {
// There are no network suggestions below Q.
isVisible = false
}
}
}
@RequiresApi(Build.VERSION_CODES.Q)
private fun Context.askToClearNetworkSuggestions() {
AlertDialog.Builder(this)
.setMessage(R.string.really_remove_all_networks)
.setPositiveButton(android.R.string.ok) { _, _ ->
clearNetworkSuggestions()
}
.setNegativeButton(android.R.string.cancel) { _, _ -> }
.show()
}
@RequiresApi(Build.VERSION_CODES.Q)
private fun Context.clearNetworkSuggestions() {
toast(
if (removeAllNetworkSuggestions() ==
WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS
) {
R.string.clear_network_suggestions_success
} else {
R.string.clear_network_suggestions_nothing_to_remove
}
)
}
override fun onResume() {
super.onResume()
if (lastProfile != prefs.profile) {
loadPreferences()
}
activity?.setTitle(R.string.preferences)
findPreference<Preference>(AUTOMATED_ACTIONS)?.let {
updateAutomatedActionsSummary(it)
}
findPreference<Preference>(IGNORE_CODES)?.let {
updateIgnoreCodesSummary(it)
}
findPreference<Preference>(PROFILE)?.let {
updateProfileSummary(it)
}
listView.setPaddingFromWindowInsets()
listView.removeOnScrollListener(systemBarRecyclerViewScrollListener)
listView.addOnScrollListener(systemBarRecyclerViewScrollListener)
preferenceScreen.sharedPreferences
.registerOnSharedPreferenceChangeListener(changeListener)
setSummaries(preferenceScreen)
}
override fun onPause() {
super.onPause()
preferenceScreen.sharedPreferences
.unregisterOnSharedPreferenceChangeListener(changeListener)
?.unregisterOnSharedPreferenceChangeListener(changeListener)
}
override fun onDisplayPreferenceDialog(preference: Preference) {
if (preference is UrlPreference) {
val fm = fragmentManager
val fm = parentFragmentManager
UrlDialogFragment.newInstance(preference.key).apply {
setTargetFragment(this@PreferencesFragment, 0)
show(fm, null)
}
} else if (preference.key == "send_scan_bluetooth_host") {
val ac = activity ?: return
if (ac.hasBluetoothPermission()) {
setBluetoothHosts(preference as ListPreference)
}
super.onDisplayPreferenceDialog(preference)
} else {
super.onDisplayPreferenceDialog(preference)
}
@@ -74,30 +239,132 @@ class PreferencesFragment : PreferenceFragmentCompat() {
}
private fun setSummary(preference: Preference) {
when (preference) {
is UrlPreference -> {
preference.setSummary(preference.getUrl())
}
is ListPreference -> {
preference.setSummary(preference.entry)
}
is PreferenceGroup -> {
setSummaries(preference)
}
when (preference.key) {
AUTOMATED_ACTIONS -> return updateAutomatedActionsSummary(preference)
IGNORE_CODES -> return updateIgnoreCodesSummary(preference)
}
when (preference) {
is UrlPreference -> preference.summary = preference.getUrl()
is ListPreference -> preference.setSummary(preference.entry)
is MultiSelectListPreference -> preference.summary =
getSortedSummary(preference)
is PreferenceGroup -> setSummaries(preference)
}
}
private fun getSortedSummary(preference: MultiSelectListPreference): String {
val labelsByValue = mutableMapOf<String, String>()
val entries = preference.entries
val entryValues = preference.entryValues
val count = minOf(entries.size, entryValues.size)
for (i in 0 until count) {
labelsByValue[entryValues[i].toString()] = entries[i].toString()
}
return preference.values
.map { value ->
labelsByValue[value] ?: value.prettifyFormatName()
}
.sortedBy { it.lowercase() }
.joinToString(", ")
}
private fun setIcons() {
setIcon(PROFILE, R.drawable.ic_action_profile)
setIcon("formats", R.drawable.ic_action_scan)
setIcon("show_crop_handle", R.drawable.ic_action_crop)
setIcon("show_crosshairs", R.drawable.ic_action_search)
setIcon("zoom_by_swiping", R.drawable.ic_action_search)
setIcon("auto_rotate", R.drawable.ic_action_down)
setIcon("try_harder", R.drawable.ic_action_search)
setIcon("bulk_mode", R.drawable.ic_action_bulk_mode)
setIcon("bulk_mode_delay", R.drawable.ic_action_delay)
setIcon("show_toast_in_bulk_mode", R.drawable.ic_action_toast)
setIcon("vibrate", R.drawable.ic_action_vibrate)
setIcon("beep", R.drawable.ic_action_beep)
setIcon("beep_tone_name", R.drawable.ic_action_notification_sound)
setIcon("beep_stream_name", R.drawable.ic_action_notification_sound)
setIcon("use_history", R.drawable.ic_action_history)
setIcon("ignore_duplicates_name", R.drawable.ic_action_remove)
setIcon(IGNORE_CODES, R.drawable.ic_action_remove)
setIcon("copy_immediately", R.drawable.ic_action_copy)
setIcon("send_scan_active", R.drawable.ic_action_forward)
setIcon("send_scan_url", R.drawable.ic_action_link)
setIcon("send_scan_type", R.drawable.ic_action_link)
setIcon("send_scan_bluetooth", R.drawable.ic_action_bluetooth)
setIcon("send_scan_bluetooth_host", R.drawable.ic_action_bluetooth)
setIcon("open_immediately", R.drawable.ic_action_open)
setIcon("show_meta_data", R.drawable.ic_action_info)
setIcon("show_hex_dump", R.drawable.ic_action_info)
setIcon("show_checksum", R.drawable.ic_action_info)
setIcon("show_recreation", R.drawable.ic_action_scan)
setIcon("close_automatically", R.drawable.ic_action_back)
setIcon("default_search_url", R.drawable.ic_action_search)
setIcon("open_with_url", R.drawable.ic_action_link)
setIcon(AUTOMATED_ACTIONS, R.drawable.ic_action_create)
setIcon("clear_network_suggestions", R.drawable.ic_action_wifi)
setIcon("brighten_screen", R.drawable.ic_action_bright)
setIcon("custom_locale", R.drawable.ic_action_preferences)
}
private fun setIcon(key: String, iconResId: Int) {
findPreference<Preference>(key)?.setIcon(iconResId)
}
private fun updateAutomatedActionsSummary(preference: Preference) {
val count = prefs.automatedActions.size
preference.summary = if (count == 0) {
getString(R.string.automated_actions_none)
} else {
resources.getQuantityString(
R.plurals.automated_actions_count,
count,
count
)
}
}
private fun updateIgnoreCodesSummary(preference: Preference) {
val count = prefs.ignoreCodes.size
preference.summary = if (count == 0) {
getString(R.string.ignore_codes_none)
} else {
resources.getQuantityString(
R.plurals.ignore_codes_count,
count,
count
)
}
}
private fun updateProfileSummary(preference: Preference) {
preference.summary = prefs.profile ?: getString(R.string.profile_default)
lastProfile = prefs.profile
}
companion object {
private const val PROFILE = "profile"
private const val AUTOMATED_ACTIONS = "automated_actions"
private const val IGNORE_CODES = "ignore_codes"
}
}
private fun Activity.restartApp() {
val intent = Intent(this, SplashActivity::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
intent.addFlags(
Intent.FLAG_ACTIVITY_NEW_TASK or
Intent.FLAG_ACTIVITY_CLEAR_TASK
)
}
intent.addFlags(
Intent.FLAG_ACTIVITY_NEW_TASK or
Intent.FLAG_ACTIVITY_CLEAR_TASK
)
startActivity(intent)
finish()
// restart to begin with an unmodified Locale to follow system settings
// Restart to begin with an unmodified Locale to follow system settings.
Runtime.getRuntime().exit(0)
}
@RequiresApi(Build.VERSION_CODES.Q)
private fun Context.removeAllNetworkSuggestions(): Int =
(applicationContext.getSystemService(
Context.WIFI_SERVICE
) as WifiManager).removeNetworkSuggestions(listOf())
@@ -1,23 +1,24 @@
package de.markusfisch.android.binaryeye.fragment
import android.os.Bundle
import android.support.v7.preference.PreferenceDialogFragmentCompat
import android.view.View
import android.widget.TextView
import androidx.preference.PreferenceDialogFragmentCompat
import de.markusfisch.android.binaryeye.R
import de.markusfisch.android.binaryeye.app.prefs
import de.markusfisch.android.binaryeye.database.Scan
import de.markusfisch.android.binaryeye.net.sendAsync
import de.markusfisch.android.binaryeye.preference.UrlPreference
import de.markusfisch.android.zxingcpp.ZxingCpp.BarcodeFormat
class UrlDialogFragment : PreferenceDialogFragmentCompat() {
private var urlView: TextView? = null
private var testButton: TextView? = null
override fun onBindDialogView(view: View?) {
override fun onBindDialogView(view: View) {
super.onBindDialogView(view)
urlView = view?.findViewById(R.id.url)
testButton = view?.findViewById(R.id.test_url)
urlView = view.findViewById(R.id.url)
testButton = view.findViewById(R.id.test_url)
testButton?.setOnClickListener {
testUrl(testButton)
}
@@ -50,15 +51,7 @@ class UrlDialogFragment : PreferenceDialogFragmentCompat() {
Scan(
"test",
null,
"none",
null,
null,
null,
null,
null,
null,
null,
null
BarcodeFormat.None
).sendAsync(url, prefs.sendScanType) { code, body ->
textView.text = when {
code != null -> "$code"
@@ -87,10 +80,5 @@ private fun completeUrl(template: String): String {
if (!s.startsWith("http")) {
s = "http://${s}"
}
if (prefs.sendScanType == "0" &&
!s.matches(".*/[a-zA-Z._-]*\\?[a-zA-Z0-9_-]+=$".toRegex())
) {
s = "${s}?content="
}
return s
}
@@ -11,9 +11,9 @@ import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
fun loadImageUri(cr: ContentResolver, uri: Uri): Bitmap? = try {
fun ContentResolver.loadImageUri(uri: Uri): Bitmap? = try {
val options = BitmapFactory.Options()
cr.openInputStream(uri)?.use {
openInputStream(uri)?.use {
options.inJustDecodeBounds = true
BitmapFactory.decodeStream(it, null, options)
options.inSampleSize = calculateInSampleSize(
@@ -22,10 +22,10 @@ fun loadImageUri(cr: ContentResolver, uri: Uri): Bitmap? = try {
)
options.inJustDecodeBounds = false
}
cr.openInputStream(uri)?.use {
openInputStream(uri)?.use {
BitmapFactory.decodeStream(it, null, options)
}
} catch (e: IOException) {
} catch (_: IOException) {
null
}
@@ -49,18 +49,23 @@ private fun calculateInSampleSize(
return inSampleSize
}
fun crop(bitmap: Bitmap, rect: RectF, rotation: Float) = try {
val erected = erect(bitmap, rotation)
val w = erected.width
val h = erected.height
fun Bitmap.crop(
rect: RectF,
rotation: Float,
pivotX: Float,
pivotY: Float
) = try {
val b = rotate(rotation, pivotX, pivotY)
val w = b.width
val h = b.height
val x = max(0, (rect.left * w).roundToInt())
val y = max(0, (rect.top * h).roundToInt())
Bitmap.createBitmap(
erected,
b,
x,
y,
min(w - x, (rect.width() * w).roundToInt()),
min(h - y, (rect.height() * h).roundToInt())
min(w, (rect.right * w).roundToInt()) - x,
min(h, (rect.bottom * h).roundToInt()) - y
)
} catch (e: OutOfMemoryError) {
null
@@ -68,20 +73,22 @@ fun crop(bitmap: Bitmap, rect: RectF, rotation: Float) = try {
null
}
private fun erect(bitmap: Bitmap, rotation: Float): Bitmap = if (
rotation % 360f != 0f
) {
val matrix = Matrix()
matrix.setRotate(rotation)
private fun Bitmap.rotate(
rotation: Float,
pivotX: Float,
pivotY: Float
): Bitmap = if (rotation % 360f != 0f) {
Bitmap.createBitmap(
bitmap,
this,
0,
0,
bitmap.width,
bitmap.height,
matrix,
width,
height,
Matrix().apply {
setRotate(rotation, pivotX, pivotY)
},
true
)
} else {
bitmap
this
}
@@ -0,0 +1,4 @@
package de.markusfisch.android.binaryeye.graphics
const val COLOR_BLACK = 0xff000000.toInt()
const val COLOR_WHITE = 0xffffffff.toInt()
@@ -3,7 +3,7 @@ package de.markusfisch.android.binaryeye.graphics
import android.content.Context
import android.graphics.DashPathEffect
import android.graphics.Paint
import android.support.v4.content.ContextCompat
import androidx.core.content.ContextCompat
import de.markusfisch.android.binaryeye.R
fun Context.getDashedBorderPaint() = Paint(Paint.ANTI_ALIAS_FLAG).apply {
@@ -1,29 +0,0 @@
package de.markusfisch.android.binaryeye.graphics
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Point
import android.support.v4.content.ContextCompat
import de.markusfisch.android.binaryeye.R
class Dots(context: Context) {
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
private val radius = 8f * context.resources.displayMetrics.density
init {
paint.color = ContextCompat.getColor(context, R.color.dot)
paint.style = Paint.Style.FILL
}
fun draw(canvas: Canvas, points: List<Point>) {
for (point in points) {
canvas.drawCircle(
point.x.toFloat(),
point.y.toFloat(),
radius,
paint
)
}
}
}
@@ -5,26 +5,22 @@ import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.os.Build
import androidx.core.content.res.ResourcesCompat
import androidx.core.graphics.createBitmap
fun Resources.getBitmapFromDrawable(
resId: Int
): Bitmap = getBitmapFromDrawable(getDrawableCompat(resId))
fun Resources.getDrawableCompat(
resId: Int
): Drawable = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getDrawable(resId, null)
} else {
@Suppress("DEPRECATION")
getDrawable(resId)
}
): Bitmap = getBitmapFromDrawable(
ResourcesCompat.getDrawable(this, resId, null) ?: throw Resources.NotFoundException(
"Drawable resource ID #0x${resId.toString(16)}"
)
)
private fun getBitmapFromDrawable(drawable: Drawable): Bitmap {
if (drawable is BitmapDrawable) {
return drawable.bitmap
}
val bitmap = Bitmap.createBitmap(
val bitmap = createBitmap(
drawable.intrinsicWidth,
drawable.intrinsicHeight,
Bitmap.Config.ARGB_8888
@@ -1,85 +1,110 @@
package de.markusfisch.android.binaryeye.graphics
import android.graphics.Point
import android.graphics.Matrix
import android.graphics.Rect
import com.google.zxing.Result
import com.google.zxing.ResultPoint
import android.graphics.RectF
import de.markusfisch.android.zxingcpp.ZxingCpp.Position
import kotlin.math.roundToInt
fun mapResult(
frameWidth: Int,
frameHeight: Int,
frameOrientation: Int,
viewRect: Rect,
result: Result
): List<Point> = frameToView(
frameWidth,
frameHeight,
frameOrientation,
viewRect
).map(
result.resultPoints
)
fun frameToView(
frameWidth: Int,
frameHeight: Int,
frameOrientation: Int,
viewRect: Rect
) = Mapping(
frameWidth,
frameHeight,
frameOrientation,
viewRect.width().toFloat(),
viewRect.height().toFloat(),
viewRect.left,
viewRect.top
)
fun isPortrait(orientation: Int) = orientation == 90 || orientation == 270
data class Mapping(
val frameWidth: Int,
val frameHeight: Int,
val frameOrientation: Int,
val viewWidth: Float,
val viewHeight: Float,
val offsetX: Int,
val offsetY: Int
data class FrameMetrics(
var width: Int = 0,
var height: Int = 0,
var orientation: Int = 0
) {
fun map(resultPoint: ResultPoint): Point {
val point = Point(
resultPoint.x.roundToInt(),
resultPoint.y.roundToInt()
fun isValid() = width > 0 && height > 0
}
fun Rect.setFrameRoi(
frameMetrics: FrameMetrics,
viewRect: Rect,
viewRoi: Rect
) {
Matrix().apply {
// Map ROI from view coordinates to frame coordinates.
setTranslate(-viewRect.left.toFloat(), -viewRect.top.toFloat())
postScale(1f / viewRect.width(), 1f / viewRect.height())
postRotate(-frameMetrics.orientation.toFloat(), .5f, .5f)
postScale(frameMetrics.width.toFloat(), frameMetrics.height.toFloat())
val frameRoiF = RectF()
val viewRoiF = RectF(
viewRoi.left.toFloat(),
viewRoi.top.toFloat(),
viewRoi.right.toFloat(),
viewRoi.bottom.toFloat()
)
rotate(point)
val w: Int
val h: Int
if (isPortrait(frameOrientation)) {
w = frameHeight
h = frameWidth
} else {
w = frameWidth
h = frameHeight
}
val ratioX = viewWidth / w.toFloat()
val ratioY = viewHeight / h.toFloat()
point.set(
(point.x * ratioX).roundToInt() + offsetX,
(point.y * ratioY).roundToInt() + offsetY
mapRect(frameRoiF, viewRoiF)
set(
frameRoiF.left.roundToInt(),
frameRoiF.top.roundToInt(),
frameRoiF.right.roundToInt(),
frameRoiF.bottom.roundToInt()
)
return point
}
fun map(points: Array<ResultPoint?>): List<Point> =
// because ZXing apparently returns null in this array sometimes
points.filterNotNull().map { map(it) }
private fun rotate(point: Point) = when (frameOrientation) {
90 -> point.set(frameHeight - point.y, point.x)
180 -> point.set(frameWidth - point.x, frameHeight - point.y)
270 -> point.set(point.y, frameWidth - point.x)
else -> {
}
val clampedLeft = left.coerceIn(0, frameMetrics.width)
val clampedTop = top.coerceIn(0, frameMetrics.height)
val clampedRight = right.coerceIn(0, frameMetrics.width)
val clampedBottom = bottom.coerceIn(0, frameMetrics.height)
if (clampedLeft >= clampedRight || clampedTop >= clampedBottom) {
setEmpty()
} else {
set(clampedLeft, clampedTop, clampedRight, clampedBottom)
}
}
fun Matrix.setFrameToView(
frameMetrics: FrameMetrics,
viewRect: Rect,
viewRoi: Rect? = null
) {
// Configure this matrix to map points in frame coordinates to
// view coordinates.
val uprightWidth: Int
val uprightHeight: Int
when (frameMetrics.orientation) {
90, 270 -> {
uprightWidth = frameMetrics.height
uprightHeight = frameMetrics.width
}
else -> {
uprightWidth = frameMetrics.width
uprightHeight = frameMetrics.height
}
}
setScale(
viewRect.width().toFloat() / uprightWidth,
viewRect.height().toFloat() / uprightHeight
)
viewRoi?.let {
postTranslate(viewRoi.left.toFloat(), viewRoi.top.toFloat())
}
}
fun Matrix.mapPosition(
position: Position,
coords: FloatArray
): Int {
var i = 0
setOf(
position.topLeft,
position.topRight,
position.bottomRight,
position.bottomLeft
).forEach {
coords[i++] = it.x.toFloat()
coords[i++] = it.y.toFloat()
}
mapPoints(coords)
return i
}
fun Matrix.mapViewYToFrame(viewY: Float): Float {
val values = FloatArray(9)
getValues(values)
val scaleY = values[Matrix.MSCALE_Y]
return if (scaleY != 0f) {
(viewY - values[Matrix.MTRANS_Y]) / scaleY
} else {
viewY
}
}
@@ -0,0 +1,59 @@
package de.markusfisch.android.binaryeye.graphics
import android.graphics.Bitmap
import android.graphics.Canvas
import androidx.core.graphics.createBitmap
fun Bitmap.fixTransparency(): Bitmap {
val result = analyzeTransparency()
val cfg = config
return if (cfg != null && result.hasTransparentPixels) {
val copy = createBitmap(
width,
height,
cfg
)
Canvas(copy).apply {
drawColor(result.backgroundColor)
drawBitmap(this@fixTransparency, 0f, 0f, null)
}
copy
} else {
this
}
}
private fun Bitmap.analyzeTransparency(): Result {
val pixels = IntArray(width * height)
getPixels(pixels, 0, width, 0, 0, width, height)
var transparent = 0
var visible = 0
var bright = 0
for (pixel in pixels) {
val alpha = (pixel shr 24) and 0xff
if (alpha < 0xff) {
++transparent
}
if (alpha > 0) {
++visible
if (
((pixel shr 16) and 0xff) +
((pixel shr 8) and 0xff) +
(pixel and 0xff) > 128
) ++bright
}
}
return Result(
transparent > 0,
if (bright > 0 && visible / bright < 2) {
COLOR_BLACK
} else {
COLOR_WHITE
}
)
}
private data class Result(
val hasTransparentPixels: Boolean,
val backgroundColor: Int
)
@@ -6,8 +6,8 @@ import android.content.Context
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.support.annotation.MainThread
import android.widget.EditText
import androidx.annotation.MainThread
import de.markusfisch.android.binaryeye.R
import de.markusfisch.android.binaryeye.app.alertDialog
import java.io.File
@@ -46,24 +46,21 @@ fun Boolean.toSaveResult() = if (this) {
R.string.error_saving_file
}
fun writeExternalFile(
context: Context,
fun Context.writeExternalFile(
fileName: String,
mimeType: String,
write: (outputStream: OutputStream) -> Unit
): Boolean = try {
openExternalOutputStream(context, fileName, mimeType).use { write(it) }
openExternalOutputStream(fileName, mimeType).use { write(it) }
true
} catch (e: IOException) {
} catch (_: IOException) {
false
}
private fun openExternalOutputStream(
context: Context,
private fun Context.openExternalOutputStream(
fileName: String,
mimeType: String
): OutputStream = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
@Suppress("DEPRECATION")
val file = File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS
@@ -75,7 +72,7 @@ private fun openExternalOutputStream(
}
FileOutputStream(file)
} else {
val resolver = context.contentResolver
val resolver = contentResolver
val uri = resolver.insert(
MediaStore.Downloads.EXTERNAL_CONTENT_URI,
ContentValues().apply {
@@ -0,0 +1,41 @@
package de.markusfisch.android.binaryeye.media
import android.media.AudioManager
import android.media.ToneGenerator
import de.markusfisch.android.binaryeye.app.prefs
private var confirmToneGenerator: ToneGenerator? = null
private var confirmToneStream = AudioManager.STREAM_MUSIC
private var errorToneGenerator: ToneGenerator? = null
fun beepConfirm() {
val stream = prefs.beepStream()
val tg = if (confirmToneGenerator == null || confirmToneStream != stream) {
confirmToneGenerator?.release()
ToneGenerator(stream, ToneGenerator.MAX_VOLUME).also {
confirmToneGenerator = it
confirmToneStream = stream
}
} else {
confirmToneGenerator!!
}
confirmToneGenerator = tg
tg.startTone(prefs.beepTone())
}
fun beepError() {
val tg = errorToneGenerator ?: ToneGenerator(
AudioManager.STREAM_ALARM,
ToneGenerator.MAX_VOLUME
)
errorToneGenerator = tg
tg.startTone(ToneGenerator.TONE_SUP_ERROR, 1000)
}
fun releaseToneGenerators() {
confirmToneGenerator?.release()
confirmToneGenerator = null
confirmToneStream = AudioManager.STREAM_MUSIC
errorToneGenerator?.release()
errorToneGenerator = null
}
@@ -0,0 +1,30 @@
package de.markusfisch.android.binaryeye.net
import android.net.Uri
private const val SCHEME = "binaryeye"
private const val HOSTNAME = "markusfisch.de"
private const val ENCODE_PATH = "encode"
fun isScanDeeplink(text: String) = listOf(
"$SCHEME://scan",
"http://$HOSTNAME/BinaryEye",
"https://$HOSTNAME/BinaryEye"
).any { text.startsWith(it) }
fun isEncodeDeeplink(text: String) = listOf(
"$SCHEME://$ENCODE_PATH",
"http://$HOSTNAME/$ENCODE_PATH",
"https://$HOSTNAME/$ENCODE_PATH"
).any { text.startsWith(it) }
fun createEncodeDeeplink(format: String, content: String): String {
return Uri.Builder()
.scheme("https")
.authority(HOSTNAME)
.appendPath(ENCODE_PATH)
.appendQueryParameter("format", format)
.appendQueryParameter("content", content)
.build()
.toString()
}
@@ -1,6 +1,5 @@
package de.markusfisch.android.binaryeye.net
import de.markusfisch.android.binaryeye.app.toHexString
import de.markusfisch.android.binaryeye.database.Scan
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@@ -14,9 +13,12 @@ import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.ProtocolException
import java.net.URL
import java.net.URLEncoder
fun Scan.sendAsync(url: String, type: String, callback: (Int?, String?) -> Unit) {
fun Scan.sendAsync(
url: String,
type: String,
callback: (Int?, String?) -> Unit
) {
CoroutineScope(Dispatchers.IO).launch(Dispatchers.IO) {
val response = send(url, type)
withContext(Dispatchers.Main) {
@@ -30,14 +32,19 @@ private fun Scan.send(url: String, type: String): Response {
"1" -> request(
url + "?" + asUrlArguments()
)
"2" -> request(url) { con ->
con.requestMethod = "POST"
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
con.setRequestProperty(
"Content-Type",
"application/x-www-form-urlencoded"
)
con.outputStream.apply {
write(asUrlArguments().toByteArray())
close()
}
}
"3" -> request(url) { con ->
con.requestMethod = "POST"
con.setRequestProperty("Content-Type", "application/json")
@@ -46,35 +53,35 @@ private fun Scan.send(url: String, type: String): Response {
close()
}
}
else -> request(
url + urlEncode(content)
url + text.urlEncode()
)
}
}
private fun Scan.asUrlArguments(): String = getMap().map { (k, v) ->
"${k}=${urlEncode(v)}"
"${k}=${v.urlEncode()}"
}.joinToString("&")
private fun Scan.asJson() = JSONObject().apply {
getMap().forEach { (k, v) -> put(k, v) }
}
private fun urlEncode(s: String) = URLEncoder.encode(s, "utf-8")
private fun Scan.getMap(): Map<String, String> = mapOf(
"content" to content,
"content" to text,
"raw" to raw?.toHexString(),
"format" to format,
"format" to format.name,
"errorCorrectionLevel" to errorCorrectionLevel,
"version" to version,
"sequenceSize" to sequenceSize.toString(),
"sequenceIndex" to sequenceIndex.toString(),
"sequenceId" to sequenceId,
"country" to country,
"addOn" to addOn,
"price" to price,
"issueNumber" to issueNumber,
"orientation" to orientation,
"otherMetaData" to otherMetaData,
"pdf417ExtraMetaData" to pdf417ExtraMetaData,
"possibleCountry" to possibleCountry,
"suggestedPrice" to suggestedPrice,
"upcEanExtension" to upcEanExtension,
"timestamp" to timestamp
"timestamp" to dateTime
).filterNullValues()
private fun Map<String, String?>.filterNullValues() =
@@ -0,0 +1,10 @@
package de.markusfisch.android.binaryeye.net
import java.io.UnsupportedEncodingException
import java.net.URLEncoder
fun String.urlEncode(): String = try {
URLEncoder.encode(this, "UTF-8")
} catch (_: UnsupportedEncodingException) {
this
}
@@ -0,0 +1,24 @@
package de.markusfisch.android.binaryeye.os
import android.app.Activity
import android.view.WindowManager
fun Activity.getScreenBrightness(): Float {
val layoutParams = window.attributes
return if (layoutParams.screenBrightness ==
WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE
) {
android.provider.Settings.System.getInt(
contentResolver,
android.provider.Settings.System.SCREEN_BRIGHTNESS
) / 255.0f
} else {
layoutParams.screenBrightness
}
}
fun Activity.setScreenBrightness(brightness: Float) {
val layoutParams = window.attributes
layoutParams.screenBrightness = brightness
window.attributes = layoutParams
}
@@ -1,11 +1,13 @@
package de.markusfisch.android.binaryeye.os
import android.content.Context
import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import de.markusfisch.android.binaryeye.app.prefs
private const val MILLISECONDS = 100L
private const val DURATION_IN_MS = 250L
private val beforeO = Build.VERSION.SDK_INT < Build.VERSION_CODES.O
private val errorPatternTimings = longArrayOf(
50L, 100L, 50L, 100L, 50L
)
@@ -13,17 +15,35 @@ private val errorPatternAmplitudes = intArrayOf(
255, 0, 255, 0, 255
)
// On SDK 31 and better, we should ask the `VIBRATOR_MANAGER_SERVICE`
// for the default vibrator. This was implemented here before:
/*fun Context.getVibrator(): Vibrator = if (
Build.VERSION.SDK_INT < Build.VERSION_CODES.S
) {
@Suppress("DEPRECATION")
getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
} else {
(getSystemService(
Context.VIBRATOR_MANAGER_SERVICE
) as VibratorManager).defaultVibrator
}*/
// But for reasons beyond my interests, using `VIBRATOR_MANAGER_SERVICE`
// leads to a very cryptic `java.lang.VerifyError: r0/b` on Android 4.
// This is probably a Proguard/R8 issue, but I don't want to waste more
// time just to get rid of the deprecation warning. So let's use the old
// `VIBRATOR_SERVICE` and wait for Google to fix their stuff.
fun Context.getVibrator(): Vibrator = getSystemService(
Context.VIBRATOR_SERVICE
) as Vibrator
fun Vibrator.vibrate() {
if (!prefs.vibrate) {
return
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
if (beforeO) {
@Suppress("DEPRECATION")
vibrate(MILLISECONDS)
vibrate(DURATION_IN_MS)
} else {
vibrate(
VibrationEffect.createOneShot(
MILLISECONDS,
DURATION_IN_MS,
VibrationEffect.DEFAULT_AMPLITUDE
)
)
@@ -31,10 +51,7 @@ fun Vibrator.vibrate() {
}
fun Vibrator.error() {
if (!prefs.vibrate) {
return
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
if (beforeO) {
@Suppress("DEPRECATION")
vibrate(errorPatternTimings, -1)
} else {
@@ -0,0 +1,49 @@
package de.markusfisch.android.binaryeye.preference
import android.content.SharedPreferences
import android.graphics.Point
import androidx.core.content.edit
import org.json.JSONObject
fun SharedPreferences.storeCropHandle(
name: String,
viewWidth: Int,
viewHeight: Int,
cropHandle: Point
) {
edit {
putString(
cropHandleKey(name, viewWidth, viewHeight),
JSONObject().apply {
put("x", cropHandle.x)
put("y", cropHandle.y)
}.toString()
)
}
}
fun SharedPreferences.restoreCropHandle(
name: String,
viewWidth: Int,
viewHeight: Int,
default: Point = Point(-2, -2) // -2 means set default roi.
): Point {
val s = getString(
cropHandleKey(name, viewWidth, viewHeight), null
) ?: return default
return try {
val json = JSONObject(s)
Point(
json.getInt("x"),
json.getInt("y")
)
} catch (_: Exception) {
return default
}
}
private fun cropHandleKey(
name: String,
viewWidth: Int,
viewHeight: Int
) = "${name}:${viewWidth}:${viewHeight}"

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