Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cb48544896 | ||
|
|
10ceb4ac4e | ||
|
|
a48f67ebd5 | ||
|
|
328d0d704c | ||
|
|
dcecec4d6f | ||
|
|
7546cf25c0 | ||
|
|
bedb0a81d6 | ||
|
|
658988525a | ||
|
|
8298ce70ef | ||
|
|
ae29a4d207 | ||
|
|
7fe8126703 | ||
|
|
4adce7c958 | ||
|
|
d11dac7f13 | ||
|
|
f90aaac4f9 | ||
|
|
d5ffcabdd2 | ||
|
|
52ca14c9ba | ||
|
|
6c2c7bef90 | ||
|
|
f285e1d200 | ||
|
|
d7e687871c | ||
|
|
5472993e19 | ||
|
|
702dc75ddd | ||
|
|
45054c80f8 | ||
|
|
5a899b5eb3 | ||
|
|
1d002b645d | ||
|
|
456da10f84 | ||
|
|
7fbf89380c | ||
|
|
91a549e96e | ||
|
|
3ef6f874b8 | ||
|
|
45661b75ba | ||
|
|
cd30a86c69 | ||
|
|
13eabaee19 | ||
|
|
2035c935dc | ||
|
|
1ff170a279 | ||
|
|
4fab21c88d | ||
|
|
1ef9f39978 | ||
|
|
5378e50fe9 | ||
|
|
c325713a8c | ||
|
|
a043fba948 | ||
|
|
386f882944 | ||
|
|
65979cbddd | ||
|
|
26747d709f | ||
|
|
22b6a9f66e | ||
|
|
ded532c523 | ||
|
|
17c49a4a27 | ||
|
|
7ff8db0880 | ||
|
|
d7837f5795 | ||
|
|
1f5c77e802 | ||
|
|
a4da488a41 | ||
|
|
d177c08420 | ||
|
|
a6123ed233 | ||
|
|
2ebb376a8b | ||
|
|
6cac7e8ead | ||
|
|
59f6c9f654 | ||
|
|
f0c1d2a936 | ||
|
|
e7aff150f6 | ||
|
|
10755555ff | ||
|
|
a78a85df2c | ||
|
|
de9c490429 | ||
|
|
77e686af75 | ||
|
|
0ae13f22b6 | ||
|
|
bedfcdec14 | ||
|
|
a6ba968ea8 | ||
|
|
5301da5900 | ||
|
|
cb7d64991b | ||
|
|
6194dc29d5 | ||
|
|
3fa39b9fe0 | ||
|
|
f37b846241 | ||
|
|
8ce33c0071 | ||
|
|
e6823386b0 | ||
|
|
3e57a59e16 | ||
|
|
758220200e | ||
|
|
b3584392b3 | ||
|
|
3bb26f06d1 | ||
|
|
fe4a021cd0 | ||
|
|
0de5565b78 | ||
|
|
d9a9acd8c1 | ||
|
|
1be31f71ed | ||
|
|
8859c61119 | ||
|
|
c52778f59d | ||
|
|
5bde3947e3 | ||
|
|
08be31814f | ||
|
|
c5db04b84e | ||
|
|
9dccc6a7f5 | ||
|
|
a5deab656b | ||
|
|
b773dfa392 | ||
|
|
7b5106f09d | ||
|
|
16ce45093e | ||
|
|
e6345f09b3 | ||
|
|
de00ed779a | ||
|
|
d740aa121b | ||
|
|
38c40d36bb | ||
|
|
3e51f70c7c | ||
|
|
502702c7a5 | ||
|
|
96ff9b6239 | ||
|
|
afd6c74c80 | ||
|
|
5ffea2edd8 | ||
|
|
78d62395e2 | ||
|
|
a5d1465528 | ||
|
|
14517bad17 | ||
|
|
7a5e07fb3c | ||
|
|
c6b3ca08f4 | ||
|
|
73047cdee6 | ||
|
|
bec4aa3120 | ||
|
|
eaaaaf14c2 | ||
|
|
971742aff4 | ||
|
|
28915eacdb | ||
|
|
a2c1d11b5b | ||
|
|
e9dd396f34 | ||
|
|
c7edba746c | ||
|
|
34c8dfd169 | ||
|
|
459980899f | ||
|
|
2e0693cb45 | ||
|
|
187825932e | ||
|
|
a80802b4bc | ||
|
|
aa589a5d53 | ||
|
|
6a42e54f0b | ||
|
|
e134b18bba | ||
|
|
a112484dcb | ||
|
|
4f36030e38 | ||
|
|
90c2c03d12 | ||
|
|
3f853be51a | ||
|
|
835a348fad | ||
|
|
198a35fc15 | ||
|
|
6be1b25c38 | ||
|
|
ac632e3aac | ||
|
|
ddc5a14558 | ||
|
|
8b1ffe3e5a | ||
|
|
e9ba66848f | ||
|
|
7bdef27a50 | ||
|
|
ccd16a0f95 | ||
|
|
a385678de1 | ||
|
|
43c597f6fb | ||
|
|
ecccf34418 | ||
|
|
4027ce2cc6 | ||
|
|
209e6c5c30 | ||
|
|
5e29f3fbe9 | ||
|
|
ba3d63277a | ||
|
|
fe34b7209d | ||
|
|
0efdca7b4a | ||
|
|
827fbedc1f | ||
|
|
107b5bafd4 | ||
|
|
19a71480fa | ||
|
|
909e97a591 | ||
|
|
bc2be96871 | ||
|
|
d834621d99 | ||
|
|
ad83be1a60 | ||
|
|
d65ea02b49 | ||
|
|
c8d1357ceb | ||
|
|
4c05d046e6 | ||
|
|
4423ee62c8 | ||
|
|
bc69f99f8b | ||
|
|
6b088031fd | ||
|
|
b27d03e9c0 | ||
|
|
9a13838f28 | ||
|
|
cce2a460f6 | ||
|
|
36352ecde2 | ||
|
|
9a0bc324cb | ||
|
|
6dabafd6a3 | ||
|
|
dde4b1e0bd | ||
|
|
8a8c7bd1ff | ||
|
|
a2aed42e25 | ||
|
|
a38b7b647f | ||
|
|
76e82ed842 | ||
|
|
fd54bc604e | ||
|
|
59b62ecbc4 | ||
|
|
de6a2863f3 | ||
|
|
4b2eb80612 | ||
|
|
2de40d2277 | ||
|
|
7673b7cb0d | ||
|
|
097c5e4453 | ||
|
|
1fab30089e | ||
|
|
f9bf16dd47 | ||
|
|
7a59126312 | ||
|
|
694c854650 | ||
|
|
b1cd12ec77 | ||
|
|
0c27b15025 | ||
|
|
5de950bdbf | ||
|
|
ae9e304ef6 | ||
|
|
c4cc14554b | ||
|
|
d6afccf562 | ||
|
|
a90bdad117 | ||
|
|
52d4f082f2 | ||
|
|
1c63f5b3ac | ||
|
|
21985b4533 | ||
|
|
012ac644aa | ||
|
|
19f19739fd | ||
|
|
f01f9fcd91 | ||
|
|
4177b248c3 | ||
|
|
e4182a265b | ||
|
|
98df5a447c | ||
|
|
a0a1405359 | ||
|
|
76922c421c | ||
|
|
cac9dd16da | ||
|
|
a1f9ba1056 | ||
|
|
0b67c272b6 | ||
|
|
9b8be5305d | ||
|
|
a026ade13b | ||
|
|
b1771bc5ea | ||
|
|
5199460669 | ||
|
|
fd040e1660 | ||
|
|
2e1528364e | ||
|
|
d21af142bb | ||
|
|
8395e135f9 | ||
|
|
c0caa0ce44 | ||
|
|
96927ef9b2 | ||
|
|
84d9a3b55a | ||
|
|
ffe8e4c5ba | ||
|
|
bc7c5dca97 | ||
|
|
d9737f4df1 | ||
|
|
0e8147713a | ||
|
|
3d425a097a | ||
|
|
c26765cc63 | ||
|
|
fb6dc8ba55 | ||
|
|
70f4d166a0 | ||
|
|
6c136ce719 | ||
|
|
c6dee80c0a | ||
|
|
1f43dd4827 | ||
|
|
a366157977 | ||
|
|
6bb72672a3 | ||
|
|
04774527a0 | ||
|
|
6f3e644aa8 | ||
|
|
5e3176b703 | ||
|
|
0f0aaff284 | ||
|
|
f0d09e81b4 | ||
|
|
771258cb5c | ||
|
|
9482086666 | ||
|
|
bcad50c3e8 | ||
|
|
dbd055699e | ||
|
|
d67f8273d6 | ||
|
|
649be0ceb6 | ||
|
|
f5eb5dd8d2 | ||
|
|
eb805dad2f | ||
|
|
202bb32b29 | ||
|
|
50b8a4d329 | ||
|
|
fa15478fb4 | ||
|
|
20c2a5a8aa | ||
|
|
00b95678ed | ||
|
|
5df3517563 | ||
|
|
fd6946d2c2 | ||
|
|
c74d229e1f | ||
|
|
fa99a19db5 | ||
|
|
b083fcf213 | ||
|
|
46930ddea6 | ||
|
|
7bef77b96e | ||
|
|
c5f4c088b4 | ||
|
|
73f7210e18 | ||
|
|
469429e663 | ||
|
|
1a7ac59740 | ||
|
|
c13c59e728 | ||
|
|
bc17e25717 | ||
|
|
5017bd4c8d | ||
|
|
a44a913eca | ||
|
|
007e83e243 | ||
|
|
de8f97c246 | ||
|
|
1287591e53 | ||
|
|
8c17238572 | ||
|
|
5dbb36e6a9 | ||
|
|
ca7dfb3a33 | ||
|
|
419b7d5765 | ||
|
|
fa38866669 | ||
|
|
19ca521f59 | ||
|
|
be657d86cf | ||
|
|
5199a4a526 | ||
|
|
ff48a543c9 | ||
|
|
2eadd01a87 | ||
|
|
dd2abe7d89 | ||
|
|
8e05caac70 | ||
|
|
46aeced09f | ||
|
|
3681c5d011 | ||
|
|
20b4f7aac5 | ||
|
|
bc6e350271 | ||
|
|
c9c1b2f5bf | ||
|
|
1dbc0f0fa1 | ||
|
|
ab8170ee72 | ||
|
|
551464dc6f | ||
|
|
c3aac0a1e1 | ||
|
|
d678e1cfd0 | ||
|
|
a445ade877 | ||
|
|
1fd0b7637f | ||
|
|
fdc88df897 | ||
|
|
d0f133ae00 | ||
|
|
67646261e7 | ||
|
|
faeae9e904 | ||
|
|
77b21a9e83 | ||
|
|
cbe7860a3d | ||
|
|
fc29267d3d | ||
|
|
890506328b | ||
|
|
04036b6cd6 | ||
|
|
2602021c1c | ||
|
|
17a0bdc0a9 | ||
|
|
d71a220eca | ||
|
|
0c2e711d79 | ||
|
|
ca342a83d3 | ||
|
|
3c44ff56eb | ||
|
|
bcae64c0d0 | ||
|
|
c2f673729b | ||
|
|
2043e0f349 | ||
|
|
b93eb5963e | ||
|
|
5189fc9c5a | ||
|
|
2d311ff92a | ||
|
|
14bb08003d | ||
|
|
42f9887030 | ||
|
|
a59d241b50 | ||
|
|
9f31160c7b | ||
|
|
2eb4e51c17 | ||
|
|
53a554e7a2 | ||
|
|
7f6887716a | ||
|
|
5ef93802ce | ||
|
|
c1eff08bb9 | ||
|
|
8798d44ec7 | ||
|
|
d4e31ff97e | ||
|
|
ae8b08a85a | ||
|
|
09430d776e | ||
|
|
ef88c3179d | ||
|
|
c732ec726b | ||
|
|
801c768df4 | ||
|
|
552a2f6d57 | ||
|
|
7fa8810197 | ||
|
|
254af25bbb | ||
|
|
a27656c174 | ||
|
|
2ca55ebccc | ||
|
|
ec1d40942d | ||
|
|
7852e5ce9d | ||
|
|
f36a81d4a0 | ||
|
|
d86ea4073c | ||
|
|
a69530621d | ||
|
|
3c0f29a768 | ||
|
|
ccf5157fa7 | ||
|
|
c1ebb1c154 | ||
|
|
a4778bcc02 | ||
|
|
24d2c6d8d6 | ||
|
|
0f3a07f602 | ||
|
|
751d8932f8 | ||
|
|
9c2d063c24 | ||
|
|
0f9bbf5b2f | ||
|
|
530280981e | ||
|
|
ddfbb305c7 | ||
|
|
8d1a29922b | ||
|
|
c710f7c6ab | ||
|
|
111c587eef | ||
|
|
264e494487 | ||
|
|
8135b2a3dc | ||
|
|
dce62b70d3 | ||
|
|
533812c638 | ||
|
|
5dc5bed281 | ||
|
|
2a13561962 | ||
|
|
1476f41cda | ||
|
|
0da1ffbe02 | ||
|
|
980679b6a3 | ||
|
|
28cbb55299 | ||
|
|
1a4e7d100a | ||
|
|
265e43b439 | ||
|
|
03a58c3412 | ||
|
|
327cad48f0 | ||
|
|
8e64fe2f56 | ||
|
|
368d4dbb66 | ||
|
|
c8c3c094db | ||
|
|
aa4aefe35f | ||
|
|
536b3d77c1 | ||
|
|
bbf2a80981 | ||
|
|
ae99214d6c | ||
|
|
73b5a0969c | ||
|
|
bf5dc96ac9 | ||
|
|
301d9c2513 | ||
|
|
0a11611b8f | ||
|
|
249e310e43 | ||
|
|
6279c5731a | ||
|
|
df98637951 | ||
|
|
08b3558e46 | ||
|
|
648ef6fdf8 | ||
|
|
807f075a51 | ||
|
|
27789beeed | ||
|
|
97bee27827 | ||
|
|
3fee49301e | ||
|
|
8a6073291b | ||
|
|
47151de4a4 | ||
|
|
248c4edca1 | ||
|
|
2c7386d536 | ||
|
|
e19cad4c87 | ||
|
|
585e0f3372 | ||
|
|
2b7f611774 | ||
|
|
05b2a0d9c9 | ||
|
|
e7287eb088 | ||
|
|
4b45ad3fe7 | ||
|
|
449d8fdbbd | ||
|
|
f44cff9912 | ||
|
|
24730dfde3 | ||
|
|
be6539d41f | ||
|
|
60dd40554e | ||
|
|
837119b6ec | ||
|
|
abe11b82e5 | ||
|
|
4fc1e36d04 | ||
|
|
54aa15e1be | ||
|
|
876d8fc7b3 | ||
|
|
7bdcdaaa5d | ||
|
|
fd44728e89 | ||
|
|
8242520a0b | ||
|
|
2e7e9a942b | ||
|
|
dcc9d5b3ff | ||
|
|
607aab854c | ||
|
|
cc2b2f076b | ||
|
|
90e9723de5 | ||
|
|
ab6787e60b | ||
|
|
698686a45a | ||
|
|
95bdaa1252 | ||
|
|
f0c02e5156 | ||
|
|
a8c50308d0 | ||
|
|
6b359d4c65 | ||
|
|
863caed387 | ||
|
|
e4f17b9bdf | ||
|
|
c2071d8d81 | ||
|
|
4758c2d337 | ||
|
|
91336fe15c | ||
|
|
2c437f3771 | ||
|
|
cb082b20fe | ||
|
|
bce3630686 | ||
|
|
4feb4d066c | ||
|
|
e7d84cd916 | ||
|
|
84e2917694 | ||
|
|
b87464ec40 | ||
|
|
269e0f41a6 | ||
|
|
aefbc4a296 | ||
|
|
c64984dc6a | ||
|
|
24c7ad0ba4 | ||
|
|
643a935852 | ||
|
|
4fcb836b53 | ||
|
|
48ed5f1a2c | ||
|
|
3aa2371eeb | ||
|
|
88f92943c0 | ||
|
|
39710d4ab9 | ||
|
|
93f7cd3cb8 | ||
|
|
69baa3b824 | ||
|
|
bb05e38278 | ||
|
|
554f5a5e73 | ||
|
|
2dcf7772f2 | ||
|
|
3c7012e3c4 | ||
|
|
08e11c3c40 | ||
|
|
31854dab0c | ||
|
|
4f12c3e270 | ||
|
|
3ec43dabce | ||
|
|
0d4f536f71 | ||
|
|
b064a293fb | ||
|
|
d124c29919 | ||
|
|
2e89f1530a | ||
|
|
ef7e2a4b0d | ||
|
|
f680533819 | ||
|
|
a8c977c40e | ||
|
|
1e89b22953 | ||
|
|
11f028e0f3 | ||
|
|
1f7f4a23b5 | ||
|
|
41581d07ec | ||
|
|
dc819a6e1a | ||
|
|
5b51072f1a | ||
|
|
1b10e82cb2 | ||
|
|
eeae1eb0ad | ||
|
|
21c29ca373 | ||
|
|
8bcb72e91b | ||
|
|
8f345fbfbe | ||
|
|
2c88dbca02 | ||
|
|
bd1c629c85 | ||
|
|
f89e6612c4 | ||
|
|
7a0cd0ce19 | ||
|
|
8544affa1e | ||
|
|
48d3588341 | ||
|
|
783f6e4892 | ||
|
|
032cd64daf | ||
|
|
96626e6b00 | ||
|
|
11ae65ec3e | ||
|
|
91e3acb647 | ||
|
|
40c2f5947b | ||
|
|
58b9466cfc | ||
|
|
12210e1768 | ||
|
|
ad2ac457c9 | ||
|
|
634b6e8d2b | ||
|
|
6dd47f4dd0 | ||
|
|
8426f66cfb | ||
|
|
3dfa84a33e | ||
|
|
38f658e253 | ||
|
|
287d99e2b4 | ||
|
|
5cfcde9d4a | ||
|
|
b2730259fc | ||
|
|
61a2d3023c | ||
|
|
239ac7bd1a | ||
|
|
4048314cf7 | ||
|
|
3dbd772847 | ||
|
|
3a08465c35 | ||
|
|
92e3669ee5 | ||
|
|
8b297f4768 | ||
|
|
42b7f1179b | ||
|
|
9d6854c282 | ||
|
|
d943b7deff | ||
|
|
a138da9d9b | ||
|
|
194338a0d2 | ||
|
|
7eb8fdcce1 | ||
|
|
2bf1796340 | ||
|
|
cc42015da2 | ||
|
|
648c39c439 | ||
|
|
8c25b05cda | ||
|
|
780bebc9d1 | ||
|
|
bf7eb7efd5 | ||
|
|
d00d08bae3 | ||
|
|
379256a7fe | ||
|
|
180339269f | ||
|
|
49af17cba8 | ||
|
|
a03a187d2d | ||
|
|
84806e70d7 | ||
|
|
058de5a141 | ||
|
|
d330fbd195 | ||
|
|
f5bc6f664f | ||
|
|
464279807c | ||
|
|
f7e5ef473a | ||
|
|
ff733ef59e | ||
|
|
35b110a472 | ||
|
|
58eabf4754 | ||
|
|
1f273a48a5 | ||
|
|
785a64725d | ||
|
|
7a42e1de73 | ||
|
|
9856ab7b6b | ||
|
|
746ff143d8 | ||
|
|
b0d4d94973 | ||
|
|
c604ad5ef2 | ||
|
|
91c2b324ac | ||
|
|
df59fd7446 | ||
|
|
449fd1f26c | ||
|
|
72d839c6e2 | ||
|
|
ab8c993a81 | ||
|
|
5f5bd913d6 | ||
|
|
92fe4dd55f | ||
|
|
dab95176f0 | ||
|
|
650503ba70 | ||
|
|
61078f214e | ||
|
|
a4b639edfe | ||
|
|
f37878dbb8 | ||
|
|
10fde7c3d6 | ||
|
|
a098fcb48c | ||
|
|
f162977640 | ||
|
|
66cab58d7b | ||
|
|
e99e2d7dcc | ||
|
|
9045a27a5d | ||
|
|
9e1208c72b | ||
|
|
90410f232a | ||
|
|
6769fa7e37 | ||
|
|
72444f5081 | ||
|
|
9a3ca4ffa3 | ||
|
|
f572923720 | ||
|
|
4971f58f44 | ||
|
|
0bf24080a8 | ||
|
|
04a21f71ef | ||
|
|
e22a215863 | ||
|
|
881829e7b2 | ||
|
|
2ad261f3b6 | ||
|
|
e0fdda78b3 | ||
|
|
9c3710c56d | ||
|
|
ddcab46d47 | ||
|
|
076da26075 | ||
|
|
dbc37714f9 | ||
|
|
50e57eaf25 | ||
|
|
340f7f9d1d | ||
|
|
a42bd793bb | ||
|
|
6e531f5395 | ||
|
|
79b3fddcf8 | ||
|
|
09f3c8f193 | ||
|
|
5f82f216fd | ||
|
|
8424e3ea31 | ||
|
|
15ce34aa92 | ||
|
|
8dfc1e37c0 | ||
|
|
a0d3b7ba87 | ||
|
|
a234dc3a9a | ||
|
|
a00f70e25b | ||
|
|
ef555c0153 | ||
|
|
9fffb53f73 | ||
|
|
b82c6200c0 | ||
|
|
5bb347c392 | ||
|
|
f8033614fa | ||
|
|
46cc2fb1a1 | ||
|
|
f2ac1e77bb | ||
|
|
89c84880c6 | ||
|
|
352fe07850 | ||
|
|
00abe33314 | ||
|
|
142df25d7e | ||
|
|
021d775835 | ||
|
|
06df0c4d64 | ||
|
|
32c70af812 | ||
|
|
7cc1777e7a | ||
|
|
23e0564594 | ||
|
|
0447384bea | ||
|
|
b4d66e28e2 | ||
|
|
ee1c56d99f | ||
|
|
33ef78443e | ||
|
|
9f1e34b06d | ||
|
|
24766f55d4 | ||
|
|
0ae7d080e3 | ||
|
|
7d8c6016db | ||
|
|
3d923035e3 | ||
|
|
a489f3aa22 | ||
|
|
7dfd7a1303 | ||
|
|
9abc01fc4f | ||
|
|
d10a33c1b7 | ||
|
|
357b2b5d59 | ||
|
|
dfd64405da | ||
|
|
045daf9deb | ||
|
|
46b9ef516c | ||
|
|
0265909fd7 | ||
|
|
ceef92bb7c | ||
|
|
46785bab01 | ||
|
|
ccbb0f9e8a | ||
|
|
833d8e93d3 | ||
|
|
6dff9992d8 | ||
|
|
0b3dfe93cf | ||
|
|
e79ad49d15 | ||
|
|
38f7ba1ec6 | ||
|
|
4d268240fd | ||
|
|
1131f749a9 | ||
|
|
93a3cd2620 | ||
|
|
a866a2eab3 | ||
|
|
c5d6bfa4b2 | ||
|
|
6a63bc4e06 | ||
|
|
09ff334c4c | ||
|
|
45a2ac0647 | ||
|
|
425f3a7b80 | ||
|
|
f895b42cfe | ||
|
|
ecd4c487e3 | ||
|
|
750671c408 | ||
|
|
ead856221f | ||
|
|
34f14d0ff0 | ||
|
|
1b21297d83 | ||
|
|
53cb6fe007 | ||
|
|
f1daa19056 | ||
|
|
bd9da5889c | ||
|
|
d5949e557a | ||
|
|
51079e5208 | ||
|
|
09f3368bf0 | ||
|
|
84e03e3cc8 | ||
|
|
cff299771a | ||
|
|
7a327ab7c4 | ||
|
|
72b8924574 | ||
|
|
527b7a6a59 | ||
|
|
e9267e4e5a | ||
|
|
ac18733368 | ||
|
|
300c3bfd26 | ||
|
|
6449d9962d | ||
|
|
12554e63e2 | ||
|
|
af60ee6edb | ||
|
|
fe31fc6df2 | ||
|
|
6d4f3cafbf | ||
|
|
fa23b8078c | ||
|
|
e3c0fe8857 | ||
|
|
fa568686b6 | ||
|
|
304357b43c | ||
|
|
1e76b14038 | ||
|
|
d0777350a2 | ||
|
|
c7c1e74240 | ||
|
|
c793e1399b | ||
|
|
c550a6ff51 | ||
|
|
05b0f719e0 | ||
|
|
4326df5069 | ||
|
|
ba24287f04 | ||
|
|
bd8f1b17dd | ||
|
|
2c21aeb83a | ||
|
|
9ccff808bc | ||
|
|
32e936dd71 | ||
|
|
58eebacd4f | ||
|
|
75b945e842 | ||
|
|
a9ea77f74f | ||
|
|
3df658165b | ||
|
|
40a6a77b8d | ||
|
|
301a33a176 | ||
|
|
8d6623786c | ||
|
|
a225eab6f2 | ||
|
|
9f2efeb001 | ||
|
|
105c81d409 | ||
|
|
4e1eb28ca4 | ||
|
|
b72ed746bf | ||
|
|
1aaee3c85a | ||
|
|
eb0218e733 | ||
|
|
bef7365f28 | ||
|
|
c72b6a2e5f | ||
|
|
a7e358852c | ||
|
|
7cf8cbe6d8 | ||
|
|
e379e55570 | ||
|
|
a55795a7b6 | ||
|
|
83c0cd0293 | ||
|
|
d138148cb8 | ||
|
|
c3c08879e0 | ||
|
|
d0f02faca7 | ||
|
|
c9db3514d1 | ||
|
|
f2a0e1a392 | ||
|
|
f4de041407 | ||
|
|
73ba2914e8 | ||
|
|
2907c8c49c | ||
|
|
f28f956a8d | ||
|
|
972eb6a0b0 | ||
|
|
08bb3f2127 | ||
|
|
b28e939f58 | ||
|
|
2edb8112b7 | ||
|
|
cf5a6dc8b8 | ||
|
|
3ec6f18fe0 | ||
|
|
3a8f6cb827 | ||
|
|
65c7fe52ee | ||
|
|
5d3b3eb195 | ||
|
|
0e4c2963a5 | ||
|
|
791c50cd4a | ||
|
|
c04b08ab87 | ||
|
|
f07c4ac0f4 | ||
|
|
05d63bd73f | ||
|
|
558fd5212d | ||
|
|
b918be76e4 | ||
|
|
2136a8c73e | ||
|
|
959c6e7d4d | ||
|
|
50930d07a6 | ||
|
|
36e7aab27c | ||
|
|
bb4fc8ed08 | ||
|
|
7a33ebd1a3 | ||
|
|
c8444b8935 | ||
|
|
4c6d66a4aa | ||
|
|
39f95a1c04 | ||
|
|
9e30b108e7 | ||
|
|
1b6b1cefe3 | ||
|
|
b634370a0b | ||
|
|
f32d44c3a1 | ||
|
|
2e060d1ca8 | ||
|
|
6acdce32f2 | ||
|
|
092ec694f6 | ||
|
|
7fed7877a0 | ||
|
|
b17393d5ef | ||
|
|
319ae53b3b | ||
|
|
6a47a7e477 | ||
|
|
19fb733182 | ||
|
|
ce6c6f26d2 | ||
|
|
3633af5e0a | ||
|
|
87502f7226 | ||
|
|
f4af35ad46 | ||
|
|
60f0d8bd87 | ||
|
|
1ccfcfcb8f | ||
|
|
213689e9f9 | ||
|
|
6e2f2cab92 | ||
|
|
4b3d745154 | ||
|
|
a2bcd67568 | ||
|
|
072eec5306 | ||
|
|
d505c6b07d | ||
|
|
dbfbaab030 | ||
|
|
3d1402add4 | ||
|
|
1d2bd8d778 | ||
|
|
2bb413e3e8 | ||
|
|
75a59bc3e9 | ||
|
|
9a15bf0871 | ||
|
|
53248fd23d |
@@ -1,5 +1,407 @@
|
||||
# Change Log
|
||||
|
||||
## 1.74.3
|
||||
* Fix layout for Material You
|
||||
|
||||
## 1.74.2
|
||||
* Fix layout for some Android versions
|
||||
|
||||
## 1.74.1
|
||||
* Allow scanning while device is locked
|
||||
* Fix rendering bug for some GPUs
|
||||
|
||||
## 1.74.0
|
||||
* Add an option to choose a custom beep tone
|
||||
* Add an option to set a custom scanner ID
|
||||
* Improve display of content type
|
||||
* Support fido:/ URIs
|
||||
* Update Italian and French translations
|
||||
* Update ZXingCpp
|
||||
* Fix FAB and crop handle positioning
|
||||
* Fix splash screen for some Android versions
|
||||
|
||||
## 1.73.1
|
||||
* Update ZXingCpp and support Telepen format
|
||||
* Update vdstools
|
||||
* Fix stale history row highlighting
|
||||
|
||||
## 1.73.0
|
||||
* Support Material You and Dynamic Colors
|
||||
* Strip common tracking parameters before opening scanned URLs
|
||||
* Parse and display otpauth:// code fields
|
||||
* Update Italian and Latvian language
|
||||
* Update BouncyCastle and vdstools library
|
||||
* Fix deeplink argument parsing
|
||||
|
||||
## 1.72.2
|
||||
* Import/export preferences using QR codes
|
||||
* Add predefined expert and simple profiles
|
||||
* Update ZXingCpp library
|
||||
* Fix beeping on scans
|
||||
|
||||
## 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
|
||||
|
||||
@@ -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/
|
||||
|
||||
@@ -5,10 +5,10 @@ all: debug install start
|
||||
debug:
|
||||
./gradlew assembleDebug
|
||||
|
||||
release: lint
|
||||
release: lint test
|
||||
./gradlew assembleRelease
|
||||
|
||||
bundle: lint
|
||||
bundle: lint test
|
||||
./gradlew bundleRelease
|
||||
|
||||
lint:
|
||||
@@ -20,9 +20,6 @@ infer: clean
|
||||
test:
|
||||
./gradlew test
|
||||
|
||||
cat:
|
||||
./gradlew test cAT
|
||||
|
||||
testview:
|
||||
adb shell am start -W -a android.intent.action.VIEW -d 'binaryeye://scan'
|
||||
|
||||
@@ -31,11 +28,36 @@ testscan:
|
||||
-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
|
||||
|
||||
|
||||
@@ -12,10 +12,17 @@ hesitate to contact me.
|
||||
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.
|
||||
|
||||
### [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]
|
||||
|
||||
@@ -46,15 +53,23 @@ which requires `CHANGE_WIFI_STATE`.
|
||||
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`.
|
||||
|
||||
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
|
||||
[configuredNetworks]: https://developer.android.com/reference/android/net/wifi/WifiManager#getConfiguredNetworks()
|
||||
[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()
|
||||
|
||||
@@ -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> <a
|
||||
href="https://liberapay.com/markusfisch/" target="_blank"><img
|
||||
src="https://liberapay.com/assets/widgets/donate.svg"
|
||||
alt="Liberapay"
|
||||
style="height: 60px !important"/></a> <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,16 @@ 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]
|
||||
* [Telepen][telepen]
|
||||
* [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,14 +84,14 @@ ZXing can generate the following barcode formats:
|
||||
* [QR CODE][qr_code]
|
||||
* [UPC A][upc_a]
|
||||
|
||||
## Deep Links and Intents
|
||||
|
||||
### Deep Links
|
||||
## Deep Links
|
||||
|
||||
You can invoke Binary Eye with a web URI intent from anything that can
|
||||
open URIs. There are two options:
|
||||
open URIs.
|
||||
|
||||
1. [binaryeye://scan](binaryeye://scan)
|
||||
### Decoding
|
||||
|
||||
1. [binaryeye://scan](binaryeye://scan) (note: GitHub does not render this as clickable link)
|
||||
2. [http(s)://markusfisch.de/BinaryEye](http://markusfisch.de/BinaryEye)
|
||||
|
||||
If you want to get the scanned contents, you can add a `ret` query
|
||||
@@ -84,12 +104,33 @@ Supported symbols are:
|
||||
* `RESULT` - scanned content
|
||||
* `RESULT_BYTES` - raw result as a hex string
|
||||
* `FORMAT` - barcode format
|
||||
* `META` - the meta data, if available
|
||||
|
||||
### Encoding
|
||||
|
||||
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
|
||||
|
||||
You can also use Binary Eye from other apps by using the
|
||||
`com.google.zxing.client.android.SCAN` Intent with
|
||||
Use the `com.google.zxing.client.android.SCAN` `Intent` with
|
||||
[startActivityForResult()][start_activity] like this:
|
||||
|
||||
```kotlin
|
||||
@@ -121,10 +162,12 @@ If you're using AndroidX, this would be the new,
|
||||
[recommended way][intent_result]:
|
||||
|
||||
```kotlin
|
||||
class YourActivity : Activity() {
|
||||
private val resultLauncher = registerForActivityResult(StartActivityForResult()) { result ->
|
||||
if (result.resultCode == Activity.RESULT_OK) {
|
||||
val scan = result.data?.getStringExtra("SCAN_RESULT")
|
||||
class YourActivity : AppCompatActivity() {
|
||||
private val resultLauncher = registerForActivityResult(
|
||||
ActivityResultContracts.StartActivityForResult()
|
||||
) { result ->
|
||||
if (result.resultCode == RESULT_OK) {
|
||||
val content = result.data?.getStringExtra("SCAN_RESULT")
|
||||
…
|
||||
}
|
||||
}
|
||||
@@ -135,37 +178,23 @@ class YourActivity : Activity() {
|
||||
}
|
||||
```
|
||||
|
||||
## RenderScript
|
||||
## Forwarding scans via Bluetooth
|
||||
|
||||
This app uses [RenderScript][rs] to resize and rotate the camera image.
|
||||
Unfortunately, RenderScript has some nasty gotchas.
|
||||
**Note:** The companion apps aren't developed nor maintained by the
|
||||
author of Binary Eye.
|
||||
|
||||
### RenderScript.forceCompat()
|
||||
In order to set up Bluetooth forwarding to a computer:
|
||||
|
||||
It's necessary to call `RenderScript.forceCompat()` on some devices/roms.
|
||||
|
||||
`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 `RenderScript.forceCompat()` is necessary, a `RSRuntimeException` will
|
||||
be thrown and the only option is to restart the app, this time with calling
|
||||
`forceCompat()` first.
|
||||
|
||||
Calling `RenderScript.forceCompat()` means the processing is done in
|
||||
software so you probably don't want to enable it by default.
|
||||
|
||||
### 2D barcodes
|
||||
|
||||
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.
|
||||
|
||||
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. Pair your devices (phone and pc) if not paired already
|
||||
2. Download and run a companion app:
|
||||
- Windows: https://github.com/KamaleiZestri/BinaryReceptor
|
||||
- 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
|
||||
@@ -173,18 +202,23 @@ 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
|
||||
[telepen]: https://en.wikipedia.org/wiki/Telepen
|
||||
[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
|
||||
|
||||
@@ -1,27 +1,15 @@
|
||||
apply plugin: 'com.android.application'
|
||||
apply plugin: 'kotlin-android'
|
||||
|
||||
android {
|
||||
namespace 'de.markusfisch.android.binaryeye'
|
||||
compileSdkVersion sdk_version
|
||||
namespace "de.markusfisch.android.binaryeye"
|
||||
compileSdk sdk_version
|
||||
|
||||
defaultConfig {
|
||||
minSdkVersion 9
|
||||
targetSdkVersion sdk_version
|
||||
minSdk 21
|
||||
targetSdk sdk_version
|
||||
|
||||
versionCode 97
|
||||
versionName '1.50.0'
|
||||
|
||||
// Required for desugaring.
|
||||
multiDexEnabled true
|
||||
|
||||
// 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 174
|
||||
versionName '1.74.3'
|
||||
}
|
||||
|
||||
signingConfigs {
|
||||
@@ -46,13 +34,17 @@ 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.release
|
||||
}
|
||||
}
|
||||
|
||||
buildFeatures {
|
||||
buildConfig true
|
||||
}
|
||||
|
||||
bundle {
|
||||
language {
|
||||
// To make the app bundle contain all language resources
|
||||
@@ -65,38 +57,40 @@ android {
|
||||
}
|
||||
}
|
||||
|
||||
// Required since Gradle 8.
|
||||
compileOptions {
|
||||
// To desugar fancy Java features in ZXing 3.4.+ that don't
|
||||
// work on SDK < 24. See:
|
||||
// https://github.com/zxing/zxing/issues/1170
|
||||
coreLibraryDesugaringEnabled true
|
||||
}
|
||||
|
||||
lint {
|
||||
// Because at the time of writing, even the latest version
|
||||
// of RenderScript is raising this error no matter if
|
||||
// renderscriptTargetApi matches targetSdkVersion.
|
||||
disable 'GradleCompatible'
|
||||
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.13.2'
|
||||
|
||||
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'
|
||||
// Kotlin
|
||||
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
|
||||
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.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"
|
||||
implementation 'com.google.zxing:core:3.5.0'
|
||||
implementation 'com.github.markusfisch:CameraView:1.9.1'
|
||||
implementation 'com.github.markusfisch:ScalingImageView:1.3.0'
|
||||
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.11.0"
|
||||
implementation 'org.jetbrains.kotlinx:kotlinx-datetime:0.8.0'
|
||||
implementation "androidx.core:core-ktx:1.17.0" // Keep for minSDK 21.
|
||||
|
||||
// Support
|
||||
implementation "androidx.appcompat:appcompat:1.7.1"
|
||||
implementation "com.google.android.material:material:1.13.0" // Keep for minSDK 21.
|
||||
implementation "androidx.preference:preference:1.2.1"
|
||||
|
||||
// External
|
||||
var camerax_version = '1.4.2' // Keep for minSDK 21.
|
||||
implementation "androidx.camera:camera-core:$camerax_version"
|
||||
implementation "androidx.camera:camera-camera2:$camerax_version"
|
||||
implementation "androidx.camera:camera-lifecycle:$camerax_version"
|
||||
implementation "androidx.camera:camera-view:$camerax_version"
|
||||
implementation 'com.github.markusfisch:ScalingImageView:1.4.3'
|
||||
implementation 'com.github.markusfisch:zxing-cpp:v3.0.2.7'
|
||||
implementation 'de.tsenger:vdstools:0.17.0'
|
||||
implementation 'org.bouncycastle:bcpkix-jdk15to18:1.84'
|
||||
|
||||
// Testing
|
||||
testImplementation 'junit:junit:4.13.2'
|
||||
testImplementation 'org.robolectric:robolectric:4.16.1'
|
||||
|
||||
// Debugging
|
||||
debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.14'
|
||||
}
|
||||
|
||||
@@ -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.** { *; }
|
||||
|
||||
|
Before Width: | Height: | Size: 97 KiB |
|
Before Width: | Height: | Size: 79 KiB |
|
Before Width: | Height: | Size: 88 KiB |
|
Before Width: | Height: | Size: 77 KiB |
|
Before Width: | Height: | Size: 52 KiB |
|
Before Width: | Height: | Size: 47 KiB |
@@ -1,107 +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 assets = InstrumentationRegistry.getInstrumentation()
|
||||
.context.assets
|
||||
val samples = assets.list("samples")
|
||||
checkNotNull(samples) { "no samples found" }
|
||||
val pattern = Pattern.compile(
|
||||
"[0-9]+-([0-9]+)deg.jpg"
|
||||
)
|
||||
val rs = RenderScript.create(
|
||||
InstrumentationRegistry.getTargetContext(),
|
||||
)
|
||||
val zxing = Zxing()
|
||||
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 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()
|
||||
checkNotNull(result) { "no barcode found in $sample" }
|
||||
}
|
||||
rs.destroy()
|
||||
}
|
||||
}
|
||||
|
||||
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 (t in 0 until height) {
|
||||
for (s 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 (t % 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
|
||||
|
Before Width: | Height: | Size: 3.9 KiB After Width: | Height: | Size: 3.0 KiB |
|
Before Width: | Height: | Size: 1.9 KiB After Width: | Height: | Size: 1.5 KiB |
|
Before Width: | Height: | Size: 2.6 KiB After Width: | Height: | Size: 2.1 KiB |
|
Before Width: | Height: | Size: 5.4 KiB After Width: | Height: | Size: 4.1 KiB |
|
Before Width: | Height: | Size: 8.2 KiB After Width: | Height: | Size: 6.0 KiB |
|
Before Width: | Height: | Size: 11 KiB After Width: | Height: | Size: 8.2 KiB |
@@ -6,17 +6,22 @@
|
||||
android:xlargeScreens="true"/>
|
||||
<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"
|
||||
android:maxSdkVersion="28"/>
|
||||
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
|
||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"
|
||||
android:maxSdkVersion="28"/>
|
||||
<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"/>
|
||||
@@ -41,7 +46,7 @@
|
||||
android:theme="@style/AppTheme">
|
||||
<activity
|
||||
android:name=".activity.SplashActivity"
|
||||
android:theme="@style/SplashTheme"
|
||||
android:theme="@style/AppTheme"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN"/>
|
||||
@@ -58,13 +63,20 @@
|
||||
<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"/>
|
||||
<category android:name="android.intent.category.DEFAULT"/>
|
||||
</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: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"/>
|
||||
@@ -97,20 +109,64 @@
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<activity
|
||||
android:name=".activity.MainActivity"
|
||||
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:exported="true"
|
||||
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
|
||||
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">
|
||||
|
||||
@@ -2,19 +2,21 @@ 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.content.startIntentOrToast
|
||||
import de.markusfisch.android.binaryeye.widget.toast
|
||||
|
||||
interface IAction {
|
||||
val iconResId: Int
|
||||
val titleResId: Int
|
||||
abstract class Action {
|
||||
abstract val iconResId: Int
|
||||
abstract val titleResId: Int
|
||||
|
||||
fun canExecuteOn(data: ByteArray): Boolean
|
||||
suspend fun execute(context: Context, data: ByteArray)
|
||||
var executed: Boolean = false
|
||||
|
||||
abstract fun canExecuteOn(data: ByteArray): Boolean
|
||||
abstract suspend fun execute(context: Context, data: ByteArray)
|
||||
}
|
||||
|
||||
abstract class IntentAction : IAction {
|
||||
abstract class IntentAction : Action() {
|
||||
abstract val errorMsg: Int
|
||||
|
||||
final override suspend fun execute(context: Context, data: ByteArray) {
|
||||
@@ -22,7 +24,7 @@ abstract class IntentAction : IAction {
|
||||
if (intent == null) {
|
||||
context.toast(errorMsg)
|
||||
} else {
|
||||
context.execShareIntent(intent)
|
||||
executed = context.startIntentOrToast(intent)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,15 +34,17 @@ abstract class IntentAction : IAction {
|
||||
): Intent?
|
||||
}
|
||||
|
||||
abstract class SchemeAction : IAction {
|
||||
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)
|
||||
content.matches(
|
||||
"""^$scheme://[\w\W]+$""".toRegex(
|
||||
RegexOption.IGNORE_CASE
|
||||
)
|
||||
)
|
||||
} else {
|
||||
content.startsWith("$scheme://", ignoreCase = true)
|
||||
@@ -48,6 +52,6 @@ abstract class SchemeAction : IAction {
|
||||
}
|
||||
|
||||
final override suspend fun execute(context: Context, data: ByteArray) {
|
||||
context.openUrl(String(data))
|
||||
executed = context.openUrl(String(data))
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package de.markusfisch.android.binaryeye.actions
|
||||
|
||||
import de.markusfisch.android.binaryeye.actions.fido.FidoAction
|
||||
import de.markusfisch.android.binaryeye.actions.mail.MailAction
|
||||
import de.markusfisch.android.binaryeye.actions.mail.MatMsgAction
|
||||
import de.markusfisch.android.binaryeye.actions.otpauth.OtpauthAction
|
||||
@@ -12,11 +13,12 @@ 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,
|
||||
FidoAction,
|
||||
OtpauthAction,
|
||||
SmsAction,
|
||||
TelAction,
|
||||
@@ -28,7 +30,7 @@ object ActionRegistry {
|
||||
WebAction
|
||||
)
|
||||
|
||||
fun getAction(data: ByteArray): IAction = REGISTRY.find {
|
||||
fun getAction(data: ByteArray): Action = REGISTRY.find {
|
||||
it.canExecuteOn(data)
|
||||
} ?: DEFAULT_ACTION
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package de.markusfisch.android.binaryeye.actions.fido
|
||||
|
||||
import android.content.Context
|
||||
import de.markusfisch.android.binaryeye.R
|
||||
import de.markusfisch.android.binaryeye.actions.Action
|
||||
import de.markusfisch.android.binaryeye.content.openUrl
|
||||
|
||||
object FidoAction : Action() {
|
||||
private val fidoUriRegex = "^fido:/[0-9]+$".toRegex(
|
||||
RegexOption.IGNORE_CASE
|
||||
)
|
||||
|
||||
override val iconResId: Int = R.drawable.ic_action_open
|
||||
override val titleResId: Int = R.string.open_url
|
||||
|
||||
override fun canExecuteOn(data: ByteArray): Boolean {
|
||||
return String(data).trim().matches(fidoUriRegex)
|
||||
}
|
||||
|
||||
override suspend fun execute(context: Context, data: ByteArray) {
|
||||
executed = context.openUrl(String(data).trim())
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -19,31 +19,37 @@ object MatMsgAction : IntentAction() {
|
||||
context: Context,
|
||||
data: ByteArray
|
||||
): Intent? {
|
||||
val encoded = String(data)
|
||||
// Allow arbitrary order.
|
||||
val to = encoded.extractFirst("""[:;]TO:([\w.%@+-]+);""")
|
||||
val sub = encoded.extractFirst("""[:;]SUB:([^;]+);""")
|
||||
val body = encoded.extractFirst("""[:;]BODY:([^;]+);""")
|
||||
val mm = MatMsg(String(data))
|
||||
// Allow incomplete but not completely missing data.
|
||||
if (to == null && sub == null && body == null) {
|
||||
if (mm.isEmpty()) {
|
||||
return null
|
||||
}
|
||||
return Intent(
|
||||
Intent.ACTION_SENDTO,
|
||||
Uri.parse("mailto:")
|
||||
"mailto:".toUri()
|
||||
).apply {
|
||||
to?.let {
|
||||
putExtra(Intent.EXTRA_EMAIL, to)
|
||||
mm.to?.let {
|
||||
putExtra(Intent.EXTRA_EMAIL, arrayOf(mm.to))
|
||||
}
|
||||
sub?.let {
|
||||
putExtra(Intent.EXTRA_SUBJECT, sub)
|
||||
mm.sub?.let {
|
||||
putExtra(Intent.EXTRA_SUBJECT, mm.sub)
|
||||
}
|
||||
body?.let {
|
||||
putExtra(Intent.EXTRA_TEXT, body)
|
||||
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)
|
||||
|
||||
@@ -2,62 +2,65 @@ package de.markusfisch.android.binaryeye.actions.search
|
||||
|
||||
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.app.alertDialog
|
||||
import de.markusfisch.android.binaryeye.app.urlEncode
|
||||
import de.markusfisch.android.binaryeye.app.prefs
|
||||
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) {
|
||||
view(context, String(data), true)
|
||||
}
|
||||
|
||||
private suspend fun view(
|
||||
context: Context,
|
||||
url: String,
|
||||
search: Boolean
|
||||
) {
|
||||
if (!context.openUrl(url) && search) {
|
||||
openSearch(context, url)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun openSearch(context: Context, query: String) {
|
||||
val defaultSearchUrl = prefs.defaultSearchUrl
|
||||
if (defaultSearchUrl.isNotEmpty()) {
|
||||
view(
|
||||
context,
|
||||
defaultSearchUrl + query.urlEncode(),
|
||||
false
|
||||
)
|
||||
return
|
||||
}
|
||||
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.removeFirst()
|
||||
urls.removeFirst()
|
||||
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] + query.urlEncode())
|
||||
}
|
||||
} ?: return
|
||||
view(context, queryUri, false)
|
||||
executed = 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,7 +2,7 @@ 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
|
||||
|
||||
@@ -27,7 +27,7 @@ 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)
|
||||
|
||||
@@ -4,7 +4,7 @@ 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(
|
||||
|
||||
@@ -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 =
|
||||
@@ -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
|
||||
@@ -46,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 {
|
||||
@@ -66,10 +67,13 @@ object VCardAction : IntentAction() {
|
||||
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 {
|
||||
@@ -93,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())
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -185,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))
|
||||
|
||||
@@ -47,7 +41,7 @@ object VEventAction : IntentAction() {
|
||||
dateFormats.simpleFindParse(eventStart.value)?.also {
|
||||
putExtra(
|
||||
CalendarContract.EXTRA_EVENT_BEGIN_TIME,
|
||||
it.localTime()
|
||||
it.time
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -55,37 +49,39 @@ object VEventAction : IntentAction() {
|
||||
dateFormats.simpleFindParse(eventEnd.value)?.also {
|
||||
putExtra(
|
||||
CalendarContract.EXTRA_EVENT_END_TIME,
|
||||
it.localTime()
|
||||
it.time
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// We definitely don't wan't the local format.
|
||||
@SuppressLint("SimpleDateFormat")
|
||||
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 fun Date.localTime() = time - timezoneOffset * 60000L
|
||||
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
|
||||
}
|
||||
|
||||
@@ -2,13 +2,12 @@ package de.markusfisch.android.binaryeye.actions.web
|
||||
|
||||
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.content.openUrl
|
||||
|
||||
object WebAction : IAction {
|
||||
private val colloquialRegex = """^(http[s]*://)*([a-z0-9]+[a-z0-9-]*[a-z0-9]+[.])+[a-z]{2,}([?#/]+[\w/=&;._-]*)*$""".toRegex(
|
||||
RegexOption.IGNORE_CASE
|
||||
)
|
||||
object WebAction : Action() {
|
||||
private val colloquialRegex =
|
||||
"^(URL:[ ]*)*(http[s]*://)*[A-Za-z0-9.-]{3,}\\.[A-Za-z]{2,}[^ \t\r\n]*$".toRegex()
|
||||
|
||||
override val iconResId: Int = R.drawable.ic_action_open
|
||||
override val titleResId: Int = R.string.open_url
|
||||
@@ -19,9 +18,12 @@ object WebAction : IAction {
|
||||
|
||||
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}"
|
||||
}
|
||||
context.openUrl(url)
|
||||
executed = 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) {
|
||||
executed = WifiConnector.parse(String(data))?.let {
|
||||
WifiConnector.addNetwork(context, it)
|
||||
} ?: false
|
||||
withContext(Dispatchers.Main) {
|
||||
context.toast(
|
||||
if (executed) {
|
||||
R.string.wifi_added
|
||||
} else {
|
||||
R.string.wifi_config_failed
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,20 +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.*
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.Q)
|
||||
fun removeNetworkSuggestions(context: Context): Int =
|
||||
(context.applicationContext.getSystemService(
|
||||
Context.WIFI_SERVICE
|
||||
) as WifiManager).removeNetworkSuggestions(listOf())
|
||||
import android.provider.Settings
|
||||
import androidx.annotation.RequiresApi
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* Normal:
|
||||
@@ -41,55 +36,50 @@ fun removeNetworkSuggestions(context: Context): Int =
|
||||
* 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>? {
|
||||
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()
|
||||
@@ -97,10 +87,10 @@ object WifiConnector {
|
||||
// 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].uppercase(Locale.US) to pair.groupValues[2]
|
||||
pair.groupValues[1].uppercase(Locale.US) to pair.groupValues[2].unescape
|
||||
}.toMap()
|
||||
}
|
||||
}
|
||||
@@ -110,47 +100,43 @@ object WifiConnector {
|
||||
) {
|
||||
// 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 ?: inputMap["A"]?.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
|
||||
}
|
||||
@@ -179,10 +165,11 @@ object WifiConnector {
|
||||
data: SimpleDataAccessor
|
||||
): WifiNetworkSuggestion.Builder? {
|
||||
try {
|
||||
when (data.securityType) {
|
||||
when (data.securityType.uppercase()) {
|
||||
"WPA", "WPA2" -> {
|
||||
data.password?.let { setWpa2Passphrase(it) }
|
||||
}
|
||||
|
||||
"WPA2-EAP" -> {
|
||||
setWpa2EnterpriseConfig(WifiEnterpriseConfig().apply {
|
||||
identity = data.identity
|
||||
@@ -192,9 +179,11 @@ object WifiConnector {
|
||||
data.phase2Method?.let { phase2Method = it }
|
||||
})
|
||||
}
|
||||
|
||||
"WPA3" -> {
|
||||
data.password?.let { setWpa3Passphrase(it) }
|
||||
}
|
||||
|
||||
"WPA3-EAP" -> {
|
||||
setWpa3EnterpriseConfig(WifiEnterpriseConfig().apply {
|
||||
identity = data.identity
|
||||
@@ -205,7 +194,7 @@ object WifiConnector {
|
||||
})
|
||||
}
|
||||
}
|
||||
} catch (e: IllegalArgumentException) {
|
||||
} catch (_: IllegalArgumentException) {
|
||||
// Don't accept passphrases that aren't ASCII encodeable.
|
||||
return null
|
||||
}
|
||||
@@ -240,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
|
||||
@@ -254,6 +243,7 @@ object WifiConnector {
|
||||
allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40)
|
||||
allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104)
|
||||
}
|
||||
|
||||
"WPA" -> {
|
||||
passwordWithQuotes?.let {
|
||||
preSharedKey = it
|
||||
@@ -270,7 +260,8 @@ 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
|
||||
@@ -290,7 +281,7 @@ 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
|
||||
}
|
||||
@@ -303,11 +294,47 @@ object WifiConnector {
|
||||
}
|
||||
}
|
||||
|
||||
@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]
|
||||
}
|
||||
|
||||
@@ -347,7 +374,7 @@ private fun WifiManager.removeOldNetwork(
|
||||
}?.networkId?.also {
|
||||
removeNetwork(it)
|
||||
}
|
||||
} catch (e: SecurityException) {
|
||||
} catch (_: SecurityException) {
|
||||
// The user didn't allow ACCESS_FINE_LOCATION which is
|
||||
// required to access configuredNetworks and that's fine.
|
||||
}
|
||||
|
||||
@@ -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,305 @@
|
||||
package de.markusfisch.android.binaryeye.activity
|
||||
|
||||
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 androidx.appcompat.app.AlertDialog
|
||||
import com.google.android.material.dialog.MaterialAlertDialogBuilder
|
||||
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(bottom = false)
|
||||
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 = MaterialAlertDialogBuilder(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) {
|
||||
MaterialAlertDialogBuilder(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.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 com.google.android.material.dialog.MaterialAlertDialogBuilder
|
||||
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(bottom = false)
|
||||
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()
|
||||
MaterialAlertDialogBuilder(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}")
|
||||
)
|
||||
MaterialAlertDialogBuilder(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)
|
||||
MaterialAlertDialogBuilder(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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,904 @@
|
||||
package de.markusfisch.android.binaryeye.activity
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.res.ColorStateList
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.Environment
|
||||
import android.provider.DocumentsContract
|
||||
import android.text.Editable
|
||||
import android.text.Spannable
|
||||
import android.text.SpannableString
|
||||
import android.text.TextWatcher
|
||||
import android.text.style.TypefaceSpan
|
||||
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.LinearLayout
|
||||
import android.widget.TableLayout
|
||||
import android.widget.TableRow
|
||||
import android.widget.TextView
|
||||
import androidx.core.widget.TextViewCompat
|
||||
import com.google.android.material.dialog.MaterialAlertDialogBuilder
|
||||
import com.google.android.material.floatingactionbutton.FloatingActionButton
|
||||
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.adapter.prettifyFormatName
|
||||
import de.markusfisch.android.binaryeye.adapter.toFormatDescriptionResId
|
||||
import de.markusfisch.android.binaryeye.app.db
|
||||
import de.markusfisch.android.binaryeye.app.hasLocationPermission
|
||||
import de.markusfisch.android.binaryeye.app.hasWritePermission
|
||||
import de.markusfisch.android.binaryeye.app.prefs
|
||||
import de.markusfisch.android.binaryeye.content.ContentBarcode
|
||||
import de.markusfisch.android.binaryeye.content.ParsedContentType
|
||||
import de.markusfisch.android.binaryeye.content.copyToClipboard
|
||||
import de.markusfisch.android.binaryeye.content.openUrl
|
||||
import de.markusfisch.android.binaryeye.content.parseData
|
||||
import de.markusfisch.android.binaryeye.content.shareAsFile
|
||||
import de.markusfisch.android.binaryeye.content.shareText
|
||||
import de.markusfisch.android.binaryeye.content.toBarcode
|
||||
import de.markusfisch.android.binaryeye.content.toErrorCorrectionInt
|
||||
import de.markusfisch.android.binaryeye.content.wipeLastShareFile
|
||||
import de.markusfisch.android.binaryeye.database.Scan
|
||||
import de.markusfisch.android.binaryeye.database.toBundle
|
||||
import de.markusfisch.android.binaryeye.database.toScan
|
||||
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.net.createEncodeDeeplink
|
||||
import de.markusfisch.android.binaryeye.os.showWhenLocked
|
||||
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
|
||||
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.security.MessageDigest
|
||||
import kotlin.math.roundToInt
|
||||
import de.markusfisch.android.binaryeye.content.ParsedField as Field
|
||||
|
||||
class DecodeActivity : AbstractBaseActivity() {
|
||||
private lateinit var labelHeadlineView: TextView
|
||||
private lateinit var contentView: EditText
|
||||
private lateinit var contentHeadlineView: TextView
|
||||
private lateinit var characterCountView: TextView
|
||||
private lateinit var dataHeadlineView: TextView
|
||||
private lateinit var formatHeadlineView: TextView
|
||||
private lateinit var dataView: LinearLayout
|
||||
private lateinit var metaHeadlineView: TextView
|
||||
private lateinit var metaView: TableLayout
|
||||
private lateinit var hexHeadlineView: TextView
|
||||
private lateinit var hexView: TextView
|
||||
private lateinit var formatDescriptionView: TextView
|
||||
private lateinit var recreationView: ImageView
|
||||
private lateinit var labelView: EditText
|
||||
private lateinit var fab: FloatingActionButton
|
||||
private lateinit var scan: Scan
|
||||
private lateinit var format: String
|
||||
|
||||
private val parentJob = Job()
|
||||
private val scope: CoroutineScope = CoroutineScope(
|
||||
Dispatchers.Main + parentJob
|
||||
)
|
||||
private val dp: Float
|
||||
get() = resources.displayMetrics.density
|
||||
private val content: String
|
||||
get() = contentView.text.toString()
|
||||
|
||||
private var closeAutomatically = false
|
||||
private var action = ActionRegistry.DEFAULT_ACTION
|
||||
private var isBinary = false
|
||||
private var originalBytes: ByteArray = ByteArray(0)
|
||||
private var lastParsedDataItems: List<Field> = emptyList()
|
||||
private var showingDimmed = false
|
||||
private var label: String? = null
|
||||
private var recreationSize = 0
|
||||
|
||||
override fun onActivityResult(
|
||||
requestCode: Int,
|
||||
resultCode: Int,
|
||||
resultData: Intent?
|
||||
) {
|
||||
super.onActivityResult(requestCode, resultCode, resultData)
|
||||
when (requestCode) {
|
||||
OPEN_DOCUMENT -> {
|
||||
if (resultCode == Activity.RESULT_OK) {
|
||||
val uri = resultData?.data ?: return
|
||||
openPickedFile(uri)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCreate(state: Bundle?) {
|
||||
super.onCreate(state)
|
||||
if (intent.getBooleanExtra(SHOW_WHEN_LOCKED, false)) {
|
||||
showWhenLocked()
|
||||
}
|
||||
setScreenContentView(R.layout.activity_decode)
|
||||
setTitle(R.string.content)
|
||||
|
||||
val justScanned = intent.hasExtra(DECODED) || intent.hasExtra(DECODED_SCAN)
|
||||
closeAutomatically = prefs.closeAutomatically && justScanned
|
||||
|
||||
scan = intent?.extras?.getBundle(SCAN_BUNDLE)?.toScan()
|
||||
?: throw IllegalArgumentException("DecodeActivity needs a Scan")
|
||||
|
||||
isBinary = scan.text.isEmpty()
|
||||
originalBytes = scan.raw ?: scan.text.toByteArray()
|
||||
format = scan.format.name
|
||||
recreationSize = (200f * dp).roundToInt()
|
||||
|
||||
labelHeadlineView = findViewById(R.id.label_headline)
|
||||
contentView = findViewById(R.id.content)
|
||||
contentHeadlineView = findViewById(R.id.content_headline)
|
||||
characterCountView = findViewById(R.id.character_count)
|
||||
dataHeadlineView = findViewById(R.id.data_headline)
|
||||
formatHeadlineView = findViewById(R.id.format_headline)
|
||||
dataView = findViewById(R.id.data)
|
||||
metaHeadlineView = findViewById(R.id.meta_headline)
|
||||
metaView = findViewById(R.id.meta)
|
||||
hexHeadlineView = findViewById(R.id.hex_headline)
|
||||
hexView = findViewById(R.id.hex)
|
||||
formatDescriptionView = findViewById(R.id.format_description)
|
||||
recreationView = findViewById(R.id.recreation)
|
||||
labelView = findViewById(R.id.label)
|
||||
fab = findViewById(R.id.open)
|
||||
|
||||
contentHeadlineView.setText(
|
||||
if (isBinary) {
|
||||
R.string.section_raw_barcode_content
|
||||
} else {
|
||||
R.string.section_raw_barcode_content_editable
|
||||
}
|
||||
)
|
||||
|
||||
if (prefs.showMetaData) {
|
||||
val descResId = format.toFormatDescriptionResId()
|
||||
formatHeadlineView.text = getString(
|
||||
R.string.section_format_details,
|
||||
format.prettifyFormatName()
|
||||
)
|
||||
formatHeadlineView.visibility = View.VISIBLE
|
||||
if (descResId != 0) {
|
||||
formatDescriptionView.setText(descResId)
|
||||
} else {
|
||||
formatDescriptionView.visibility = View.GONE
|
||||
}
|
||||
metaView.fillMetaView(scan)
|
||||
} else {
|
||||
formatHeadlineView.visibility = View.GONE
|
||||
formatDescriptionView.visibility = View.GONE
|
||||
metaHeadlineView.visibility = View.GONE
|
||||
metaView.visibility = View.GONE
|
||||
}
|
||||
|
||||
if (scan.id > 0) {
|
||||
labelHeadlineView.visibility = View.VISIBLE
|
||||
scan.label?.let {
|
||||
labelView.setText(it)
|
||||
label = it
|
||||
}
|
||||
} else {
|
||||
labelHeadlineView.visibility = View.GONE
|
||||
labelView.visibility = View.GONE
|
||||
}
|
||||
|
||||
findViewById<View>(R.id.inset_layout).setPaddingFromWindowInsets(bottom = false)
|
||||
findViewById<View>(R.id.scroll_view).setPaddingFromWindowInsets()
|
||||
|
||||
initContentAndFab(justScanned)
|
||||
updateViewsAndFab(scan.text, originalBytes)
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
super.onPause()
|
||||
val id = scan.id
|
||||
if (id > 0) {
|
||||
val newLabel = labelView.text.toString().trim()
|
||||
if (newLabel != (label ?: "")) {
|
||||
db.renameScan(id, newLabel)
|
||||
label = newLabel
|
||||
}
|
||||
}
|
||||
if (action.executed) {
|
||||
maybeBackOrFinish()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
parentJob.cancel()
|
||||
wipeLastShareFile()
|
||||
}
|
||||
|
||||
private fun initContentAndFab(justScanned: Boolean) {
|
||||
if (isBinary) {
|
||||
contentView.setText(String(originalBytes).foldNonAlNum())
|
||||
contentView.isEnabled = false
|
||||
fab.setImageResource(R.drawable.ic_action_save)
|
||||
fab.setOnClickListener {
|
||||
askForFileNameAndSave(originalBytes)
|
||||
}
|
||||
} else {
|
||||
contentView.setText(scan.text)
|
||||
contentView.addTextChangedListener(object : TextWatcher {
|
||||
override fun afterTextChanged(s: Editable?) {
|
||||
updateViewsAndFab(s?.toString() ?: "")
|
||||
}
|
||||
|
||||
override fun beforeTextChanged(
|
||||
s: CharSequence?,
|
||||
start: Int,
|
||||
count: Int,
|
||||
after: Int
|
||||
) = Unit
|
||||
|
||||
override fun onTextChanged(
|
||||
s: CharSequence?,
|
||||
start: Int,
|
||||
before: Int,
|
||||
count: Int
|
||||
) = Unit
|
||||
})
|
||||
fab.setOnClickListener {
|
||||
executeAction(content)
|
||||
}
|
||||
if (justScanned && prefs.openImmediately) {
|
||||
closeAutomatically = true
|
||||
executeAction(content)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun updateViewsAndFab(text: String, bytes: ByteArray? = null) {
|
||||
val b = bytes ?: text.toByteArray()
|
||||
resolveActionAndUpdateFab(b)
|
||||
updateViews(text, b)
|
||||
}
|
||||
|
||||
private fun resolveActionAndUpdateFab(bytes: ByteArray) {
|
||||
if (!isBinary) {
|
||||
val prevAction = action
|
||||
if (!prevAction.canExecuteOn(bytes)) {
|
||||
action = ActionRegistry.getAction(bytes)
|
||||
}
|
||||
if (prevAction !== action) {
|
||||
fab.setImageResource(action.iconResId)
|
||||
}
|
||||
}
|
||||
// Run this for the initial action too.
|
||||
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 updateViews(text: String, bytes: ByteArray) {
|
||||
dataView.fillDataView(text, bytes, text != scan.text)
|
||||
characterCountView.text = resources.getQuantityString(
|
||||
R.plurals.character_count,
|
||||
bytes.size,
|
||||
bytes.size
|
||||
)
|
||||
recreationView.showIf(prefs.showRecreation) { v ->
|
||||
val unmodified: Boolean
|
||||
val content = if (isBinary) {
|
||||
if (bytes.isEmpty()) {
|
||||
clearRecreation()
|
||||
return@showIf
|
||||
}
|
||||
unmodified = bytes.contentEquals(originalBytes)
|
||||
bytes
|
||||
} else {
|
||||
if (text.isEmpty()) {
|
||||
clearRecreation()
|
||||
return@showIf
|
||||
}
|
||||
unmodified = text == scan.text
|
||||
text
|
||||
}
|
||||
val barcode = if (unmodified) {
|
||||
scan.toBarcode()
|
||||
} else {
|
||||
ContentBarcode(
|
||||
content,
|
||||
scan.format,
|
||||
scan.errorCorrectionLevel.toErrorCorrectionInt(),
|
||||
addQuietZone = true
|
||||
)
|
||||
}
|
||||
try {
|
||||
v.setImageBitmap(barcode.bitmap(recreationSize))
|
||||
v.setOnClickListener {
|
||||
v.context.hideSoftKeyboard(contentView)
|
||||
v.post {
|
||||
startActivity(
|
||||
BarcodeActivity.newIntent(this, barcode)
|
||||
)
|
||||
}
|
||||
}
|
||||
} catch (_: RuntimeException) {
|
||||
clearRecreation()
|
||||
}
|
||||
}
|
||||
hexView.showIf(prefs.showHexDump) { v ->
|
||||
hexHeadlineView.visibility = View.VISIBLE
|
||||
v.text = hexDump(bytes)
|
||||
v.setOnClickListener {
|
||||
copyToClipboard(bytes.toHexString())
|
||||
}
|
||||
}
|
||||
if (!prefs.showHexDump) {
|
||||
hexHeadlineView.visibility = View.GONE
|
||||
}
|
||||
}
|
||||
|
||||
private fun clearRecreation() {
|
||||
recreationView.apply {
|
||||
setImageBitmap(null)
|
||||
setOnClickListener(null)
|
||||
}
|
||||
}
|
||||
|
||||
private fun LinearLayout.fillDataView(
|
||||
text: String,
|
||||
bytes: ByteArray,
|
||||
isEditing: Boolean
|
||||
) {
|
||||
val items = mutableListOf<Field>()
|
||||
val parsedData = parseData(this@DecodeActivity, text, bytes, format, action)
|
||||
items.addAll(parsedData.fields)
|
||||
when (prefs.showChecksum) {
|
||||
"CRC4" -> items.addField(R.string.crc4, String.format("%X", crc4(bytes)))
|
||||
"MD5" -> items.addField(R.string.md5, bytes.md5().toHexString().fold())
|
||||
"SHA1" -> items.addField(R.string.sha1, bytes.sha1().toHexString().fold())
|
||||
"SHA256" -> items.addField(R.string.sha256, bytes.sha256().toHexString().fold())
|
||||
}
|
||||
if (parsedData.type != ParsedContentType.UNKNOWN) {
|
||||
items.add(
|
||||
0,
|
||||
Field(
|
||||
R.string.parsed_type,
|
||||
getString(parsedData.type.resId)
|
||||
)
|
||||
)
|
||||
lastParsedDataItems = items
|
||||
fillDataItems(items, false)
|
||||
return
|
||||
}
|
||||
if (isEditing && lastParsedDataItems.isNotEmpty()) {
|
||||
if (!showingDimmed) {
|
||||
fillDataItems(lastParsedDataItems, true)
|
||||
}
|
||||
return
|
||||
}
|
||||
fillDataItems(items, false)
|
||||
}
|
||||
|
||||
private fun TableLayout.fillMetaView(scan: Scan) {
|
||||
val items = mutableListOf(
|
||||
Field(R.string.error_correction_level, scan.errorCorrectionLevel),
|
||||
Field(R.string.sequence_size, scan.sequenceSize.positiveToString()),
|
||||
Field(R.string.sequence_index, scan.sequenceIndex.positiveToString()),
|
||||
Field(R.string.sequence_id, scan.sequenceId),
|
||||
Field(R.string.gtin_country, scan.country),
|
||||
Field(R.string.gtin_add_on, scan.addOn),
|
||||
Field(R.string.gtin_price, scan.price),
|
||||
Field(R.string.gtin_issue_number, scan.issueNumber),
|
||||
)
|
||||
if (!scan.version.isNullOrBlank()) {
|
||||
val versionString = if (scan.format == ZxingCpp.BarcodeFormat.QRCode) {
|
||||
getString(
|
||||
R.string.qr_version_and_modules,
|
||||
scan.version,
|
||||
(scan.version.toIntOrNull() ?: 0) * 4 + 17
|
||||
)
|
||||
} else {
|
||||
scan.version
|
||||
}
|
||||
items.addField(R.string.barcode_version_number, versionString)
|
||||
}
|
||||
if (scan.format == ZxingCpp.BarcodeFormat.QRCode &&
|
||||
scan.dataMask > -1
|
||||
) {
|
||||
items.addField(R.string.qr_data_mask, scan.dataMask.toString())
|
||||
}
|
||||
val itemsWithValues = items.filter { !it.value.isNullOrBlank() }
|
||||
if (!itemsWithValues.isEmpty()) {
|
||||
metaHeadlineView.visibility = View.VISIBLE
|
||||
fillTable(itemsWithValues)
|
||||
}
|
||||
}
|
||||
|
||||
private fun TableLayout.fillTable(items: List<Field>) {
|
||||
removeAllViews()
|
||||
visibility = if (items.isEmpty()) View.GONE else {
|
||||
val ctx = context
|
||||
val spaceBetween = (16f * dp).roundToInt()
|
||||
items.forEach { item ->
|
||||
val text = item.value
|
||||
val tr = TableRow(ctx)
|
||||
val keyView = TextView(ctx).apply {
|
||||
when (val key = item.key) {
|
||||
is Int -> setText(key)
|
||||
is String -> this.text = key
|
||||
else -> this.text = key.toString()
|
||||
}
|
||||
}
|
||||
val valueView = TextView(ctx).apply {
|
||||
setPadding(spaceBetween, 0, 0, 0)
|
||||
this.text = text
|
||||
setOnClickListener {
|
||||
copyToClipboard(text.toString())
|
||||
}
|
||||
}
|
||||
tr.addView(keyView)
|
||||
tr.addView(valueView)
|
||||
addView(tr)
|
||||
}
|
||||
View.VISIBLE
|
||||
}
|
||||
}
|
||||
|
||||
private fun LinearLayout.fillDataItems(
|
||||
items: List<Field>,
|
||||
dimmed: Boolean
|
||||
) {
|
||||
showingDimmed = dimmed
|
||||
removeAllViews()
|
||||
if (items.isEmpty()) {
|
||||
dataHeadlineView.visibility = View.GONE
|
||||
visibility = View.GONE
|
||||
return
|
||||
}
|
||||
dataHeadlineView.visibility = View.VISIBLE
|
||||
val ctx = context
|
||||
val spaceBetween = (16f * dp).roundToInt()
|
||||
for (item in items) {
|
||||
val text = item.value
|
||||
if (text.isNullOrBlank()) {
|
||||
continue
|
||||
}
|
||||
|
||||
val rowView = LinearLayout(ctx).apply {
|
||||
orientation = LinearLayout.VERTICAL
|
||||
layoutParams = LinearLayout.LayoutParams(
|
||||
LinearLayout.LayoutParams.MATCH_PARENT,
|
||||
LinearLayout.LayoutParams.WRAP_CONTENT
|
||||
).apply {
|
||||
bottomMargin = spaceBetween
|
||||
}
|
||||
setBackgroundResource(R.drawable.list_selector)
|
||||
setOnClickListener {
|
||||
item.link?.let {
|
||||
openUrl(it)
|
||||
}
|
||||
copyToClipboard(text.toString())
|
||||
}
|
||||
}
|
||||
|
||||
val keyView = TextView(ctx).apply {
|
||||
TextViewCompat.setTextAppearance(
|
||||
this,
|
||||
R.style.SecondaryText
|
||||
)
|
||||
when (val key = item.key) {
|
||||
is Int -> setText(key)
|
||||
is String -> this.text = key
|
||||
else -> this.text = key.toString()
|
||||
}
|
||||
}
|
||||
|
||||
val valueView = TextView(ctx).apply {
|
||||
TextViewCompat.setTextAppearance(
|
||||
this,
|
||||
android.R.style.TextAppearance_Medium
|
||||
)
|
||||
setTextColor(
|
||||
ColorStateList.valueOf(
|
||||
ctx.obtainStyledAttributes(
|
||||
intArrayOf(android.R.attr.textColorPrimary)
|
||||
).run {
|
||||
try {
|
||||
getColor(0, currentTextColor)
|
||||
} finally {
|
||||
recycle()
|
||||
}
|
||||
}
|
||||
)
|
||||
)
|
||||
this.text = text
|
||||
if (item.link != null) {
|
||||
setCompoundDrawablesWithIntrinsicBounds(
|
||||
0,
|
||||
0,
|
||||
R.drawable.ic_action_open,
|
||||
0
|
||||
)
|
||||
compoundDrawablePadding = spaceBetween / 2
|
||||
}
|
||||
}
|
||||
|
||||
val alpha = if (dimmed) 0.5f else 1f
|
||||
keyView.alpha = alpha
|
||||
valueView.alpha = alpha
|
||||
|
||||
rowView.addView(keyView)
|
||||
rowView.addView(valueView)
|
||||
addView(rowView)
|
||||
}
|
||||
visibility = View.VISIBLE
|
||||
}
|
||||
|
||||
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
|
||||
inflater.inflate(R.menu.fragment_decode, menu)
|
||||
if (scan.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(textOrHex())
|
||||
maybeBackOrFinish()
|
||||
true
|
||||
}
|
||||
|
||||
R.id.copy_as_deeplink -> {
|
||||
copyToClipboard(deeplinkToCopy())
|
||||
maybeBackOrFinish()
|
||||
true
|
||||
}
|
||||
|
||||
R.id.share -> {
|
||||
shareText(textOrHex())
|
||||
maybeBackOrFinish()
|
||||
true
|
||||
}
|
||||
|
||||
R.id.share_file -> {
|
||||
val (data, name) = if (isBinary) {
|
||||
Pair(originalBytes, "barcode_content.bin")
|
||||
} else {
|
||||
Pair(content, "barcode_content.txt")
|
||||
}
|
||||
shareAsFile(data, name)
|
||||
maybeBackOrFinish()
|
||||
true
|
||||
}
|
||||
|
||||
R.id.create -> {
|
||||
startActivity(
|
||||
EncodeActivity.newIntent(
|
||||
this,
|
||||
if (isBinary) originalBytes else content,
|
||||
format
|
||||
)
|
||||
)
|
||||
true
|
||||
}
|
||||
|
||||
R.id.remove -> {
|
||||
askToRemoveScan(scan.id)
|
||||
true
|
||||
}
|
||||
|
||||
else -> super.onOptionsItemSelected(item)
|
||||
}
|
||||
}
|
||||
|
||||
private fun askToRemoveScan(id: Long) {
|
||||
MaterialAlertDialogBuilder(this)
|
||||
.setMessage(R.string.really_remove_scan)
|
||||
.setPositiveButton(android.R.string.ok) { _, _ ->
|
||||
db.removeScan(id)
|
||||
backOrFinish()
|
||||
}
|
||||
.setNegativeButton(android.R.string.cancel) { _, _ ->
|
||||
}
|
||||
.show()
|
||||
}
|
||||
|
||||
private fun textOrHex() = if (isBinary) {
|
||||
originalBytes.toHexString()
|
||||
} else {
|
||||
content
|
||||
}
|
||||
|
||||
private fun deeplinkToCopy() = createEncodeDeeplink(
|
||||
format = format,
|
||||
content = textOrHex(),
|
||||
)
|
||||
|
||||
private fun copyPasswordToClipboard() {
|
||||
val ac = action
|
||||
if (ac is WifiAction) {
|
||||
ac.password?.let { password ->
|
||||
copyToClipboard(password, isSensitive = true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun copyToClipboard(text: String, isSensitive: Boolean = false) {
|
||||
(this as android.content.Context).copyToClipboard(text, isSensitive)
|
||||
// There's a clipboard popup from Android 13 on.
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
|
||||
toast(R.string.copied_to_clipboard)
|
||||
}
|
||||
}
|
||||
|
||||
private fun maybeBackOrFinish() {
|
||||
if (closeAutomatically) {
|
||||
backOrFinish()
|
||||
}
|
||||
}
|
||||
|
||||
private fun backOrFinish() {
|
||||
finish()
|
||||
}
|
||||
|
||||
private fun executeAction(str: String) {
|
||||
if (str.isEmpty() || openLocalDocument(str)) {
|
||||
return
|
||||
}
|
||||
if (action is WifiAction &&
|
||||
Build.VERSION.SDK_INT < Build.VERSION_CODES.Q &&
|
||||
!hasLocationPermission { executeAction(str) }
|
||||
) {
|
||||
return
|
||||
}
|
||||
scope.launch {
|
||||
action.execute(this@DecodeActivity, str.toByteArray())
|
||||
}
|
||||
}
|
||||
|
||||
private fun openLocalDocument(str: String): Boolean {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N ||
|
||||
!str.startsWith(SCHEME_FILE)
|
||||
) {
|
||||
return false
|
||||
}
|
||||
// Needs to be disabled so we get the result.
|
||||
closeAutomatically = false
|
||||
// file:// can't be used with Scoped Storage anymore.
|
||||
startActivityForResult(
|
||||
Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
|
||||
addCategory(Intent.CATEGORY_OPENABLE)
|
||||
type = "*/*"
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
val primary = str.substring(
|
||||
SCHEME_FILE.length
|
||||
).localDirName() ?: Environment.getExternalStorageDirectory().path
|
||||
putExtra(
|
||||
DocumentsContract.EXTRA_INITIAL_URI,
|
||||
DocumentsContract.buildDocumentUri(
|
||||
"com.android.externalstorage.documents",
|
||||
"primary:$primary"
|
||||
)
|
||||
)
|
||||
}
|
||||
},
|
||||
OPEN_DOCUMENT
|
||||
)
|
||||
return true
|
||||
}
|
||||
|
||||
private fun askForFileNameAndSave(raw: ByteArray) {
|
||||
// Write permission is only required before Android Q.
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q &&
|
||||
!hasWritePermission { askForFileNameAndSave(raw) }
|
||||
) {
|
||||
return
|
||||
}
|
||||
scope.launch(Dispatchers.Main) {
|
||||
val name = askForFileName() ?: return@launch
|
||||
withContext(Dispatchers.IO) {
|
||||
val message = writeExternalFile(
|
||||
name,
|
||||
"application/octet-stream"
|
||||
) {
|
||||
it.write(raw)
|
||||
}.toSaveResult()
|
||||
withContext(Dispatchers.Main) {
|
||||
toast(message)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val DECODED_SCAN = "decoded_scan"
|
||||
const val DECODED = "decoded"
|
||||
private const val SCAN_BUNDLE = "scan_bundle"
|
||||
private const val OPEN_DOCUMENT = 1
|
||||
private const val SCHEME_FILE = "file://"
|
||||
private const val SHOW_WHEN_LOCKED = "show_when_locked"
|
||||
|
||||
fun newIntent(
|
||||
context: Context,
|
||||
scan: Scan,
|
||||
showWhenLocked: Boolean = false
|
||||
): Intent {
|
||||
val args = Bundle()
|
||||
args.putBundle(SCAN_BUNDLE, scan.toBundle())
|
||||
return Intent(context, DecodeActivity::class.java).apply {
|
||||
putExtra(DECODED_SCAN, true)
|
||||
putExtra(SHOW_WHEN_LOCKED, showWhenLocked)
|
||||
putExtras(args)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun MutableList<Field>.addField(
|
||||
key: Any,
|
||||
value: CharSequence?,
|
||||
link: String? = null
|
||||
) {
|
||||
add(Field(key, value, link))
|
||||
}
|
||||
|
||||
private inline fun <T : View> T.showIf(
|
||||
visible: Boolean,
|
||||
block: (T) -> Unit
|
||||
) {
|
||||
visibility = if (visible) {
|
||||
block.invoke(this)
|
||||
View.VISIBLE
|
||||
} else {
|
||||
View.GONE
|
||||
}
|
||||
}
|
||||
|
||||
private val nonAlNum = "[^a-zA-Z0-9]".toRegex()
|
||||
private val multipleDots = "…+".toRegex()
|
||||
private fun String.foldNonAlNum() = replace(nonAlNum, "…")
|
||||
.replace(multipleDots, "…")
|
||||
|
||||
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.toInt().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()
|
||||
}
|
||||
|
||||
private fun Int.positiveToString() = if (this > -1) this.toString() else ""
|
||||
|
||||
// CRC-4 with polynomial x^4 + x + 1.
|
||||
private fun crc4(input: ByteArray): Int {
|
||||
var crc = 0
|
||||
var i = 0
|
||||
while (i < input.size) {
|
||||
val c = input[i].toInt()
|
||||
var j = 0x80
|
||||
while (j != 0) {
|
||||
var bit = crc and 0x8
|
||||
crc = crc shl 1
|
||||
if (c and j != 0) {
|
||||
bit = bit xor 0x8
|
||||
}
|
||||
if (bit != 0) {
|
||||
crc = crc xor 0x3
|
||||
}
|
||||
j = j ushr 1
|
||||
}
|
||||
++i
|
||||
}
|
||||
crc = crc and 0xF
|
||||
return crc
|
||||
}
|
||||
|
||||
private fun ByteArray.md5(): ByteArray = MessageDigest.getInstance(
|
||||
"MD5"
|
||||
).run {
|
||||
update(this@md5)
|
||||
digest()
|
||||
}
|
||||
|
||||
private fun ByteArray.sha1(): ByteArray = MessageDigest.getInstance(
|
||||
"SHA-1"
|
||||
).run {
|
||||
update(this@sha1)
|
||||
digest()
|
||||
}
|
||||
|
||||
private fun ByteArray.sha256(): ByteArray = MessageDigest.getInstance(
|
||||
"SHA-256"
|
||||
).run {
|
||||
update(this@sha256)
|
||||
digest()
|
||||
}
|
||||
|
||||
private fun String.fold(): CharSequence {
|
||||
val l = length
|
||||
return if (l > 10) {
|
||||
val half = l / 2
|
||||
val s = substring(0, half) + "\n" + substring(half)
|
||||
SpannableString(s).apply {
|
||||
setSpan(
|
||||
TypefaceSpan("monospace"),
|
||||
0, s.length,
|
||||
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
|
||||
)
|
||||
}
|
||||
} else {
|
||||
this
|
||||
}
|
||||
}
|
||||
|
||||
private fun String.localDirName(): String? = when {
|
||||
endsWith("/") -> this
|
||||
else -> File(this).parentFile?.absolutePath
|
||||
}?.replaceFirst(Regex("^/storage/emulated/0/"), "")
|
||||
?.replaceFirst(Regex("^/sdcard/"), "")
|
||||
?.trim('/')
|
||||
|
||||
private fun Activity.openPickedFile(uri: Uri) {
|
||||
startActivity(
|
||||
Intent.createChooser(
|
||||
Intent(Intent.ACTION_VIEW).apply {
|
||||
setDataAndType(uri, contentResolver.getType(uri) ?: "*/*")
|
||||
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
},
|
||||
getString(R.string.open_url)
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,470 @@
|
||||
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(bottom = false)
|
||||
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 = Bundle().apply {
|
||||
intent?.extras?.let { putAll(it) }
|
||||
getExtrasFromDeeplink()?.let { putAll(it) }
|
||||
}.takeIf { !it.isEmpty }
|
||||
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,40 +1,54 @@
|
||||
package de.markusfisch.android.binaryeye.fragment
|
||||
package de.markusfisch.android.binaryeye.activity
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.app.AlertDialog
|
||||
import android.app.SearchManager
|
||||
import android.content.Context
|
||||
import android.database.Cursor
|
||||
import android.graphics.Color
|
||||
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 com.google.android.material.color.MaterialColors
|
||||
import com.google.android.material.dialog.MaterialAlertDialogBuilder
|
||||
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.getString
|
||||
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
|
||||
@@ -51,12 +65,15 @@ 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
|
||||
ac.window.statusBarColor = ContextCompat.getColor(
|
||||
val ac = this@HistoryActivity
|
||||
@Suppress("DEPRECATION")
|
||||
ac.window.statusBarColor = MaterialColors.getColor(
|
||||
ac,
|
||||
R.color.accent_dark
|
||||
com.google.android.material.R.attr.colorSecondaryContainer,
|
||||
Color.TRANSPARENT
|
||||
)
|
||||
}
|
||||
return true
|
||||
@@ -73,34 +90,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
|
||||
}
|
||||
}
|
||||
@@ -116,40 +138,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
|
||||
)
|
||||
}
|
||||
@@ -157,25 +169,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(bottom = false)
|
||||
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() {
|
||||
@@ -185,49 +199,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()
|
||||
true
|
||||
}
|
||||
|
||||
R.id.share_as_file -> {
|
||||
this.pickListSeparatorAndShare(true)
|
||||
true
|
||||
}
|
||||
|
||||
else -> super.onOptionsItemSelected(item)
|
||||
}
|
||||
}
|
||||
@@ -251,13 +277,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) {
|
||||
@@ -265,10 +291,19 @@ class HistoryFragment : Fragment() {
|
||||
} else {
|
||||
View.GONE
|
||||
}
|
||||
cursor?.let { 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)
|
||||
@@ -281,6 +316,7 @@ class HistoryFragment : Fragment() {
|
||||
private fun enableMenuItems(enabled: Boolean) {
|
||||
clearListMenuItem?.isEnabled = enabled
|
||||
exportHistoryMenuItem?.isEnabled = enabled
|
||||
shareAsFileMenuItem?.isEnabled = enabled
|
||||
}
|
||||
|
||||
private fun closeActionMode() {
|
||||
@@ -294,26 +330,28 @@ class HistoryFragment : Fragment() {
|
||||
private fun showScan(id: Long) = db.getScan(id)?.also { scan ->
|
||||
closeActionMode()
|
||||
try {
|
||||
fragmentManager?.addFragment(DecodeFragment.newInstance(scan))
|
||||
} catch (e: IllegalArgumentException) {
|
||||
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(Database.SCANS_NAME)
|
||||
}
|
||||
|
||||
// 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)
|
||||
MaterialAlertDialogBuilder(this)
|
||||
.setTitle(
|
||||
if (content.isNullOrEmpty()) {
|
||||
getString(R.string.binary_data)
|
||||
} else {
|
||||
content
|
||||
}
|
||||
)
|
||||
.setView(view)
|
||||
.setPositiveButton(android.R.string.ok) { _, _ ->
|
||||
val name = nameView.text.toString()
|
||||
@@ -324,11 +362,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>) {
|
||||
MaterialAlertDialogBuilder(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 {
|
||||
@@ -340,8 +384,8 @@ class HistoryFragment : Fragment() {
|
||||
.show()
|
||||
}
|
||||
|
||||
private fun askToRemoveScans(context: Context) {
|
||||
AlertDialog.Builder(context)
|
||||
private fun Context.askToRemoveScans() {
|
||||
MaterialAlertDialogBuilder(this)
|
||||
.setMessage(
|
||||
if (filter == null) {
|
||||
R.string.really_remove_all_scans
|
||||
@@ -360,7 +404,7 @@ class HistoryFragment : Fragment() {
|
||||
|
||||
private fun askToExportToFile() {
|
||||
scope.launch {
|
||||
val ac = activity ?: return@launch
|
||||
val ac = this@HistoryActivity
|
||||
progressView.useVisibility {
|
||||
// Write permission is only required before Android Q.
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q &&
|
||||
@@ -388,12 +432,12 @@ class HistoryFragment : Fragment() {
|
||||
} ?: return@useVisibility
|
||||
val message = when (delimiter) {
|
||||
"db" -> ac.exportDatabase(name)
|
||||
else -> db.getScansDetailed(filter)?.use {
|
||||
else -> db.getScansDetailed(filter).use {
|
||||
when (delimiter) {
|
||||
"json" -> ac.exportJson(name, it)
|
||||
else -> ac.exportCsv(name, it, delimiter)
|
||||
}
|
||||
} ?: false
|
||||
}
|
||||
}.toSaveResult()
|
||||
withContext(Dispatchers.Main) {
|
||||
ac.toast(message)
|
||||
@@ -402,32 +446,44 @@ 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)
|
||||
MaterialAlertDialogBuilder(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" -> cursor.exportText(details[1])
|
||||
"csv" -> cursor.exportCsv(details[1])
|
||||
else -> cursor.exportJson()
|
||||
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) {
|
||||
context.shareText(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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -436,7 +492,7 @@ class HistoryFragment : Fragment() {
|
||||
|
||||
private fun Cursor.exportText(separator: String): String {
|
||||
val sb = StringBuilder()
|
||||
val contentIndex = getColumnIndex(Database.SCANS_CONTENT)
|
||||
val contentIndex = getColumnIndex(Database.SCANS_TEXT)
|
||||
if (contentIndex > -1 && moveToFirst()) {
|
||||
do {
|
||||
val content = getString(contentIndex)
|
||||
@@ -0,0 +1,172 @@
|
||||
package de.markusfisch.android.binaryeye.activity
|
||||
|
||||
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 androidx.appcompat.app.AlertDialog
|
||||
import com.google.android.material.dialog.MaterialAlertDialogBuilder
|
||||
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(bottom = false)
|
||||
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 = MaterialAlertDialogBuilder(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) {
|
||||
MaterialAlertDialogBuilder(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) {
|
||||
supportFragmentManager?.setFragment(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(bottom = false)
|
||||
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,47 +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.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.mapResultToView
|
||||
import de.markusfisch.android.binaryeye.os.getVibrator
|
||||
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 kotlinx.coroutines.*
|
||||
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 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 lateinit var rs: RenderScript
|
||||
private lateinit var vibrator: Vibrator
|
||||
private lateinit var cropImageView: CropImageView
|
||||
private lateinit var detectorView: DetectorView
|
||||
|
||||
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?) {
|
||||
@@ -59,44 +72,45 @@ class PickActivity : AppCompatActivity() {
|
||||
// locale.
|
||||
setTitle(R.string.pick_code_to_scan)
|
||||
|
||||
zxing.updateHints(
|
||||
true,
|
||||
prefs.barcodeFormats
|
||||
)
|
||||
rs = RenderScript.create(this)
|
||||
vibrator = getVibrator()
|
||||
|
||||
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()
|
||||
detectorView.restoreCropHandlePos()
|
||||
|
||||
findViewById(R.id.scan).setOnClickListener {
|
||||
findViewById<View>(R.id.scan).setOnClickListener {
|
||||
showResult()
|
||||
}
|
||||
}
|
||||
@@ -116,39 +130,53 @@ class PickActivity : AppCompatActivity() {
|
||||
}
|
||||
|
||||
private fun scanWithinBounds(bitmap: Bitmap) {
|
||||
val roi = Rect(detectorView.roi)
|
||||
val rectInView = if (roi.width() < 1) {
|
||||
cropImageView.getBoundsRect()
|
||||
} else {
|
||||
roi
|
||||
}
|
||||
val imageRect = cropImageView.mappedRect
|
||||
val rectInImage = normalizeRoi(imageRect, rectInView)
|
||||
val cropped = bitmap.crop(
|
||||
rectInImage,
|
||||
cropImageView.imageRotation
|
||||
) ?: return
|
||||
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 {
|
||||
result = zxing.decodePositiveNegative(cropped)
|
||||
result?.let {
|
||||
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) {
|
||||
return@withContext
|
||||
}
|
||||
vibrator.vibrate()
|
||||
val rc = Rect()
|
||||
imageRect.round(rc)
|
||||
if (!rectInView.intersect(rc)) {
|
||||
return@withContext
|
||||
}
|
||||
detectorView.update(
|
||||
mapResultToView(
|
||||
cropped.width,
|
||||
cropped.height,
|
||||
0,
|
||||
rectInView,
|
||||
it.resultPoints,
|
||||
detectorView.coordinates
|
||||
result = it
|
||||
scanFeedback()
|
||||
dv.update(
|
||||
matrix.mapPosition(
|
||||
it.position,
|
||||
dv.coordinates
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -156,15 +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()
|
||||
detectorView.saveCropHandlePos()
|
||||
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
|
||||
}
|
||||
|
||||
@@ -174,18 +225,35 @@ 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
|
||||
val uri = intent.getUriExtra() ?: return null
|
||||
return contentResolver.loadImageUri(uri)
|
||||
}
|
||||
|
||||
@@ -197,7 +265,7 @@ class PickActivity : AppCompatActivity() {
|
||||
private fun showResult() {
|
||||
val r = result
|
||||
if (r != null) {
|
||||
showResult(this, r, vibrator)
|
||||
showResult(r)
|
||||
finish()
|
||||
} else {
|
||||
applicationContext.toast(R.string.no_barcode_found)
|
||||
@@ -205,7 +273,7 @@ class PickActivity : AppCompatActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
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(
|
||||
@@ -215,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,180 @@
|
||||
package de.markusfisch.android.binaryeye.activity
|
||||
|
||||
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 com.google.android.material.dialog.MaterialAlertDialogBuilder
|
||||
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
|
||||
import de.markusfisch.android.zxingcpp.ZxingCpp.BarcodeFormat
|
||||
|
||||
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(bottom = false)
|
||||
listView.setPaddingFromWindowInsets()
|
||||
}
|
||||
|
||||
private fun refreshProfiles() {
|
||||
profiles.clear()
|
||||
profiles.add(
|
||||
ProfileItem(
|
||||
null,
|
||||
prefs.profileLabel(this, null)
|
||||
)
|
||||
)
|
||||
prefs.profiles.forEach { name ->
|
||||
profiles.add(ProfileItem(name, prefs.profileLabel(this, 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)
|
||||
MaterialAlertDialogBuilder(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
|
||||
MaterialAlertDialogBuilder(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,
|
||||
R.layout.row_profile,
|
||||
R.id.title,
|
||||
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 {
|
||||
current = item
|
||||
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(R.id.title),
|
||||
view.findViewById(R.id.subtitle),
|
||||
view.findViewById(R.id.share_qr),
|
||||
).also { holder ->
|
||||
holder.shareQr.setOnClickListener {
|
||||
val item = holder.current ?: return@setOnClickListener
|
||||
context.startActivity(
|
||||
BarcodeActivity.newIntent(
|
||||
context,
|
||||
prefs.toJson(context, item.name),
|
||||
BarcodeFormat.QRCode,
|
||||
addQuietZone = true
|
||||
)
|
||||
)
|
||||
}
|
||||
view.tag = holder
|
||||
}
|
||||
|
||||
private class ViewHolder(
|
||||
val title: TextView,
|
||||
val subtitle: TextView,
|
||||
val shareQr: View,
|
||||
) {
|
||||
var current: ProfileItem? = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private data class ProfileItem(
|
||||
val name: String?,
|
||||
val label: String
|
||||
)
|
||||
@@ -1,11 +1,10 @@
|
||||
package de.markusfisch.android.binaryeye.activity
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.support.v7.app.AppCompatActivity
|
||||
import de.markusfisch.android.binaryeye.app.setRestartCount
|
||||
|
||||
class SplashActivity : AppCompatActivity() {
|
||||
class SplashActivity : Activity() {
|
||||
override fun onCreate(state: Bundle?) {
|
||||
super.onCreate(state)
|
||||
|
||||
@@ -13,7 +12,6 @@ class SplashActivity : AppCompatActivity() {
|
||||
// because that would happen after the app is fully
|
||||
// initialized what is too late.
|
||||
|
||||
intent?.setRestartCount()
|
||||
startActivity(Intent(applicationContext, CameraActivity::class.java))
|
||||
finish()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
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 {
|
||||
prefs.loadExpertProfile(this)
|
||||
finish()
|
||||
}
|
||||
findViewById<View>(R.id.simple).setOnClickListener {
|
||||
prefs.loadSimpleProfile(this)
|
||||
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 de.markusfisch.android.binaryeye.R
|
||||
import de.markusfisch.android.binaryeye.content.ParsedContentType
|
||||
import de.markusfisch.android.binaryeye.content.getContentPreview
|
||||
import de.markusfisch.android.binaryeye.content.parsedContentTypeFromName
|
||||
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 rawIndex = cursor.getColumnIndex(Database.SCANS_RAW)
|
||||
private val contentTypeIndex = cursor.getColumnIndex(Database.SCANS_CONTENT_TYPE)
|
||||
private val formatIndex = cursor.getColumnIndex(Database.SCANS_FORMAT)
|
||||
|
||||
fun select(id: Long, position: Int) {
|
||||
selectedScanId = id
|
||||
selectedScanPosition = position
|
||||
private val selections = mutableMapOf<Long, Int>()
|
||||
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,58 +98,196 @@ class ScansAdapter(context: Context, cursor: Cursor) :
|
||||
context: Context,
|
||||
cursor: Cursor
|
||||
) {
|
||||
val id = cursor.getLong(idIndex)
|
||||
val pinned = cursor.getInt(pinnedIndex) != 0
|
||||
val format = cursor.getString(formatIndex)
|
||||
val contentType = parsedContentTypeFromName(
|
||||
cursor.getString(contentTypeIndex)
|
||||
)
|
||||
getViewHolder(view).apply {
|
||||
timeView.text = formatDateTime(cursor.getString(timeIndex))
|
||||
metaView.text = formatDateTime(cursor.getString(timeIndex))
|
||||
formatView.text = format.prettifyFormatName().withContentType(
|
||||
context,
|
||||
contentType
|
||||
)
|
||||
formatIconView.setImageResource(format.toBarcodeIcon())
|
||||
val name = cursor.getString(nameIndex)
|
||||
val content = cursor.getString(contentIndex)
|
||||
val text = cursor.getString(textIndex)
|
||||
val raw = cursor.getBlob(rawIndex)
|
||||
var icon = 0
|
||||
contentView.text = when {
|
||||
name?.isNotEmpty() == true -> {
|
||||
icon = R.drawable.ic_label
|
||||
name
|
||||
}
|
||||
content?.isEmpty() == true -> context.getString(
|
||||
R.string.binary_data
|
||||
|
||||
text.isNullOrEmpty() -> getContentPreview(
|
||||
context,
|
||||
text ?: "",
|
||||
raw ?: ByteArray(0),
|
||||
format
|
||||
)
|
||||
else -> content
|
||||
|
||||
else -> text
|
||||
}
|
||||
contentView.setCompoundDrawablesWithIntrinsicBounds(
|
||||
icon, 0, 0, 0
|
||||
)
|
||||
formatView.text = prettifyFormatName(cursor.getString(formatIndex))
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
// 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 View.select(selected: Boolean) {
|
||||
isActivated = selected
|
||||
refreshDrawableState()
|
||||
}
|
||||
|
||||
private fun getViewHolder(
|
||||
view: View
|
||||
): ViewHolder = view.tag as ViewHolder? ?: ViewHolder(
|
||||
view.findViewById(R.id.time),
|
||||
view.findViewById(R.id.format_icon),
|
||||
view.findViewById(R.id.meta),
|
||||
view.findViewById(R.id.format),
|
||||
view.findViewById(R.id.content),
|
||||
view.findViewById(R.id.format)
|
||||
view.findViewById(R.id.pin)
|
||||
).also {
|
||||
view.tag = it
|
||||
}
|
||||
|
||||
private data class ViewHolder(
|
||||
val timeView: TextView,
|
||||
val formatIconView: ImageView,
|
||||
val metaView: TextView,
|
||||
val formatView: 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, " ")
|
||||
|
||||
private fun String.withContentType(
|
||||
context: Context,
|
||||
type: ParsedContentType
|
||||
) = if (type == ParsedContentType.UNKNOWN) {
|
||||
this
|
||||
} else {
|
||||
context.getString(
|
||||
R.string.scan_meta_data,
|
||||
this,
|
||||
context.getString(type.resId)
|
||||
)
|
||||
}
|
||||
|
||||
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
|
||||
"Telepen" -> R.string.format_description_telepen
|
||||
"TelepenAlpha" -> R.string.format_description_telepen_alpha
|
||||
"TelepenNumeric" -> R.string.format_description_telepen_numeric
|
||||
"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.content.Context
|
||||
import android.app.AlertDialog
|
||||
import com.google.android.material.dialog.MaterialAlertDialogBuilder
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlin.coroutines.resume
|
||||
@@ -9,10 +9,10 @@ import kotlin.coroutines.suspendCoroutine
|
||||
|
||||
suspend inline fun <T : Any> alertDialog(
|
||||
context: Context,
|
||||
crossinline build: AlertDialog.Builder.(resume: (T?) -> Unit) -> Unit
|
||||
crossinline build: MaterialAlertDialogBuilder.(resume: (T?) -> Unit) -> Unit
|
||||
): T? = withContext(Dispatchers.Main) {
|
||||
suspendCoroutine { continuation ->
|
||||
AlertDialog.Builder(context).apply {
|
||||
MaterialAlertDialogBuilder(context).apply {
|
||||
setOnCancelListener {
|
||||
continuation.resume(null)
|
||||
}
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
package de.markusfisch.android.binaryeye.app
|
||||
|
||||
import android.support.multidex.MultiDexApplication;
|
||||
import android.support.v8.renderscript.RenderScript
|
||||
import android.app.Application
|
||||
import com.google.android.material.color.DynamicColors
|
||||
import de.markusfisch.android.binaryeye.database.Database
|
||||
import de.markusfisch.android.binaryeye.preference.Preferences
|
||||
|
||||
val db = Database()
|
||||
val prefs = Preferences()
|
||||
|
||||
class BinaryEyeApp : MultiDexApplication() {
|
||||
class BinaryEyeApp : Application() {
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
db.open(this)
|
||||
prefs.init(this)
|
||||
|
||||
if (prefs.forceCompat) {
|
||||
RenderScript.forceCompat()
|
||||
}
|
||||
DynamicColors.applyToActivitiesIfAvailable(
|
||||
this,
|
||||
DynamicColors.Precondition { _, _ -> prefs.dynamicColors }
|
||||
)
|
||||
db.open(this)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
package de.markusfisch.android.binaryeye.app
|
||||
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import java.io.UnsupportedEncodingException
|
||||
import java.net.URLEncoder
|
||||
|
||||
private val nonPrintable = "[\\x00-\\x08\\x0e-\\x1f]".toRegex()
|
||||
fun String.hasNonPrintableCharacters() = nonPrintable.containsMatchIn(this)
|
||||
|
||||
private val nonAlNum = "[^a-zA-Z0-9]".toRegex()
|
||||
private val multipleDots = "[…]+".toRegex()
|
||||
fun String.foldNonAlNum() = replace(nonAlNum, "…")
|
||||
.replace(multipleDots, "…")
|
||||
|
||||
fun String.urlEncode(): String = try {
|
||||
URLEncoder.encode(this, "UTF-8")
|
||||
} catch (e: UnsupportedEncodingException) {
|
||||
this
|
||||
}
|
||||
|
||||
fun String.parseAndNormalizeUri(): Uri = Uri.parse(this).let {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
|
||||
it.normalizeScheme()
|
||||
} else {
|
||||
it
|
||||
}
|
||||
}
|
||||
|
||||
fun ByteArray.toHexString() = joinToString("") { "%02X".format(it) }
|
||||
@@ -1,19 +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 FragmentManager.setFragment(fragment: Fragment) {
|
||||
getTransaction(fragment).commit()
|
||||
}
|
||||
|
||||
fun FragmentManager.addFragment(fragment: Fragment) {
|
||||
getTransaction(fragment).addToBackStack(null).commit()
|
||||
}
|
||||
|
||||
@SuppressLint("CommitTransaction")
|
||||
private fun FragmentManager.getTransaction(
|
||||
fragment: Fragment
|
||||
) = beginTransaction().replace(R.id.content_frame, fragment)
|
||||
@@ -2,7 +2,7 @@ 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.isEmpty()) {
|
||||
|
||||
@@ -3,15 +3,16 @@ 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 Activity.hasCameraPermission() = hasPermission(
|
||||
fun Activity.hasCameraPermission(request: Boolean = true) = hasPermission(
|
||||
Manifest.permission.CAMERA,
|
||||
PERMISSION_CAMERA
|
||||
if (request) PERMISSION_CAMERA else 0
|
||||
)
|
||||
|
||||
const val PERMISSION_WRITE = 2
|
||||
@@ -32,6 +33,18 @@ fun Activity.hasLocationPermission(callback: () -> Any): Boolean {
|
||||
)
|
||||
}
|
||||
|
||||
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
|
||||
@@ -40,11 +53,13 @@ private fun Activity.hasPermission(
|
||||
permission
|
||||
) != PackageManager.PERMISSION_GRANTED
|
||||
) {
|
||||
ActivityCompat.requestPermissions(
|
||||
this,
|
||||
arrayOf(permission),
|
||||
requestCode
|
||||
)
|
||||
if (requestCode > 0) {
|
||||
ActivityCompat.requestPermissions(
|
||||
this,
|
||||
arrayOf(permission),
|
||||
requestCode
|
||||
)
|
||||
}
|
||||
false
|
||||
} else {
|
||||
true
|
||||
|
||||
@@ -1,24 +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 Intent.setRestartCount() {
|
||||
restartCount = getIntExtra(RESTART_COUNT, restartCount)
|
||||
}
|
||||
|
||||
fun Activity.restartApp() {
|
||||
if (restartCount < 3) {
|
||||
startActivity(Intent(this, SplashActivity::class.java).apply {
|
||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
putExtra(RESTART_COUNT, ++restartCount)
|
||||
})
|
||||
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.openUrl
|
||||
import de.markusfisch.android.binaryeye.content.startIntentOrToast
|
||||
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 startIntentOrToast(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,221 @@
|
||||
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.Telepen,
|
||||
BarcodeFormat.TelepenAlpha,
|
||||
BarcodeFormat.TelepenNumeric,
|
||||
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,239 @@
|
||||
package de.markusfisch.android.binaryeye.content
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import androidx.core.net.toUri
|
||||
import de.markusfisch.android.binaryeye.R
|
||||
import de.markusfisch.android.binaryeye.actions.Action
|
||||
import de.markusfisch.android.binaryeye.actions.ActionRegistry
|
||||
import de.markusfisch.android.binaryeye.actions.mail.MatMsg
|
||||
import de.markusfisch.android.binaryeye.actions.mail.MatMsgAction
|
||||
import de.markusfisch.android.binaryeye.actions.otpauth.OtpauthAction
|
||||
import de.markusfisch.android.binaryeye.actions.vtype.VTypeParser
|
||||
import de.markusfisch.android.binaryeye.actions.vtype.vcard.VCardAction
|
||||
import de.markusfisch.android.binaryeye.actions.vtype.vevent.VEventAction
|
||||
import de.markusfisch.android.binaryeye.actions.web.WebAction
|
||||
import de.markusfisch.android.binaryeye.actions.wifi.WifiAction
|
||||
import de.markusfisch.android.binaryeye.actions.wifi.WifiConnector
|
||||
import org.json.JSONException
|
||||
import org.json.JSONObject
|
||||
|
||||
enum class ParsedContentType(
|
||||
val resId: Int
|
||||
) {
|
||||
UNKNOWN(0),
|
||||
DEUTSCHE_POST(R.string.parsed_type_deutsche_post),
|
||||
JSON(R.string.parsed_type_json),
|
||||
INTERNATIONAL_DRIVER_LICENSE(
|
||||
R.string.parsed_type_international_driver_license
|
||||
),
|
||||
DIGITAL_SEAL(R.string.parsed_type_digital_seal),
|
||||
SEPA_EPC_QR(R.string.parsed_type_sepa_epc_qr),
|
||||
EMAIL(R.string.parsed_type_email),
|
||||
URL(R.string.parsed_type_url),
|
||||
OTP(R.string.parsed_type_otp),
|
||||
CONTACT_CARD(R.string.parsed_type_contact_card),
|
||||
CALENDAR_EVENT(R.string.parsed_type_calendar_event),
|
||||
WIFI_NETWORK(R.string.parsed_type_wifi_network);
|
||||
}
|
||||
|
||||
data class ParsedData(
|
||||
val type: ParsedContentType,
|
||||
val fields: List<ParsedField>
|
||||
)
|
||||
|
||||
data class ParsedField(
|
||||
val key: Any,
|
||||
val value: CharSequence?,
|
||||
val link: String? = null
|
||||
)
|
||||
|
||||
fun parseData(
|
||||
context: Context,
|
||||
text: String,
|
||||
bytes: ByteArray,
|
||||
format: String,
|
||||
action: Action = ActionRegistry.getAction(bytes)
|
||||
): ParsedData {
|
||||
val fields = mutableListOf<ParsedField>()
|
||||
|
||||
DeutschePostParser.parse(bytes, format)?.let {
|
||||
fields.addField(
|
||||
context.getString(R.string.tracking_number),
|
||||
it.label,
|
||||
it.link,
|
||||
)
|
||||
return ParsedData(ParsedContentType.DEUTSCHE_POST, fields)
|
||||
}
|
||||
|
||||
try {
|
||||
fields.addField(R.string.formatted_json, JSONObject(text).toString(2))
|
||||
return ParsedData(ParsedContentType.JSON, fields)
|
||||
} catch (_: JSONException) {
|
||||
// Ignore
|
||||
}
|
||||
|
||||
IdlParser.parse(String(bytes))?.let {
|
||||
fields.addField("IIN", it.iin)
|
||||
it.elements.forEach { (id, value) ->
|
||||
fields.addField(context.idlToRes(id), value)
|
||||
}
|
||||
return ParsedData(ParsedContentType.INTERNATIONAL_DRIVER_LICENSE, fields)
|
||||
}
|
||||
|
||||
SealParser.parse(context, bytes)?.let { sealFields ->
|
||||
sealFields.forEach { vf ->
|
||||
fields.addField(vf.name, vf.value)
|
||||
}
|
||||
return ParsedData(ParsedContentType.DIGITAL_SEAL, fields)
|
||||
}
|
||||
|
||||
EpcQrParser.parse(text)?.let {
|
||||
fields.addAll(it.map { (id, value) ->
|
||||
ParsedField(context.epcQrToRes(id), value)
|
||||
})
|
||||
return ParsedData(ParsedContentType.SEPA_EPC_QR, fields)
|
||||
}
|
||||
|
||||
when (action) {
|
||||
is MatMsgAction -> MatMsg(text).run {
|
||||
fields.addField(R.string.email_to, to)
|
||||
fields.addField(R.string.email_subject, sub)
|
||||
fields.addField(R.string.email_body, body)
|
||||
return ParsedData(ParsedContentType.EMAIL, fields)
|
||||
}
|
||||
|
||||
is VCardAction,
|
||||
is VEventAction -> VTypeParser.parseMap(text).let { parsedMap ->
|
||||
parsedMap.forEach { item ->
|
||||
fields.addField(item.key, item.value.joinToString("\n") { it.value })
|
||||
}
|
||||
return ParsedData(
|
||||
if (action is VCardAction) {
|
||||
ParsedContentType.CONTACT_CARD
|
||||
} else {
|
||||
ParsedContentType.CALENDAR_EVENT
|
||||
},
|
||||
fields
|
||||
)
|
||||
}
|
||||
|
||||
is WebAction -> try {
|
||||
text.toUri().run {
|
||||
fields.addField(R.string.scheme, scheme)
|
||||
fields.addField(R.string.host, host)
|
||||
fields.addField(R.string.query, query)
|
||||
}
|
||||
return ParsedData(ParsedContentType.URL, fields)
|
||||
} catch (_: Exception) {
|
||||
// Ignore
|
||||
}
|
||||
|
||||
is OtpauthAction -> try {
|
||||
text.toUri().run {
|
||||
val label = pathSegments.firstOrNull()?.let {
|
||||
Uri.decode(it)
|
||||
} ?: ""
|
||||
val colonIdx = label.indexOf(':')
|
||||
val issuerFromLabel = if (colonIdx >= 0) {
|
||||
label.substring(0, colonIdx)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val account = if (colonIdx >= 0) {
|
||||
label.substring(colonIdx + 1).trim()
|
||||
} else {
|
||||
label
|
||||
}
|
||||
val issuer = getQueryParameter("issuer") ?: issuerFromLabel
|
||||
fields.addField(R.string.entry_type, host?.uppercase())
|
||||
fields.addField(R.string.otp_account, account)
|
||||
fields.addField(R.string.otp_issuer, issuer)
|
||||
fields.addField(R.string.otp_algorithm, getQueryParameter("algorithm"))
|
||||
fields.addField(R.string.otp_digits, getQueryParameter("digits"))
|
||||
if (host == "totp") {
|
||||
fields.addField(R.string.otp_period, getQueryParameter("period"))
|
||||
} else {
|
||||
fields.addField(R.string.otp_counter, getQueryParameter("counter"))
|
||||
}
|
||||
}
|
||||
return ParsedData(ParsedContentType.OTP, fields)
|
||||
} catch (_: Exception) {
|
||||
// Ignore
|
||||
}
|
||||
|
||||
is WifiAction -> WifiConnector.parseMap(text)?.let { wifiData ->
|
||||
fields.addField(R.string.wifi_ssid, wifiData["S"])
|
||||
fields.addField(R.string.wifi_password, wifiData["P"])
|
||||
fields.addField(R.string.wifi_type, wifiData["T"])
|
||||
fields.addField(R.string.wifi_hidden, wifiData["H"])
|
||||
fields.addField(R.string.wifi_eap, wifiData["E"])
|
||||
fields.addField(R.string.wifi_identity, wifiData["I"])
|
||||
fields.addField(R.string.wifi_anonymous_identity, wifiData["A"])
|
||||
fields.addField(R.string.wifi_phase2, wifiData["PH2"])
|
||||
return ParsedData(ParsedContentType.WIFI_NETWORK, fields)
|
||||
}
|
||||
}
|
||||
return ParsedData(ParsedContentType.UNKNOWN, emptyList())
|
||||
}
|
||||
|
||||
fun parsedContentTypeFromName(
|
||||
name: String?
|
||||
): ParsedContentType = try {
|
||||
ParsedContentType.valueOf(name ?: "")
|
||||
} catch (_: IllegalArgumentException) {
|
||||
ParsedContentType.UNKNOWN
|
||||
}
|
||||
|
||||
fun getContentPreview(
|
||||
context: Context,
|
||||
text: String,
|
||||
bytes: ByteArray,
|
||||
format: String,
|
||||
action: Action = ActionRegistry.getAction(bytes)
|
||||
): CharSequence {
|
||||
val parsedData = parseData(context, text, bytes, format, action)
|
||||
return when (parsedData.type) {
|
||||
ParsedContentType.UNKNOWN -> text.ifEmpty {
|
||||
bytes.toHexString()
|
||||
}
|
||||
|
||||
ParsedContentType.URL -> parsedData.valueFor(R.string.host)
|
||||
?: text
|
||||
|
||||
ParsedContentType.WIFI_NETWORK -> parsedData.valueFor(R.string.wifi_ssid)
|
||||
?: parsedData.firstValue()
|
||||
?: text
|
||||
|
||||
ParsedContentType.EMAIL -> parsedData.valueFor(R.string.email_to)
|
||||
?: parsedData.valueFor(R.string.email_subject)
|
||||
?: parsedData.firstValue()
|
||||
?: text
|
||||
|
||||
ParsedContentType.OTP -> parsedData.valueFor(R.string.otp_account)
|
||||
?: parsedData.firstValue()
|
||||
?: text
|
||||
|
||||
else -> parsedData.firstValue() ?: text
|
||||
}
|
||||
}
|
||||
|
||||
private fun ParsedData.valueFor(key: Int): CharSequence? =
|
||||
fields.firstValue { it.key == key }
|
||||
|
||||
private fun ParsedData.firstValue(): CharSequence? =
|
||||
fields.firstValue()
|
||||
|
||||
private fun List<ParsedField>.firstValue(
|
||||
predicate: (ParsedField) -> Boolean = { true }
|
||||
): CharSequence? = firstOrNull {
|
||||
predicate(it) && !it.value.isNullOrBlank()
|
||||
}?.value
|
||||
|
||||
private fun MutableList<ParsedField>.addField(
|
||||
key: Any,
|
||||
value: CharSequence?,
|
||||
link: String? = null
|
||||
) {
|
||||
add(ParsedField(key, value, link))
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package de.markusfisch.android.binaryeye.content
|
||||
|
||||
import de.markusfisch.android.zxingcpp.ZxingCpp
|
||||
|
||||
data class DeutschePostTrackingLink(
|
||||
val label: String,
|
||||
val link: String
|
||||
)
|
||||
|
||||
object DeutschePostParser {
|
||||
fun parse(
|
||||
bytes: ByteArray,
|
||||
format: String
|
||||
): DeutschePostTrackingLink? {
|
||||
var isStamp = false
|
||||
var rawData = bytes
|
||||
if (format == ZxingCpp.BarcodeFormat.DataMatrix.name &&
|
||||
bytes.toString(Charsets.ISO_8859_1).startsWith("DEA5")
|
||||
) {
|
||||
if (bytes.size == 47) {
|
||||
isStamp = true
|
||||
} else if (bytes.size > 47) {
|
||||
// Transform back to original data.
|
||||
rawData = bytes.toString(Charsets.UTF_8).toByteArray(
|
||||
Charsets.ISO_8859_1
|
||||
)
|
||||
if (rawData.size == 47) {
|
||||
isStamp = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!isStamp) {
|
||||
return null
|
||||
}
|
||||
|
||||
val hex = StringBuilder()
|
||||
hex.append(String.format("%02X", rawData[9]))
|
||||
hex.append(String.format("%02X", rawData[10]))
|
||||
hex.append(String.format("%02X", rawData[11]))
|
||||
hex.append(String.format("%02X", rawData[12]))
|
||||
hex.append(String.format("%02X", rawData[13]))
|
||||
hex.append(String.format("%X", (rawData[4].toInt() and 0x0f).toByte()))
|
||||
hex.append(String.format("%02X", rawData[5]))
|
||||
hex.append(String.format("%02X", rawData[6]))
|
||||
hex.append(String.format("%02X", rawData[7]))
|
||||
hex.append(String.format("%02X", rawData[8]))
|
||||
val hexString = hex.toString()
|
||||
val trackingNumber = hexString + String.format(
|
||||
"%X",
|
||||
crc4(hexString.toByteArray(Charsets.ISO_8859_1))
|
||||
)
|
||||
return DeutschePostTrackingLink(
|
||||
trackingNumber,
|
||||
"https://www.deutschepost.de/de/s/sendungsverfolgung.html?piececode=$trackingNumber",
|
||||
)
|
||||
}
|
||||
|
||||
// CRC-4 with polynomial x^4 + x + 1.
|
||||
private fun crc4(input: ByteArray): Int {
|
||||
var crc = 0
|
||||
var i = 0
|
||||
while (i < input.size) {
|
||||
val c = input[i].toInt()
|
||||
var j = 0x80
|
||||
while (j != 0) {
|
||||
var bit = crc and 0x8
|
||||
crc = crc shl 1
|
||||
if (c and j != 0) {
|
||||
bit = bit xor 0x8
|
||||
}
|
||||
if (bit != 0) {
|
||||
crc = crc xor 0x3
|
||||
}
|
||||
j = j ushr 1
|
||||
}
|
||||
++i
|
||||
}
|
||||
crc = crc and 0xF
|
||||
return crc
|
||||
}
|
||||
}
|
||||
@@ -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"))
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -5,14 +5,17 @@ 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.app.parseAndNormalizeUri
|
||||
import de.markusfisch.android.binaryeye.app.prefs
|
||||
import de.markusfisch.android.binaryeye.widget.toast
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.io.IOException
|
||||
|
||||
fun Context.execShareIntent(intent: Intent): Boolean = if (
|
||||
fun Context.startIntentOrToast(intent: Intent): Boolean = if (
|
||||
!startIntent(intent)
|
||||
) {
|
||||
toast(R.string.cannot_resolve_action)
|
||||
@@ -32,23 +35,79 @@ fun Context.startIntent(intent: Intent): Boolean = try {
|
||||
// necessary.
|
||||
startActivity(intent)
|
||||
true
|
||||
} catch (e: ActivityNotFoundException) {
|
||||
} catch (_: ActivityNotFoundException) {
|
||||
false
|
||||
}
|
||||
|
||||
fun Context.openUrl(url: String): Boolean = openUri(url.parseAndNormalizeUri())
|
||||
fun Context.openUrl(url: String, silent: Boolean = false): Boolean {
|
||||
return openUri(url.parseAndNormalizeUri(), silent)
|
||||
}
|
||||
|
||||
fun Context.openUri(uri: Uri): Boolean = execShareIntent(
|
||||
Intent(Intent.ACTION_VIEW, uri)
|
||||
)
|
||||
fun Context.openUri(uri: Uri, silent: Boolean = false): Boolean {
|
||||
val cleaned = if (prefs.stripTrackingParams) {
|
||||
uri.stripTrackingParams()
|
||||
} else {
|
||||
uri
|
||||
}
|
||||
val intent = Intent(Intent.ACTION_VIEW, cleaned).apply {
|
||||
if (cleaned.scheme == "content") {
|
||||
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
}
|
||||
}
|
||||
return if (silent) {
|
||||
startIntent(intent)
|
||||
} else {
|
||||
startIntentOrToast(intent)
|
||||
}
|
||||
}
|
||||
|
||||
fun String.parseAndNormalizeUri(): Uri = toUri().normalizeScheme()
|
||||
|
||||
fun Context.shareText(text: String, mimeType: String = "text/plain") {
|
||||
execShareIntent(Intent(Intent.ACTION_SEND).apply {
|
||||
startIntentOrToast(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 <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)
|
||||
@@ -68,7 +127,7 @@ private fun Context.getUriForFile(file: File): Uri? = if (
|
||||
}
|
||||
|
||||
private fun Context.shareUri(uri: Uri, mimeType: String) {
|
||||
execShareIntent(Intent(Intent.ACTION_SEND).apply {
|
||||
startIntentOrToast(Intent(Intent.ACTION_SEND).apply {
|
||||
putExtra(Intent.EXTRA_STREAM, uri)
|
||||
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
type = mimeType
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package de.markusfisch.android.binaryeye.content
|
||||
|
||||
import android.net.Uri
|
||||
|
||||
private val TRACKING_PARAMS = setOf(
|
||||
"utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content",
|
||||
"utm_id", "utm_name", "utm_referrer", "utm_brand", "utm_social",
|
||||
"fbclid", "gclid", "dclid", "gclsrc", "yclid", "msclkid",
|
||||
"mc_eid", "mc_cid",
|
||||
"_ga", "_gl", "ga_source", "ga_medium",
|
||||
"igshid", "igsh",
|
||||
"hsa_acc", "hsa_cam", "hsa_grp", "hsa_ad", "hsa_src",
|
||||
"hsa_tgt", "hsa_kw", "hsa_mt", "hsa_net", "hsa_ver",
|
||||
"spm", "scm", "vero_id", "vero_conv"
|
||||
)
|
||||
|
||||
fun Uri.stripTrackingParams(): Uri {
|
||||
val scheme = scheme?.lowercase()
|
||||
if (scheme != "http" && scheme != "https") {
|
||||
return this
|
||||
}
|
||||
|
||||
val queryNames = runCatching {
|
||||
queryParameterNames
|
||||
}.getOrDefault(emptySet())
|
||||
if (queryNames.isEmpty()) {
|
||||
return this
|
||||
}
|
||||
|
||||
val keep = queryNames.filter { paramName ->
|
||||
paramName.lowercase() !in TRACKING_PARAMS
|
||||
}
|
||||
if (keep.size == queryNames.size) {
|
||||
return this
|
||||
}
|
||||
|
||||
val builder = buildUpon().clearQuery()
|
||||
for (paramName in keep) {
|
||||
getQueryParameters(paramName).forEach { paramValue ->
|
||||
builder.appendQueryParameter(paramName, paramValue)
|
||||
}
|
||||
}
|
||||
return builder.build()
|
||||
}
|
||||
@@ -2,7 +2,6 @@ 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
|
||||
@@ -30,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(
|
||||
|
||||
@@ -1,6 +1,17 @@
|
||||
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)
|
||||
@@ -12,7 +23,17 @@ fun Cursor.getBlob(name: String): ByteArray? {
|
||||
return if (idx < 0) null else getBlob(idx)
|
||||
}
|
||||
|
||||
fun Cursor.getLong(name: String): Long {
|
||||
val idx = getColumnIndex(name)
|
||||
return if (idx < 0) 0L else getLong(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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,46 +6,62 @@ import android.database.Cursor
|
||||
import android.database.sqlite.SQLiteDatabase
|
||||
import android.database.sqlite.SQLiteOpenHelper
|
||||
import de.markusfisch.android.binaryeye.app.prefs
|
||||
import de.markusfisch.android.binaryeye.content.ParsedContentType
|
||||
import de.markusfisch.android.binaryeye.content.parseData
|
||||
import de.markusfisch.android.binaryeye.content.parsedContentTypeFromName
|
||||
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
|
||||
private lateinit var context: Context
|
||||
|
||||
fun open(context: Context) {
|
||||
this.context = context.applicationContext
|
||||
db = OpenHelper(context).writableDatabase
|
||||
fillMissingContentTypes()
|
||||
}
|
||||
|
||||
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_RAW,
|
||||
$SCANS_CONTENT_TYPE,
|
||||
$SCANS_FORMAT
|
||||
FROM $SCANS
|
||||
${getWhereClause(query)}
|
||||
ORDER BY $SCANS_DATETIME DESC
|
||||
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,
|
||||
$SCANS_CONTENT_TYPE
|
||||
FROM $SCANS
|
||||
${getWhereClause(query)}
|
||||
ORDER BY $SCANS_DATETIME DESC
|
||||
ORDER BY $SCANS_PINNED DESC, $SCANS_DATETIME DESC
|
||||
""".trimMargin(), getWhereArguments(query)
|
||||
)
|
||||
|
||||
@@ -53,8 +69,9 @@ class Database {
|
||||
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 {
|
||||
""
|
||||
}
|
||||
@@ -63,115 +80,200 @@ 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,
|
||||
$SCANS_CONTENT_TYPE
|
||||
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,
|
||||
$SCANS_CONTENT_TYPE
|
||||
FROM $SCANS
|
||||
WHERE $SCANS_ID = ?
|
||||
""".trimMargin(), arrayOf("$id")
|
||||
)?.use {
|
||||
).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,
|
||||
parsedContentTypeFromName(it.getString(SCANS_CONTENT_TYPE))
|
||||
)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
fun insertScan(scan: Scan): Long = db.insert(
|
||||
SCANS,
|
||||
null,
|
||||
ContentValues().apply {
|
||||
put(SCANS_DATETIME, scan.dateTime)
|
||||
val isRaw = scan.raw != null
|
||||
if (isRaw) {
|
||||
put(SCANS_CONTENT, "")
|
||||
put(SCANS_RAW, scan.raw)
|
||||
} else {
|
||||
put(SCANS_CONTENT, scan.content)
|
||||
}
|
||||
put(SCANS_FORMAT, scan.format)
|
||||
scan.errorCorrectionLevel?.let {
|
||||
put(SCANS_ERROR_CORRECTION_LEVEL, it)
|
||||
}
|
||||
scan.issueNumber?.let { put(SCANS_ISSUE_NUMBER, it) }
|
||||
scan.orientation?.let { put(SCANS_ORIENTATION, it) }
|
||||
scan.otherMetaData?.let { put(SCANS_OTHER_META_DATA, it) }
|
||||
scan.pdf417ExtraMetaData?.let { put(SCANS_PDF417_EXTRA_METADATA, it) }
|
||||
scan.possibleCountry?.let { put(SCANS_POSSIBLE_COUNTRY, it) }
|
||||
scan.suggestedPrice?.let { put(SCANS_SUGGESTED_PRICE, it) }
|
||||
scan.upcEanExtension?.let { put(SCANS_UPC_EAN_EXTENSION, it) }
|
||||
if (prefs.ignoreConsecutiveDuplicates) {
|
||||
fun insertScan(scan: Scan): Long {
|
||||
when (prefs.ignoreDuplicates()) {
|
||||
Preferences.Companion.IgnoreDuplicates.Consecutive -> {
|
||||
val id = getIdOfLastScan(
|
||||
get(SCANS_CONTENT) as String,
|
||||
if (isRaw) get(SCANS_RAW) as ByteArray else null,
|
||||
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,
|
||||
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)
|
||||
put(
|
||||
SCANS_CONTENT_TYPE,
|
||||
getContentType(scan.text, scan.raw, scan.format.name).name
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
private fun getIdOfLastScan(
|
||||
content: String,
|
||||
raw: ByteArray?,
|
||||
format: String
|
||||
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
|
||||
""".trimMargin(), null
|
||||
)?.use {
|
||||
).use {
|
||||
if (it.count > 0 &&
|
||||
it.moveToFirst() &&
|
||||
it.getString(SCANS_CONTENT) == content &&
|
||||
it.getString(SCANS_TEXT) == content &&
|
||||
(raw == null || it.getBlob(SCANS_RAW)
|
||||
?.contentEquals(raw) == true) &&
|
||||
it.getString(SCANS_FORMAT) == format
|
||||
it.getString(SCANS_FORMAT) == format.name
|
||||
) {
|
||||
it.getLong(SCANS_ID)
|
||||
} else {
|
||||
0L
|
||||
}
|
||||
} ?: 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) {
|
||||
db.delete(SCANS, "$SCANS_ID = ?", arrayOf("$id"))
|
||||
@@ -187,10 +289,60 @@ 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 fun fillMissingContentTypes() {
|
||||
Thread {
|
||||
db.rawQuery(
|
||||
"""SELECT
|
||||
$SCANS_ID,
|
||||
$SCANS_TEXT,
|
||||
$SCANS_RAW,
|
||||
$SCANS_FORMAT
|
||||
FROM $SCANS
|
||||
WHERE $SCANS_CONTENT_TYPE IS NULL
|
||||
""".trimMargin(),
|
||||
null
|
||||
).use {
|
||||
while (it.moveToNext()) {
|
||||
val id = it.getLong(SCANS_ID)
|
||||
val type = getContentType(
|
||||
it.getString(SCANS_TEXT),
|
||||
it.getBlob(SCANS_RAW),
|
||||
it.getString(SCANS_FORMAT)
|
||||
)
|
||||
db.update(
|
||||
SCANS,
|
||||
ContentValues().apply {
|
||||
put(SCANS_CONTENT_TYPE, type.name)
|
||||
},
|
||||
"$SCANS_ID = ?",
|
||||
arrayOf("$id")
|
||||
)
|
||||
}
|
||||
}
|
||||
}.start()
|
||||
}
|
||||
|
||||
private fun getContentType(
|
||||
text: String,
|
||||
raw: ByteArray?,
|
||||
format: String
|
||||
) = parseData(
|
||||
context,
|
||||
text,
|
||||
raw ?: text.toByteArray(),
|
||||
format
|
||||
).type
|
||||
|
||||
private class OpenHelper(context: Context) :
|
||||
SQLiteOpenHelper(context, FILE_NAME, null, 4) {
|
||||
SQLiteOpenHelper(context, FILE_NAME, null, 11) {
|
||||
override fun onCreate(db: SQLiteDatabase) {
|
||||
createScans(db)
|
||||
db.createScans()
|
||||
}
|
||||
|
||||
override fun onUpgrade(
|
||||
@@ -199,13 +351,34 @@ 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()
|
||||
}
|
||||
if (oldVersion < 11) {
|
||||
db.addContentTypeColumn()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -216,10 +389,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"
|
||||
@@ -227,48 +406,114 @@ 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"
|
||||
const val SCANS_CONTENT_TYPE = "content_type"
|
||||
|
||||
private fun createScans(db: SQLiteDatabase) {
|
||||
db.execSQL("DROP TABLE IF EXISTS $SCANS".trimMargin())
|
||||
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,
|
||||
$SCANS_CONTENT_TYPE TEXT NOT NULL DEFAULT '${ParsedContentType.UNKNOWN.name}'
|
||||
)""".trimMargin()
|
||||
)
|
||||
}
|
||||
|
||||
private fun addRawColumn(db: SQLiteDatabase) {
|
||||
db.execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_RAW BLOB".trimMargin())
|
||||
private fun SQLiteDatabase.addRawColumn() {
|
||||
execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_RAW BLOB".trimMargin())
|
||||
}
|
||||
|
||||
private fun addMetaDataColumns(db: SQLiteDatabase) {
|
||||
db.apply {
|
||||
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 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 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 addNameColumn(db: SQLiteDatabase) {
|
||||
db.execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_NAME TEXT".trimMargin())
|
||||
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 SQLiteDatabase.addContentTypeColumn() {
|
||||
execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_CONTENT_TYPE TEXT")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ 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
|
||||
@@ -22,22 +21,25 @@ fun Cursor.exportJson(): String? {
|
||||
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(getColumnIndex(it), it)
|
||||
}
|
||||
val contentIndex = getColumnIndex(Database.SCANS_CONTENT)
|
||||
val contentIndex = getColumnIndex(Database.SCANS_TEXT)
|
||||
val rawIndex = getColumnIndex(Database.SCANS_RAW)
|
||||
val root = JSONArray()
|
||||
do {
|
||||
@@ -68,7 +70,7 @@ private fun Cursor.toJsonObject(
|
||||
obj.put(it.second, value ?: "")
|
||||
}
|
||||
obj
|
||||
} catch (e: JSONException) {
|
||||
} catch (_: JSONException) {
|
||||
obj
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,29 +1,39 @@
|
||||
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.app.hasNonPrintableCharacters
|
||||
import de.markusfisch.android.binaryeye.content.ParsedContentType
|
||||
import de.markusfisch.android.binaryeye.content.parsedContentTypeFromName
|
||||
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 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
|
||||
) : Parcelable {
|
||||
var id: Long = 0L,
|
||||
val label: String? = null,
|
||||
val pinned: Boolean = false,
|
||||
val contentType: ParsedContentType = ParsedContentType.UNKNOWN
|
||||
) {
|
||||
// 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
|
||||
@@ -36,152 +46,172 @@ data class Scan(
|
||||
|
||||
return id == other.id &&
|
||||
dateTime == other.dateTime &&
|
||||
content == other.content &&
|
||||
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 &&
|
||||
contentType == other.contentType
|
||||
}
|
||||
|
||||
// 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 + dateTime.hashCode()
|
||||
result = 31 * result + content.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()
|
||||
result = 31 * result + contentType.hashCode()
|
||||
return result
|
||||
}
|
||||
|
||||
private constructor(parcel: Parcel) : this(
|
||||
content = parcel.readString() ?: "",
|
||||
raw = parcel.readSizedByteArray(),
|
||||
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(),
|
||||
dateTime = 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.apply {
|
||||
writeString(content)
|
||||
writeSizedByteArray(raw)
|
||||
writeString(format)
|
||||
writeString(errorCorrectionLevel)
|
||||
writeString(issueNumber)
|
||||
writeString(orientation)
|
||||
writeString(otherMetaData)
|
||||
writeString(pdf417ExtraMetaData)
|
||||
writeString(possibleCountry)
|
||||
writeString(suggestedPrice)
|
||||
writeString(upcEanExtension)
|
||||
writeString(dateTime)
|
||||
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()
|
||||
|
||||
private fun Parcel.writeSizedByteArray(array: ByteArray?) {
|
||||
val size = array?.size ?: 0
|
||||
writeInt(size)
|
||||
if (size > 0) {
|
||||
writeByteArray(array)
|
||||
}
|
||||
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)
|
||||
putString(SCAN_CONTENT_TYPE, contentType.name)
|
||||
}
|
||||
|
||||
private fun Parcel.readSizedByteArray(): ByteArray? {
|
||||
val size = readInt()
|
||||
return if (size > 0) {
|
||||
val array = ByteArray(size)
|
||||
readByteArray(array)
|
||||
array
|
||||
} else {
|
||||
fun Bundle.toScan(): Scan? {
|
||||
val formatName = getString(SCAN_FORMAT)?.migrateBarcodeFormatName()
|
||||
if (formatName.isNullOrEmpty()) {
|
||||
return null
|
||||
}
|
||||
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),
|
||||
contentType = parsedContentTypeFromName(getString(SCAN_CONTENT_TYPE))
|
||||
)
|
||||
} catch (_: IllegalArgumentException) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
fun Result.toScan(): Scan {
|
||||
val content: String
|
||||
val raw: ByteArray?
|
||||
if (text.hasNonPrintableCharacters()) {
|
||||
content = ""
|
||||
raw = getRawData() ?: text.toByteArray()
|
||||
} else {
|
||||
content = text
|
||||
raw = 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 Scan(
|
||||
content,
|
||||
raw,
|
||||
barcodeFormat.toString(),
|
||||
getMetaString(ResultMetadataType.ERROR_CORRECTION_LEVEL),
|
||||
getMetaString(ResultMetadataType.ISSUE_NUMBER),
|
||||
getMetaString(ResultMetadataType.ORIENTATION),
|
||||
getMetaString(ResultMetadataType.OTHER),
|
||||
getMetaString(ResultMetadataType.PDF417_EXTRA_METADATA),
|
||||
getMetaString(ResultMetadataType.POSSIBLE_COUNTRY),
|
||||
getMetaString(ResultMetadataType.SUGGESTED_PRICE),
|
||||
getMetaString(ResultMetadataType.UPC_EAN_EXTENSION)
|
||||
)
|
||||
return BitMatrix(width, height, data)
|
||||
}
|
||||
|
||||
private fun Result.getRawData(): ByteArray? {
|
||||
val metadata = 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
|
||||
}
|
||||
// If the byte segments are shorter than the converted string, the
|
||||
// content of the QR Code has been encoded with different encoding
|
||||
// modes (e.g. some parts in alphanumeric, some in byte encoding).
|
||||
// This is because Zxing only records byte segments for byte encoded
|
||||
// parts. Please note the byte segments can actually be longer than
|
||||
// the string because Zxing cuts off prefixes like "WIFI:".
|
||||
return if (bytes.size >= text.length) bytes else null
|
||||
}
|
||||
|
||||
private fun Result.getMetaString(
|
||||
key: ResultMetadataType
|
||||
): String? = this.resultMetadata?.let {
|
||||
it[key]?.toString()
|
||||
}
|
||||
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"
|
||||
private const val SCAN_CONTENT_TYPE = "content_type"
|
||||
|
||||
@@ -1,285 +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.Build
|
||||
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.*
|
||||
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 val parentJob = Job()
|
||||
private val scope = CoroutineScope(Dispatchers.IO + parentJob)
|
||||
|
||||
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 {
|
||||
it.context?.apply {
|
||||
pickFileType(R.string.share_as) { fileType ->
|
||||
shareAs(fileType)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
(view.findViewById(R.id.inset_layout) as View).setPaddingFromWindowInsets()
|
||||
imageView.doOnApplyWindowInsets { v, insets ->
|
||||
(v as ConfinedScalingImageView).insets.set(insets)
|
||||
}
|
||||
|
||||
return view
|
||||
}
|
||||
|
||||
override fun onDestroyView() {
|
||||
super.onDestroyView()
|
||||
parentJob.cancel()
|
||||
}
|
||||
|
||||
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 -> {
|
||||
context.pickFileType(R.string.export_as) {
|
||||
askForFileNameAndSave(it)
|
||||
}
|
||||
true
|
||||
}
|
||||
else -> super.onOptionsItemSelected(item)
|
||||
}
|
||||
}
|
||||
|
||||
private fun Context.pickFileType(
|
||||
title: Int,
|
||||
action: (FileType) -> Unit
|
||||
) {
|
||||
val fileTypes = FileType.values()
|
||||
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) {
|
||||
val ac = activity ?: return
|
||||
// Write permission is only required before Android Q.
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q &&
|
||||
!ac.hasWritePermission { 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
|
||||
scope.launch(Dispatchers.IO) {
|
||||
val message = ac.writeExternalFile(fileName, mimeType, write).toSaveResult()
|
||||
withContext(Dispatchers.Main) {
|
||||
ac.toast(message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun Context.shareAs(fileType: FileType) {
|
||||
when (fileType) {
|
||||
FileType.PNG -> barcodeBitmap?.let { share(it) }
|
||||
FileType.SVG -> barcodeSvg?.let { shareText(it, MIME_SVG) }
|
||||
FileType.TXT -> barcodeTxt?.let { shareText(it) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun Context.share(bitmap: Bitmap) {
|
||||
scope.launch(Dispatchers.IO) {
|
||||
val file = File(
|
||||
externalCacheDir,
|
||||
"shared_barcode.png"
|
||||
)
|
||||
val success = try {
|
||||
FileOutputStream(file).use {
|
||||
bitmap.saveAsPng(it)
|
||||
}
|
||||
true
|
||||
} catch (e: IOException) {
|
||||
false
|
||||
}
|
||||
withContext(Dispatchers.Main) {
|
||||
if (success) {
|
||||
shareFile(file, "image/png")
|
||||
} else {
|
||||
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) =
|
||||
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('_').lowercase(Locale.getDefault())
|
||||
@@ -1,425 +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 com.google.zxing.qrcode.decoder.ErrorCorrectionLevel
|
||||
import com.google.zxing.qrcode.encoder.Encoder
|
||||
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.actions.wifi.WifiConnector
|
||||
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 dataView: TableLayout
|
||||
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 raw: ByteArray = ByteArray(0)
|
||||
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 = scan.raw != null
|
||||
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(String(raw).foldNonAlNum())
|
||||
contentView.isEnabled = false
|
||||
fab.setImageResource(R.drawable.ic_action_save)
|
||||
fab.setOnClickListener {
|
||||
askForFileNameAndSave(raw)
|
||||
}
|
||||
}
|
||||
|
||||
formatView = view.findViewById(R.id.format)
|
||||
dataView = view.findViewById(R.id.data)
|
||||
metaView = view.findViewById(R.id.meta)
|
||||
hexView = view.findViewById(R.id.hex)
|
||||
|
||||
updateViewsAndAction(raw)
|
||||
|
||||
if (!isBinary) {
|
||||
fillDataView(dataView, inputContent)
|
||||
}
|
||||
|
||||
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 fillDataView(tableLayout: TableLayout, content: String) {
|
||||
val items = LinkedHashMap<Int, String?>()
|
||||
if (action is WifiAction) {
|
||||
WifiConnector.parseMap(content)?.let { wifiData ->
|
||||
items.putAll(
|
||||
linkedMapOf(
|
||||
R.string.entry_type to getString(R.string.wifi_network),
|
||||
R.string.wifi_ssid to wifiData["S"],
|
||||
R.string.wifi_password to wifiData["P"],
|
||||
R.string.wifi_type to wifiData["T"],
|
||||
R.string.wifi_hidden to wifiData["H"],
|
||||
R.string.wifi_eap to wifiData["E"],
|
||||
R.string.wifi_identity to wifiData["I"],
|
||||
R.string.wifi_anonymous_identity to wifiData["A"],
|
||||
R.string.wifi_phase2 to wifiData["PH2"]
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
fillDataTable(tableLayout, items)
|
||||
}
|
||||
|
||||
private fun fillMetaView(tableLayout: TableLayout, scan: Scan) {
|
||||
val items = linkedMapOf(
|
||||
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
|
||||
)
|
||||
if (prefs.showQrVersion && scan.format == "QR_CODE") {
|
||||
items.putAll(
|
||||
linkedMapOf(
|
||||
R.string.qr_version to "${scan.version()}"
|
||||
)
|
||||
)
|
||||
}
|
||||
fillDataTable(tableLayout, items)
|
||||
}
|
||||
|
||||
private fun fillDataTable(
|
||||
tableLayout: TableLayout,
|
||||
items: LinkedHashMap<Int, String?>
|
||||
) {
|
||||
val ctx = tableLayout.context
|
||||
val spaceBetween = (16f * ctx.resources.displayMetrics.density).toInt()
|
||||
items.forEach { item ->
|
||||
val text = item.value
|
||||
if (!text.isNullOrBlank()) {
|
||||
val tr = TableRow(ctx)
|
||||
val keyView = TextView(ctx)
|
||||
keyView.setText(item.key)
|
||||
val valueView = TextView(ctx)
|
||||
valueView.setPadding(spaceBetween, 0, 0, 0)
|
||||
valueView.text = text
|
||||
tr.addView(keyView)
|
||||
tr.addView(valueView)
|
||||
tableLayout.addView(tr)
|
||||
}
|
||||
}
|
||||
if (tableLayout.childCount > 0) {
|
||||
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(textOrHex())
|
||||
maybeBackOrFinish()
|
||||
true
|
||||
}
|
||||
R.id.share -> {
|
||||
context?.apply {
|
||||
shareText(textOrHex())
|
||||
maybeBackOrFinish()
|
||||
}
|
||||
true
|
||||
}
|
||||
R.id.create -> {
|
||||
fragmentManager?.addFragment(
|
||||
EncodeFragment.newInstance(content, format)
|
||||
)
|
||||
true
|
||||
}
|
||||
R.id.remove -> {
|
||||
db.removeScan(id)
|
||||
backOrFinish()
|
||||
true
|
||||
}
|
||||
else -> super.onOptionsItemSelected(item)
|
||||
}
|
||||
}
|
||||
|
||||
private fun textOrHex() = if (isBinary) {
|
||||
raw.toHexString()
|
||||
} else {
|
||||
content
|
||||
}
|
||||
|
||||
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 &&
|
||||
!ac.hasLocationPermission { executeAction(content) }
|
||||
) {
|
||||
return
|
||||
}
|
||||
scope.launch {
|
||||
action.execute(ac, content)
|
||||
maybeBackOrFinish()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun askForFileNameAndSave(raw: ByteArray) {
|
||||
val ac = activity ?: return
|
||||
// Write permission is only required before Android Q.
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q &&
|
||||
!ac.hasWritePermission { askForFileNameAndSave(raw) }
|
||||
) {
|
||||
return
|
||||
}
|
||||
scope.launch(Dispatchers.Main) {
|
||||
val name = ac.askForFileName() ?: return@launch
|
||||
val message = ac.writeExternalFile(
|
||||
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.toInt().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()
|
||||
}
|
||||
|
||||
private fun Scan.version(): Int = Encoder.encode(
|
||||
content,
|
||||
ErrorCorrectionLevel.valueOf(errorCorrectionLevel ?: "L")
|
||||
).version.versionNumber
|
||||
@@ -1,201 +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)
|
||||
fragmentManager?.addFragment(
|
||||
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,79 +1,224 @@
|
||||
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.database.Cursor
|
||||
import android.net.Uri
|
||||
import android.net.wifi.WifiManager
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.support.annotation.RequiresApi
|
||||
import android.support.v14.preference.MultiSelectListPreference
|
||||
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 android.provider.OpenableColumns
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.annotation.RequiresApi
|
||||
import androidx.core.net.toUri
|
||||
import androidx.preference.EditTextPreference
|
||||
import androidx.preference.ListPreference
|
||||
import androidx.preference.MultiSelectListPreference
|
||||
import androidx.preference.Preference
|
||||
import androidx.preference.PreferenceFragmentCompat
|
||||
import androidx.preference.PreferenceGroup
|
||||
import com.google.android.material.dialog.MaterialAlertDialogBuilder
|
||||
import de.markusfisch.android.binaryeye.R
|
||||
import de.markusfisch.android.binaryeye.actions.wifi.removeNetworkSuggestions
|
||||
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.Preferences
|
||||
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 pickBeepTone = registerForActivityResult(
|
||||
ActivityResultContracts.OpenDocument()
|
||||
) { uri ->
|
||||
if (uri != null) {
|
||||
setCustomBeepTone(uri)
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
DYNAMIC_COLORS -> {
|
||||
activity?.restartApp()
|
||||
return
|
||||
}
|
||||
|
||||
BEEP_TONE_NAME,
|
||||
BEEP_STREAM_NAME -> activity?.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)
|
||||
wireClearNetworkPreferences()
|
||||
loadPreferences(rootKey)
|
||||
}
|
||||
|
||||
private fun wireClearNetworkPreferences() {
|
||||
val pref = findPreference("clear_network_suggestions") ?: return
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
|
||||
pref.isVisible = false
|
||||
} else {
|
||||
pref.setOnPreferenceClickListener {
|
||||
askToClearNetworkSuggestions(context)
|
||||
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()
|
||||
|
||||
wireBeepTonePicker()
|
||||
wireProfiles()
|
||||
wireAutomatedActions()
|
||||
wireIgnoreCodes()
|
||||
setBluetoothResources()
|
||||
wireClearNetworkPreferences()
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
|
||||
findPreference<PreferenceGroup>("appearance_category")?.isVisible = false
|
||||
}
|
||||
}
|
||||
|
||||
private fun wireProfiles() {
|
||||
findPreference<Preference>(PROFILE)?.apply {
|
||||
updateProfileSummary(this)
|
||||
onPreferenceClickListener = Preference.OnPreferenceClickListener {
|
||||
startActivity(Intent(activity, ProfilesActivity::class.java))
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun wireBeepTonePicker() {
|
||||
findPreference<ListPreference>(BEEP_TONE_NAME)?.apply {
|
||||
onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue ->
|
||||
val toneName = newValue as? String ?: return@OnPreferenceChangeListener false
|
||||
if (toneName == Preferences.CUSTOM_BEEP_TONE_NAME) {
|
||||
pickBeepTone.launch(arrayOf("audio/*"))
|
||||
false
|
||||
} else {
|
||||
if (prefs.usesCustomBeepTone()) {
|
||||
clearCustomBeepTone()
|
||||
}
|
||||
prefs.beepToneName = toneName
|
||||
value = toneName
|
||||
setSummary(this)
|
||||
activity?.beepConfirm()
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 askToClearNetworkSuggestions(context: Context) {
|
||||
AlertDialog.Builder(context)
|
||||
private fun Context.askToClearNetworkSuggestions() {
|
||||
MaterialAlertDialogBuilder(this)
|
||||
.setMessage(R.string.really_remove_all_networks)
|
||||
.setPositiveButton(android.R.string.ok) { _, _ ->
|
||||
clearNetworkSuggestions(context)
|
||||
clearNetworkSuggestions()
|
||||
}
|
||||
.setNegativeButton(android.R.string.cancel) { _, _ -> }
|
||||
.show()
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.Q)
|
||||
private fun clearNetworkSuggestions(context: Context) {
|
||||
context.toast(
|
||||
if (
|
||||
removeNetworkSuggestions(context) == WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS
|
||||
private fun Context.clearNetworkSuggestions() {
|
||||
toast(
|
||||
if (removeAllNetworkSuggestions() ==
|
||||
WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS
|
||||
) {
|
||||
R.string.clear_network_suggestions_success
|
||||
} else {
|
||||
@@ -84,27 +229,43 @@ class PreferencesFragment : PreferenceFragmentCompat() {
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -118,37 +279,229 @@ class PreferencesFragment : PreferenceFragmentCompat() {
|
||||
}
|
||||
|
||||
private fun setSummary(preference: Preference) {
|
||||
when (preference) {
|
||||
is UrlPreference -> {
|
||||
preference.setSummary(preference.getUrl())
|
||||
}
|
||||
is ListPreference -> {
|
||||
preference.setSummary(preference.entry)
|
||||
}
|
||||
is MultiSelectListPreference -> {
|
||||
preference.setSummary(
|
||||
preference.values.joinToString(", ") {
|
||||
it.replace(Regex("_"), " ")
|
||||
}
|
||||
)
|
||||
}
|
||||
is PreferenceGroup -> {
|
||||
setSummaries(preference)
|
||||
when (preference.key) {
|
||||
AUTOMATED_ACTIONS -> return updateAutomatedActionsSummary(preference)
|
||||
IGNORE_CODES -> return updateIgnoreCodesSummary(preference)
|
||||
BEEP_TONE_NAME -> {
|
||||
setBeepToneSummary(preference)
|
||||
return
|
||||
}
|
||||
}
|
||||
when (preference) {
|
||||
is EditTextPreference -> preference.summary = preference.text
|
||||
is UrlPreference -> preference.summary = preference.getUrl()
|
||||
is ListPreference -> preference.setSummary(preference.entry)
|
||||
is MultiSelectListPreference -> preference.summary =
|
||||
getSortedSummary(preference)
|
||||
|
||||
is PreferenceGroup -> setSummaries(preference)
|
||||
}
|
||||
}
|
||||
|
||||
private fun setBeepToneSummary(preference: Preference) {
|
||||
preference.summary = if (prefs.usesCustomBeepTone()) {
|
||||
getBeepToneLabel(prefs.beepToneUri.toUri())
|
||||
} else {
|
||||
findPreference<ListPreference>(BEEP_TONE_NAME)?.let {
|
||||
val index = it.findIndexOfValue(prefs.beepToneName)
|
||||
if (index >= 0) {
|
||||
it.entries[index]
|
||||
} else {
|
||||
""
|
||||
}
|
||||
} ?: ""
|
||||
}
|
||||
}
|
||||
|
||||
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_device_id", R.drawable.ic_label)
|
||||
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("strip_tracking_params", R.drawable.ic_action_remove)
|
||||
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)
|
||||
setIcon(DYNAMIC_COLORS, 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.profileLabel(requireContext(), prefs.profile)
|
||||
lastProfile = prefs.profile
|
||||
}
|
||||
|
||||
private fun setCustomBeepTone(uri: Uri) {
|
||||
val context = requireContext()
|
||||
val resolver = context.contentResolver
|
||||
clearCustomBeepTone()
|
||||
try {
|
||||
resolver.takePersistableUriPermission(
|
||||
uri,
|
||||
Intent.FLAG_GRANT_READ_URI_PERMISSION
|
||||
)
|
||||
} catch (e: SecurityException) {
|
||||
val message = e.message
|
||||
if (!message.isNullOrEmpty()) {
|
||||
context.toast(message)
|
||||
}
|
||||
return
|
||||
}
|
||||
prefs.beepToneUri = uri.toString()
|
||||
prefs.beepToneName = Preferences.CUSTOM_BEEP_TONE_NAME
|
||||
findPreference<ListPreference>(BEEP_TONE_NAME)?.apply {
|
||||
value = Preferences.CUSTOM_BEEP_TONE_NAME
|
||||
setSummary(this)
|
||||
}
|
||||
activity?.beepConfirm()
|
||||
}
|
||||
|
||||
private fun clearCustomBeepTone(releaseSelection: Boolean = true) {
|
||||
if (releaseSelection) {
|
||||
releaseBeepTonePermission(prefs.beepToneUri)
|
||||
}
|
||||
prefs.beepToneUri = ""
|
||||
}
|
||||
|
||||
private fun releaseBeepTonePermission(uriString: String) {
|
||||
if (uriString.isEmpty()) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
requireContext().contentResolver.releasePersistableUriPermission(
|
||||
uriString.toUri(),
|
||||
Intent.FLAG_GRANT_READ_URI_PERMISSION
|
||||
)
|
||||
} catch (_: SecurityException) {
|
||||
}
|
||||
}
|
||||
|
||||
private fun getBeepToneLabel(uri: Uri): String {
|
||||
var cursor: Cursor? = null
|
||||
return try {
|
||||
cursor = requireContext().contentResolver.query(
|
||||
uri,
|
||||
arrayOf(OpenableColumns.DISPLAY_NAME),
|
||||
null,
|
||||
null,
|
||||
null
|
||||
)
|
||||
if (cursor?.moveToFirst() == true) {
|
||||
cursor.getString(0)
|
||||
} else {
|
||||
uri.lastPathSegment ?: uri.toString()
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
uri.lastPathSegment ?: uri.toString()
|
||||
} finally {
|
||||
cursor?.close()
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val PROFILE = "profile"
|
||||
private const val AUTOMATED_ACTIONS = "automated_actions"
|
||||
private const val BEEP_TONE_NAME = "beep_tone_name"
|
||||
private const val BEEP_STREAM_NAME = "beep_stream_name"
|
||||
private const val CLEAR_NETWORK_SUGGESTIONS = "clear_network_suggestions"
|
||||
private const val CUSTOM_LOCALE = "custom_locale"
|
||||
private const val DYNAMIC_COLORS = "dynamic_colors"
|
||||
private const val IGNORE_CODES = "ignore_codes"
|
||||
private const val SEND_SCAN_BLUETOOTH = "send_scan_bluetooth"
|
||||
private const val SEND_SCAN_BLUETOOTH_HOST = "send_scan_bluetooth_host"
|
||||
}
|
||||
}
|
||||
|
||||
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.
|
||||
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)
|
||||
}
|
||||
@@ -47,19 +48,14 @@ class UrlDialogFragment : PreferenceDialogFragmentCompat() {
|
||||
}
|
||||
textView ?: return
|
||||
textView.text = "…"
|
||||
Scan(
|
||||
"test",
|
||||
null,
|
||||
"none",
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null
|
||||
).sendAsync(url, prefs.sendScanType) { code, body ->
|
||||
textView.context.sendAsync(
|
||||
Scan(
|
||||
"test",
|
||||
null,
|
||||
BarcodeFormat.None
|
||||
),
|
||||
url
|
||||
) { code, body ->
|
||||
textView.text = when {
|
||||
code != null -> "$code"
|
||||
body != null -> body
|
||||
@@ -87,10 +83,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
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ fun ContentResolver.loadImageUri(uri: Uri): Bitmap? = try {
|
||||
openInputStream(uri)?.use {
|
||||
BitmapFactory.decodeStream(it, null, options)
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
} catch (_: IOException) {
|
||||
null
|
||||
}
|
||||
|
||||
@@ -49,18 +49,23 @@ private fun calculateInSampleSize(
|
||||
return inSampleSize
|
||||
}
|
||||
|
||||
fun Bitmap.crop(rect: RectF, rotation: Float) = try {
|
||||
val erected = erect(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.right * w).roundToInt() - x),
|
||||
min(h - y, (rect.bottom * h).roundToInt() - y)
|
||||
min(w, (rect.right * w).roundToInt()) - x,
|
||||
min(h, (rect.bottom * h).roundToInt()) - y
|
||||
)
|
||||
} catch (e: OutOfMemoryError) {
|
||||
null
|
||||
@@ -68,9 +73,11 @@ fun Bitmap.crop(rect: RectF, rotation: Float) = try {
|
||||
null
|
||||
}
|
||||
|
||||
private fun Bitmap.erect(rotation: Float): Bitmap = if (
|
||||
rotation % 360f != 0f
|
||||
) {
|
||||
private fun Bitmap.rotate(
|
||||
rotation: Float,
|
||||
pivotX: Float,
|
||||
pivotY: Float
|
||||
): Bitmap = if (rotation % 360f != 0f) {
|
||||
Bitmap.createBitmap(
|
||||
this,
|
||||
0,
|
||||
@@ -78,7 +85,7 @@ private fun Bitmap.erect(rotation: Float): Bitmap = if (
|
||||
width,
|
||||
height,
|
||||
Matrix().apply {
|
||||
setRotate(rotation)
|
||||
setRotate(rotation, pivotX, pivotY)
|
||||
},
|
||||
true
|
||||
)
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
package de.markusfisch.android.binaryeye.graphics
|
||||
|
||||
const val COLOR_BLACK = 0xff000000.toInt()
|
||||
const val COLOR_WHITE = 0xffffffff.toInt()
|
||||
@@ -3,12 +3,12 @@ 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 {
|
||||
val dp = resources.displayMetrics.density
|
||||
color = ContextCompat.getColor(applicationContext, R.color.crop_bound)
|
||||
color = ContextCompat.getColor(this@getDashedBorderPaint, R.color.crop_bound)
|
||||
style = Paint.Style.STROKE
|
||||
strokeWidth = dp * 2f
|
||||
pathEffect = DashPathEffect(floatArrayOf(10f * dp, 10f * dp), 0f)
|
||||
|
||||
@@ -1,30 +1,32 @@
|
||||
package de.markusfisch.android.binaryeye.graphics
|
||||
|
||||
import android.content.res.Resources
|
||||
import android.content.res.Resources.Theme
|
||||
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))
|
||||
): Bitmap = getBitmapFromDrawable(resId, null)
|
||||
|
||||
fun Resources.getDrawableCompat(
|
||||
resId: Int
|
||||
): Drawable = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
|
||||
getDrawable(resId, null)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
getDrawable(resId)
|
||||
}
|
||||
fun Resources.getBitmapFromDrawable(
|
||||
resId: Int,
|
||||
theme: Theme?
|
||||
): Bitmap = getBitmapFromDrawable(
|
||||
ResourcesCompat.getDrawable(this, resId, theme) ?: 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
|
||||
|
||||
@@ -2,61 +2,152 @@ package de.markusfisch.android.binaryeye.graphics
|
||||
|
||||
import android.graphics.Matrix
|
||||
import android.graphics.Rect
|
||||
import com.google.zxing.ResultPoint
|
||||
import android.graphics.RectF
|
||||
import de.markusfisch.android.zxingcpp.ZxingCpp.Position
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
fun mapResultToView(
|
||||
frameWidth: Int,
|
||||
frameHeight: Int,
|
||||
frameOrientation: Int,
|
||||
viewRect: Rect,
|
||||
resultPoints: Array<ResultPoint?>,
|
||||
targetArray: FloatArray
|
||||
): Int = getFrameToViewMatrix(
|
||||
frameWidth,
|
||||
frameHeight,
|
||||
frameOrientation,
|
||||
viewRect
|
||||
).map(
|
||||
resultPoints,
|
||||
targetArray
|
||||
)
|
||||
|
||||
fun getFrameToViewMatrix(
|
||||
frameWidth: Int,
|
||||
frameHeight: Int,
|
||||
frameOrientation: Int,
|
||||
viewRect: Rect
|
||||
) = Matrix().apply {
|
||||
// Normalize to frame dimensions for rotation.
|
||||
postScale(
|
||||
1f / frameWidth,
|
||||
1f / frameHeight
|
||||
)
|
||||
// Rotate around center.
|
||||
postRotate(frameOrientation.toFloat(), 0.5f, 0.5f)
|
||||
// Scale up to view size.
|
||||
postScale(viewRect.width().toFloat(), viewRect.height().toFloat())
|
||||
// Apply view displacement.
|
||||
postTranslate(viewRect.left.toFloat(), viewRect.top.toFloat())
|
||||
data class FrameMetrics(
|
||||
var width: Int = 0,
|
||||
var height: Int = 0,
|
||||
var orientation: Int = 0
|
||||
) {
|
||||
fun isValid() = width > 0 && height > 0
|
||||
}
|
||||
|
||||
fun Matrix.map(
|
||||
resultPoints: Array<ResultPoint?>,
|
||||
targetArray: FloatArray
|
||||
): Int {
|
||||
val max = targetArray.size
|
||||
var i = 0
|
||||
for (resultPoint in resultPoints) {
|
||||
// Because ZXing apparently returns null in this array sometimes.
|
||||
if (resultPoint == null) {
|
||||
continue
|
||||
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()
|
||||
)
|
||||
mapRect(frameRoiF, viewRoiF)
|
||||
set(
|
||||
frameRoiF.left.roundToInt(),
|
||||
frameRoiF.top.roundToInt(),
|
||||
frameRoiF.right.roundToInt(),
|
||||
frameRoiF.bottom.roundToInt()
|
||||
)
|
||||
}
|
||||
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
|
||||
}
|
||||
targetArray[i++] = resultPoint.x
|
||||
targetArray[i++] = resultPoint.y
|
||||
if (i >= max) {
|
||||
break
|
||||
|
||||
else -> {
|
||||
uprightWidth = frameMetrics.width
|
||||
uprightHeight = frameMetrics.height
|
||||
}
|
||||
}
|
||||
mapPoints(targetArray, 0, targetArray, 0, i)
|
||||
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 Rect.setCovered(
|
||||
viewWidth: Int,
|
||||
viewHeight: Int,
|
||||
frameMetrics: FrameMetrics
|
||||
) {
|
||||
val frameWidth: Int
|
||||
val frameHeight: Int
|
||||
when (frameMetrics.orientation) {
|
||||
90, 270 -> {
|
||||
frameWidth = frameMetrics.height
|
||||
frameHeight = frameMetrics.width
|
||||
}
|
||||
|
||||
else -> {
|
||||
frameWidth = frameMetrics.width
|
||||
frameHeight = frameMetrics.height
|
||||
}
|
||||
}
|
||||
if (frameWidth < 1 || frameHeight < 1) {
|
||||
set(0, 0, 0, 0)
|
||||
return
|
||||
}
|
||||
var coveredWidth = frameWidth
|
||||
var coveredHeight = frameHeight
|
||||
if (viewWidth.toLong() * coveredWidth <
|
||||
viewHeight.toLong() * coveredHeight
|
||||
) {
|
||||
coveredWidth = coveredWidth * viewHeight / coveredHeight
|
||||
coveredHeight = viewHeight
|
||||
} else {
|
||||
coveredHeight = coveredHeight * viewWidth / coveredWidth
|
||||
coveredWidth = viewWidth
|
||||
}
|
||||
val left = (viewWidth - coveredWidth) / 2
|
||||
val top = (viewHeight - coveredHeight) / 2
|
||||
set(
|
||||
left,
|
||||
top,
|
||||
left + coveredWidth,
|
||||
top + coveredHeight
|
||||
)
|
||||
}
|
||||
|
||||
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
|
||||
@@ -53,7 +53,7 @@ fun Context.writeExternalFile(
|
||||
): Boolean = try {
|
||||
openExternalOutputStream(fileName, mimeType).use { write(it) }
|
||||
true
|
||||
} catch (e: IOException) {
|
||||
} catch (_: IOException) {
|
||||
false
|
||||
}
|
||||
|
||||
@@ -61,7 +61,6 @@ 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
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
package de.markusfisch.android.binaryeye.media
|
||||
|
||||
import android.content.Context
|
||||
import android.media.AudioAttributes
|
||||
import android.media.AudioManager
|
||||
import android.media.MediaPlayer
|
||||
import android.media.ToneGenerator
|
||||
import androidx.core.net.toUri
|
||||
import de.markusfisch.android.binaryeye.app.prefs
|
||||
|
||||
private var confirmToneGenerator: ToneGenerator? = null
|
||||
private var confirmToneStream = AudioManager.STREAM_MUSIC
|
||||
private var confirmMediaPlayer: MediaPlayer? = null
|
||||
private var errorToneGenerator: ToneGenerator? = null
|
||||
|
||||
fun Context.beepConfirm() {
|
||||
val stream = prefs.beepStream()
|
||||
if (prefs.usesCustomBeepTone() &&
|
||||
playCustomConfirmTone(prefs.beepToneUri, stream)
|
||||
) {
|
||||
return
|
||||
}
|
||||
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())
|
||||
}
|
||||
|
||||
private fun Context.playCustomConfirmTone(
|
||||
uriString: String,
|
||||
stream: Int
|
||||
): Boolean {
|
||||
return try {
|
||||
confirmToneGenerator?.release()
|
||||
confirmToneGenerator = null
|
||||
confirmToneStream = stream
|
||||
confirmMediaPlayer?.release()
|
||||
confirmMediaPlayer = MediaPlayer().also { mp ->
|
||||
mp.apply {
|
||||
setAudioAttributes(
|
||||
AudioAttributes.Builder()
|
||||
.setLegacyStreamType(stream)
|
||||
.build()
|
||||
)
|
||||
setDataSource(this@playCustomConfirmTone, uriString.toUri())
|
||||
setOnCompletionListener { completed ->
|
||||
if (confirmMediaPlayer === completed) {
|
||||
confirmMediaPlayer = null
|
||||
}
|
||||
completed.release()
|
||||
}
|
||||
setOnErrorListener { failed, _, _ ->
|
||||
if (confirmMediaPlayer === failed) {
|
||||
confirmMediaPlayer = null
|
||||
}
|
||||
failed.release()
|
||||
true
|
||||
}
|
||||
prepare()
|
||||
start()
|
||||
}
|
||||
}
|
||||
true
|
||||
} catch (_: Exception) {
|
||||
confirmMediaPlayer?.release()
|
||||
confirmMediaPlayer = null
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
confirmMediaPlayer?.release()
|
||||
confirmMediaPlayer = null
|
||||
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,7 +1,8 @@
|
||||
package de.markusfisch.android.binaryeye.net
|
||||
|
||||
import de.markusfisch.android.binaryeye.app.toHexString
|
||||
import de.markusfisch.android.binaryeye.app.urlEncode
|
||||
import android.content.Context
|
||||
import de.markusfisch.android.binaryeye.app.prefs
|
||||
import de.markusfisch.android.binaryeye.content.openUrl
|
||||
import de.markusfisch.android.binaryeye.database.Scan
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -16,68 +17,109 @@ import java.net.HttpURLConnection
|
||||
import java.net.ProtocolException
|
||||
import java.net.URL
|
||||
|
||||
fun Scan.sendAsync(
|
||||
url: String,
|
||||
type: String,
|
||||
private const val SEND_TYPE_GET_ADD_CONTENT = "0"
|
||||
private const val SEND_TYPE_GET_QUERY_STRING = "1"
|
||||
private const val SEND_TYPE_POST_FORM = "2"
|
||||
private const val SEND_TYPE_POST_JSON = "3"
|
||||
private const val SEND_TYPE_EXTERNAL_BROWSER = "4"
|
||||
|
||||
fun Context.sendAsync(
|
||||
scan: Scan,
|
||||
url: String = prefs.sendScanUrl,
|
||||
type: String = prefs.sendScanType,
|
||||
callback: (Int?, String?) -> Unit
|
||||
) {
|
||||
val extras = mapOf(
|
||||
"deviceId" to prefs.sendScanDeviceId.trim()
|
||||
)
|
||||
if (type == SEND_TYPE_EXTERNAL_BROWSER) {
|
||||
openUrl(buildUrl(url, scan.asUrlArguments(extras)))
|
||||
return
|
||||
}
|
||||
CoroutineScope(Dispatchers.IO).launch(Dispatchers.IO) {
|
||||
val response = send(url, type)
|
||||
val response = scan.send(url, type, extras) ?: return@launch
|
||||
withContext(Dispatchers.Main) {
|
||||
callback(response.code, response.body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun Scan.send(url: String, type: String): Response {
|
||||
return when (type) {
|
||||
"1" -> request(
|
||||
url + "?" + asUrlArguments()
|
||||
private fun Scan.send(
|
||||
url: String,
|
||||
type: String,
|
||||
extras: Map<String, String>
|
||||
): Response? = when (type) {
|
||||
SEND_TYPE_GET_ADD_CONTENT -> request(
|
||||
buildUrl(url, text.urlEncode())
|
||||
)
|
||||
|
||||
SEND_TYPE_GET_QUERY_STRING -> request(
|
||||
buildUrl(url, asUrlArguments(extras))
|
||||
)
|
||||
|
||||
SEND_TYPE_POST_FORM -> request(url) { con ->
|
||||
con.requestMethod = "POST"
|
||||
con.setRequestProperty(
|
||||
"Content-Type",
|
||||
"application/x-www-form-urlencoded"
|
||||
)
|
||||
"2" -> request(url) { con ->
|
||||
con.requestMethod = "POST"
|
||||
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
|
||||
con.outputStream.apply {
|
||||
write(asUrlArguments().toByteArray())
|
||||
close()
|
||||
}
|
||||
con.outputStream.apply {
|
||||
write(asUrlArguments(extras).toByteArray())
|
||||
close()
|
||||
}
|
||||
"3" -> request(url) { con ->
|
||||
con.requestMethod = "POST"
|
||||
con.setRequestProperty("Content-Type", "application/json")
|
||||
con.outputStream.apply {
|
||||
write(asJson().toString().toByteArray())
|
||||
close()
|
||||
}
|
||||
}
|
||||
else -> request(
|
||||
url + content.urlEncode()
|
||||
)
|
||||
}
|
||||
|
||||
SEND_TYPE_POST_JSON -> request(url) { con ->
|
||||
con.requestMethod = "POST"
|
||||
con.setRequestProperty("Content-Type", "application/json")
|
||||
con.outputStream.apply {
|
||||
write(asJson(extras).toString().toByteArray())
|
||||
close()
|
||||
}
|
||||
}
|
||||
|
||||
else -> null
|
||||
}
|
||||
|
||||
private fun Scan.asUrlArguments(): String = getMap().map { (k, v) ->
|
||||
private fun buildUrl(url: String, arguments: String): String {
|
||||
if (arguments.isEmpty()) {
|
||||
return url
|
||||
}
|
||||
val separator = when {
|
||||
url.endsWith("?") || url.endsWith("&") -> ""
|
||||
url.contains("?") -> "&"
|
||||
else -> "?"
|
||||
}
|
||||
return url + separator + arguments
|
||||
}
|
||||
|
||||
private fun Scan.asUrlArguments(
|
||||
extras: Map<String, String>
|
||||
): String = getMap(extras).map { (k, v) ->
|
||||
"${k}=${v.urlEncode()}"
|
||||
}.joinToString("&")
|
||||
|
||||
private fun Scan.asJson() = JSONObject().apply {
|
||||
getMap().forEach { (k, v) -> put(k, v) }
|
||||
private fun Scan.asJson(
|
||||
extras: Map<String, String>
|
||||
) = JSONObject().apply {
|
||||
getMap(extras).forEach { (k, v) -> put(k, v) }
|
||||
}
|
||||
|
||||
private fun Scan.getMap(): Map<String, String> = mapOf(
|
||||
"content" to content,
|
||||
private fun Scan.getMap(extras: Map<String, String>): Map<String, String> = (mapOf(
|
||||
"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 dateTime
|
||||
).filterNullValues()
|
||||
"timestamp" to dateTime,
|
||||
) + extras).filterNullValues()
|
||||
|
||||
private fun Map<String, String?>.filterNullValues() =
|
||||
filterValues { it != null }.mapValues { it.value as String }
|
||||
|
||||
@@ -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,14 @@
|
||||
package de.markusfisch.android.binaryeye.os
|
||||
|
||||
import android.app.Activity
|
||||
import android.os.Build
|
||||
import android.view.WindowManager
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
fun Activity.showWhenLocked() {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
|
||||
setShowWhenLocked(true)
|
||||
} else {
|
||||
window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -4,10 +4,8 @@ import android.content.Context
|
||||
import android.os.Build
|
||||
import android.os.VibrationEffect
|
||||
import android.os.Vibrator
|
||||
import android.os.VibratorManager
|
||||
import de.markusfisch.android.binaryeye.app.prefs
|
||||
|
||||
private const val DURATION_IN_MS = 100L
|
||||
private const val DURATION_IN_MS = 250L
|
||||
|
||||
private val beforeO = Build.VERSION.SDK_INT < Build.VERSION_CODES.O
|
||||
private val errorPatternTimings = longArrayOf(
|
||||
@@ -17,7 +15,9 @@ private val errorPatternAmplitudes = intArrayOf(
|
||||
255, 0, 255, 0, 255
|
||||
)
|
||||
|
||||
fun Context.getVibrator(): Vibrator = if (
|
||||
// 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")
|
||||
@@ -26,12 +26,18 @@ fun Context.getVibrator(): Vibrator = if (
|
||||
(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
|
||||
} else if (beforeO) {
|
||||
if (beforeO) {
|
||||
@Suppress("DEPRECATION")
|
||||
vibrate(DURATION_IN_MS)
|
||||
} else {
|
||||
@@ -45,9 +51,7 @@ fun Vibrator.vibrate() {
|
||||
}
|
||||
|
||||
fun Vibrator.error() {
|
||||
if (!prefs.vibrate) {
|
||||
return
|
||||
} else if (beforeO) {
|
||||
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}"
|
||||