Compare commits
742
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2b350e69d5 | ||
|
|
71c3a73abf | ||
|
|
43e5e67752 | ||
|
|
ab88112915 | ||
|
|
dae934d136 | ||
|
|
71764ef0b8 | ||
|
|
c9ee36cec5 | ||
|
|
23adec2122 | ||
|
|
e22befd4c2 | ||
|
|
55dfb08aa3 | ||
|
|
3bc2240407 | ||
|
|
e46891ae87 | ||
|
|
a110e84119 | ||
|
|
c2a667725b | ||
|
|
d46d795741 | ||
|
|
981a966b82 | ||
|
|
ce31e506f8 | ||
|
|
74549b2ec0 | ||
|
|
e5a5c10dea | ||
|
|
e8d651fe96 | ||
|
|
524c4cbb90 | ||
|
|
1bd055a0b7 | ||
|
|
2c3e909515 | ||
|
|
5e03916d12 | ||
|
|
ec060056dd | ||
|
|
e23a87c672 | ||
|
|
ed72920da1 | ||
|
|
84acc33bd6 | ||
|
|
efe454f200 | ||
|
|
0884288d8f | ||
|
|
b1ff5912fc | ||
|
|
10e18ef888 | ||
|
|
14f2dfe158 | ||
|
|
00a8040efe | ||
|
|
07a2bb632f | ||
|
|
281d511402 | ||
|
|
ad5f0f4662 | ||
|
|
a902f5f862 | ||
|
|
783916e3a7 | ||
|
|
09c20ee90f | ||
|
|
fb178a779e | ||
|
|
95c40c9d88 | ||
|
|
34cd75e9a3 | ||
|
|
8df21b965a | ||
|
|
6758b7fada | ||
|
|
1aa66ffc99 | ||
|
|
d39ceb9ee0 | ||
|
|
70f72d03db | ||
|
|
081675906b | ||
|
|
dca98bbb2d | ||
|
|
661300728a | ||
|
|
93b795ed72 | ||
|
|
18b9f19a61 | ||
|
|
6b108fb585 | ||
|
|
f18ae694a7 | ||
|
|
d5b51f2c01 | ||
|
|
b2498d362b | ||
|
|
8e99c46f3e | ||
|
|
dda0164c9f | ||
|
|
1e83000696 | ||
|
|
bbcb8e00ed | ||
|
|
d943937b3a | ||
|
|
05887d2ed0 | ||
|
|
f181ae7ac9 | ||
|
|
04f3b7ec8f | ||
|
|
028d8d0e1e | ||
|
|
d1880d04b2 | ||
|
|
05ac15f63c | ||
|
|
30af150197 | ||
|
|
31ba82a295 | ||
|
|
0345b6a713 | ||
|
|
99a584a82d | ||
|
|
f1554fbcf3 | ||
|
|
2e71e4dc5f | ||
|
|
6a384b03e9 | ||
|
|
738a28fc0a | ||
|
|
955dccff2b | ||
|
|
041f8ec2f7 | ||
|
|
10208a332e | ||
|
|
0a36a6d287 | ||
|
|
d5079f0618 | ||
|
|
3ed56b8596 | ||
|
|
1e2ed15e82 | ||
|
|
145ef6c6bf | ||
|
|
08d2452c51 | ||
|
|
126f1d51ef | ||
|
|
6161efab40 | ||
|
|
9ed6bbbe8e | ||
|
|
a6ff2c06ef | ||
|
|
34e8e8571c | ||
|
|
b1e03db27c | ||
|
|
a026f24bed | ||
|
|
2c71b7da4a | ||
|
|
2dbc4c49b7 | ||
|
|
3f4bf65b1a | ||
|
|
026970501e | ||
|
|
46882d154e | ||
|
|
e5d9b4965b | ||
|
|
c6901c9c63 | ||
|
|
8754f046f2 | ||
|
|
14a0725b21 | ||
|
|
bb075d052e | ||
|
|
e88ad7f533 | ||
|
|
5c05563785 | ||
|
|
67052352ac | ||
|
|
88de8f42b0 | ||
|
|
88c64d5786 | ||
|
|
328c874670 | ||
|
|
50e1c4e25e | ||
|
|
c03dba9f90 | ||
|
|
5394898af7 | ||
|
|
d05af5d765 | ||
|
|
739c5f2a50 | ||
|
|
2269c2648b | ||
|
|
fe7a4b4719 | ||
|
|
5e7918f105 | ||
|
|
2a452125eb | ||
|
|
47f3844d75 | ||
|
|
f2b27bf6ac | ||
|
|
44ccc15341 | ||
|
|
6e1bbf8ec4 | ||
|
|
5ee25c2115 | ||
|
|
38e7910d3c | ||
|
|
90b640054a | ||
|
|
aa1ce0405a | ||
|
|
6a9274402a | ||
|
|
9511444c6b | ||
|
|
9577e6c0c8 | ||
|
|
4186640a63 | ||
|
|
22173be22e | ||
|
|
dad1f2cd9c | ||
|
|
60166b349d | ||
|
|
db8d649467 | ||
|
|
8c31e0f6ee | ||
|
|
1688b206a5 | ||
|
|
91fdaba6a2 | ||
|
|
55934664e2 | ||
|
|
e3e9865d3f | ||
|
|
d1c601a6e2 | ||
|
|
13e4908c1e | ||
|
|
1dcbffd6f2 | ||
|
|
c353ac8072 | ||
|
|
fb5cb226ee | ||
|
|
7361e8d98e | ||
|
|
741e1e9a65 | ||
|
|
9178828b41 | ||
|
|
0b6cdf992e | ||
|
|
589f2c3862 | ||
|
|
014d31f9b9 | ||
|
|
c28582ae6f | ||
|
|
4287862f47 | ||
|
|
6cf6a6fdbf | ||
|
|
d2b6637f72 | ||
|
|
0b223f53fc | ||
|
|
c52c6c54cc | ||
|
|
d86a09b744 | ||
|
|
f314761e45 | ||
|
|
46818cd0ae | ||
|
|
fa999f8cf0 | ||
|
|
515c7c3d26 | ||
|
|
240ed5237a | ||
|
|
9b5880b719 | ||
|
|
deb2fd4482 | ||
|
|
994fc1026f | ||
|
|
e9cf7d66ba | ||
|
|
e01d6efb84 | ||
|
|
b7c801c8db | ||
|
|
b15e90cc64 | ||
|
|
8d3be6aba3 | ||
|
|
464ae8952e | ||
|
|
2007541adf | ||
|
|
d6167617a9 | ||
|
|
38d7c1494d | ||
|
|
c0c0d56e86 | ||
|
|
745301d14b | ||
|
|
8d640b595e | ||
|
|
1925e1c2f4 | ||
|
|
0595124ecd | ||
|
|
8e3202d1ad | ||
|
|
5f8eb39206 | ||
|
|
e7bf700f36 | ||
|
|
c10342818a | ||
|
|
0f29dc4db6 | ||
|
|
80fae240da | ||
|
|
ab2e11a2e4 | ||
|
|
fb4fd17603 | ||
|
|
86f7637213 | ||
|
|
c5084b86af | ||
|
|
919b95c378 | ||
|
|
ec7db10601 | ||
|
|
73403ee799 | ||
|
|
a294542eda | ||
|
|
786bde2965 | ||
|
|
e2ac8bbdc7 | ||
|
|
673cfc2f99 | ||
|
|
c533cc0439 | ||
|
|
7a49dffe0d | ||
|
|
e6ab85d382 | ||
|
|
011356e103 | ||
|
|
c8595ccedd | ||
|
|
9e1fd2956d | ||
|
|
6a1697dc5a | ||
|
|
2641145b60 | ||
|
|
70a7bf1033 | ||
|
|
a92dd013bc | ||
|
|
6d6baf3f35 | ||
|
|
72f2b33754 | ||
|
|
89a456f88c | ||
|
|
d98d995326 | ||
|
|
20a76f1921 | ||
|
|
0c4a7992a7 | ||
|
|
5e6b88fa31 | ||
|
|
d8735cc738 | ||
|
|
185671adb5 | ||
|
|
ee268444b7 | ||
|
|
9387bdc1ee | ||
|
|
7cfdb43f37 | ||
|
|
06f658917f | ||
|
|
88d5614158 | ||
|
|
f896153fb7 | ||
|
|
1004356e75 | ||
|
|
77b0c6db09 | ||
|
|
dec2d1cb05 | ||
|
|
76314aebbd | ||
|
|
7d149d2ab1 | ||
|
|
ff4082d5df | ||
|
|
51f58e76b2 | ||
|
|
347ce74808 | ||
|
|
726dbbbaf3 | ||
|
|
fb434f3f15 | ||
|
|
aacd86cebe | ||
|
|
bd3b4605cb | ||
|
|
f267744c1c | ||
|
|
fffb033e39 | ||
|
|
f574f039f5 | ||
|
|
506ebdb092 | ||
|
+3 |
9ccc303a2a | ||
|
|
a5c4a73de1 | ||
|
|
dbd5ce6700 | ||
|
|
068a96b228 | ||
|
|
7c522c5903 | ||
|
|
6ef516fe4d | ||
|
|
9a7d65be6b | ||
|
|
c2aae1629f | ||
|
|
a697803e29 | ||
|
|
f4b6cb3acb | ||
|
|
c3f3eb83f2 | ||
|
|
5d10f773ca | ||
|
|
b2fcc55018 | ||
|
|
10414fcf05 | ||
|
|
49f604bdc2 | ||
|
|
56763f58da | ||
|
|
af34f014a7 | ||
|
|
3280191309 | ||
|
|
76cdc1c535 | ||
|
|
68c0a262fa | ||
|
|
39e13e86d2 | ||
|
|
1cc7f40f7e | ||
|
|
8a15325fdc | ||
|
|
7f977971ed | ||
|
|
632155c016 | ||
|
|
8834884d4e | ||
|
|
236372d740 | ||
|
|
678a526cb9 | ||
|
|
84fd51baf6 | ||
|
|
450b8b0107 | ||
|
|
8078fb4f10 | ||
|
|
46b88cc03e | ||
|
|
6afcfd49f1 | ||
|
|
5f77cac7ea | ||
|
|
20a6548ac8 | ||
|
|
9c35712573 | ||
|
|
4342c6ab6d | ||
|
|
57bad5c74c | ||
|
|
ebf833d0bd | ||
|
|
2f24a9878c | ||
|
|
2313671965 | ||
|
|
e1b80d9f89 | ||
|
|
99bb6adf80 | ||
|
|
06ee010f07 | ||
|
|
5f07adef2f | ||
|
|
bfc05795f0 | ||
|
|
9de5f3f00d | ||
|
|
bfdbd49aa1 | ||
|
|
844a3c22ff | ||
|
|
87a08a4d24 | ||
|
|
dc0637c37c | ||
|
|
381eca6660 | ||
|
|
36018b3e52 | ||
|
|
3c0324c071 | ||
|
|
a70108dff8 | ||
|
|
83447ab68a | ||
|
|
4ac937c54f | ||
|
|
b5f28929d7 | ||
|
|
d729a928ea | ||
|
|
01a4ad742b | ||
|
|
6f77a5e12e | ||
|
|
e29c38d88c | ||
|
|
04f509fc4c | ||
|
|
b6061f1384 | ||
|
|
38c3a82b54 | ||
|
|
d3f1409503 | ||
|
|
3475a073ad | ||
|
|
643c61db65 | ||
|
|
1734b7863c | ||
|
|
d45d4f443b | ||
|
|
994fa010b8 | ||
|
|
5c20c5f6eb | ||
|
|
c4bb7ae0b2 | ||
|
|
0c985a280c | ||
|
|
17ebb9fd42 | ||
|
|
cadc2b14db | ||
|
|
1fdca903be | ||
|
|
5e7658aa80 | ||
|
|
bea31032fb | ||
|
|
f7c1dbdbc4 | ||
|
|
a1ed010963 | ||
|
|
7be6b7ac31 | ||
|
|
20c20b71ea | ||
|
|
0fb3df0b3a | ||
|
|
e10b09a9b5 | ||
|
|
806a576380 | ||
|
|
3c365c6792 | ||
|
|
4fb4a85ac4 | ||
|
|
e7312e5d6e | ||
|
|
12c2de7ed8 | ||
|
|
8a3cc95c66 | ||
|
|
9c06ffdb48 | ||
|
|
870a903015 | ||
|
|
b5768e3b17 | ||
|
|
02b33dbf07 | ||
|
|
a0c0b875f0 | ||
|
|
512bf8c746 | ||
|
|
04257e8a66 | ||
|
|
c04b2ecee2 | ||
|
|
e10fae0710 | ||
|
|
b3fe98907e | ||
|
|
b19493e925 | ||
|
|
19b4cf06b2 | ||
|
|
f9a5618b84 | ||
|
|
822a9799db | ||
|
|
eb4fd3108e | ||
|
|
4c86c261ba | ||
|
|
dc5c9db68a | ||
|
|
befcad586e | ||
|
|
9f950cba9f | ||
|
|
51a1d1e8ef | ||
|
|
631c9da0a4 | ||
|
|
5fa214b9ba | ||
|
|
eb406c3132 | ||
|
|
3a90e94958 | ||
|
|
248842871b | ||
|
|
1cab023abc | ||
|
|
9ca29bb797 | ||
|
|
13640751d2 | ||
|
|
0c7d1a97e2 | ||
|
|
d0202783d4 | ||
|
|
f72f810e4f | ||
|
|
13f4c86113 | ||
|
|
65d9f95717 | ||
|
|
19fa8203f1 | ||
|
|
0f1df4800d | ||
|
|
7351b2d35c | ||
|
|
1a66a31563 | ||
|
|
fe3c659804 | ||
|
|
a2172dce12 | ||
|
|
4099f66e91 | ||
|
|
49112b11b3 | ||
|
|
1218bb523c | ||
|
|
17600a3905 | ||
|
|
db5104a7d0 | ||
|
|
6306064fc3 | ||
|
|
d5a4761f2c | ||
|
|
66d6681798 | ||
|
|
fb61169656 | ||
|
|
62079fba0b | ||
|
|
cc0fc8edc3 | ||
|
|
62174fcd53 | ||
|
|
55c1b2ac25 | ||
|
|
0ccc610144 | ||
|
|
5d009b7dc0 | ||
|
|
28924daf02 | ||
|
|
e71fb2a625 | ||
|
|
aa5f76fc1b | ||
|
|
5b099714f6 | ||
|
|
163d821d1f | ||
|
|
fe98b1ed66 | ||
|
|
c0270ab3a0 | ||
|
|
6019d6c0b8 | ||
|
|
19bc5967a4 | ||
|
|
ddab3454bb | ||
|
|
247c9ee6cd | ||
|
|
6be170cae2 | ||
|
|
8133584f1e | ||
|
|
4cdb42afba | ||
|
|
19a4c05e93 | ||
|
|
aba06affbf | ||
|
|
2b132a5b7a | ||
|
|
52ecce03b8 | ||
|
|
0eb76db12d | ||
|
|
d03985eada | ||
|
|
34108b9c50 | ||
|
|
49a0c114c2 | ||
|
|
b1ce6f85cc | ||
|
|
ca5f87af11 | ||
|
|
7445092767 | ||
|
|
5ef66120bf | ||
|
|
bda86cd73d | ||
|
|
56953b0c50 | ||
|
|
7c8cd1e145 | ||
|
|
bce36956d1 | ||
|
|
e0fdadc7ca | ||
|
|
136167b54c | ||
|
|
02fd599e6b | ||
|
|
b0412a96f3 | ||
|
|
06dbb89868 | ||
|
|
b002f45f29 | ||
|
|
c1eb702384 | ||
|
|
307517e85a | ||
|
|
a8ba227e8b | ||
|
|
cbfdfb9710 | ||
|
|
d85003416e | ||
|
|
61c516149e | ||
|
|
560225cb8c | ||
|
|
2e8367afd4 | ||
|
|
8c40109341 | ||
|
|
4259c996b6 | ||
|
|
d4218227bd | ||
|
|
6a4c5084a5 | ||
|
|
e38b9cde1f | ||
|
|
dbae8b5bcf | ||
|
|
2d06b7ad32 | ||
|
|
10a674deba | ||
|
|
93b9aa8f34 | ||
|
|
ca826737ed | ||
|
|
5365cc67eb | ||
|
|
25e3640ba0 | ||
|
|
3f85bac74e | ||
|
|
5b83b9da73 | ||
|
|
3c8c555b94 | ||
|
|
a6a6c0c714 | ||
|
|
66dbdc8913 | ||
|
|
6a125b7c73 | ||
|
|
44233cff35 | ||
|
|
5764bd889b | ||
|
|
a8a83a39d0 | ||
|
|
9557ca73ed | ||
|
|
9767fbbbaf | ||
|
|
9054742503 | ||
|
|
3d62036d79 | ||
|
|
34a8e91ea5 | ||
|
|
0097a9c534 | ||
|
|
4e51e33356 | ||
|
|
e8657117d6 | ||
|
|
d5c53df6b5 | ||
|
|
2f4e05899a | ||
|
|
06653bf5b1 | ||
|
|
e952393116 | ||
|
|
384ba39cf9 | ||
|
|
3fca28810b | ||
|
|
c988e1f028 | ||
|
|
a3d136f55d | ||
|
|
db7094c54e | ||
|
|
c70412c782 | ||
|
|
ac0c43f930 | ||
|
|
314236ac0c | ||
|
|
c6e83fc071 | ||
|
|
4c1bfc052e | ||
|
|
bba536394f | ||
|
|
bb34973047 | ||
|
|
108a1890be | ||
|
|
521c0ffd78 | ||
|
|
33a37d4105 | ||
|
|
6ccc0cbed2 | ||
|
|
6e6ffce271 | ||
|
|
23386bb998 | ||
|
|
28b1568486 | ||
|
|
5127971a37 | ||
|
|
0562af8d66 | ||
|
|
e3d3728bbd | ||
|
|
8cc9d075fd | ||
|
|
ede6d967c1 | ||
|
|
c30f6ab318 | ||
|
|
dd2b96b5fd | ||
|
|
c22658db4c | ||
|
|
7b3893ddc6 | ||
|
|
9e28fa4981 | ||
|
|
7549c8fe04 | ||
|
|
75f699b714 | ||
|
|
3e821c9092 | ||
|
|
7602f158a3 | ||
|
|
052335e842 | ||
|
|
28fb7404d8 | ||
|
|
6ab235e1d8 | ||
|
|
fb90c94e37 | ||
|
|
7a05fc3ac1 | ||
|
|
bf38dac5d7 | ||
|
|
1e9581528e | ||
|
|
279872aa3b | ||
|
|
ff6c4b6a4d | ||
|
|
7fb01ab8d1 | ||
|
|
bdb16d069e | ||
|
|
beb8536e8a | ||
|
|
63ba69729e | ||
|
|
01a6c8bab8 | ||
|
|
f70b33b864 | ||
|
|
0df420e551 | ||
|
|
488de490f9 | ||
|
|
f15fffa799 | ||
|
|
1499b5803d | ||
|
|
39cc70be95 | ||
|
|
f9619e74d9 | ||
|
|
e691336b5e | ||
|
|
4cee160c12 | ||
|
|
a7ae8ff912 | ||
|
|
d23a1d5b6d | ||
|
|
b417900ddd | ||
|
|
95f4d28bbb | ||
|
|
24b005126e | ||
|
|
ee9d65068d | ||
|
|
6e3d10858f | ||
|
|
94a82c2f6c | ||
|
|
81dcbbdce7 | ||
|
|
becb9a6710 | ||
|
|
542744e342 | ||
|
|
7510e1f9af | ||
|
|
498250650c | ||
|
|
ada6976e85 | ||
|
|
6a454e0b33 | ||
|
|
cd6ae31d0f | ||
|
|
463811056d | ||
|
|
98d76deee5 | ||
|
|
20e18768eb | ||
|
|
a34f29bcf8 | ||
|
|
997296e21e | ||
|
|
94355bf340 | ||
|
|
722fc87259 | ||
|
|
30fcbfa59f | ||
|
|
c956ac79ed | ||
|
|
b90f07a816 | ||
|
|
7d357bad87 | ||
|
|
3ffe76412e | ||
|
|
91c4a84818 | ||
|
|
ccd433fee1 | ||
|
|
03f6b7c8c1 | ||
|
|
426ddf27ee | ||
|
|
4148196a36 | ||
|
|
9a1d753abc | ||
|
|
1b29abed17 | ||
|
|
85d72ad051 | ||
|
|
fd3bcdf2f7 | ||
|
|
46afa830b3 | ||
|
|
7de9b2f81b | ||
|
|
3ec46c8631 | ||
|
|
529dc9c374 | ||
|
|
60ef920b82 | ||
|
|
7b7b859fee | ||
|
|
53d42341c0 | ||
|
|
b5c2930609 | ||
|
|
3feafe38f2 | ||
|
|
55ffaad94f | ||
|
|
5bdde146c1 | ||
|
|
97f87fb927 | ||
|
|
469166c0bb | ||
|
|
b10965babe | ||
|
|
e5c122a2ee | ||
|
|
3aefc5c8f8 | ||
|
|
ecc643ac81 | ||
|
|
8e4d0defa2 | ||
|
|
19baed9291 | ||
|
|
4ea68adf8b | ||
|
|
f459f7d39c | ||
|
|
c3ba8ccf64 | ||
|
|
7ed1d89b66 | ||
|
|
734bcae02d | ||
|
|
629896b74d | ||
|
|
6a49539ae5 | ||
|
|
01ac61185b | ||
|
|
ca01f6e729 | ||
|
|
0588609c75 | ||
|
|
ab3df639b9 | ||
|
|
fefe1f3652 | ||
|
|
7634df3cff | ||
|
|
60938af9f0 | ||
|
|
accf0ac142 | ||
|
|
f90badfcd5 | ||
|
|
249606a358 | ||
|
|
5be5ff77d0 | ||
|
|
6519cbca79 | ||
|
|
50510a23da | ||
|
|
2279738371 | ||
|
|
3d59962112 | ||
|
|
a96d8b6de9 | ||
|
|
94b9eeaa78 | ||
|
|
85fb091e22 | ||
|
|
2139f8729c | ||
|
|
98a48aa795 | ||
|
|
d255d232b9 | ||
|
|
9999fcdd2a | ||
|
|
953ffdff97 | ||
|
|
5377a2b466 | ||
|
|
e73148dc6c | ||
|
|
a19772e3a7 | ||
|
|
b3386eff43 | ||
|
|
79e74d9995 | ||
|
|
396a5610aa | ||
|
|
b9329f6fb6 | ||
|
|
1b731a4ab0 | ||
|
|
ab631365b2 | ||
|
|
9aa370d583 | ||
|
|
8cd75716ae | ||
|
|
4feccf2008 | ||
|
|
23e9a5a35b | ||
|
|
38a35be0f0 | ||
|
|
f9f0572ec5 | ||
|
|
0221972e6d | ||
|
|
86ea72d56f | ||
|
|
114db7939c | ||
|
|
4503847c0d | ||
|
|
95c5fe76e6 | ||
|
|
34fa9c9c3e | ||
|
|
53793bfb68 | ||
|
|
9c7c8cb03a | ||
|
|
4fea176e28 | ||
|
|
cf9492c7ba | ||
|
|
e6def9e5f7 | ||
|
|
974185f354 | ||
|
|
6aacdd9111 | ||
|
|
4f263d00fe | ||
|
|
bda002684c | ||
|
|
b6bcd195b0 | ||
|
|
9fb4502ed0 | ||
|
|
d398c72005 | ||
|
|
9d718e0f51 | ||
|
|
8ddc11159b | ||
|
|
2218c11d3f | ||
|
|
6736bae5ee | ||
|
|
60aa889c57 | ||
|
|
3c9767387b | ||
|
|
21d1726d7a | ||
|
|
1e7ee5b98a | ||
|
|
a82df3f6d0 | ||
|
|
e0e3eb73b9 | ||
|
|
8a7a0af207 | ||
|
|
71a652ce3b | ||
|
|
5fa6eac1ad | ||
|
|
21ba3fb7cf | ||
|
|
316c2b0b12 | ||
|
|
ef77eab627 | ||
|
|
955d47ef12 | ||
|
|
8536774522 | ||
|
|
a8aeae5f32 | ||
|
|
988ac009b5 | ||
|
|
494e486998 | ||
|
|
3c73028c80 | ||
|
|
2be1be19fe | ||
|
|
1f050c2be9 | ||
|
|
5771b603f2 | ||
|
|
5725989aff | ||
|
|
8b22e1b2af | ||
|
|
a514b8b506 | ||
|
|
60fcc6b64c | ||
|
|
d6bc660983 | ||
|
|
b449fff77c | ||
|
|
f0cc35f2ce | ||
|
|
2ce79942c4 | ||
|
|
df426bb8df | ||
|
|
31f51554f9 | ||
|
|
e967007bdc | ||
|
|
9f7427e72f | ||
|
|
79d9e0eaa0 | ||
|
|
a98dd654a6 | ||
|
|
a138e179dd | ||
|
|
94e3887345 | ||
|
|
f440d385fa | ||
|
|
8fb4767888 | ||
|
|
993d74502f | ||
|
|
4a11c951ae | ||
|
|
f25f308326 | ||
|
|
bff683a403 | ||
|
|
bb7954d026 | ||
|
|
d9f4239729 | ||
|
|
cf3b897305 | ||
|
|
87a78ca924 | ||
|
|
13debac340 | ||
|
|
76846420a2 | ||
|
|
65bd6c4254 | ||
|
|
1a3e4f501f | ||
|
|
974d65f619 | ||
|
|
721ca0d7e0 | ||
|
|
2556eba84b | ||
|
|
fc1ff97d22 | ||
|
|
b7f3d421ef | ||
|
|
2722b3427a | ||
|
|
e28c293d27 | ||
|
|
5cb2a836ab | ||
|
|
b5978e7a61 | ||
|
|
c4a048adee | ||
|
|
2746ca5784 | ||
|
|
fc9bd33992 | ||
|
|
2239c38ecc | ||
|
|
79ad70e0c0 | ||
|
|
f168021f51 | ||
|
|
a2b1e7792b | ||
|
|
c6ce0830b1 | ||
|
|
be13f97802 | ||
|
|
f6d40de832 | ||
|
|
fdee311658 | ||
|
|
1ff41153e9 | ||
|
|
49d04bcee0 | ||
|
|
5e470baf4e | ||
|
|
84e6402031 | ||
|
|
7fe59b36c3 | ||
|
|
8881559e67 | ||
|
|
9f7e93d5f8 | ||
|
|
86d4e11584 | ||
|
|
67a07a9346 | ||
|
|
b8a420bdab | ||
|
|
442697d57c | ||
|
|
8e3a17fdc3 | ||
|
|
5844539db2 | ||
|
|
2cc83d7714 | ||
|
|
dada1bbe72 | ||
|
|
e061cbe127 | ||
|
|
4e125e58d5 | ||
|
|
52816b327a | ||
|
|
cbb241bc4d | ||
|
|
0fd579b19b | ||
|
|
030c3e6ce1 | ||
|
|
e67960d352 | ||
|
|
22bbfef3e2 | ||
|
|
4da9abe05b | ||
|
|
4540faf2a0 | ||
|
|
3aecb19a0c | ||
|
|
f7c0b8a957 | ||
|
|
9a8d9b2177 | ||
|
|
93ca38d974 | ||
|
|
a38093cae3 | ||
|
|
67511ce9be | ||
|
|
2e90682874 | ||
|
|
2a4cb6a896 | ||
|
|
25ff7ce7ca |
No files matched your search
@@ -0,0 +1,30 @@
|
|||||||
|
---
|
||||||
|
name: Bug report
|
||||||
|
about: Something doesn't work the way it should
|
||||||
|
title: ""
|
||||||
|
labels:
|
||||||
|
- bug
|
||||||
|
---
|
||||||
|
|
||||||
|
### What happened
|
||||||
|
|
||||||
|
|
||||||
|
### What you expected
|
||||||
|
|
||||||
|
|
||||||
|
### Steps to reproduce
|
||||||
|
1.
|
||||||
|
2.
|
||||||
|
3.
|
||||||
|
|
||||||
|
### Environment
|
||||||
|
- Calendula version: <!-- Settings → bottom of the screen -->
|
||||||
|
- Android version:
|
||||||
|
- Device:
|
||||||
|
- Installed from: <!-- official F-Droid / the self-hosted repo / Google Play / Codeberg APK or Obtainium / built from source -->
|
||||||
|
- Affected calendar: <!-- Google, CalDAV (DAVx5, Nextcloud, …), on-device/local,
|
||||||
|
subscribed/WebCal, birthdays. Provider behaviour differs
|
||||||
|
a lot per account type, so this often points straight at
|
||||||
|
the cause -->
|
||||||
|
- Time zone: <!-- only if the problem involves dates or all-day events -->
|
||||||
|
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
# Kept enabled so anything that doesn't fit the four templates still has a way
|
||||||
|
# in (the `ToDo` label exists for exactly those).
|
||||||
|
blank_issues_enabled: true
|
||||||
|
|
||||||
|
contact_links:
|
||||||
|
- name: Translate Calendula
|
||||||
|
url: https://weblate.dev.jeanlucmakiola.de/engage/calendula/
|
||||||
|
about: >-
|
||||||
|
Translations are managed on Weblate. It owns every values-* file, so a
|
||||||
|
hand-edited translation gets overwritten on the next sync.
|
||||||
|
No coding needed: pick or request a language and translate in the browser.
|
||||||
|
|
||||||
|
- name: Contributing guide
|
||||||
|
url: https://codeberg.org/jlmakiola/calendula/src/branch/main/CONTRIBUTING.md
|
||||||
|
about: >-
|
||||||
|
Before opening a pull request: the issue-first workflow, which release
|
||||||
|
branch to target, how to build (there's a submodule), and the
|
||||||
|
architectural rules a change is reviewed against.
|
||||||
@@ -1,20 +1,20 @@
|
|||||||
---
|
---
|
||||||
name: Crash report
|
name: Crash report
|
||||||
about: Report a crash. Calendula can capture this for you (Settings → Report a problem, or the prompt after a crash) — it copies the report to your clipboard and prefills this form.
|
about: Report a crash. Calendula can capture this for you (Settings → Report a problem, or the prompt after a crash). It copies the report to your clipboard and prefills this form.
|
||||||
title: "Crash: "
|
title: "Crash: "
|
||||||
labels:
|
labels:
|
||||||
- bug
|
- bug
|
||||||
- crash
|
- crash
|
||||||
- priority:high
|
- priority/high
|
||||||
---
|
---
|
||||||
|
|
||||||
<!--
|
<!--
|
||||||
Thanks for reporting a crash in Calendula!
|
Thanks for reporting a crash in Calendula!
|
||||||
|
|
||||||
If the app prefilled this for you, the crash report is already below — just add
|
If the app prefilled this for you, the crash report is already below. Add
|
||||||
what you were doing and submit. Otherwise, paste the report from your clipboard
|
what you were doing and submit. Otherwise, paste the report from your clipboard
|
||||||
into the code block. The report contains only app/Android/device versions and the
|
into the code block. The report contains only app/Android/device versions and the
|
||||||
stack trace — no personal data or calendar content.
|
stack trace, with no personal data or calendar content.
|
||||||
-->
|
-->
|
||||||
|
|
||||||
### What happened
|
### What happened
|
||||||
+1
-1
@@ -9,7 +9,7 @@ labels:
|
|||||||
### What would you like Calendula to do?
|
### What would you like Calendula to do?
|
||||||
|
|
||||||
|
|
||||||
### Why — what problem does it solve?
|
### What problem does it solve?
|
||||||
|
|
||||||
|
|
||||||
### Anything else
|
### Anything else
|
||||||
File renamed without changes.
@@ -0,0 +1,41 @@
|
|||||||
|
<!--
|
||||||
|
Thanks for contributing to Calendula!
|
||||||
|
|
||||||
|
Please skim CONTRIBUTING.md if you haven't:
|
||||||
|
https://codeberg.org/jlmakiola/calendula/src/branch/main/CONTRIBUTING.md
|
||||||
|
|
||||||
|
Two things it's easy to get wrong:
|
||||||
|
• Features need a discussed issue first. An undiscussed feature PR may be
|
||||||
|
closed unmerged even when the code is good.
|
||||||
|
• Target the release branch for your issue's milestone (milestone 2.18.0 →
|
||||||
|
release/v2.18.0), not main. If you targeted main, just say so below and it
|
||||||
|
will be retargeted.
|
||||||
|
-->
|
||||||
|
|
||||||
|
### What this changes
|
||||||
|
|
||||||
|
|
||||||
|
### Why
|
||||||
|
|
||||||
|
<!-- Closes #123: link the issue this implements or fixes. -->
|
||||||
|
|
||||||
|
|
||||||
|
### How it was tested
|
||||||
|
|
||||||
|
<!--
|
||||||
|
Which of these ran green, and anything you exercised by hand. On-device notes
|
||||||
|
are especially useful for UI changes.
|
||||||
|
|
||||||
|
./gradlew lint test assembleDebug
|
||||||
|
python3 scripts/check_translations.py
|
||||||
|
-->
|
||||||
|
|
||||||
|
|
||||||
|
### Checklist
|
||||||
|
|
||||||
|
- [ ] There's an issue for this, and (for a feature) it got a go-ahead
|
||||||
|
- [ ] Targeting the release branch for that issue's milestone (or `main`, noted above)
|
||||||
|
- [ ] `./gradlew lint test assembleDebug` passes locally
|
||||||
|
- [ ] No `values-*/strings.xml` touched (Weblate owns those; new English strings in `values/` are fine)
|
||||||
|
- [ ] `CHANGELOG.md` updated under `## [Unreleased]`, if the change is user-visible
|
||||||
|
- [ ] No planning or design documents committed
|
||||||
@@ -29,6 +29,7 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
# Full history so the base..HEAD diff below has a merge-base.
|
# Full history so the base..HEAD diff below has a merge-base.
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
submodules: recursive
|
||||||
|
|
||||||
# Cheap, always-on guard: the release build must stay reproducible for the
|
# Cheap, always-on guard: the release build must stay reproducible for the
|
||||||
# official F-Droid repo (no AGP VCS-info embedding). Runs regardless of
|
# official F-Droid repo (no AGP VCS-info embedding). Runs regardless of
|
||||||
@@ -36,14 +37,63 @@ jobs:
|
|||||||
- name: Reproducible-release invariant
|
- name: Reproducible-release invariant
|
||||||
run: bash scripts/check_reproducible_release.sh
|
run: bash scripts/check_reproducible_release.sh
|
||||||
|
|
||||||
# Decide whether anything that affects the app build changed. Docs,
|
# versionCode must match versionName (the official F-Droid repo builds the
|
||||||
# F-Droid metadata and the licence don't, so those PRs skip the SDK +
|
# tag as committed), and a beta must never reach main.
|
||||||
# Gradle work below but still report a green `ci`.
|
- name: Committed version is well-formed
|
||||||
|
env:
|
||||||
|
BASE: ${{ github.base_ref }}
|
||||||
|
run: |
|
||||||
|
set -e
|
||||||
|
bash scripts/version_info.sh --check
|
||||||
|
if [ "${BASE#refs/heads/}" = "main" ] && [ "$(bash scripts/version_info.sh channel)" = "beta" ]; then
|
||||||
|
echo "ERROR: versionName $(bash scripts/version_info.sh version) is a beta." >&2
|
||||||
|
echo "Set the stable version (and its versionCode) before merging into main." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Play rejects a "What's New" over 500 characters, which would fail the
|
||||||
|
# upload after the release had already shipped everywhere else. Cheap, so
|
||||||
|
# it runs on every PR rather than only on the release merge. A beta ships
|
||||||
|
# no What's New, so only the older files are checked for one.
|
||||||
|
- name: Changelog length invariant
|
||||||
|
run: bash scripts/check_changelog_lengths.sh
|
||||||
|
|
||||||
|
# The whole listing goes to Play with every release; a field over its cap
|
||||||
|
# or an image Play rejects would fail that upload.
|
||||||
|
- name: Store listing invariant
|
||||||
|
run: |
|
||||||
|
if ! command -v python3 >/dev/null 2>&1; then
|
||||||
|
if command -v apt-get >/dev/null 2>&1; then
|
||||||
|
apt-get update && apt-get install -y python3
|
||||||
|
elif command -v apk >/dev/null 2>&1; then
|
||||||
|
apk add --no-cache python3
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
python3 scripts/check_store_listing.py
|
||||||
|
|
||||||
|
# Decide whether anything that affects the app build changed. Docs, store
|
||||||
|
# metadata, licence texts and forge housekeeping don't, so those PRs skip
|
||||||
|
# the SDK + Gradle work below but still report a green `ci`.
|
||||||
- name: Classify change scope
|
- name: Classify change scope
|
||||||
id: scope
|
id: scope
|
||||||
|
env:
|
||||||
|
# Deliberately a skip-list, not a build-list: a path nobody thought
|
||||||
|
# about defaults to building. Only paths the Gradle build provably
|
||||||
|
# never reads belong here — note that the workflows themselves, the
|
||||||
|
# `.gitmodules` submodule pointer and `scripts/` are *not* in it.
|
||||||
|
SKIP_RE: '(\.md$|^docs/|^fastlane/|^fdroid-metadata/|^licenses/|^\.planning/|^\.(forgejo|gitea)/ISSUE_TEMPLATE/|^\.editorconfig$|^\.gitattributes$|^\.gitignore$|^renovate\.json5$|^LICENSE$)'
|
||||||
run: |
|
run: |
|
||||||
set -e
|
set -e
|
||||||
BASE="${{ github.base_ref }}"
|
BASE="${{ github.base_ref }}"
|
||||||
|
# Normally the bare branch name; tolerate a full ref, which would
|
||||||
|
# otherwise make the merge-base lookup fail and quietly degrade this
|
||||||
|
# guard into "always build".
|
||||||
|
BASE="${BASE#refs/heads/}"
|
||||||
|
if [ -z "$BASE" ]; then
|
||||||
|
echo "No base branch on this event — running the full build to be safe."
|
||||||
|
echo "code=true" >> "$GITHUB_OUTPUT"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
# Full (not --depth=1) base fetch so the merge-base is present even when
|
# Full (not --depth=1) base fetch so the merge-base is present even when
|
||||||
# the PR branch forked several commits back; a shallow tip has no merge
|
# the PR branch forked several commits back; a shallow tip has no merge
|
||||||
# base with a divergent branch and `git diff base...HEAD` aborts.
|
# base with a divergent branch and `git diff base...HEAD` aborts.
|
||||||
@@ -57,11 +107,15 @@ jobs:
|
|||||||
fi
|
fi
|
||||||
CHANGED=$(git diff --name-only "$MB" HEAD)
|
CHANGED=$(git diff --name-only "$MB" HEAD)
|
||||||
echo "Changed files:"; echo "$CHANGED"
|
echo "Changed files:"; echo "$CHANGED"
|
||||||
if echo "$CHANGED" | grep -vE '(\.md$|^docs/|^fdroid-metadata/|^fastlane/|^LICENSE$)' | grep -q .; then
|
RELEVANT=$(echo "$CHANGED" | grep -vE "$SKIP_RE" || true)
|
||||||
|
if [ -n "$RELEVANT" ]; then
|
||||||
|
# Naming them makes "why did my docs PR build for four minutes?"
|
||||||
|
# answerable from the log alone.
|
||||||
|
echo "Build-relevant changes:"; echo "$RELEVANT"
|
||||||
echo "code=true" >> "$GITHUB_OUTPUT"
|
echo "code=true" >> "$GITHUB_OUTPUT"
|
||||||
else
|
else
|
||||||
echo "code=false" >> "$GITHUB_OUTPUT"
|
|
||||||
echo "Docs/metadata-only change — skipping the Android build."
|
echo "Docs/metadata-only change — skipping the Android build."
|
||||||
|
echo "code=false" >> "$GITHUB_OUTPUT"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
- name: Setup Java
|
- name: Setup Java
|
||||||
@@ -71,9 +125,14 @@ jobs:
|
|||||||
distribution: 'zulu'
|
distribution: 'zulu'
|
||||||
java-version: '17'
|
java-version: '17'
|
||||||
|
|
||||||
|
# Fully qualified on purpose. Codeberg resolves bare `uses:` refs against
|
||||||
|
# data.forgejo.org, Forgejo's own action mirror — actions/checkout,
|
||||||
|
# setup-java and cache all exist there, but android-actions/setup-android
|
||||||
|
# does not, and the job dies with "repository not found". Gitea's instance
|
||||||
|
# defaults to GitHub, which is why this never surfaced before the split.
|
||||||
- name: Setup Android SDK
|
- name: Setup Android SDK
|
||||||
if: steps.scope.outputs.code == 'true'
|
if: steps.scope.outputs.code == 'true'
|
||||||
uses: android-actions/setup-android@v3
|
uses: https://github.com/android-actions/setup-android@v3
|
||||||
with:
|
with:
|
||||||
# Default ("tools platform-tools") drags in the Android Emulator
|
# Default ("tools platform-tools") drags in the Android Emulator
|
||||||
# (~300 MB) which the build never uses.
|
# (~300 MB) which the build never uses.
|
||||||
@@ -3,13 +3,15 @@ name: Translations
|
|||||||
# Fast, SDK-free parity check for translation resources, so Weblate PRs (which
|
# Fast, SDK-free parity check for translation resources, so Weblate PRs (which
|
||||||
# only touch values-*/strings.xml) get quick feedback without the full Android
|
# only touch values-*/strings.xml) get quick feedback without the full Android
|
||||||
# build. The deeper checks still run in CI via lintDebug (ExtraTranslation).
|
# build. The deeper checks still run in CI via lintDebug (ExtraTranslation).
|
||||||
|
#
|
||||||
|
# Runs on every PR (no path filter) so the required "Translations / check"
|
||||||
|
# status is always reported — like the `ci` job. A path-filtered workflow is
|
||||||
|
# skipped on unrelated PRs and never posts its status, which leaves that
|
||||||
|
# required check pending forever and blocks the merge of any code-only PR into a
|
||||||
|
# release/* branch. The check itself is cheap and simply passes when the
|
||||||
|
# committed translations are consistent, so always running it costs nothing.
|
||||||
on:
|
on:
|
||||||
pull_request:
|
pull_request:
|
||||||
paths:
|
|
||||||
- 'app/src/main/res/values*/strings.xml'
|
|
||||||
- 'app/src/main/res/xml/locales_config.xml'
|
|
||||||
- 'scripts/check_translations.py'
|
|
||||||
- '.gitea/workflows/translations.yaml'
|
|
||||||
|
|
||||||
concurrency:
|
concurrency:
|
||||||
group: translations-${{ github.ref }}
|
group: translations-${{ github.ref }}
|
||||||
@@ -5,3 +5,4 @@
|
|||||||
*.jpg binary
|
*.jpg binary
|
||||||
*.gif binary
|
*.gif binary
|
||||||
*.webp binary
|
*.webp binary
|
||||||
|
app/src/test/resources/ics/*.ics -text
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
---
|
|
||||||
name: Bug report
|
|
||||||
about: Something doesn't work the way it should
|
|
||||||
title: ""
|
|
||||||
labels:
|
|
||||||
- bug
|
|
||||||
---
|
|
||||||
|
|
||||||
### What happened
|
|
||||||
|
|
||||||
|
|
||||||
### What you expected
|
|
||||||
|
|
||||||
|
|
||||||
### Steps to reproduce
|
|
||||||
1.
|
|
||||||
2.
|
|
||||||
3.
|
|
||||||
|
|
||||||
### Environment
|
|
||||||
- Calendula version: <!-- Settings → bottom of the screen -->
|
|
||||||
- Android version:
|
|
||||||
- Device:
|
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
name: Android build environment
|
||||||
|
description: JDK 17, Android SDK + build tools, Gradle cache and jq for the release and beta pipelines.
|
||||||
|
runs:
|
||||||
|
using: composite
|
||||||
|
steps:
|
||||||
|
- name: Setup Java
|
||||||
|
uses: actions/setup-java@v4
|
||||||
|
with:
|
||||||
|
distribution: 'zulu'
|
||||||
|
java-version: '17'
|
||||||
|
|
||||||
|
- name: Setup Android SDK
|
||||||
|
uses: android-actions/setup-android@v3
|
||||||
|
with:
|
||||||
|
packages: ''
|
||||||
|
|
||||||
|
- name: Setup Android SDK cache
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: /opt/android-sdk
|
||||||
|
key: ${{ runner.os }}-android-sdk-37-36.0.0
|
||||||
|
|
||||||
|
- name: Install Android SDK packages
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
yes | sdkmanager --licenses >/dev/null || true
|
||||||
|
sdkmanager \
|
||||||
|
"platform-tools" \
|
||||||
|
"platforms;android-37.0" \
|
||||||
|
"build-tools;36.0.0"
|
||||||
|
|
||||||
|
- name: Setup Gradle cache
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
~/.gradle/caches
|
||||||
|
~/.gradle/wrapper
|
||||||
|
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties', 'gradle/libs.versions.toml') }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-gradle-
|
||||||
|
|
||||||
|
- name: Install jq
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -e
|
||||||
|
SUDO=""
|
||||||
|
if command -v sudo >/dev/null 2>&1; then SUDO="sudo"; fi
|
||||||
|
if command -v apt-get >/dev/null 2>&1; then
|
||||||
|
$SUDO apt-get update
|
||||||
|
$SUDO apt-get install -y jq
|
||||||
|
elif command -v apk >/dev/null 2>&1; then
|
||||||
|
$SUDO apk add --no-cache jq
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Grant execute permission for gradlew
|
||||||
|
shell: bash
|
||||||
|
run: chmod +x ./gradlew
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
name: Beta — Codeberg pre-release
|
||||||
|
|
||||||
|
# Pushing a release/* branch whose versionName is X.Y.Z-beta.N publishes a
|
||||||
|
# Codeberg pre-release (APK + SHA-256) and a Gitea pre-release (R8 mapping).
|
||||||
|
# Betas never reach F-Droid or Play. See docs/RELEASING.md.
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: ['release/**']
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: beta
|
||||||
|
cancel-in-progress: false
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
detect:
|
||||||
|
# Gitea only; see the same guard in release.yaml.
|
||||||
|
if: github.repository_owner == 'makiolaj'
|
||||||
|
runs-on: light
|
||||||
|
outputs:
|
||||||
|
is_beta: ${{ steps.v.outputs.is_beta }}
|
||||||
|
version: ${{ steps.v.outputs.version }}
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Resolve version and whether it still needs publishing
|
||||||
|
id: v
|
||||||
|
run: |
|
||||||
|
set -e
|
||||||
|
INFO=$(bash scripts/version_info.sh)
|
||||||
|
echo "$INFO"
|
||||||
|
echo "$INFO" >> "$GITHUB_OUTPUT"
|
||||||
|
if [ "$(bash scripts/version_info.sh channel)" != beta ]; then
|
||||||
|
echo "Not a beta — nothing to do."
|
||||||
|
echo "is_beta=false" >> "$GITHUB_OUTPUT"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
GATE=$(bash scripts/release_gate.sh)
|
||||||
|
echo "is_beta=${GATE#cut=}" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
|
beta:
|
||||||
|
needs: detect
|
||||||
|
if: needs.detect.outputs.is_beta == 'true'
|
||||||
|
runs-on: gradle
|
||||||
|
env:
|
||||||
|
ANDROID_HOME: /opt/android-sdk
|
||||||
|
ANDROID_SDK_ROOT: /opt/android-sdk
|
||||||
|
VERSION: ${{ needs.detect.outputs.version }}
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
submodules: recursive
|
||||||
|
|
||||||
|
- name: Android build environment
|
||||||
|
uses: ./.gitea/actions/android-env
|
||||||
|
|
||||||
|
- name: Pin versionCode to versionName
|
||||||
|
run: bash scripts/version_info.sh --pin
|
||||||
|
|
||||||
|
- name: Unit tests
|
||||||
|
run: ./gradlew testDebugUnitTest
|
||||||
|
|
||||||
|
# The real app key, so a beta updates in place to later betas and stable.
|
||||||
|
- name: Setup Android Keystore
|
||||||
|
env:
|
||||||
|
KEYSTORE_BASE64: ${{ secrets.KEYSTORE_BASE64 }}
|
||||||
|
KEY_PASSWORD: ${{ secrets.KEY_PASSWORD }}
|
||||||
|
KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
|
||||||
|
run: bash scripts/write_keystore.sh
|
||||||
|
|
||||||
|
- name: Build release APK
|
||||||
|
run: ./gradlew assembleRelease
|
||||||
|
|
||||||
|
- name: Create tag + Gitea pre-release
|
||||||
|
env:
|
||||||
|
TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
|
||||||
|
SHA: ${{ github.sha }}
|
||||||
|
run: |
|
||||||
|
set -e
|
||||||
|
bash scripts/release_notes.sh "$VERSION" > release-notes.md
|
||||||
|
cat release-notes.md
|
||||||
|
TAG="v$VERSION" PRERELEASE=true NOTES_FILE=release-notes.md \
|
||||||
|
MAPPING=app/build/outputs/mapping/release/mapping.txt \
|
||||||
|
bash scripts/publish_gitea_release.sh
|
||||||
|
|
||||||
|
- name: Publish pre-release to Codeberg
|
||||||
|
env:
|
||||||
|
TOKEN: ${{ secrets.CODEBERG_RELEASE_TOKEN }}
|
||||||
|
API: https://codeberg.org/api/v1/repos/jlmakiola/calendula
|
||||||
|
SHA: ${{ github.sha }}
|
||||||
|
run: |
|
||||||
|
set -e
|
||||||
|
TAG="v$VERSION" PRERELEASE=true NOTES_FILE=release-notes.md \
|
||||||
|
APK=app/build/outputs/apk/release/app-release.apk \
|
||||||
|
bash scripts/publish_codeberg_release.sh
|
||||||
+242
-156
@@ -1,11 +1,21 @@
|
|||||||
name: Release — F-Droid repo + Gitea release
|
name: Release — F-Droid repo + Gitea/Codeberg release + Play
|
||||||
|
|
||||||
# A release is cut by merging a release branch into main with a bumped
|
# A release is cut by merging a release branch into main with a bumped
|
||||||
# versionName (see docs/RELEASING.md). This workflow reads that versionName and,
|
# versionName (see docs/RELEASING.md). This workflow reads that versionName and,
|
||||||
# if no matching tag exists yet, runs tests, builds + signs the APK, publishes
|
# if no matching tag exists yet, runs tests, builds + signs the APK, publishes
|
||||||
# it to the F-Droid repo, and only then creates the vX.Y.Z tag + Gitea release
|
# it to the F-Droid repo, creates the vX.Y.Z tag + Gitea release, and mirrors
|
||||||
# itself — the tag is an output of the pipeline, not its trigger. Ordinary
|
# that release to Codeberg with the signed APK + a SHA-256 checksum as a
|
||||||
# merges (no version bump) fall through `detect` and do nothing.
|
# direct-download channel — the tag is an output of the pipeline, not its
|
||||||
|
# trigger. Ordinary merges (no version bump) fall through `detect` and do
|
||||||
|
# nothing. Betas (X.Y.Z-beta.N) never come through here: beta.yaml cuts them
|
||||||
|
# from release/* branches as Codeberg-only pre-releases, and `detect` refuses
|
||||||
|
# one that reaches main.
|
||||||
|
#
|
||||||
|
# A trailing `play` job then uploads the App Bundle to Google Play. It is last
|
||||||
|
# and separate because Play is the only channel that can reject a good build for
|
||||||
|
# reasons the pipeline can't see, and that must not endanger a release which has
|
||||||
|
# already shipped to F-Droid and Codeberg. It skips cleanly until the
|
||||||
|
# PLAY_SERVICE_ACCOUNT_JSON secret exists.
|
||||||
#
|
#
|
||||||
# A manual workflow_dispatch (from a branch) runs the re-sign-only recovery
|
# A manual workflow_dispatch (from a branch) runs the re-sign-only recovery
|
||||||
# path: it re-signs the existing F-Droid index with the repo key and re-uploads,
|
# path: it re-signs the existing F-Droid index with the repo key and re-uploads,
|
||||||
@@ -25,7 +35,15 @@ jobs:
|
|||||||
# whether this push actually cuts a new release (no tag for it yet). Keeps the
|
# whether this push actually cuts a new release (no tag for it yet). Keeps the
|
||||||
# heavy job from running on every merge to main.
|
# heavy job from running on every merge to main.
|
||||||
detect:
|
detect:
|
||||||
runs-on: docker
|
# Gitea only. The workflow directory split already keeps this file invisible
|
||||||
|
# to Codeberg — Forgejo's lookup is first-match-wins, and .forgejo/workflows
|
||||||
|
# exists — but that only holds while .forgejo/ is non-empty. Move the last
|
||||||
|
# file out of it and Codeberg would fall back to .gitea/workflows and start
|
||||||
|
# running the release pipeline on the contributor-facing runner, with no
|
||||||
|
# secrets. repository_owner differs between the two forges regardless of
|
||||||
|
# URL, proxy or instance rename, so this closes it permanently.
|
||||||
|
if: github.repository_owner == 'makiolaj'
|
||||||
|
runs-on: light
|
||||||
outputs:
|
outputs:
|
||||||
is_release: ${{ steps.v.outputs.is_release }}
|
is_release: ${{ steps.v.outputs.is_release }}
|
||||||
version: ${{ steps.v.outputs.version }}
|
version: ${{ steps.v.outputs.version }}
|
||||||
@@ -33,38 +51,33 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
submodules: recursive
|
||||||
|
|
||||||
- name: Resolve version and whether it is a new release
|
- name: Resolve version and whether it is a new release
|
||||||
id: v
|
id: v
|
||||||
env:
|
|
||||||
TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
|
|
||||||
run: |
|
run: |
|
||||||
set -e
|
set -e
|
||||||
VERSION=$(grep -oP 'versionName\s*=\s*"\K[^"]+' app/build.gradle.kts)
|
INFO=$(bash scripts/version_info.sh)
|
||||||
if [ -z "$VERSION" ]; then echo "No versionName in app/build.gradle.kts" >&2; exit 1; fi
|
echo "$INFO"
|
||||||
MAJOR=$(echo "$VERSION" | cut -d. -f1); MINOR=$(echo "$VERSION" | cut -d. -f2); PATCH=$(echo "$VERSION" | cut -d. -f3)
|
echo "$INFO" >> "$GITHUB_OUTPUT"
|
||||||
MAJOR=${MAJOR:-0}; MINOR=${MINOR:-0}; PATCH=${PATCH:-0}
|
VERSION=$(echo "$INFO" | sed -n 's/^version=//p')
|
||||||
VERSION_CODE=$(( MAJOR * 10000 + MINOR * 100 + PATCH ))
|
CHANNEL=$(echo "$INFO" | sed -n 's/^channel=//p')
|
||||||
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
|
|
||||||
echo "version_code=$VERSION_CODE" >> "$GITHUB_OUTPUT"
|
|
||||||
echo "Resolved version $VERSION (code $VERSION_CODE)"
|
|
||||||
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
|
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
|
||||||
echo "Manual dispatch — re-sign path, not a release."
|
echo "Manual dispatch — re-sign path, not a release."
|
||||||
echo "is_release=false" >> "$GITHUB_OUTPUT"
|
echo "is_release=false" >> "$GITHUB_OUTPUT"
|
||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
# A tag for this version already existing means the release shipped on
|
# Backstop for CI's guard: betas ship from release/* via beta.yaml.
|
||||||
# an earlier push; do nothing. Absent => this merge cuts the release.
|
if [ "$CHANNEL" != "stable" ]; then
|
||||||
STATUS=$(curl -s -o /dev/null -w '%{http_code}' \
|
echo "versionName $VERSION on main is a beta. Set the stable version before merging to main." >&2
|
||||||
-H "Authorization: token $TOKEN" "$API/git/refs/tags/v$VERSION")
|
exit 1
|
||||||
if [ "$STATUS" = "200" ]; then
|
|
||||||
echo "Tag v$VERSION already exists — nothing to release."
|
|
||||||
echo "is_release=false" >> "$GITHUB_OUTPUT"
|
|
||||||
else
|
|
||||||
echo "No tag for v$VERSION yet — cutting the release."
|
|
||||||
echo "is_release=true" >> "$GITHUB_OUTPUT"
|
|
||||||
fi
|
fi
|
||||||
|
# Tags are read from Codeberg, the canonical forge: a tag minted here is
|
||||||
|
# wiped by the next mirror sync until Codeberg has it. A lookup error is
|
||||||
|
# fatal, since guessing "no tag" would re-cut a shipped release.
|
||||||
|
GATE=$(bash scripts/release_gate.sh)
|
||||||
|
echo "is_release=${GATE#cut=}" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
# Releases: build + sign + publish, then mint the tag and Gitea release.
|
# Releases: build + sign + publish, then mint the tag and Gitea release.
|
||||||
# Also runs on manual dispatch, where it skips the build and just re-signs and
|
# Also runs on manual dispatch, where it skips the build and just re-signs and
|
||||||
@@ -72,7 +85,7 @@ jobs:
|
|||||||
release:
|
release:
|
||||||
needs: detect
|
needs: detect
|
||||||
if: needs.detect.outputs.is_release == 'true' || github.event_name == 'workflow_dispatch'
|
if: needs.detect.outputs.is_release == 'true' || github.event_name == 'workflow_dispatch'
|
||||||
runs-on: docker
|
runs-on: gradle
|
||||||
env:
|
env:
|
||||||
ANDROID_HOME: /opt/android-sdk
|
ANDROID_HOME: /opt/android-sdk
|
||||||
ANDROID_SDK_ROOT: /opt/android-sdk
|
ANDROID_SDK_ROOT: /opt/android-sdk
|
||||||
@@ -82,66 +95,16 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Setup Java
|
|
||||||
uses: actions/setup-java@v4
|
|
||||||
with:
|
with:
|
||||||
distribution: 'zulu'
|
submodules: recursive
|
||||||
java-version: '17'
|
|
||||||
|
|
||||||
- name: Setup Android SDK
|
- name: Android build environment
|
||||||
uses: android-actions/setup-android@v3
|
uses: ./.gitea/actions/android-env
|
||||||
with:
|
|
||||||
packages: ''
|
|
||||||
|
|
||||||
- name: Setup Android SDK cache
|
# The committed versionName is the source of truth; pin the derived code.
|
||||||
uses: actions/cache@v4
|
|
||||||
with:
|
|
||||||
path: /opt/android-sdk
|
|
||||||
key: ${{ runner.os }}-android-sdk-37-36.0.0
|
|
||||||
|
|
||||||
- name: Install Android SDK packages
|
|
||||||
run: |
|
|
||||||
yes | sdkmanager --licenses >/dev/null || true
|
|
||||||
sdkmanager \
|
|
||||||
"platform-tools" \
|
|
||||||
"platforms;android-37.0" \
|
|
||||||
"build-tools;36.0.0"
|
|
||||||
|
|
||||||
- name: Setup Gradle cache
|
|
||||||
uses: actions/cache@v4
|
|
||||||
with:
|
|
||||||
path: |
|
|
||||||
~/.gradle/caches
|
|
||||||
~/.gradle/wrapper
|
|
||||||
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties', 'gradle/libs.versions.toml') }}
|
|
||||||
restore-keys: |
|
|
||||||
${{ runner.os }}-gradle-
|
|
||||||
|
|
||||||
- name: Install jq
|
|
||||||
run: |
|
|
||||||
set -e
|
|
||||||
SUDO=""
|
|
||||||
if command -v sudo >/dev/null 2>&1; then SUDO="sudo"; fi
|
|
||||||
if command -v apt-get >/dev/null 2>&1; then
|
|
||||||
$SUDO apt-get update
|
|
||||||
$SUDO apt-get install -y jq
|
|
||||||
elif command -v apk >/dev/null 2>&1; then
|
|
||||||
$SUDO apk add --no-cache jq
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: Grant execute permission for gradlew
|
|
||||||
run: chmod +x ./gradlew
|
|
||||||
|
|
||||||
# The committed versionName is the source of truth. Pin versionCode to the
|
|
||||||
# value derived from it so the published APK's code is always
|
|
||||||
# MAJOR*10000 + MINOR*100 + PATCH even if the committed code was forgotten.
|
|
||||||
- name: Pin versionCode to versionName
|
- name: Pin versionCode to versionName
|
||||||
if: env.IS_RELEASE == 'true'
|
if: env.IS_RELEASE == 'true'
|
||||||
run: |
|
run: bash scripts/version_info.sh --pin
|
||||||
set -e
|
|
||||||
sed -i "s/versionCode = .*/versionCode = $VERSION_CODE/" app/build.gradle.kts
|
|
||||||
grep -E 'versionName|versionCode' app/build.gradle.kts
|
|
||||||
|
|
||||||
# Test the exact commit being shipped (only on a real release).
|
# Test the exact commit being shipped (only on a real release).
|
||||||
- name: Unit tests
|
- name: Unit tests
|
||||||
@@ -154,15 +117,7 @@ jobs:
|
|||||||
KEYSTORE_BASE64: ${{ secrets.KEYSTORE_BASE64 }}
|
KEYSTORE_BASE64: ${{ secrets.KEYSTORE_BASE64 }}
|
||||||
KEY_PASSWORD: ${{ secrets.KEY_PASSWORD }}
|
KEY_PASSWORD: ${{ secrets.KEY_PASSWORD }}
|
||||||
KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
|
KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
|
||||||
run: |
|
run: bash scripts/write_keystore.sh
|
||||||
mkdir -p app
|
|
||||||
echo "$KEYSTORE_BASE64" | base64 --decode > app/upload-keystore.jks
|
|
||||||
cat > key.properties <<EOF
|
|
||||||
storePassword=$KEY_PASSWORD
|
|
||||||
keyPassword=$KEY_PASSWORD
|
|
||||||
keyAlias=$KEY_ALIAS
|
|
||||||
storeFile=upload-keystore.jks
|
|
||||||
EOF
|
|
||||||
|
|
||||||
- name: Build release APK
|
- name: Build release APK
|
||||||
if: env.IS_RELEASE == 'true'
|
if: env.IS_RELEASE == 'true'
|
||||||
@@ -223,9 +178,10 @@ jobs:
|
|||||||
cp app/build/outputs/apk/release/app-release.apk "fdroid/repo/calendula_v${VERSION}.apk"
|
cp app/build/outputs/apk/release/app-release.apk "fdroid/repo/calendula_v${VERSION}.apk"
|
||||||
|
|
||||||
# Per-version "What's New": ensure this version's changelog exists in the
|
# Per-version "What's New": ensure this version's changelog exists in the
|
||||||
# fastlane tree (committed at release-cut time for the official repo; this
|
# fastlane tree. The committed hand-written summary (kept under Play's
|
||||||
# regenerates it from CHANGELOG.md so the self-hosted repo never depends on
|
# 500-char cap) is used as-is; only if it is missing does the script fall
|
||||||
# the commit having happened). The transform below then carries it across.
|
# back to CHANGELOG.md, so the self-hosted repo never depends on the
|
||||||
|
# commit having happened. The transform below then carries it across.
|
||||||
- name: Ensure this version's changelog is in the fastlane tree
|
- name: Ensure this version's changelog is in the fastlane tree
|
||||||
if: env.IS_RELEASE == 'true'
|
if: env.IS_RELEASE == 'true'
|
||||||
run: bash scripts/sync_changelog_to_fastlane.sh
|
run: bash scripts/sync_changelog_to_fastlane.sh
|
||||||
@@ -270,6 +226,7 @@ jobs:
|
|||||||
# Creating it with target_commitish makes Gitea create the vX.Y.Z tag at
|
# Creating it with target_commitish makes Gitea create the vX.Y.Z tag at
|
||||||
# this commit, so the tag only ever marks a fully-shipped release (and a
|
# this commit, so the tag only ever marks a fully-shipped release (and a
|
||||||
# failure before here leaves no tag, so re-running the workflow retries).
|
# failure before here leaves no tag, so re-running the workflow retries).
|
||||||
|
# Also attaches the R8 mapping, best-effort.
|
||||||
- name: Create tag + Gitea release
|
- name: Create tag + Gitea release
|
||||||
if: env.IS_RELEASE == 'true'
|
if: env.IS_RELEASE == 'true'
|
||||||
env:
|
env:
|
||||||
@@ -278,71 +235,200 @@ jobs:
|
|||||||
SHA: ${{ github.sha }}
|
SHA: ${{ github.sha }}
|
||||||
run: |
|
run: |
|
||||||
set -e
|
set -e
|
||||||
TAG="v$VERSION"
|
bash scripts/release_notes.sh "$VERSION" > release-notes.md
|
||||||
# Notes = this version's CHANGELOG section.
|
TAG="v$VERSION" PRERELEASE=false NOTES_FILE=release-notes.md \
|
||||||
awk -v ver="$VERSION" '
|
MAPPING=app/build/outputs/mapping/release/mapping.txt \
|
||||||
$0 ~ "^## \\[" ver "\\]" { flag = 1; next }
|
bash scripts/publish_gitea_release.sh
|
||||||
/^## \[/ { flag = 0 }
|
|
||||||
flag' CHANGELOG.md > release-notes.md
|
|
||||||
sed -i -e '/./,$!d' release-notes.md
|
|
||||||
if [ ! -s release-notes.md ]; then
|
|
||||||
echo "_No changelog entry for ${VERSION} — see CHANGELOG.md._" > release-notes.md
|
|
||||||
fi
|
|
||||||
python3 - "$TAG" "$SHA" <<'PY' > payload.json
|
|
||||||
import json, sys
|
|
||||||
print(json.dumps({
|
|
||||||
"tag_name": sys.argv[1],
|
|
||||||
"target_commitish": sys.argv[2],
|
|
||||||
"name": sys.argv[1],
|
|
||||||
"body": open("release-notes.md").read(),
|
|
||||||
"draft": False,
|
|
||||||
"prerelease": False,
|
|
||||||
}))
|
|
||||||
PY
|
|
||||||
# Upsert (re-run safe): PATCH if a release for the tag already exists,
|
|
||||||
# else POST a new one (which also creates the tag at target_commitish).
|
|
||||||
curl -s -H "Authorization: token $TOKEN" "$API/releases/tags/$TAG" > existing.json
|
|
||||||
ID=$(jq -r '.id // empty' existing.json 2>/dev/null || true)
|
|
||||||
if [ -n "$ID" ]; then
|
|
||||||
CODE=$(curl -s -o response.json -w '%{http_code}' -X PATCH \
|
|
||||||
-H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
|
|
||||||
-d @payload.json "$API/releases/$ID")
|
|
||||||
OK=200
|
|
||||||
else
|
|
||||||
CODE=$(curl -s -o response.json -w '%{http_code}' -X POST \
|
|
||||||
-H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
|
|
||||||
-d @payload.json "$API/releases")
|
|
||||||
OK=201
|
|
||||||
fi
|
|
||||||
cat response.json
|
|
||||||
if [ "$CODE" != "$OK" ]; then
|
|
||||||
echo "Release upsert failed with HTTP $CODE (expected $OK)" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
echo "Created/updated release $TAG at $SHA"
|
|
||||||
|
|
||||||
# Archive the R8 mapping so user crash stacktraces stay deobfuscatable.
|
# Mirror the release to the Codeberg mirror as a direct-download channel
|
||||||
# Attached to the release (it's not an APK, so it fits the no-binaries
|
# for users who don't want F-Droid. Gitea already push-mirrors branches +
|
||||||
# rule). Best-effort: never fail a release over it.
|
# tags to Codeberg, but releases aren't git objects so they don't sync —
|
||||||
- name: Attach R8 mapping to Gitea release
|
# we create the release there over the API and attach the signed APK plus
|
||||||
|
# a SHA-256 checksum. The APK is identical to the F-Droid one (same app
|
||||||
|
# key), so this adds no trust surface. Best-effort: a Codeberg outage
|
||||||
|
# (it 504s under load) must never fail an already-published F-Droid
|
||||||
|
# release. Needs the CODEBERG_RELEASE_TOKEN secret; skips cleanly if unset.
|
||||||
|
- name: Publish release to Codeberg
|
||||||
if: env.IS_RELEASE == 'true'
|
if: env.IS_RELEASE == 'true'
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
env:
|
env:
|
||||||
TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
TOKEN: ${{ secrets.CODEBERG_RELEASE_TOKEN }}
|
||||||
API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
|
API: https://codeberg.org/api/v1/repos/jlmakiola/calendula
|
||||||
|
SHA: ${{ github.sha }}
|
||||||
run: |
|
run: |
|
||||||
set -e
|
set -e
|
||||||
MAP="app/build/outputs/mapping/release/mapping.txt"
|
[ -s release-notes.md ] || bash scripts/release_notes.sh "$VERSION" > release-notes.md
|
||||||
if [ ! -f "$MAP" ]; then echo "No mapping.txt (R8 off?) — skipping."; exit 0; fi
|
TAG="v$VERSION" PRERELEASE=false NOTES_FILE=release-notes.md \
|
||||||
TAG="v$VERSION"
|
APK=app/build/outputs/apk/release/app-release.apk \
|
||||||
ASSET="mapping-${VERSION}.txt.gz"
|
bash scripts/publish_codeberg_release.sh
|
||||||
gzip -c "$MAP" > "/tmp/$ASSET"
|
|
||||||
ID=$(curl -s -H "Authorization: token $TOKEN" "$API/releases/tags/$TAG" | jq -r '.id // empty')
|
# Play takes an App Bundle, not the APK, so it is a second artifact from
|
||||||
if [ -z "$ID" ]; then echo "Could not resolve release id — skipping."; exit 0; fi
|
# the same source and the same signing config — not a repackage of the
|
||||||
# Replace any prior asset of the same name (re-run safe).
|
# APK. The release key signs it, but Play only ever treats that key as the
|
||||||
OLD=$(curl -s -H "Authorization: token $TOKEN" "$API/releases/$ID/assets" \
|
# *upload* key: Play App Signing re-signs with Google's own key before
|
||||||
| jq -r --arg n "$ASSET" '.[] | select(.name==$n) | .id')
|
# delivery. A Play install and an F-Droid install therefore carry
|
||||||
[ -n "$OLD" ] && curl -s -X DELETE -H "Authorization: token $TOKEN" "$API/releases/$ID/assets/$OLD" >/dev/null || true
|
# different signatures and cannot update each other. That divergence is a
|
||||||
curl -s -X POST -H "Authorization: token $TOKEN" \
|
# deliberate, documented choice (docs/RELEASING.md), not an accident.
|
||||||
-F "attachment=@/tmp/$ASSET" \
|
#
|
||||||
"$API/releases/$ID/assets?name=$ASSET" -o /dev/null -w "asset upload HTTP %{http_code}\n"
|
# Built LAST and `continue-on-error`, both deliberately: everything above
|
||||||
|
# has already shipped by this point, and nothing Play-related may put that
|
||||||
|
# at risk. Sitting mid-job without continue-on-error, this block took the
|
||||||
|
# whole 2.17.0 release down with it — no F-Droid publish, no tag, no
|
||||||
|
# Codeberg mirror — over an artifact upload. A failure here now costs the
|
||||||
|
# Play upload and nothing else.
|
||||||
|
#
|
||||||
|
# Nothing here touches the F-Droid path: the AAB is never copied into the
|
||||||
|
# repo, never attached to a release, and its build cannot change the APK
|
||||||
|
# published above.
|
||||||
|
#
|
||||||
|
# AGP embeds the R8 mapping in the bundle's BUNDLE-METADATA, so Play gets
|
||||||
|
# deobfuscated stacktraces without a separate mapping upload.
|
||||||
|
- name: Build release AAB
|
||||||
|
if: env.IS_RELEASE == 'true'
|
||||||
|
continue-on-error: true
|
||||||
|
run: ./gradlew bundleRelease
|
||||||
|
|
||||||
|
# NOT actions/upload-artifact@v4: it runs @actions/artifact v2, which
|
||||||
|
# refuses to start whenever GITHUB_SERVER_URL is not github.com — it reads
|
||||||
|
# any other forge as an unsupported GHES instance and fails before it ever
|
||||||
|
# talks to the server (go-gitea/gitea#36024). Gitea 1.25 serves the v4
|
||||||
|
# artifact API fine; only the client-side check is wrong. This fork is that
|
||||||
|
# client with the check removed. Pinned to a commit, not the v4 branch: a
|
||||||
|
# third-party action in the signing pipeline must not change under us.
|
||||||
|
- name: Hand the AAB to the Play job
|
||||||
|
if: env.IS_RELEASE == 'true'
|
||||||
|
continue-on-error: true
|
||||||
|
uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7 # v4
|
||||||
|
with:
|
||||||
|
name: release-aab-${{ needs.detect.outputs.version }}
|
||||||
|
path: app/build/outputs/bundle/release/app-release.aab
|
||||||
|
if-no-files-found: error
|
||||||
|
retention-days: 14
|
||||||
|
|
||||||
|
# Google Play channel.
|
||||||
|
#
|
||||||
|
# A separate job, on purpose, running only AFTER the F-Droid publish and both
|
||||||
|
# forge releases have completed. Play is the one channel that can reject a
|
||||||
|
# perfectly good build for reasons outside the pipeline (listing rules, policy
|
||||||
|
# review, API outage, a track that needs manual promotion). Isolating it means
|
||||||
|
# such a rejection surfaces as one red job next to a release that already
|
||||||
|
# shipped everywhere else, instead of failing the workflow that publishes it.
|
||||||
|
#
|
||||||
|
# Not a `container:` job even though a fastlane image exists: act_runner does
|
||||||
|
# not provide node inside custom job containers, so JavaScript actions
|
||||||
|
# (checkout, download-artifact) can't run there. The Renovate job gets away
|
||||||
|
# with a container because its only step is a shell command. Ruby is installed
|
||||||
|
# the same way sshpass, jq and fdroidserver are in the job above, from trixie:
|
||||||
|
# fastlane >= 2.241 needs Ruby 3.2+, and bookworm's apt only has 3.1.
|
||||||
|
play:
|
||||||
|
needs: [detect, release]
|
||||||
|
# workflow_dispatch is the F-Droid re-sign recovery path — it must never
|
||||||
|
# touch Play, so gate on a real release only.
|
||||||
|
if: needs.detect.outputs.is_release == 'true'
|
||||||
|
runs-on: docker
|
||||||
|
container:
|
||||||
|
image: node:22-trixie
|
||||||
|
env:
|
||||||
|
VERSION: ${{ needs.detect.outputs.version }}
|
||||||
|
VERSION_CODE: ${{ needs.detect.outputs.version_code }}
|
||||||
|
# Where the bundle lands. `production` — the release itself is already the
|
||||||
|
# gate (a bumped versionName only reaches main after on-device review), so
|
||||||
|
# a second manual promotion in the Play Console bought nothing but delay.
|
||||||
|
# Override with the PLAY_TRACK repo variable to stage a release instead.
|
||||||
|
PLAY_TRACK: ${{ vars.PLAY_TRACK || 'production' }}
|
||||||
|
PLAY_RELEASE_STATUS: ${{ vars.PLAY_RELEASE_STATUS || 'completed' }}
|
||||||
|
# Set PLAY_DRY_RUN=true to validate the edit against the API and discard
|
||||||
|
# it instead of committing — used to rehearse the first upload.
|
||||||
|
PLAY_DRY_RUN: ${{ vars.PLAY_DRY_RUN || 'false' }}
|
||||||
|
BUNDLE_PATH: vendor/bundle
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
# Skip cleanly (not fatally) when Play isn't configured yet, so the rest
|
||||||
|
# of the release pipeline keeps working during setup — same contract as
|
||||||
|
# the Codeberg mirror step.
|
||||||
|
- name: Write the Play service-account key
|
||||||
|
id: key
|
||||||
|
env:
|
||||||
|
PLAY_SERVICE_ACCOUNT_JSON: ${{ secrets.PLAY_SERVICE_ACCOUNT_JSON }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
if [ -z "${PLAY_SERVICE_ACCOUNT_JSON:-}" ]; then
|
||||||
|
echo "PLAY_SERVICE_ACCOUNT_JSON not set — skipping the Play upload."
|
||||||
|
echo "configured=false" >> "$GITHUB_OUTPUT"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
printf '%s' "$PLAY_SERVICE_ACCOUNT_JSON" > play-service-account.json
|
||||||
|
# Fail here, with a clear message, rather than inside fastlane: a
|
||||||
|
# mangled multi-line secret is the likeliest setup mistake.
|
||||||
|
python3 -c "import json,sys; d=json.load(open('play-service-account.json')); sys.exit(0 if d.get('type')=='service_account' else 1)" \
|
||||||
|
|| { echo "PLAY_SERVICE_ACCOUNT_JSON is not a valid service-account JSON." >&2; exit 1; }
|
||||||
|
echo "configured=true" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
|
# Same GHES-detection problem as the upload side, same fix — see the
|
||||||
|
# handoff step in the release job.
|
||||||
|
- name: Download the AAB
|
||||||
|
if: steps.key.outputs.configured == 'true'
|
||||||
|
uses: https://github.com/ChristopherHX/gitea-download-artifact@75635f32b4c1c41c4b3d64e8f85210112ed4c9c7 # v4
|
||||||
|
with:
|
||||||
|
name: release-aab-${{ needs.detect.outputs.version }}
|
||||||
|
path: dist
|
||||||
|
|
||||||
|
- name: Install Ruby
|
||||||
|
if: steps.key.outputs.configured == 'true'
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
SUDO=""
|
||||||
|
if command -v sudo >/dev/null 2>&1; then SUDO="sudo"; fi
|
||||||
|
$SUDO apt-get update
|
||||||
|
# ruby-dev + build-essential: several of fastlane's dependencies build
|
||||||
|
# native extensions.
|
||||||
|
$SUDO apt-get install -y ruby-full ruby-dev build-essential
|
||||||
|
ruby -v
|
||||||
|
|
||||||
|
# Only the first release pays the full gem build; afterwards this restores.
|
||||||
|
- name: Cache bundled gems
|
||||||
|
if: steps.key.outputs.configured == 'true'
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: vendor/bundle
|
||||||
|
key: ${{ runner.os }}-gems-${{ hashFiles('Gemfile') }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-gems-
|
||||||
|
|
||||||
|
- name: Install fastlane
|
||||||
|
if: steps.key.outputs.configured == 'true'
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
gem install bundler --no-document
|
||||||
|
bundle config set --local path vendor/bundle
|
||||||
|
bundle install --jobs 4
|
||||||
|
bundle exec fastlane --version
|
||||||
|
|
||||||
|
- name: Upload to Play
|
||||||
|
if: steps.key.outputs.configured == 'true'
|
||||||
|
env:
|
||||||
|
SUPPLY_JSON_KEY: play-service-account.json
|
||||||
|
# supply is chatty on a TTY-less runner otherwise.
|
||||||
|
FASTLANE_SKIP_UPDATE_CHECK: '1'
|
||||||
|
FASTLANE_HIDE_CHANGELOG: '1'
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
AAB="$GITHUB_WORKSPACE/dist/app-release.aab"
|
||||||
|
# Absolute, because a lane body runs from fastlane/, not the
|
||||||
|
# workspace root — a relative path resolves against the wrong
|
||||||
|
# directory there and 2.17.1 died on exactly that.
|
||||||
|
test -f "$AAB" || { echo "No AAB at $AAB — the artifact handoff failed." >&2; ls -la dist || true; exit 1; }
|
||||||
|
bundle exec fastlane deploy \
|
||||||
|
aab:"$AAB" \
|
||||||
|
track:"$PLAY_TRACK" \
|
||||||
|
release_status:"$PLAY_RELEASE_STATUS" \
|
||||||
|
dry_run:"$PLAY_DRY_RUN"
|
||||||
|
echo "Uploaded $VERSION (code $VERSION_CODE) to the '$PLAY_TRACK' track."
|
||||||
|
|
||||||
|
# The workspace is reused between runs on a self-hosted runner, so the
|
||||||
|
# credential must not outlive the job.
|
||||||
|
- name: Shred the service-account key
|
||||||
|
if: always()
|
||||||
|
run: shred -u play-service-account.json 2>/dev/null || rm -f play-service-account.json
|
||||||
@@ -1,8 +1,17 @@
|
|||||||
name: Renovate
|
name: Renovate
|
||||||
|
|
||||||
on:
|
on:
|
||||||
# Weekly sweep. Mondays 05:00 UTC — this cron owns the cadence; the repo's
|
# Every merge to main. Mirror syncs from Codeberg fire push events here (the
|
||||||
# renovate.json5 deliberately has no internal schedule (avoids double-gating).
|
# same trigger release.yaml relies on), so a merged Renovate PR is followed
|
||||||
|
# within minutes by a run that rebases the sibling PRs it just conflicted —
|
||||||
|
# most bumps touch gradle/libs.versions.toml. Outside renovate.json5's
|
||||||
|
# `schedule` window such a run only maintains existing branches
|
||||||
|
# (updateNotScheduled), it never opens new PRs. Renovate's own rebases push
|
||||||
|
# to renovate/* branches, not main, so this cannot loop.
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
# Weekly sweep for new updates. Mondays 05:00 UTC, inside the schedule window
|
||||||
|
# in renovate.json5 — keep the two in step.
|
||||||
schedule:
|
schedule:
|
||||||
- cron: '0 5 * * 1'
|
- cron: '0 5 * * 1'
|
||||||
# Manual run for an on-demand sweep from the Actions tab.
|
# Manual run for an on-demand sweep from the Actions tab.
|
||||||
@@ -24,19 +33,35 @@ jobs:
|
|||||||
# directly drops the docker-in-docker requirement entirely.
|
# directly drops the docker-in-docker requirement entirely.
|
||||||
# Full tag pinned; Renovate's github-actions manager keeps it bumped.
|
# Full tag pinned; Renovate's github-actions manager keeps it bumped.
|
||||||
container:
|
container:
|
||||||
image: ghcr.io/renovatebot/renovate:43.232.0
|
image: ghcr.io/renovatebot/renovate:44.237.3
|
||||||
steps:
|
steps:
|
||||||
- name: Run Renovate
|
- name: Run Renovate
|
||||||
run: renovate
|
run: renovate
|
||||||
env:
|
env:
|
||||||
# Self-hosted Gitea, not github.com.
|
# Renovate targets Codeberg (canonical) while still RUNNING on the
|
||||||
RENOVATE_PLATFORM: gitea
|
# Gitea runner. Moving the job to Codeberg would put a repo-write
|
||||||
RENOVATE_ENDPOINT: https://gitea.jeanlucmakiola.de/api/v1
|
# token on the contributor-facing runner, which is exactly what the
|
||||||
# Bot-account token (Gitea secret). Needs repo read/write + PR scope.
|
# .forgejo/ vs .gitea/ split exists to prevent — so the token stays
|
||||||
|
# where the other secrets live and only the API calls cross over.
|
||||||
|
#
|
||||||
|
# Platform is `forgejo`, not `gitea`: Codeberg runs Forgejo, and the
|
||||||
|
# pinned image ships a distinct forgejo platform module.
|
||||||
|
RENOVATE_PLATFORM: forgejo
|
||||||
|
RENOVATE_ENDPOINT: https://codeberg.org/api/v1
|
||||||
|
# Codeberg bot-account token (Gitea secret). Needs repo read/write +
|
||||||
|
# PR scope on jlmakiola/calendula.
|
||||||
RENOVATE_TOKEN: ${{ secrets.RENOVATE_TOKEN }}
|
RENOVATE_TOKEN: ${{ secrets.RENOVATE_TOKEN }}
|
||||||
# Scope to this repo only — no org-wide autodiscovery.
|
# Scope to this repo only — no org-wide autodiscovery.
|
||||||
RENOVATE_AUTODISCOVER: 'false'
|
RENOVATE_AUTODISCOVER: 'false'
|
||||||
RENOVATE_REPOSITORIES: '["makiolaj/calendula"]'
|
RENOVATE_REPOSITORIES: '["jlmakiola/calendula"]'
|
||||||
# Commits/PRs authored as the bot, not a real maintainer.
|
# Commits/PRs authored as the bot, not a real maintainer. This address
|
||||||
|
# must be a verified email on the Codeberg bot account, otherwise the
|
||||||
|
# commits show up unattributed there.
|
||||||
RENOVATE_GIT_AUTHOR: 'Renovate Bot <renovate@jeanlucmakiola.de>'
|
RENOVATE_GIT_AUTHOR: 'Renovate Bot <renovate@jeanlucmakiola.de>'
|
||||||
|
# Read-only github.com PAT (no scopes needed). Unaffected by the forge
|
||||||
|
# move — nearly every dependency is *released* on GitHub, and without
|
||||||
|
# this,
|
||||||
|
# changelog/release-note lookups hit the 60/h anonymous rate limit
|
||||||
|
# and PRs arrive with an empty "Release Notes" section.
|
||||||
|
RENOVATE_GITHUB_COM_TOKEN: ${{ secrets.GITHUB_COM_TOKEN }}
|
||||||
LOG_LEVEL: info
|
LOG_LEVEL: info
|
||||||
+19
@@ -50,8 +50,27 @@ google-services.json
|
|||||||
.DS_Store
|
.DS_Store
|
||||||
Thumbs.db
|
Thumbs.db
|
||||||
|
|
||||||
|
# Editor swap/backup files
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
*~
|
||||||
|
|
||||||
# F-Droid local artifacts (the pipeline generates them in CI)
|
# F-Droid local artifacts (the pipeline generates them in CI)
|
||||||
/fdroid/
|
/fdroid/
|
||||||
|
|
||||||
# KSP
|
# KSP
|
||||||
.ksp/
|
.ksp/
|
||||||
|
|
||||||
|
# Google Play Developer API service-account key. Reconstructed in CI from the
|
||||||
|
# PLAY_SERVICE_ACCOUNT_JSON secret and shredded afterwards — never committed.
|
||||||
|
/play-service-account.json
|
||||||
|
|
||||||
|
# fastlane (Play uploader only — see fastlane/Fastfile)
|
||||||
|
/fastlane/report.xml
|
||||||
|
/fastlane/README.md
|
||||||
|
/vendor/bundle/
|
||||||
|
/.bundle/
|
||||||
|
Gemfile.lock
|
||||||
|
|
||||||
|
# Claude Code
|
||||||
|
/CLAUDE.md
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
[submodule "floret-kit"]
|
||||||
|
path = floret-kit
|
||||||
|
url = https://codeberg.org/jlmakiola/floret-kit.git
|
||||||
+29
-8
@@ -17,9 +17,10 @@ re-inventing the calendar sync stack — leave that to DAVx5 and the system.
|
|||||||
## Current Milestone
|
## Current Milestone
|
||||||
|
|
||||||
Milestones 1 (read, v1.0) and 2 (write support, v1.1–v2.0.0 incl. reminder
|
Milestones 1 (read, v1.0) and 2 (write support, v1.1–v2.0.0 incl. reminder
|
||||||
delivery) are **complete** — v2.0.0 shipped 2026-06-11. Next is v3.0
|
delivery) are **complete** — v2.0.0 shipped 2026-06-11. Everything since is
|
||||||
(power-user features) plus an undecided "Locations & People" idea backlog;
|
tracked as issues and milestones on Codeberg:
|
||||||
see `ROADMAP.md`.
|
<https://codeberg.org/jlmakiola/calendula/milestones>. A milestone maps to its
|
||||||
|
`release/vX.Y.Z` branch.
|
||||||
|
|
||||||
## Stack
|
## Stack
|
||||||
|
|
||||||
@@ -27,10 +28,26 @@ Kotlin 2.3.21 (paired with KSP 2.3.9 — Kotlin 2.4.0 has no KSP release
|
|||||||
yet, do not upgrade until one ships). Jetpack Compose + Material 3
|
yet, do not upgrade until one ships). Jetpack Compose + Material 3
|
||||||
Expressive 1.5.0-alpha21 (alpha is intentional — Expressive APIs only
|
Expressive 1.5.0-alpha21 (alpha is intentional — Expressive APIs only
|
||||||
live in the 1.5 alpha line). Hilt 2.59.2, DataStore. Gradle Kotlin DSL
|
live in the 1.5 alpha line). Hilt 2.59.2, DataStore. Gradle Kotlin DSL
|
||||||
with Version Catalog. AGP 9.1.1, Gradle 9.5.1. JVM target 17.
|
with Version Catalog. AGP 9.2.1, Gradle 9.5.1. JVM target 17 (exactly — AGP
|
||||||
|
requires it).
|
||||||
|
|
||||||
Android-only (minSdk 29, targetSdk 36). No iOS. No `INTERNET` permission —
|
The shared Material 3 Expressive kit, **floret-kit**, is a git submodule wired
|
||||||
any feature that would need one is an explicit product decision first.
|
in as a Gradle composite build, so it compiles from source rather than resolving
|
||||||
|
as a dependency.
|
||||||
|
|
||||||
|
## Constraints
|
||||||
|
|
||||||
|
- **Platform:** Android-only, Android 10+ (minSdk 29), targetSdk 36. No iOS.
|
||||||
|
- **Offline-first:** all data lives in `CalendarContract` — no app database, no
|
||||||
|
sync stack. No `INTERNET` permission; any feature needing one is an explicit
|
||||||
|
product decision first.
|
||||||
|
- **Privacy:** zero telemetry, zero analytics.
|
||||||
|
- **i18n:** German + English from day one; further languages come from community
|
||||||
|
translators via the self-hosted Weblate, which owns every `values-*` file.
|
||||||
|
- **Tests + CI from day one**, JVM-first.
|
||||||
|
- **Reproducible release builds**, so the official F-Droid repo can verify the
|
||||||
|
published binary against a from-source rebuild.
|
||||||
|
- **Licence:** MIT.
|
||||||
|
|
||||||
## Naming
|
## Naming
|
||||||
|
|
||||||
@@ -40,5 +57,9 @@ shows a stylized "1" on a slate squircle.
|
|||||||
|
|
||||||
## Source
|
## Source
|
||||||
|
|
||||||
Hosted on self-hosted Gitea, released through self-hosted F-Droid repo on
|
**Codeberg (`jlmakiola/calendula`) is canonical** — git, issues, PRs, tags and
|
||||||
Hetzner. Same infrastructure as `HouseHoldKeaper`.
|
releases, plus contributor CI. The self-hosted Gitea instance is build
|
||||||
|
infrastructure only: it holds the signing key, runs the release pipeline, and
|
||||||
|
publishes the self-hosted F-Droid repo on Hetzner. Codeberg push-mirrors `main`
|
||||||
|
and tags to Gitea, where a bumped `versionName` triggers the release. Also
|
||||||
|
published to the official F-Droid repo. See `docs/RELEASING.md`.
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
# Calendula — Requirements
|
|
||||||
|
|
||||||
See full design spec: `docs/superpowers/specs/2026-06-08-calendar-app-design.md`
|
|
||||||
|
|
||||||
## V1 Scope (Variant "B") — shipped in full (v1.0.0, 2026-06-11)
|
|
||||||
|
|
||||||
- [x] Foundation & CI infrastructure — v0.1.0 (2026-06-08)
|
|
||||||
- [x] Data Layer over `CalendarContract`
|
|
||||||
- [x] Permission flow (`READ_CALENDAR`)
|
|
||||||
- [x] Month view (S1)
|
|
||||||
- [x] Week view (S2)
|
|
||||||
- [x] Day view (S3)
|
|
||||||
- [x] Event Detail Sheet (S4) — became a full screen, plus full event read (v0.6)
|
|
||||||
- [x] Multi-Calendar Filter (M3)
|
|
||||||
- [x] Today button (M2) — shipped v0.5; Jump-to-Date **cut from scope**
|
|
||||||
- [x] View-Switcher (M1)
|
|
||||||
- [x] Settings screen (M4)
|
|
||||||
- [x] Empty / no-permission / no-calendars states
|
|
||||||
- [x] German + English localization
|
|
||||||
- [x] Loading/Failure/Success states per screen (architectural pattern)
|
|
||||||
|
|
||||||
## V2 Scope — write support, shipped in full (v2.0.0, 2026-06-11)
|
|
||||||
|
|
||||||
- [x] Write foundation: `WRITE_CALENDAR`, read-only-calendar detection, delete (v1.1)
|
|
||||||
- [x] Create event: form, FAB, last-used calendar (v1.2; polish v1.2.1)
|
|
||||||
- [x] Edit event: shared form, scoped recurring writes, recurrence picker (v1.3)
|
|
||||||
- [x] Reminder notifications (v1.4) — **reversal of the original
|
|
||||||
"system handles reminders" assumption:** Calendula targets
|
|
||||||
sole-calendar-app users, so it posts reminder notifications itself
|
|
||||||
(Etar model), incl. `POST_NOTIFICATIONS` onboarding
|
|
||||||
- [x] Conflict dialog on save + store polish (v2.0)
|
|
||||||
- Quick-add — **cut from scope** (the prefilled form covers it)
|
|
||||||
- Calendar switching while editing — moved to v3 backlog
|
|
||||||
|
|
||||||
### Out of Scope (V3+)
|
|
||||||
|
|
||||||
- Home-screen widget
|
|
||||||
- Full-text search
|
|
||||||
- Tablet/foldable-specific layouts
|
|
||||||
- Locations & People ideas (contact picker, OSM autocomplete) — see
|
|
||||||
`ROADMAP.md` idea backlog, undecided
|
|
||||||
- iOS support (Android-only by design)
|
|
||||||
|
|
||||||
## Constraints
|
|
||||||
|
|
||||||
- **Tech stack:** Kotlin + Jetpack Compose + Material 3 Expressive, Hilt, DataStore
|
|
||||||
- **Tech stack pin:** Hilt 2.59.2 + KSP 2.3.9; Kotlin 2.3.21 (KSP for Kotlin 2.4.0 not released yet). Material 3 pinned to `1.5.0-alpha21` (Expressive APIs only exist in alpha). Re-evaluate when KSP/Material3 stable land.
|
|
||||||
- **Platform:** Android 10+ (API 29 minimum), Android 16 (API 36) target
|
|
||||||
- **Offline-first:** all data lives in `CalendarContract`; no app-side network
|
|
||||||
- **Privacy:** zero telemetry, no analytics
|
|
||||||
- **i18n:** German + English from day one
|
|
||||||
- **Tests + CI from day one**
|
|
||||||
- **License:** MIT
|
|
||||||
@@ -1,587 +0,0 @@
|
|||||||
# Calendula — Roadmap
|
|
||||||
|
|
||||||
## v0.x — Pre-Release
|
|
||||||
|
|
||||||
| Version | Milestone | Status |
|
|
||||||
|---|---|---|
|
|
||||||
| v0.1 | Foundation & CI | complete |
|
|
||||||
| v0.2 | Data Layer & Permission Flow | complete |
|
|
||||||
| v0.3 | Month + Week + Day views, view switcher | complete |
|
|
||||||
| v0.4 | Event Detail (S4) + humanized recurrence | complete |
|
|
||||||
| v0.5 | Calendar filter (M3) + Settings (M4) | complete |
|
|
||||||
| v0.6 | Full event read — surface every readable field | complete |
|
|
||||||
| v1.0 | First public release — polish pass, F-Droid | complete |
|
|
||||||
|
|
||||||
Delivery ran ahead of the original table: Day view (S3) shipped in v0.3 and
|
|
||||||
Event Detail (S4) in v0.4, so the Filter/Settings milestone became v0.5.
|
|
||||||
|
|
||||||
Jump-to-date (the date-picker half of M2) was **cut from scope** and will not
|
|
||||||
ship. The "Today" half of M2 already shipped in v0.5 (drawer entry).
|
|
||||||
|
|
||||||
## v0.6 — Full event read
|
|
||||||
|
|
||||||
Round out the read-only model so a detail view shows everything the system
|
|
||||||
actually stores, before write support starts. Scope = `CalendarContract`
|
|
||||||
columns we don't yet read/display:
|
|
||||||
|
|
||||||
- **Reminders** (`VALARM`) — read `CalendarContract.Reminders`, list lead times
|
|
||||||
- **Status** — Confirmed / Tentative / Cancelled (cancelled shown struck-through)
|
|
||||||
- **Availability** (`TRANSP`) — Free / Busy chip
|
|
||||||
- **Attendee extras** — role (required / optional / organizer) + the user's own
|
|
||||||
`SELF_ATTENDEE_STATUS`
|
|
||||||
- **Timezone** (`EVENT_TIMEZONE`) — shown only when it differs from the device zone
|
|
||||||
- **URL** — ~~tappable link card~~ **cut**: `CalendarContract` exposes no
|
|
||||||
`Events.URL` column (only `CUSTOM_APP_URI`, an originating-app deep-link).
|
|
||||||
URLs are instead surfaced by linkifying the description text
|
|
||||||
- **Access level / class** (private / confidential) — small chip (optional, trivial)
|
|
||||||
|
|
||||||
All of the above shipped in v0.6.0 (2026-06-11).
|
|
||||||
|
|
||||||
Deliberately out of v0.6:
|
|
||||||
- Recurrence exception / modified-occurrence badges — `Instances` already
|
|
||||||
resolves correct per-occurrence times for display; this only matters for
|
|
||||||
editing, so it folds into v2
|
|
||||||
- `CATEGORIES`, `ATTACH` — not reliably exposed by `CalendarContract`
|
|
||||||
(provider limitation, not our choice)
|
|
||||||
|
|
||||||
## v1.0 — First Public Release — shipped 2026-06-11
|
|
||||||
|
|
||||||
All V1 features shipped, polished, on F-Droid. Read-only calendar. Cut directly
|
|
||||||
after v0.6 (full event read) plus the onboarding-screen polish pass.
|
|
||||||
|
|
||||||
### Polish backlog (pre-1.0)
|
|
||||||
- ~~Redesign the initial grant-access (permission) screen~~ — **done**
|
|
||||||
(Material 3 Expressive onboarding, shipped in v0.6.0 / v1.0.0)
|
|
||||||
|
|
||||||
## v2.0 — Write Support (complete, shipped 2026-06-11)
|
|
||||||
|
|
||||||
Delivered in four releasable slices (plan:
|
|
||||||
`docs/superpowers/plans/2026-06-11-03-write-support.md`). The V1 spec is a
|
|
||||||
guide here, not a contract — scope per slice is decided as we go.
|
|
||||||
|
|
||||||
| Version | Milestone | Status |
|
|
||||||
|---|---|---|
|
|
||||||
| v1.1 | Write foundation — `WRITE_CALENDAR`, read-only-calendar detection, delete (series + single occurrence) | complete (shipped 2026-06-11) |
|
|
||||||
| v1.2 | Create event — form, FAB, last-used-calendar preselect | complete (shipped 2026-06-11) |
|
|
||||||
| v1.2.1 | Form polish after on-device review — card design system, optional fields + settings defaults, OptionCard dialogs, expressive motion | complete (shipped 2026-06-11) |
|
|
||||||
| v1.3 | Edit event — shared form, scoped recurring writes (this / following / all), recurrence picker | complete (shipped 2026-06-11) |
|
|
||||||
| v1.4 | Reminder notifications — see below | complete (shipped 2026-06-11) |
|
|
||||||
| v2.0 | Conflict dialog, polish pass (store copy refresh, F-Droid screenshots), release | complete (shipped 2026-06-11) |
|
|
||||||
|
|
||||||
v2.0 scope was re-cut on 2026-06-11, after v1.4:
|
|
||||||
- **Occurrence edit** already shipped early, in v1.3.
|
|
||||||
- **Quick-add** is **cut from scope**: the full form already opens prefilled
|
|
||||||
(visible day, last-used calendar, optional fields hidden), so the sheet
|
|
||||||
would only save one screen transition while adding a second create-surface
|
|
||||||
to maintain. Revisit only if real-world feedback says creation feels heavy.
|
|
||||||
- **Calendar switching while editing** moves to the v3 backlog (sync-adapter
|
|
||||||
minefield: `CALENDAR_ID` is sync-adapter-owned, AOSP locks the field; an
|
|
||||||
honest implementation is copy+delete like Google Calendar, with sync-identity
|
|
||||||
and attendee side effects).
|
|
||||||
- **Conflict dialog** stays (plan 03, decision 5): on save, compare against
|
|
||||||
the row as it was when the form loaded; on external change, ask
|
|
||||||
overwrite / discard. Closes the silent-clobber gap on synced calendars.
|
|
||||||
|
|
||||||
## v1.4 — Reminder Notifications
|
|
||||||
|
|
||||||
**Essential**, not nice-to-have: Calendula targets users for whom it is their
|
|
||||||
*only* calendar app, so reminder delivery can't be delegated to Google/OEM
|
|
||||||
Calendar. The calendar provider schedules reminders and broadcasts
|
|
||||||
`android.intent.action.EVENT_REMINDER`, but it does **not** post the visible
|
|
||||||
notification — a calendar app must. We become that app (the Etar model).
|
|
||||||
|
|
||||||
Scope:
|
|
||||||
- Manifest-registered `BroadcastReceiver` for `EVENT_REMINDER`
|
|
||||||
(data scheme `content://com.android.calendar`) — wakes us at reminder time,
|
|
||||||
no foreground service.
|
|
||||||
- Read `CalendarContract.CalendarAlerts` / `Reminders`, filter to
|
|
||||||
`METHOD_ALERT` / `METHOD_DEFAULT` (skip `METHOD_EMAIL`); post on a dedicated
|
|
||||||
notification channel; tap opens event detail.
|
|
||||||
- `POST_NOTIFICATIONS` runtime permission (API 33+) — requested in onboarding.
|
|
||||||
- Onboarding step: (a) request `POST_NOTIFICATIONS`, (b) in-app reminders
|
|
||||||
toggle, **default ON**, with copy warning that a second calendar app with
|
|
||||||
notifications on will cause duplicate reminders. Mirrored into Settings
|
|
||||||
(reversible).
|
|
||||||
|
|
||||||
Deliberately deferred (add only if needed):
|
|
||||||
- Snooze / dismiss notification actions (Etar has them)
|
|
||||||
- Battery-optimization exemption prompt for delivery reliability
|
|
||||||
|
|
||||||
## v2.1 — Month event grid + drawer view tabs (shipped 2026-06-15)
|
|
||||||
|
|
||||||
- Month grid shows real events as continuous multi-day bars (not just dots)
|
|
||||||
- View section in the navigation drawer to switch Month / Week / Day
|
|
||||||
- Fix: text cursor no longer jumps in event text fields
|
|
||||||
|
|
||||||
## v2.2 — Tap-to-create + local calendar management (shipped 2026-06-16)
|
|
||||||
|
|
||||||
- Tap an empty slot in day/week → create form prefilled with that day + the
|
|
||||||
tapped hour (snapped to the hour, 1 h long)
|
|
||||||
- Local (device-only) calendar management in a full-screen editor from
|
|
||||||
Settings → Calendars: create / rename / recolor / delete, with name,
|
|
||||||
pastel-previewed colour, and description (stored in `CAL_SYNC1`)
|
|
||||||
- Synced calendars listed read-only, grouped by account, each with a
|
|
||||||
per-account "manage in source app" deep-link (resolved from the account's
|
|
||||||
authenticator — DAVx5/ICSx5/…) + an add-account shortcut
|
|
||||||
- Shared `InlineTextField` extracted to `ui.common` (event form + calendar
|
|
||||||
editor share one input style)
|
|
||||||
|
|
||||||
## v2.3 — Material 3 grouped-list redesign (shipped 2026-06-16)
|
|
||||||
|
|
||||||
A structural + visual pass adopting one shared blueprint (modelled on the ReFra
|
|
||||||
gallery app) across Settings, the calendar manager and the navigation drawer.
|
|
||||||
|
|
||||||
- Shared `ui/common/GroupedList.kt`: `CollapsingScaffold` (a `LargeTopAppBar`
|
|
||||||
whose title collapses on scroll) + `GroupedRow` (Position-based corner
|
|
||||||
grouping, press-animated corners, `selected` + `minHeight` knobs).
|
|
||||||
- Settings: category hub with About card on top and sliding sub-pages
|
|
||||||
(Appearance / New event form / Notifications); theme/week-start/language
|
|
||||||
pickers moved from `DropdownMenu` to OptionCard dialogs; token-based icon
|
|
||||||
chips; `ic_gitea.xml` for the About "Source" button.
|
|
||||||
- Calendar manager + drawer restyled to match; shared `CalendarColorChip`;
|
|
||||||
drawer scrolls as one with the active view highlighted.
|
|
||||||
- Cards use `surfaceContainerHigh` for readable contrast.
|
|
||||||
- Donate button on the About card deferred (target TBD).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
# Backlog (theme-based, post-v2.1)
|
|
||||||
|
|
||||||
The old v3.0 / "daily-driver polish" / "Locations & People" lists are
|
|
||||||
consolidated here by theme. Within a group, **(in progress)** /
|
|
||||||
**(next)** mark what is being or about to be worked; everything else is an
|
|
||||||
approved-but-unscheduled idea unless tagged **(idea)** /
|
|
||||||
**(go/no-go)** / **(rejected)**. Order across groups is not a commitment.
|
|
||||||
|
|
||||||
## Near-term sequence (ranked, 2026-06-16)
|
|
||||||
|
|
||||||
The theme groups below are the full menu; this is the committed *order* for
|
|
||||||
the next stretch. Ranking favours finishing the current create/edit + calendar
|
|
||||||
arc before opening new fronts, then cheap-relative-to-value items and ones that
|
|
||||||
unblock a later item. Order is a plan, not a contract — revisit after each lands.
|
|
||||||
|
|
||||||
**Tier 1 — finish the current arc (create/edit + calendars)**
|
|
||||||
1. Tap-to-create in day/week *(shipped v2.2.0)* — prefilled create from an empty slot
|
|
||||||
2. Local calendar management + "manage in source app" deep-links *(shipped v2.2.0)*
|
|
||||||
3. ~~Settings redesign & restructure~~ *(shipped v2.3.0 — grew into the full
|
|
||||||
grouped-list blueprint across Settings + calendars + drawer; see "v2.3"
|
|
||||||
above)*
|
|
||||||
4. ~~Per-event color~~ *(shipped v2.4.0)* — palette calendars write
|
|
||||||
`EVENT_COLOR_KEY` (sync-safe); local/opted-in calendars write a raw
|
|
||||||
`EVENT_COLOR`; off-by-default setting for no-palette synced calendars
|
|
||||||
Tier 1's create/edit + calendars arc is effectively closed. **Duplicate event**
|
|
||||||
was deprioritised (2026-06-17) as low-importance and dropped to the bottom of
|
|
||||||
the sequence; the next item is now **Jump-to-date** (formerly Tier 2).
|
|
||||||
|
|
||||||
(Tier 2+ numbering below shifts accordingly; ranking unchanged.)
|
|
||||||
|
|
||||||
### Settings redesign & restructure *(shipped v2.3.0)*
|
|
||||||
|
|
||||||
The original scope below is kept as a record; the implementation expanded from a
|
|
||||||
sub-screen restructure into the shared grouped-list blueprint (see "v2.3" above).
|
|
||||||
|
|
||||||
The settings screen has grown into a flat vertical scroll of divider-separated
|
|
||||||
sections (Appearance, Event form, Notifications, Calendars, Language, About) and
|
|
||||||
will keep accreting rows (per-event-color defaults, default reminder, more
|
|
||||||
calendar entries are all queued). It needs structure before it gets unwieldy.
|
|
||||||
|
|
||||||
**Decided (2026-06-16): sub-screens**, not flat-but-carded. The top level
|
|
||||||
becomes a category list; each category opens its own destination. More
|
|
||||||
M3-idiomatic for a settings surface that will keep growing, and it mirrors the
|
|
||||||
existing Calendars row, which already navigates out to its own screen.
|
|
||||||
|
|
||||||
Structure — top-level settings list → category destinations:
|
|
||||||
- **Appearance** → theme, dynamic colour, week start
|
|
||||||
- **Event form** → the 6 default-field toggles + the hint text
|
|
||||||
- **Notifications** → reminders toggle (POST_NOTIFICATIONS flow stays)
|
|
||||||
- **Calendars** → already its own screen (`CalendarsScreen`); just becomes a
|
|
||||||
peer category row, no change to that screen
|
|
||||||
- **Language** → single control; keep as a top-level row that opens an
|
|
||||||
OptionCard directly (a whole sub-screen for one choice is overkill)
|
|
||||||
- **About** → kept inline on the top-level list as a card (read-only info,
|
|
||||||
not worth a navigation hop). Card layout, top → bottom:
|
|
||||||
- **Identity** — app logo + name "Calendula", with "by Jean-Luc Makiola"
|
|
||||||
as a subtitle beneath the name
|
|
||||||
- **Action buttons** (small, button-styled, sit in a row):
|
|
||||||
- **Source** — Gitea logo, opens the repo (`about_source_url`)
|
|
||||||
- **License** — opens the LICENSE file on Gitea
|
|
||||||
- **Donate** *(tentative)* — sits next to Source; target TBD (decide
|
|
||||||
before building: Liberapay / Ko-fi / Gitea sponsor / etc.)
|
|
||||||
- **Version** — small version number at the bottom of the card
|
|
||||||
|
|
||||||
Scope:
|
|
||||||
- **Navigation** — add the settings sub-screen destinations alongside the
|
|
||||||
existing settings/calendars routes in `CalendarHost`; back pops to the
|
|
||||||
settings list (mind the existing `BackHandler` that guards against falling
|
|
||||||
through to the activity).
|
|
||||||
- **Fix the dialog-pattern violation** — theme, week-start and language use
|
|
||||||
`DropdownMenu`; the project default is the full-width tonal OptionCard modal
|
|
||||||
(radio/dropdown/text-list dialogs are banned, see
|
|
||||||
`option-card-modal-style-default`). Migrate these selectors to OptionCard.
|
|
||||||
- **Visual pass** — top-level category rows with leading icons; consistent
|
|
||||||
spacing and row affordances aligned with the event-form card design system.
|
|
||||||
|
|
||||||
Out of scope (no new settings *features* here) — this is a structure + style
|
|
||||||
pass on the existing controls; new toggles ride in with their own features.
|
|
||||||
|
|
||||||
**Tier 2 — navigation & daily-driver completeness**
|
|
||||||
5. ~~Jump-to-date — drawer date picker (un-cut from V1); cheap, fills the nav gap~~ *(done, v2.5.0)*
|
|
||||||
6. ~~Agenda view — the missing 4th view; serves daily-driver users *and* becomes the data source for the widget~~ *(done, v2.5.0)*
|
|
||||||
|
|
||||||
**Tier 3 — platform reach (depends on Tier 2)**
|
|
||||||
7. ~~Home-screen widget — built on the agenda data source from #6~~ *(done, v2.5.0 — agenda + month widgets)*
|
|
||||||
8. App shortcuts: ~~launcher long-press → New event~~ *(done, v2.5.0)*; ~~quick-settings tile~~ *(done, v2.8.0 — "New event" QS tile)*
|
|
||||||
|
|
||||||
**Tier 4 — reliability, data-safety & interop** *(re-ranked 2026-06-17)*
|
|
||||||
9. **Reminders — defaults + delivery reliability** *(shipped v2.6.0)* — global
|
|
||||||
default reminder **+ per-calendar override**, bundled with battery-exemption
|
|
||||||
hardening. Full sketch in "Reminders — defaults & delivery reliability" below.
|
|
||||||
10. **The `.ics` engine — export + import** *(shipped v2.7.0, 2026-06-18)* — one
|
|
||||||
hand-rolled serializer/parser (zero deps, stays on `kotlinx-datetime`),
|
|
||||||
four surfaces all shipped: single-event share + whole-calendar backup
|
|
||||||
(export), open-`.ics`→form + whole-calendar bulk import (import). Closed the
|
|
||||||
device-local-calendar data-loss gap (#10/#11 merged here). Built as two
|
|
||||||
sequential branches: `feat/ics-export` (write side + UID-on-create precursor)
|
|
||||||
then `feat/ics-import` (parser, restore, dedup by UID). Import is
|
|
||||||
liberal-in/strict-out: skip-and-report foreign `VTIMEZONE` / `RECURRENCE-ID`
|
|
||||||
/ guest lists it can't model. Plans:
|
|
||||||
`docs/superpowers/plans/2026-06-18-05-ics-export.md` + `…-06-ics-import.md`.
|
|
||||||
11. **Snooze / dismiss notification actions** *(merged into release/v2.8.0)* —
|
|
||||||
followed the `.ics` work; inherits v2.6's deferred exact-alarm/WorkManager
|
|
||||||
decision (snooze must re-fire an alarm).
|
|
||||||
|
|
||||||
**Tier 5 — close the read/write gap on the event model** *(opened 2026-06-22)*
|
|
||||||
12. **Attendee editing** *(shipped — merged into release/v2.8.0, `feat/attendee-editing`
|
|
||||||
MR !29 / commit `b0f34ff`, 2026-06-22)* — closed the last big read-only gap in
|
|
||||||
the event model: attendees were already *read* (queried, mapped, shown on the
|
|
||||||
detail screen since v0.6) and are now *writable* from the form. An attendees
|
|
||||||
section on `EventEditScreen` / `EventForm` adds by typed email **or** the
|
|
||||||
no-permission contact picker, edits/removes rows, and sets role (required /
|
|
||||||
optional) — writing `CalendarContract.Attendees` rows on insert + dirty-checked
|
|
||||||
update, mirroring the reminders-diff pattern. The sync-adapter *invitation*
|
|
||||||
caveat was **settled record-only** (Calendula never sends invites; the backend
|
|
||||||
decides delivery) — full sketch + decision in "Attendee editing" under Locations
|
|
||||||
& People below.
|
|
||||||
|
|
||||||
**Gated — explicit go/no-go before any work (mostly INTERNET-permission calls)**
|
|
||||||
- Remote calendar create/edit (re-implements DAVx5; INTERNET + credential storage)
|
|
||||||
- Locations & People — the no-permission contact pickers already shipped (location v2.8.0, attendee email v2.8.0); what remains gated is OSM autocomplete (needs INTERNET)
|
|
||||||
- Move event to another calendar — sync-adapter minefield (copy+delete model)
|
|
||||||
|
|
||||||
**Bottom — deprioritised, not important**
|
|
||||||
- Duplicate event (detail action → prefilled create form) — moved here
|
|
||||||
2026-06-17; cheap but low value, pick up only if asked
|
|
||||||
|
|
||||||
**Unranked / fill-in** — pinch-to-zoom time scale, tablet/foldable layouts.
|
|
||||||
Pulled in opportunistically, not sequenced.
|
|
||||||
|
|
||||||
Tier 4 is now fully shipped (#9 reminders defaults v2.6.0, #10 `.ics`
|
|
||||||
export/import v2.7.0, #11 snooze/dismiss in release/v2.8.0; drag-drop rejected),
|
|
||||||
and Tier 5 #12 — attendee editing — shipped in release/v2.8.0, closing the last
|
|
||||||
read-only gap in the event model. v2.8.0 also cleared most Tier 2/3 leftovers —
|
|
||||||
full-text search, the "New event" Quick Settings tile, and the now-line all
|
|
||||||
shipped there. **No tier work is currently committed as next;** the remaining
|
|
||||||
candidates are unscheduled theme-group ideas (pinch-to-zoom, tablet/foldable,
|
|
||||||
accessibility pass) plus the gated go/no-go items.
|
|
||||||
|
|
||||||
## Navigation & views
|
|
||||||
|
|
||||||
- ~~Tap an empty slot in day/week → create form prefilled with that
|
|
||||||
date+time, snapped to the hour~~ **shipped v2.2.0** (long-press variant
|
|
||||||
not added — single tap covers it)
|
|
||||||
- Agenda view (fourth view: upcoming events grouped by day; also the
|
|
||||||
natural data source for a future widget)
|
|
||||||
- Jump to date — drawer date picker (un-cut from V1)
|
|
||||||
- ~~Current-time "now" line in day/week~~ **shipped v2.8.0**
|
|
||||||
- Week numbers in the **month** grid — **rejected** (owner decision): clutters
|
|
||||||
the view and shrinks the day cells; the badge stays week-view-only.
|
|
||||||
- Pinch-to-zoom time scale in day/week
|
|
||||||
- Tablet / foldable layouts *(was v3.0)*
|
|
||||||
- ~~Full-text search~~ **shipped v2.8.0** — for a daily driver with real event
|
|
||||||
history, finding an event is core completeness, not optional.
|
|
||||||
|
|
||||||
## Event editing & creation
|
|
||||||
|
|
||||||
- Duplicate event (detail action → prefilled create form)
|
|
||||||
- ~~**Per-event color**~~ *(shipped v2.4.0)* — `EVENT_COLOR` / `EVENT_COLOR_KEY`
|
|
||||||
from the calendar's color list (`Colors` table, `TYPE_EVENT`), OptionCard
|
|
||||||
picker in the form, falling back to the calendar color when unset. Reused the
|
|
||||||
color-picker component and palette plumbing from local calendar management and
|
|
||||||
finished the create/edit theme.
|
|
||||||
|
|
||||||
## Calendars & accounts
|
|
||||||
|
|
||||||
- ~~Create / manage local (device-only) calendars~~ **shipped v2.2.0** —
|
|
||||||
name + color + description; rename / recolor / delete the calendars the app
|
|
||||||
owns. Inserted under `ACCOUNT_TYPE_LOCAL` as a sync adapter; description in
|
|
||||||
`CAL_SYNC1`. Full-screen "Calendars" editor reached from Settings.
|
|
||||||
- ~~Per-calendar "manage in source app" deep-link~~ **shipped v2.2.0** — for
|
|
||||||
synced calendars, open the app the calendar actually came from based on
|
|
||||||
its `ACCOUNT_TYPE` (DAVx5 `bitfire.at.davdroid`, Google `com.google`,
|
|
||||||
…); fall back to system account/sync settings. Plus an "add account"
|
|
||||||
entry into system Accounts. Honest boundary for remote calendars.
|
|
||||||
- **Remote calendar create/edit** *(go/no-go)* — creating a CalDAV
|
|
||||||
collection (`MKCALENDAR`) or a Google calendar means an in-app sync
|
|
||||||
client: **INTERNET permission, credential storage, the full server
|
|
||||||
round-trip** — i.e. re-implementing DAVx5. DAVx5 exposes no public
|
|
||||||
intent to delegate the create to it. Cosmetic local edits (color/name)
|
|
||||||
to an existing synced row are possible but don't propagate to the server
|
|
||||||
and may be overwritten on next sync — not promised. Same explicit
|
|
||||||
go/no-go gate as the OSM/INTERNET item below.
|
|
||||||
- Move event to another calendar (copy+delete model with a consequences
|
|
||||||
warning — deferred from v2.0; `CALENDAR_ID` is sync-adapter-owned) *(was v3.0)*
|
|
||||||
- ~~**Local-calendar backup / export** *(Tier 4 #10)*~~ **shipped v2.7.0** —
|
|
||||||
device-only (`ACCOUNT_TYPE_LOCAL`) calendars had no sync and therefore no
|
|
||||||
backup. Settings → Calendars → Export writes every event to a user-chosen
|
|
||||||
`.ics` file (SAF); restore is the bulk-import path (pick a calendar, dedup by
|
|
||||||
UID). Closed the silent data-loss gap.
|
|
||||||
|
|
||||||
### Disable a calendar in-app *(captured 2026-06-25)*
|
|
||||||
|
|
||||||
A second, heavier visibility level **above** the existing per-view filter. Today
|
|
||||||
the drawer's calendar filter (`hiddenCalendarIds` in `CalendarPrefs`) only hides
|
|
||||||
a calendar's *events* from the month/week/day/agenda views — the calendar itself
|
|
||||||
still clutters the drawer filter list, the event-form calendar picker, and the
|
|
||||||
import target picker. "Disable" removes a calendar from the app's surfaces
|
|
||||||
entirely; "hide" stays the lightweight, frequently-toggled control.
|
|
||||||
|
|
||||||
**Two-level model (both kept):**
|
|
||||||
- **Hidden** (existing) — `hiddenCalendarIds`; a quick per-view checkbox in the
|
|
||||||
drawer. Toggles events on/off in the views; the calendar stays listed
|
|
||||||
everywhere. Operates only over the *enabled* calendars.
|
|
||||||
- **Disabled** (new) — the calendar is gone from the app: not in the drawer
|
|
||||||
filter list, not in the event-form picker, not in the import picker, and its
|
|
||||||
events never appear (it's gated out of `instances()` like a hidden one). It
|
|
||||||
remains visible **only** in Settings → Calendars, where the enable/disable
|
|
||||||
toggle lives, so it can be brought back.
|
|
||||||
|
|
||||||
**Storage — app-side (DataStore), mirrors the hidden set.** Add
|
|
||||||
`disabledCalendarIds: Set<Long>` + `setDisabledCalendarIds(...)` to
|
|
||||||
`CalendarPrefs` (comma-separated string key, same shape as `hiddenCalendarIds`).
|
|
||||||
**Does not touch** `CalendarContract.Calendars.VISIBLE` / `SYNC_EVENTS` — purely
|
|
||||||
a Calendula-local preference, so other calendar apps are unaffected and the sync
|
|
||||||
adapters stay out of it (privacy-clean, reversible).
|
|
||||||
|
|
||||||
**Where the disabled set is applied:**
|
|
||||||
- `CalendarRepositoryImpl.instances()` + `searchEvents()` — exclude
|
|
||||||
`calendarId ∈ (hidden ∪ disabled)` so a disabled calendar's events never show
|
|
||||||
and aren't searchable. (`repository.calendars()` itself stays unfiltered/raw —
|
|
||||||
the screens that need everything still get everything.)
|
|
||||||
- `FilterViewModel.state` — drop disabled calendars from the drawer filter list
|
|
||||||
(you can't hide/show what's disabled).
|
|
||||||
- `EventEditViewModel.writableCalendars` — exclude disabled, so you can't create
|
|
||||||
into a calendar you've removed from the app. Handle the last-used-calendar
|
|
||||||
preselect falling on a now-disabled calendar (fall back to first enabled
|
|
||||||
writable).
|
|
||||||
- `ImportViewModel` — exclude disabled from the import target list.
|
|
||||||
- `CalendarsScreen` / `CalendarsViewModel` — the **only** surface that lists
|
|
||||||
disabled calendars; add `setDisabled(id, Boolean)` and a per-calendar toggle.
|
|
||||||
|
|
||||||
**UI — Settings → Calendars (no new tab).** Add an enable/disable control to each
|
|
||||||
row on the existing `CalendarsScreen` (both the local and the synced/read-only
|
|
||||||
groups — disabling is an app-side view choice, independent of write access).
|
|
||||||
Disabled rows render visibly de-emphasised (dimmed) but keep the toggle so
|
|
||||||
they're re-enableable. Follow the project dialog/list conventions (M3 grouped
|
|
||||||
list, `option-card-modal-style-default` if a confirm/selection surface is needed).
|
|
||||||
|
|
||||||
**Decided behaviour:**
|
|
||||||
- All calendars disabled → views show the existing empty state.
|
|
||||||
- A disabled calendar that still holds events: events simply vanish from
|
|
||||||
views/search until re-enabled (no data touched — it's a filter, not a delete).
|
|
||||||
- Deep links / notifications pointing at an event in a disabled calendar still
|
|
||||||
open its detail screen — detail is a direct id lookup, not an `instances()`
|
|
||||||
query, so disabling never strands an existing link.
|
|
||||||
|
|
||||||
## Reminders — defaults & delivery reliability *(shipped v2.6.0; built on `feat/default-reminders`)*
|
|
||||||
|
|
||||||
Two themes bundled because both are "make reminders trustworthy" — the core of
|
|
||||||
the "Calendula is your only calendar app" promise.
|
|
||||||
|
|
||||||
**Built in this slice (A + the safe half of B):** global timed default reminder
|
|
||||||
+ a **separate all-day default** (day-scale lead times) + per-calendar override
|
|
||||||
(timed events), applied on create with manual-edit / calendar-switch / all-day-
|
|
||||||
toggle handling; three pickers + per-calendar override list in Settings →
|
|
||||||
Notifications; battery-optimisation exemption row (status + system deep-link, no
|
|
||||||
extra permission). `resolveDefaultReminder` + prefs round-trips unit-tested.
|
|
||||||
Resolution model: all-day events use the all-day global default outright;
|
|
||||||
per-calendar overrides govern timed events only. Reviewed (8-angle), fixes
|
|
||||||
applied: form-reset state race, label-fn consolidation with the detail screen,
|
|
||||||
inline wrapper + single combined flow read.
|
|
||||||
|
|
||||||
**Deliberately deferred (documented decisions, not oversights):**
|
|
||||||
- *Absolute time-of-day for all-day reminders* — the all-day default is still
|
|
||||||
minutes-before-midnight (day-scale presets), not "9am the day before" (open
|
|
||||||
decision #2's richer half). Per-calendar all-day overrides also deferred.
|
|
||||||
- *Self-scheduled alarms* — kept the existing provider-broadcast architecture
|
|
||||||
(open decision #1). The battery exemption is the reliability lever; no
|
|
||||||
`AlarmManager`/`USE_EXACT_ALARM` subsystem was added.
|
|
||||||
- *Test-reminder diagnostic* and *battery prompt inside onboarding* — the
|
|
||||||
exemption lives only in Settings for now (onboarding flow untouched to keep
|
|
||||||
the change reviewable).
|
|
||||||
|
|
||||||
### A. Default reminders (global + per-calendar override)
|
|
||||||
|
|
||||||
**No provider backing.** `CalendarContract` has no column that auto-applies a
|
|
||||||
default reminder per calendar — Google's per-calendar defaults live server-side.
|
|
||||||
So both the global default *and* the per-calendar override are **app-side
|
|
||||||
preferences**, applied by us at event-insert time. We inherit nothing from the
|
|
||||||
synced calendar.
|
|
||||||
|
|
||||||
- **Storage (DataStore):**
|
|
||||||
- `defaultReminderMinutes: Int?` — global default; `null` = "no reminder".
|
|
||||||
- `defaultAllDayReminderMinutes: Int?` — separate all-day default (all-day
|
|
||||||
reminders are expressed as minutes before midnight / day-before-at-time, not
|
|
||||||
minutes before a start instant — they need their own value).
|
|
||||||
- `perCalendarReminderOverride: Map<Long, Int?>` — keyed by calendar id;
|
|
||||||
**absent key = inherit global**, explicit `null` = "no reminder for this
|
|
||||||
calendar". (Same for an all-day override map if we want per-calendar all-day.)
|
|
||||||
- **Apply on create:** a fresh event prefills its reminders list from
|
|
||||||
override-or-global for the preselected calendar. Changing the calendar in the
|
|
||||||
form re-applies the *new* calendar's default **only if the user hasn't manually
|
|
||||||
edited the reminders** — track a dirty flag, mirroring the per-event-color
|
|
||||||
reset pattern (v2.4).
|
|
||||||
- **Edit semantics:** defaults apply to **new events only**; never rewrite
|
|
||||||
reminders on existing events on open or on calendar-switch-during-edit.
|
|
||||||
- **Settings UI (Notifications sub-page):**
|
|
||||||
- Global default via OptionCard (None / at time of event / 5 / 10 / 15 / 30 min
|
|
||||||
/ 1 h / 1 day / custom), plus the separate all-day default.
|
|
||||||
- Per-calendar overrides: a row per writable calendar (in the Calendars screen
|
|
||||||
or a Notifications subsection), each opening the same OptionCard with a
|
|
||||||
leading **"Use global default"** option.
|
|
||||||
|
|
||||||
### B. Delivery reliability (exact alarms + battery)
|
|
||||||
|
|
||||||
The provider broadcasts `EVENT_REMINDER`, but on modern Android (Doze / OEM
|
|
||||||
battery managers) delivery can be silently delayed or dropped. v1.4 deferred this;
|
|
||||||
it directly undermines the feature's premise, so it rides in here.
|
|
||||||
|
|
||||||
- **Exact alarm — decision first:** trust the provider broadcast, or
|
|
||||||
self-schedule via `AlarmManager.setExactAndAllowWhileIdle` for reliability?
|
|
||||||
If we self-schedule, declare `USE_EXACT_ALARM` (API 33+, auto-granted for
|
|
||||||
calendar/alarm-category apps, F-Droid-clean) with a `SCHEDULE_EXACT_ALARM`
|
|
||||||
fallback for API 31–32 (user-revocable → settings deep-link prompt).
|
|
||||||
- **Battery-optimization exemption:** a *soft, optional* prompt via
|
|
||||||
`ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS` (settings deep-link — never the
|
|
||||||
auto-grant intent), honest copy: "Android may delay reminders to save battery;
|
|
||||||
exempt Calendula for on-time delivery." Shown once after the existing
|
|
||||||
`POST_NOTIFICATIONS` onboarding step, reversible in Settings → Notifications.
|
|
||||||
- **Diagnostics:** a "send a test reminder in 1 minute" button in Notifications
|
|
||||||
settings so users can verify delivery on their specific OEM (Samsung / Xiaomi
|
|
||||||
are notorious for suppressing it).
|
|
||||||
|
|
||||||
### Decisions made (as shipped in v2.6.0)
|
|
||||||
|
|
||||||
1. **Provider broadcast kept** — did not self-schedule via `AlarmManager`; the
|
|
||||||
battery-optimisation exemption is the reliability lever (simplicity + battery
|
|
||||||
cost won over the exact-alarm subsystem).
|
|
||||||
2. **All-day reminders = minutes-before-midnight** (day-scale presets); absolute
|
|
||||||
time-of-day ("9am the day before") deferred — see the deferred list above.
|
|
||||||
3. **Per-calendar overrides live in the Notifications sub-page** (override list),
|
|
||||||
governing timed events only.
|
|
||||||
|
|
||||||
### Round two
|
|
||||||
|
|
||||||
- ~~Snooze + dismiss actions on the notification~~ *(shipped in release/v2.8.0,
|
|
||||||
Tier 4 #11)* — snooze re-fires a snooze-only exact alarm.
|
|
||||||
|
|
||||||
## Sharing & interop
|
|
||||||
|
|
||||||
- ~~Share event as .ics + open/receive .ics into a prefilled create form~~
|
|
||||||
**shipped v2.7.0** — single-event share from detail; opening an `.ics` with one
|
|
||||||
event prefills the create form, many events opens a bulk import (dedup by UID)
|
|
||||||
- ~~ICS file import~~ **shipped v2.7.0** — covered by the open/receive `.ics`
|
|
||||||
flow above (single → form, many → bulk import)
|
|
||||||
|
|
||||||
## Platform & launchers
|
|
||||||
|
|
||||||
- ~~Home-screen widget~~ **shipped v2.5.0** — agenda + month widgets
|
|
||||||
- ~~App shortcuts (launcher long-press → New event)~~ **shipped v2.5.0**
|
|
||||||
- ~~"New event" Quick Settings tile~~ **shipped v2.8.0**
|
|
||||||
|
|
||||||
## Quality & reliability
|
|
||||||
|
|
||||||
- **Accessibility pass** — TalkBack content descriptions across all screens,
|
|
||||||
dynamic-type / large-font reflow, touch-target audit. Quality bar for an
|
|
||||||
F-Droid app; nothing tracks it yet.
|
|
||||||
- **Reminder delivery reliability** — exact alarms + battery-optimization
|
|
||||||
exemption; specced in the "Reminders — defaults & delivery reliability" slice
|
|
||||||
above (Tier 4 #9).
|
|
||||||
|
|
||||||
## Locations & People *(go/no-go, captured 2026-06-11)*
|
|
||||||
|
|
||||||
Beyond classic calendar-client scope; discussed, deliberately not planned
|
|
||||||
in detail yet:
|
|
||||||
|
|
||||||
- ~~**Contact address picker** for the location field via the system picker
|
|
||||||
(`ACTION_PICK`)~~ **shipped v2.8.0** — one-shot, needs no READ_CONTACTS, fits
|
|
||||||
the privacy story. The same no-permission mechanism was then reused for the
|
|
||||||
attendee email picker (v2.8.0).
|
|
||||||
- **OSM address autocomplete** in the location field (type "Brandenburger
|
|
||||||
Tor" → tap suggestion → resolved address inserted). Backend would be
|
|
||||||
Photon (Nominatim's public policy forbids autocomplete). **Requires the
|
|
||||||
INTERNET permission** — first dent in the "no network access" promise;
|
|
||||||
if built: opt-in (off by default), honest copy, configurable endpoint
|
|
||||||
for self-hosters, onboarding footnote + F-Droid copy reworded. This
|
|
||||||
trade-off is an explicit go/no-go decision before any work starts.
|
|
||||||
- **Inline contact suggestions** while typing (needs READ_CONTACTS) — only
|
|
||||||
if the picker proves clunky.
|
|
||||||
- **Attendee editing** *(promoted out of this gated bucket 2026-06-22 — now
|
|
||||||
Tier 5 #12, high-importance; the no-permission typed-email path is not an
|
|
||||||
INTERNET/contacts call)*. See the "Attendee editing" sketch below.
|
|
||||||
|
|
||||||
### Attendee editing *(Tier 5 #12, opened 2026-06-22)*
|
|
||||||
|
|
||||||
The last read-only gap in the event model: attendees are read & shown on the
|
|
||||||
detail screen (since v0.6) but the form can't write them. Make guests editable.
|
|
||||||
|
|
||||||
- **Read side already done:** `Attendee` domain model + status/relationship/type
|
|
||||||
enums, `queryAttendees` + `EventDetailMapper.toAttendee` (with tests), and the
|
|
||||||
attendees `DetailCard` + `AttendeeRow` in `EventDetailScreen`. Nothing to add
|
|
||||||
there.
|
|
||||||
- **Write side — SHIPPED (`feat/attendee-editing`, commit b0f34ff, 2026-06-22):**
|
|
||||||
`attendees` on `EventForm`; a Guests section in `EventEditScreen` rendered as an
|
|
||||||
inline grouped list — each guest a tonal card (avatar, name/email, tappable
|
|
||||||
Required/Optional role chip, remove), the trailing card an inline email field
|
|
||||||
(type → Done commits). Persisted by `reconcileAttendees` diffing the provider's
|
|
||||||
`CalendarContract.Attendees` rows on insert + dirty-checked update (new guests =
|
|
||||||
`RELATIONSHIP_ATTENDEE` / `STATUS_INVITED`; kept rows keep their status, only the
|
|
||||||
required/optional type updates; organizer/resource/no-email rows untouched).
|
|
||||||
Reminders restyled to the same grouped-list pattern in passing. Needs only the
|
|
||||||
existing `WRITE_CALENDAR` — no new permission.
|
|
||||||
- **Name on manual add — SHIPPED via a contact picker** (2026-06-22). The inline
|
|
||||||
field is email-only (the quick path); the add row also has a **"from contacts"
|
|
||||||
button**: `ACTION_PICK` on `ContactsContract.CommonDataKinds.Email.CONTENT_URI` →
|
|
||||||
the system Contacts app returns a URI to the picked email row, queried for
|
|
||||||
`Email.ADDRESS` **and** the contact `DISPLAY_NAME`, so a picked guest gets both
|
|
||||||
email and name in one tap. The result Intent grants temporary read access, so
|
|
||||||
**no `READ_CONTACTS` permission** — one-shot and user-driven, same no-permission
|
|
||||||
mechanism as the location address picker above. Self/organizer rows stay
|
|
||||||
non-editable.
|
|
||||||
- **Invitation behavior — DECIDED 2026-06-22: record-only, all writable
|
|
||||||
calendars.** Calendula has no INTERNET and never sends an invitation itself; it
|
|
||||||
only writes `Attendees` rows. Whether a guest is notified is decided downstream:
|
|
||||||
local calendars notify no one (no sync); CalDAV/DAVx5 PUTs the `ATTENDEE` lines
|
|
||||||
and the *server* decides iMIP delivery; Google's sync adapter pushes the change
|
|
||||||
and Google decides (third-party attendee writes are historically unreliable
|
|
||||||
there). Editing is allowed on **any writable calendar** — not gated to local.
|
|
||||||
- **Honest, backend-aware copy is mandatory** (this is the whole point of the
|
|
||||||
decision): on a synced calendar show "Calendula doesn't send invitations —
|
|
||||||
your calendar account may email guests when it syncs"; on a local calendar
|
|
||||||
show "Stored on this device. No one is notified."
|
|
||||||
- Calendula must **not fabricate an ORGANIZER** or otherwise fake scheduling
|
|
||||||
state to coax a send — it writes the guest list faithfully and leaves
|
|
||||||
scheduling entirely to the backend.
|
|
||||||
- The optional "send an .ics invite via your email app" delegate (`ACTION_SEND`,
|
|
||||||
still no INTERNET) was considered and **deferred** — revisit only if users ask
|
|
||||||
to notify guests explicitly.
|
|
||||||
- **Out of scope (for now):** RSVP/your-own-response editing, free/busy lookups,
|
|
||||||
resource booking — all carry server round-trips or richer sync semantics.
|
|
||||||
|
|
||||||
## Consciously rejected
|
|
||||||
|
|
||||||
- Travel time / weather / smart suggestions (network, core-promise conflict)
|
|
||||||
- Natural-language quick entry (high effort, locale-fragile; the prefilled
|
|
||||||
form already covers fast entry)
|
|
||||||
- Quick-add sheet (the prefilled full form already covers it — cut in v2.0)
|
|
||||||
- Drag & drop rescheduling in day/week — **rejected** (owner decision,
|
|
||||||
reaffirmed 2026-06-22): not wanted. Rescheduling stays via the edit form.
|
|
||||||
@@ -1,177 +0,0 @@
|
|||||||
# Calendula — Current State
|
|
||||||
|
|
||||||
*Last updated: 2026-06-22*
|
|
||||||
|
|
||||||
## Status
|
|
||||||
|
|
||||||
**Milestone:** 2 (write support) **complete** — v2.0.0 shipped 2026-06-11.
|
|
||||||
**Phase:** post-2.x theme-based backlog work (organised in `ROADMAP.md`).
|
|
||||||
**Latest released tag: v2.7.5.** The whole Tier 4 (reliability/data-safety/
|
|
||||||
interop) arc is now done or in flight:
|
|
||||||
- v2.4.0 per-event colors (2026-06-17)
|
|
||||||
- v2.5.0 jump-to-date, Agenda view, agenda + month home-screen widgets, "New
|
|
||||||
event" launcher shortcut (2026-06-17)
|
|
||||||
- v2.6.0 default reminders (global + per-calendar override, all-day default,
|
|
||||||
battery-exemption row) + system per-app language (2026-06-18)
|
|
||||||
- v2.7.0 **`.ics` engine** — single-event share, local-calendar backup export,
|
|
||||||
open/receive `.ics` (single → form, many → bulk import, dedup by UID)
|
|
||||||
(2026-06-18)
|
|
||||||
- v2.7.1–v2.7.5 — crash-reporting + F-Droid reproducible-build hardening + fixes
|
|
||||||
|
|
||||||
**Next release `release/v2.8.0` (integration branch, not yet cut to main):**
|
|
||||||
holds crash reports via the public Codeberg tracker (MR !27) + reminder
|
|
||||||
snooze/dismiss notification actions (MR !28). Version bump to 2.8.0 happens at
|
|
||||||
release-cut.
|
|
||||||
|
|
||||||
## Progress
|
|
||||||
|
|
||||||
- [x] Design spec written and committed (`docs/superpowers/specs/2026-06-08-calendar-app-design.md`)
|
|
||||||
- [x] V1 design decisions resolved (App name "Calendula", icon, seed color)
|
|
||||||
- [x] Plan 01 written and executed — foundation lands (theme, icon, i18n, Hilt, DataStore, CI green)
|
|
||||||
- [x] Plan 02 written and executed — data layer + permission flow + debug screen
|
|
||||||
- [x] Month view (S1) — 6-week grid, event dots, today marker, swipe nav, three states (replaces debug screen)
|
|
||||||
- [x] Week view (S2) — time schedule with overlap-resolved lanes, all-day strip, swipe nav, three states
|
|
||||||
- [x] Day view (S3) — single-column slice reusing the week layout
|
|
||||||
- [x] View-switcher (M1) wired — cycles Month ↔ Week ↔ Day
|
|
||||||
- [x] Event-detail screen (S4) — full-screen, humanized recurrence
|
|
||||||
- [x] Filter sheet (M3) — per-calendar visibility, grouped by account, persisted, applied centrally in the repository
|
|
||||||
- [x] Settings (M4) — appearance (theme, dynamic colour, week start), language (per-app locales), about
|
|
||||||
- [~] Jump-to-date (M2) — **cut from scope**; "Today" half shipped in v0.5, date-picker dropped
|
|
||||||
- [x] Full event read (v0.6) — reminders, status, availability, access level,
|
|
||||||
attendee role + self-response, foreign timezone, and linkified description
|
|
||||||
URLs in the detail view; new domain enums + mapper unit tests. (A dedicated
|
|
||||||
URL field was cut — no `CalendarContract` column backs it.)
|
|
||||||
|
|
||||||
- [x] v1.1 write foundation — `WRITE_CALENDAR` (onboarding asks READ+WRITE,
|
|
||||||
only READ gates; contextual upgrade for v1.0 installs), read-only-calendar
|
|
||||||
detection (`CALENDAR_ACCESS_LEVEL` → `canModifyContents`, actions hidden for
|
|
||||||
WebCal/birthday calendars), delete from the detail screen (recurring:
|
|
||||||
"only this event" via cancelled exception / "all events in the series"),
|
|
||||||
repository + mapper tests
|
|
||||||
|
|
||||||
- [x] v1.2 create event — full-screen `EventEditScreen` (title, all-day,
|
|
||||||
M3 date/time pickers with duration-preserving start moves, writable-only
|
|
||||||
calendar picker preselecting the last-used calendar, location, description),
|
|
||||||
"+" FAB on all three views prefilled with the visible day, `insertEvent`
|
|
||||||
with provider-correct all-day normalisation (UTC midnights, exclusive end),
|
|
||||||
domain/mapper/repository tests
|
|
||||||
|
|
||||||
- [x] v1.3 edit event (shipped 2026-06-11) — `EventEditScreen` reused for
|
|
||||||
edit (detail-screen Edit action, `canModify`-gated, contextual WRITE
|
|
||||||
upgrade), dirty-checked partial `update` on the Events row (recurring:
|
|
||||||
series DTSTART moves by the user's delta, DURATION instead of DTEND),
|
|
||||||
reminder diff by minutes (kept rows keep their method), simple recurrence
|
|
||||||
picker (FREQ/INTERVAL/UNTIL/COUNT; complex RRULEs preserved verbatim and
|
|
||||||
shown humanized), `EventFormField.Recurrence` incl. settings default,
|
|
||||||
recurrence also available on create; domain/mapper/repository tests.
|
|
||||||
Review round 1: weekly BYDAY day-toggles in the custom picker ("every week
|
|
||||||
on Mon+Fri"). Review rounds 2–4: occurrence edit pulled forward from v2.0
|
|
||||||
and made three-way like delete ("this" = exception row via
|
|
||||||
`CONTENT_EXCEPTION_URI`, "this and following" = series split, "all" =
|
|
||||||
series update); delete equally three-way (truncation via RRULE UNTIL);
|
|
||||||
the edit-scope question moved to save time (Google model) — dirty
|
|
||||||
recurring saves park in `SaveUiState.AwaitingScope`, a changed rule drops
|
|
||||||
the "only this event" option
|
|
||||||
|
|
||||||
- [x] v1.4 reminder notifications (shipped 2026-06-11) — exported
|
|
||||||
`EVENT_REMINDER` receiver → `CalendarAlerts` (SCHEDULED & due) →
|
|
||||||
dedicated channel, tap opens detail (singleTop deep link); best-effort
|
|
||||||
FIRED marking; one-time onboarding step requesting `POST_NOTIFICATIONS`
|
|
||||||
with duplicate-reminders warning; Settings mirror. Provider only fires
|
|
||||||
`METHOD_ALERT` rows (AOSP-verified), so email reminders never reach us
|
|
||||||
|
|
||||||
- [x] v2.0 conflict dialog + store polish (shipped 2026-06-11 as v2.0.0) —
|
|
||||||
`EditSnapshot` compare on save (overwrite/discard; deleted → close),
|
|
||||||
quick-add cut, calendar-switch → v3 backlog; F-Droid/README copy
|
|
||||||
refreshed, fastlane screenshots DE+EN captured on-device
|
|
||||||
|
|
||||||
- [x] v2.1 (shipped 2026-06-15) — month grid shows real events as
|
|
||||||
continuous multi-day bars; navigation-drawer View section
|
|
||||||
(Month/Week/Day); cursor-jump fix in event text fields
|
|
||||||
|
|
||||||
- [x] v2.2 (shipped 2026-06-16) — tap an empty slot in day/week to create
|
|
||||||
(prefilled with that day + tapped hour, snapped to the hour); local
|
|
||||||
calendar management in a full-screen editor from Settings →
|
|
||||||
Calendars: create/rename/recolor/delete device-only calendars
|
|
||||||
(`ACCOUNT_TYPE_LOCAL`, sync-adapter insert) with name, pastel-previewed
|
|
||||||
colour, and description (stored in `CAL_SYNC1`); synced calendars listed
|
|
||||||
read-only grouped by account with a per-account "manage in source app"
|
|
||||||
deep-link (resolved from the account's authenticator: DAVx5/ICSx5/…) and
|
|
||||||
an add-account shortcut. Shared `InlineTextField` extracted to `ui.common`
|
|
||||||
|
|
||||||
- [x] v2.3 settings/calendars/drawer redesign (shipped 2026-06-16) — adopted a
|
|
||||||
shared Material 3 grouped-list blueprint, modelled on the ReFra gallery app
|
|
||||||
and extracted to `ui/common/GroupedList.kt` (`CollapsingScaffold` with a
|
|
||||||
`LargeTopAppBar` exit-until-collapsed title; `GroupedRow` with Position-based
|
|
||||||
corner grouping, press-animated corners, `selected` + `minHeight` knobs).
|
|
||||||
- Settings: category hub (About card on top → version mark at the foot) with
|
|
||||||
sliding sub-pages (Appearance / New event form / Notifications); token-
|
|
||||||
based icon chips; theme/week-start/language pickers migrated from
|
|
||||||
`DropdownMenu` to OptionCard dialogs. New `ic_gitea.xml` (Simple Icons,
|
|
||||||
verbatim path) for the About "Source" button; en+de strings.
|
|
||||||
- Calendar manager: same collapsing scaffold + grouped rows; shared
|
|
||||||
`CalendarColorChip` (neutral chip, pastelised calendar glyph).
|
|
||||||
- Navigation drawer: branded header, grouped View switcher (active view
|
|
||||||
highlighted via `secondaryContainer`), the filter list restyled to
|
|
||||||
grouped rows with a trailing checkbox; the whole drawer scrolls as one.
|
|
||||||
- Cards use `surfaceContainerHigh` for readable contrast against `surface`.
|
|
||||||
- Donate button on the About card deferred (target still TBD).
|
|
||||||
|
|
||||||
- [x] v2.4 per-event color (shipped 2026-06-17) — an optional "Color" field in
|
|
||||||
the event form. Read/render already resolved `EVENT_COLOR` with a calendar
|
|
||||||
fallback; this adds the write side and the picker. Palette-backed calendars
|
|
||||||
(Google, some CalDAV) pick from the account's `Colors` (`TYPE_EVENT`) and
|
|
||||||
write `EVENT_COLOR_KEY` so the color round-trips through sync; local
|
|
||||||
calendars write a raw `EVENT_COLOR` from the shared `CALENDAR_COLOR_PALETTE`
|
|
||||||
(extracted with the swatch row to `ui/common/ColorSwatchRow.kt`). Switching
|
|
||||||
calendars resets the choice (a key is account-scoped). A settings toggle
|
|
||||||
("Allow colors on unsupported calendars", off by default) extends the raw
|
|
||||||
path to synced calendars with no palette, with an honest "may not survive
|
|
||||||
sync" warning on the picker and in Settings. Color writes flow through
|
|
||||||
insert / dirty-checked update / occurrence-exception; mapper + form tests.
|
|
||||||
|
|
||||||
- [x] v2.5 (shipped 2026-06-17) — Agenda view (4th top-level view),
|
|
||||||
jump-to-date drawer date picker, two home-screen widgets (scrolling
|
|
||||||
"Upcoming" agenda + month grid), and a "New event" launcher long-press
|
|
||||||
shortcut
|
|
||||||
|
|
||||||
- [x] v2.6 (shipped 2026-06-18) — default reminders: global timed default +
|
|
||||||
separate all-day default + per-calendar override (timed), applied on create
|
|
||||||
with dirty-flag handling; three pickers + override list in Settings →
|
|
||||||
Notifications; battery-optimisation exemption row (status + system deep-link,
|
|
||||||
no new permission). Plus system per-app language (Android 13+) and an
|
|
||||||
immediate-effect fix for the in-app language picker
|
|
||||||
|
|
||||||
- [x] v2.7 (shipped 2026-06-18) — the `.ics` engine: share a single event as
|
|
||||||
`.ics` from the detail screen; back up local calendars (Settings → Calendars
|
|
||||||
→ Export) to a SAF file; open/receive an `.ics` — one event prefills the
|
|
||||||
create form, many events open a bulk import into a chosen calendar (dedup by
|
|
||||||
UID, skip-and-report unrepresentable VTIMEZONE / RECURRENCE-ID / guests).
|
|
||||||
Hand-rolled serializer/parser, zero deps. Plus all-day single-day UTC fix and
|
|
||||||
a widget R8 keep-rule crash fix
|
|
||||||
|
|
||||||
- [x] v2.7.1–v2.7.5 (2026-06-21) — launch crash fix (listener before grant),
|
|
||||||
user-controlled crash reporting, widget loading-spinner R8 keep rule, and
|
|
||||||
F-Droid reproducible-build cleanups for the official repo
|
|
||||||
|
|
||||||
- [~] release/v2.8.0 (not yet cut) — crash reports via the public Codeberg
|
|
||||||
tracker (MR !27) + reminder snooze/dismiss notification actions (MR !28,
|
|
||||||
snooze self-schedules an exact alarm; primary delivery stays provider-broadcast)
|
|
||||||
|
|
||||||
## Next
|
|
||||||
|
|
||||||
1. Cut **v2.8.0** from `release/v2.8.0` (bump versionName → tag via the
|
|
||||||
merge-driven pipeline) once on-device review signs off
|
|
||||||
2. **Attendee editing** — the committed next feature (Tier 5 #12, high-
|
|
||||||
importance, opened 2026-06-22). Attendees are already read & shown on the
|
|
||||||
detail screen since v0.6; the gap is the write side — make guests editable
|
|
||||||
in `EventEditScreen` / `EventForm` (add by typed email, role, remove),
|
|
||||||
persisted by diffing `CalendarContract.Attendees`. No new permission for the
|
|
||||||
typed-email path. **Invitation behavior DECIDED 2026-06-22: record-only on all
|
|
||||||
writable calendars** — Calendula never sends (no INTERNET); honest backend-aware
|
|
||||||
copy ("your account may email guests when it syncs" on synced calendars, "no one
|
|
||||||
is notified" on local). Full sketch in `ROADMAP.md` → "Attendee editing".
|
|
||||||
3. Then: the two INTERNET go/no-go calls (OSM autocomplete, remote calendar
|
|
||||||
create/edit) and Tier 2/3 leftovers (quick-settings tile, now-line, week
|
|
||||||
numbers in month, full-text search, accessibility pass). Drag-and-drop
|
|
||||||
rescheduling is **rejected**.
|
|
||||||
+1260
File diff suppressed because it is too large.
Load diff
+184
@@ -0,0 +1,184 @@
|
|||||||
|
# Contributing to Calendula
|
||||||
|
|
||||||
|
Calendula is a Material 3 Expressive calendar app that lives strictly on top of
|
||||||
|
Android's `CalendarContract`, with no app database, sync stack or network access.
|
||||||
|
That constraint shapes most review comments, so skim
|
||||||
|
[`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) before you write code. This file
|
||||||
|
covers the practical side.
|
||||||
|
|
||||||
|
[Codeberg](https://codeberg.org/jlmakiola/calendula) is the canonical home for
|
||||||
|
issues, pull requests and releases. The self-hosted Gitea instance referenced in the
|
||||||
|
release docs is build infrastructure only; there is nothing to contribute there.
|
||||||
|
Be decent to the people you meet in the tracker.
|
||||||
|
|
||||||
|
## Start with an issue
|
||||||
|
|
||||||
|
| You want to | Do this |
|
||||||
|
|---|---|
|
||||||
|
| Add a feature | **Open an issue first** and wait for a go-ahead |
|
||||||
|
| Fix a bug | Open an issue, then a pull request |
|
||||||
|
| Fix a typo, a comment, or docs | Just open the pull request |
|
||||||
|
| Add or fix a translation | Use [Weblate](#translations), not a pull request |
|
||||||
|
|
||||||
|
Features get an opinion before they get code: whether Calendula should do a
|
||||||
|
thing at all is the one decision a patch can't make. A feature PR that arrives
|
||||||
|
without a discussed issue may be closed unmerged even when the code is good, so
|
||||||
|
please don't spend a weekend on one first.
|
||||||
|
|
||||||
|
Bugs are more straightforward, but still start with an issue: it's what carries
|
||||||
|
the milestone and gives the changelog something to link.
|
||||||
|
|
||||||
|
Issue templates cover bug, crash, feature and question. For a crash, let the app
|
||||||
|
do the work: *Settings → Report a problem*, or the prompt shown after a crash,
|
||||||
|
captures the stack trace and prefills the form. The report contains app, Android
|
||||||
|
and device versions plus the trace, and no calendar content or personal data.
|
||||||
|
|
||||||
|
## Which branch to target
|
||||||
|
|
||||||
|
Calendula releases by merging a version bump into `main`, so `main` is a release
|
||||||
|
trigger rather than a staging area. Work is assembled on release branches first.
|
||||||
|
|
||||||
|
Once your issue has a milestone, that milestone names your branch:
|
||||||
|
|
||||||
|
| Milestone | Target branch |
|
||||||
|
|---|---|
|
||||||
|
| `2.18.0` | `release/v2.18.0` |
|
||||||
|
|
||||||
|
Every milestone has a matching branch. If it's somehow missing, target `main` and
|
||||||
|
mention it in the PR, and it will be retargeted. Don't pick an older release branch:
|
||||||
|
they're kept after shipping, so the newest one isn't necessarily yours.
|
||||||
|
|
||||||
|
## Translations
|
||||||
|
|
||||||
|
**Never edit a `values-*/strings.xml` file in a pull request**, German included.
|
||||||
|
Translations are owned by a self-hosted Weblate that writes to this repository
|
||||||
|
directly, and a hand-edit is overwritten on the next sync.
|
||||||
|
|
||||||
|
[Translate Calendula on Weblate](https://weblate.dev.jeanlucmakiola.de/engage/calendula/)
|
||||||
|
|
||||||
|
Adding a *new* English string to `values/strings.xml` is normal PR work; Weblate
|
||||||
|
picks it up and offers it to translators. Partial translations are expected and
|
||||||
|
fine; missing keys are informational. Stale and orphaned keys are not, so run
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 scripts/check_translations.py
|
||||||
|
```
|
||||||
|
|
||||||
|
before pushing. It reports those more clearly than lint's `MissingTranslation`
|
||||||
|
does.
|
||||||
|
|
||||||
|
## Build and test
|
||||||
|
|
||||||
|
```sh
|
||||||
|
git clone --recurse-submodules https://codeberg.org/jlmakiola/calendula.git
|
||||||
|
```
|
||||||
|
|
||||||
|
The `floret-kit` submodule is a composite build compiled from source. An
|
||||||
|
existing clone needs `git submodule update --init --recursive`, or nothing
|
||||||
|
resolves.
|
||||||
|
|
||||||
|
- **JDK 17**, not newer: the Android Gradle Plugin requires exactly 17. Set
|
||||||
|
`JAVA_HOME` if your default differs.
|
||||||
|
- **Android SDK**: platform 37 (`compileSdk`) and build-tools 36.0.0, located
|
||||||
|
via `ANDROID_HOME` or a gitignored `local.properties` with `sdk.dir`. If you
|
||||||
|
go the `local.properties` route, the included build needs its own copy at
|
||||||
|
`floret-kit/local.properties`; `ANDROID_HOME` covers both at once and is the
|
||||||
|
easier path.
|
||||||
|
|
||||||
|
The Gradle wrapper is checked in, so no system Gradle is needed.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
./gradlew lint test assembleDebug # roughly what CI runs
|
||||||
|
```
|
||||||
|
|
||||||
|
A single test class, or a pattern:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
./gradlew testDebugUnitTest --tests "de.jeanlucmakiola.calendula.domain.SimpleRecurrenceTest"
|
||||||
|
./gradlew testDebugUnitTest --tests "*SimpleRecurrence*"
|
||||||
|
```
|
||||||
|
|
||||||
|
CI reports one `CI` check per pull request: `lintDebug`, `testDebugUnitTest`,
|
||||||
|
`assembleDebug`, and a Trivy scan. Pull requests touching only docs, F-Droid
|
||||||
|
metadata or the licence skip the Android build and go green quickly. More detail
|
||||||
|
in [`docs/BUILDING.md`](docs/BUILDING.md).
|
||||||
|
|
||||||
|
## The rules
|
||||||
|
|
||||||
|
These are the ones that turn into review comments.
|
||||||
|
|
||||||
|
1. **No network.** Calendula holds no `INTERNET` permission, and that's a
|
||||||
|
feature rather than an oversight. Anything that would need one is a product
|
||||||
|
decision before it's a patch. The crash reporter opens a prefilled web issue
|
||||||
|
on purpose instead of posting anything itself.
|
||||||
|
2. **The provider is the only database.** No Room, no cache, no local mirror of
|
||||||
|
events. `CalendarContract` is the single source of truth, which is also why
|
||||||
|
externally synced changes work for free.
|
||||||
|
3. **Don't patch UI state after a write.** A `ContentObserver` re-queries and
|
||||||
|
views recompose from fresh provider state. Hand-patching a list after saving
|
||||||
|
appears to work, then drifts away from what the provider stored.
|
||||||
|
4. **`domain/` has no Android imports.** Models, validation, recurrence
|
||||||
|
rendering, conflict snapshots and the `.ics` codec stay pure Kotlin so they
|
||||||
|
remain JVM-testable.
|
||||||
|
5. **Tests run on the JVM.** JUnit 5 + Truth + Turbine. The seams exist for you:
|
||||||
|
fake the data source (`FakeCalendarDataSource`), and feed mappers plain maps
|
||||||
|
through `ColumnReader` instead of cursors. Instrumented tests are a last
|
||||||
|
resort.
|
||||||
|
6. **Read before touching the subtle pipelines.** Recurring writes (UNTIL vs
|
||||||
|
DURATION, exception URIs, series splits), save-conflict detection and reminder
|
||||||
|
delivery (post-before-mark) follow provider-driven rules that are documented
|
||||||
|
in [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) and are not guessable from
|
||||||
|
the code alone.
|
||||||
|
7. **Don't break reproducible builds.** `vcsInfo`, `dependenciesInfo` and the AGP
|
||||||
|
metadata block are disabled on purpose so the official F-Droid repo can verify
|
||||||
|
our binary against a from-source rebuild.
|
||||||
|
`scripts/check_reproducible_release.sh` runs on every pull request, including
|
||||||
|
docs-only ones.
|
||||||
|
|
||||||
|
## UI conventions
|
||||||
|
|
||||||
|
Material 3 Expressive throughout, built from the system's own tokens and
|
||||||
|
components: colour-scheme tokens rather than hardcoded colours, `ListItem` for
|
||||||
|
settings rows.
|
||||||
|
|
||||||
|
**Selection pickers are full-screen.** Every browse-style "choose one" surface
|
||||||
|
uses floret-kit's `FullScreenPicker` / `OptionPicker`; one that needs a commit or
|
||||||
|
extra action passes it through the picker's `actions` slot. The exception is the
|
||||||
|
recurring-scope chooser (*this / this and following / all*), which stays a
|
||||||
|
compact dialog, because a two- or three-option decision reads better as a popup than as
|
||||||
|
a nearly empty screen. `AlertDialog` is for plain confirmations only, and radio-
|
||||||
|
or text-list dialogs aren't used at all.
|
||||||
|
|
||||||
|
Shared UI machinery lives in the `floret-kit` submodule and has
|
||||||
|
[its own contributing guide](https://codeberg.org/jlmakiola/floret-kit/src/branch/main/CONTRIBUTING.md);
|
||||||
|
changing it means a pull request against that repository plus a submodule bump
|
||||||
|
here.
|
||||||
|
|
||||||
|
## Commits and pull requests
|
||||||
|
|
||||||
|
Conventional commits, scoped to the area you touched:
|
||||||
|
|
||||||
|
```
|
||||||
|
fix(calendars): keep an event's own calendar when it is switched off
|
||||||
|
feat(month): pull-to-expand the split view (#38)
|
||||||
|
docs(architecture): record what the second review pass changed
|
||||||
|
```
|
||||||
|
|
||||||
|
Types in use: `feat` `fix` `docs` `refactor` `style` `chore` `ci` `build`
|
||||||
|
`revert`. Reference the issue in the subject or the body. Keep commits small.
|
||||||
|
Small commits revert cleanly, which matters more here than a tidy history.
|
||||||
|
|
||||||
|
If your change is user-visible, add an entry under `## [Unreleased]` in
|
||||||
|
[`CHANGELOG.md`](CHANGELOG.md). Match the surrounding voice: entries describe
|
||||||
|
what changed *for the person using the app*, and why. Code changes don't go
|
||||||
|
there. Link the issue and add its reference at the bottom of the file. It may get
|
||||||
|
reworded when the release is cut, so don't agonise over it.
|
||||||
|
|
||||||
|
Please don't commit planning or design documents. Code, tests, architecture notes
|
||||||
|
and the changelog land; the reasoning belongs in the commit message and the
|
||||||
|
issue.
|
||||||
|
|
||||||
|
## Licence
|
||||||
|
|
||||||
|
Calendula is [MIT](LICENSE). By contributing you agree your changes ship under
|
||||||
|
the same licence.
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
source "https://rubygems.org"
|
||||||
|
|
||||||
|
# fastlane is used ONLY to upload the release bundle to Google Play
|
||||||
|
# (see fastlane/Fastfile). It is not part of the build or the signing path, so
|
||||||
|
# it never runs on a PR — only in release.yaml's `play` job.
|
||||||
|
#
|
||||||
|
# Pinned exactly; Renovate's bundler manager keeps it bumped. No Gemfile.lock is
|
||||||
|
# committed on purpose: this resolves an uploader's transitive deps, not the
|
||||||
|
# app's, and none of it affects the reproducible release build.
|
||||||
|
gem "fastlane", "2.241.1"
|
||||||
@@ -4,11 +4,11 @@
|
|||||||
|
|
||||||
<h1>Calendula</h1>
|
<h1>Calendula</h1>
|
||||||
|
|
||||||
<p><strong>A modern Material 3 Expressive calendar for Android.</strong><br>
|
<p><strong>A Material 3 Expressive calendar for Android.</strong><br>
|
||||||
Reads, writes, and reminds — on top of the system calendar, with zero network access.</p>
|
It works on top of the system calendar and has no network access.</p>
|
||||||
|
|
||||||
<p>
|
<p>
|
||||||
<a href="https://gitea.jeanlucmakiola.de/makiolaj/calendula/actions"><img src="https://gitea.jeanlucmakiola.de/makiolaj/calendula/actions/workflows/ci.yaml/badge.svg?branch=main" alt="CI"></a>
|
<a href="https://codeberg.org/jlmakiola/calendula/actions"><img src="https://codeberg.org/jlmakiola/calendula/actions/workflows/ci.yaml/badge.svg?branch=main" alt="CI"></a>
|
||||||
<img src="https://img.shields.io/badge/Android-10%2B-3DDC84?logo=android&logoColor=white" alt="Android 10+">
|
<img src="https://img.shields.io/badge/Android-10%2B-3DDC84?logo=android&logoColor=white" alt="Android 10+">
|
||||||
<img src="https://img.shields.io/badge/Kotlin-Compose-7F52FF?logo=kotlin&logoColor=white" alt="Kotlin + Compose">
|
<img src="https://img.shields.io/badge/Kotlin-Compose-7F52FF?logo=kotlin&logoColor=white" alt="Kotlin + Compose">
|
||||||
<img src="https://img.shields.io/badge/Material%203-Expressive-4285F4" alt="Material 3 Expressive">
|
<img src="https://img.shields.io/badge/Material%203-Expressive-4285F4" alt="Material 3 Expressive">
|
||||||
@@ -18,74 +18,100 @@ Reads, writes, and reminds — on top of the system calendar, with zero network
|
|||||||
<p>
|
<p>
|
||||||
<a href="https://f-droid.org/packages/de.jeanlucmakiola.calendula/"><img src="https://fdroid.gitlab.io/artwork/badge/get-it-on.png" alt="Get it on F-Droid" height="56"></a>
|
<a href="https://f-droid.org/packages/de.jeanlucmakiola.calendula/"><img src="https://fdroid.gitlab.io/artwork/badge/get-it-on.png" alt="Get it on F-Droid" height="56"></a>
|
||||||
|
|
||||||
|
<a href="https://play.google.com/store/apps/details?id=de.jeanlucmakiola.calendula"><img src="https://play.google.com/intl/en_us/badges/static/images/badges/en_badge_web_generic.png" alt="Get it on Google Play" height="56"></a>
|
||||||
|
|
||||||
|
<a href="https://apps.obtainium.imranr.dev/redirect?r=obtainium://add/https://codeberg.org/jlmakiola/calendula"><img src="https://github.com/ImranR98/Obtainium/blob/main/assets/graphics/badge_obtainium.png?raw=true" alt="Get it on Obtainium" height="56"></a>
|
||||||
|
|
||||||
<a href="https://ko-fi.com/jeanlucmakiola"><img src="https://storage.ko-fi.com/cdn/brandasset/v2/support_me_on_kofi_badge_beige.png" alt="Support me on Ko-fi" height="56"></a>
|
<a href="https://ko-fi.com/jeanlucmakiola"><img src="https://storage.ko-fi.com/cdn/brandasset/v2/support_me_on_kofi_badge_beige.png" alt="Support me on Ko-fi" height="56"></a>
|
||||||
|
|
||||||
|
<a href="https://liberapay.com/Jean-Luc_Makiola/donate"><img src="https://liberapay.com/assets/widgets/donate.svg" alt="Donate using Liberapay" height="56"></a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p>
|
<p>
|
||||||
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/01-week.png" width="19%" alt="Week view">
|
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/01-week.png" width="13%" alt="Week view">
|
||||||
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/02-month.png" width="19%" alt="Month view">
|
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/02-month.png" width="13%" alt="Month view">
|
||||||
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/04-detail.png" width="19%" alt="Event detail">
|
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/03-agenda.png" width="13%" alt="Agenda view">
|
||||||
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/05-edit.png" width="19%" alt="Event form">
|
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/04-detail.png" width="13%" alt="Event detail">
|
||||||
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/06-onboarding.png" width="19%" alt="Reminder onboarding">
|
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/05-recurring.png" width="13%" alt="Editing a recurring event">
|
||||||
|
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/06-calendars.png" width="13%" alt="Calendars from your accounts">
|
||||||
|
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/07-dark.png" width="13%" alt="Dark theme">
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
Calendula is named after the flower whose name — like the word *calendar* —
|
Calendula is named after the flower. Both its name and the word *calendar*
|
||||||
comes from the Latin *kalendae*, the first day of the month. It lives
|
come from the Latin *kalendae*, the first day of the month.
|
||||||
entirely on top of Android's `CalendarContract`: any calendar synced to your
|
|
||||||
device (CalDAV via DAVx5, Google, local, WebCal subscriptions, …) simply
|
|
||||||
appears, and everything you create or edit syncs back the same way. No own
|
|
||||||
database, no sync stack reinvented.
|
|
||||||
|
|
||||||
## ✨ Features
|
The app works directly on Android's `CalendarContract`. Any calendar synced to
|
||||||
|
your device (CalDAV via DAVx5, Google, local, WebCal subscriptions) shows up in
|
||||||
|
Calendula, and whatever you create or edit syncs back the same way. Calendula
|
||||||
|
has no database or sync code of its own.
|
||||||
|
|
||||||
**Calendar**
|
## Features
|
||||||
|
|
||||||
- Month, week, and day views with a one-tap view switcher
|
### Calendar
|
||||||
- Full event details — attendees and their responses, reminders, recurrence
|
|
||||||
(humanized), availability, visibility, foreign time zones
|
|
||||||
- Per-calendar visibility toggle, grouped by account
|
|
||||||
|
|
||||||
**Editing**
|
- Month, week and day views, with a switcher in the top bar
|
||||||
|
- Event details with attendees and their responses, reminders, recurrence in
|
||||||
|
plain words, availability, visibility and foreign time zones
|
||||||
|
- Calendars can be shown or hidden one by one, grouped by account
|
||||||
|
- Your contacts' birthdays, anniversaries and other dates, if you turn it on.
|
||||||
|
Contacts are read on the device and never changed.
|
||||||
|
|
||||||
- Create, edit, and delete events — including recurring events with scoped
|
### Editing
|
||||||
writes: *only this event*, *this and all following*, or *the whole series*
|
|
||||||
- Recurrence picker with one-tap presets and custom rules (interval, weekday
|
|
||||||
toggles, end conditions); rules it can't express are preserved verbatim
|
|
||||||
- Conflict-safe saves: if an event changed elsewhere while you were editing,
|
|
||||||
Calendula asks instead of silently overwriting
|
|
||||||
- Read-only calendars (WebCal, birthdays) are detected and respected
|
|
||||||
|
|
||||||
**Reminders**
|
- Create, edit and delete events. For a recurring event you choose whether a
|
||||||
|
change applies to *only this event*, *this and all following*, or *the whole
|
||||||
|
series*.
|
||||||
|
- The repeat picker has presets and custom rules (interval, weekdays, end
|
||||||
|
condition). Rules it can't show are kept as they are.
|
||||||
|
- If an event changed elsewhere while you were editing it, Calendula asks
|
||||||
|
before saving over it.
|
||||||
|
- Read-only calendars such as WebCal subscriptions and birthdays are detected
|
||||||
|
and can't be edited by accident.
|
||||||
|
|
||||||
- Event reminders delivered by Calendula itself as notifications —
|
### Reminders
|
||||||
essential when it's your only calendar app, since Android delegates
|
|
||||||
reminder delivery to calendar apps
|
|
||||||
- Tap a reminder to land on the event
|
|
||||||
|
|
||||||
**Design & privacy**
|
- Calendula shows event reminders as notifications itself. Android leaves
|
||||||
|
reminder delivery to calendar apps, so if Calendula is your only one, this is
|
||||||
|
where your reminders come from.
|
||||||
|
- Tapping a reminder opens the event.
|
||||||
|
|
||||||
- Real Material 3 Expressive throughout — dynamic color (Android 12+),
|
### Design and privacy
|
||||||
expressive motion and shapes, light/dark theme
|
|
||||||
- German and English UI, per-app language setting — and [open to community
|
|
||||||
translations](#-translations)
|
|
||||||
- **Zero telemetry, zero analytics, no internet permission** — your data
|
|
||||||
never leaves the device
|
|
||||||
|
|
||||||
## 📦 Install
|
- Material 3 Expressive throughout, with dynamic color on Android 12+, light
|
||||||
|
and dark themes, and expressive motion and shapes
|
||||||
|
- Available in 16 languages, with a per-app language setting.
|
||||||
|
[Help translate](#translations).
|
||||||
|
- No telemetry, no analytics and no internet permission. Your data stays on
|
||||||
|
the device.
|
||||||
|
|
||||||
|
## Install
|
||||||
|
|
||||||
|
All channels install the same app:
|
||||||
|
|
||||||
|
| Channel | Updates | Notes |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| [Official F-Droid](#f-droid-recommended) | On F-Droid's build schedule | Recommended; no extra setup |
|
||||||
|
| [Self-hosted F-Droid repo](#self-hosted-f-droid-repo-fastest-updates) | Minutes after a release | Fastest; add the repo once |
|
||||||
|
| [Codeberg release / Obtainium](#codeberg-release--obtainium) | Per release | Plain APK download, or automatic with Obtainium |
|
||||||
|
| [Google Play](#google-play) | Per release | Signed with Google's key, see below |
|
||||||
|
| [Build from source](#build-from-source) | Whenever you build | Full control |
|
||||||
|
|
||||||
### F-Droid (recommended)
|
### F-Droid (recommended)
|
||||||
|
|
||||||
Calendula is on the **official [F-Droid](https://f-droid.org) repository** —
|
Calendula is in the official [F-Droid](https://f-droid.org) repository. Search
|
||||||
just search for **Calendula** in any F-Droid client, or
|
for Calendula in any F-Droid client, or
|
||||||
[install it from f-droid.org](https://f-droid.org/packages/de.jeanlucmakiola.calendula/).
|
[install it from f-droid.org](https://f-droid.org/packages/de.jeanlucmakiola.calendula/).
|
||||||
|
|
||||||
### Self-hosted repo (latest builds)
|
F-Droid builds from source on its own schedule, so a new version usually shows
|
||||||
|
up there a few days after release.
|
||||||
|
|
||||||
New versions are built, signed, and published to a self-hosted repository the
|
### Self-hosted F-Droid repo (fastest updates)
|
||||||
moment each tag lands — usually a few days ahead of the official repo, which
|
|
||||||
rebuilds on F-Droid's own schedule. Add it for the freshest builds:
|
The release pipeline builds, signs and publishes every release to a
|
||||||
|
self-hosted F-Droid repository, so new versions land there first. Add it once
|
||||||
|
and your F-Droid client handles updates from then on:
|
||||||
|
|
||||||
1. In your F-Droid client, open *Settings → Repositories → Add* (or open the
|
1. In your F-Droid client, open *Settings → Repositories → Add* (or open the
|
||||||
link below on your phone):
|
link below on your phone):
|
||||||
@@ -98,28 +124,94 @@ rebuilds on F-Droid's own schedule. Add it for the freshest builds:
|
|||||||
fingerprint (SHA-256):
|
fingerprint (SHA-256):
|
||||||
`C2C0 6404 02BF 458F C0ED 957A F0B3 7AA4 C140 22E7 2F89 CE90 B596 5B45 8CF7 3425`</sub>
|
`C2C0 6404 02BF 458F C0ED 957A F0B3 7AA4 C140 22E7 2F89 CE90 B596 5B45 8CF7 3425`</sub>
|
||||||
|
|
||||||
2. Refresh, search for **Calendula**, install.
|
2. Refresh, search for Calendula and install it.
|
||||||
|
|
||||||
Both channels share the same signing key, so you can switch between them
|
### Codeberg release / Obtainium
|
||||||
without reinstalling. Or build from source — see below.
|
|
||||||
|
|
||||||
## 📚 Documentation
|
Every release is also on
|
||||||
|
[Codeberg](https://codeberg.org/jlmakiola/calendula/releases) with the signed
|
||||||
|
APK (`calendula_vX.Y.Z.apk`) and a `.sha256` checksum. Download it and install
|
||||||
|
it directly.
|
||||||
|
|
||||||
- **[Building from source](docs/BUILDING.md)** — requirements and Gradle tasks
|
For automatic updates from Codeberg, use
|
||||||
- **[Architecture](docs/ARCHITECTURE.md)** — the layered design and key pipelines
|
[Obtainium](https://github.com/ImranR98/Obtainium). On your phone,
|
||||||
- **[Roadmap](.planning/ROADMAP.md)** — what's shipped and what's next
|
[add Calendula in one tap](https://apps.obtainium.imranr.dev/redirect?r=obtainium://add/https://codeberg.org/jlmakiola/calendula),
|
||||||
|
or add it by hand: *Add App*, paste `https://codeberg.org/jlmakiola/calendula`,
|
||||||
|
then *Add*. Obtainium then watches the releases and tells you when a new one
|
||||||
|
is out. Betas of upcoming versions are published there too, as pre-releases; to
|
||||||
|
test them, switch on *Include prereleases* for Calendula in Obtainium.
|
||||||
|
|
||||||
## 🌍 Translations
|
### Google Play
|
||||||
|
|
||||||
Calendula ships in German and English, and you're warmly invited to add your
|
Calendula is on
|
||||||
language. Translations are managed on a self-hosted **Weblate**:
|
[Google Play](https://play.google.com/store/apps/details?id=de.jeanlucmakiola.calendula).
|
||||||
|
|
||||||
**→ [Help translate Calendula](https://weblate.dev.jeanlucmakiola.de/engage/calendula/)**
|
Play builds are signed with Google's key rather than mine, so switching between
|
||||||
|
Play and any other channel means uninstalling first. You lose the app settings.
|
||||||
|
Your events live in the system calendar and aren't affected.
|
||||||
|
|
||||||
No coding needed — register on the Weblate server, pick (or request) a language,
|
### Build from source
|
||||||
and translate the strings in your browser. You can also reach this link in the
|
|
||||||
app from the top of **Settings → App language**.
|
|
||||||
|
|
||||||
## 📜 License
|
It's a plain Gradle build with no proprietary dependencies. See
|
||||||
|
[docs/BUILDING.md](docs/BUILDING.md), and note the `floret-kit` submodule.
|
||||||
|
|
||||||
[MIT](LICENSE) — Jean-Luc Makiola, 2026
|
<sub>Official F-Droid, the self-hosted repo and the Codeberg releases share the
|
||||||
|
same signing key, so you can switch between them without reinstalling. Google
|
||||||
|
Play is the exception (see above).</sub>
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
|
||||||
|
- [Contributing](CONTRIBUTING.md): how to report bugs, propose features and send patches
|
||||||
|
- [Building from source](docs/BUILDING.md): requirements and Gradle tasks
|
||||||
|
- [Architecture](docs/ARCHITECTURE.md): the layers and the main pipelines
|
||||||
|
- [Milestones](https://codeberg.org/jlmakiola/calendula/milestones): what has shipped and what's next
|
||||||
|
- [Privacy policy](docs/PRIVACY.md): the source of the page at
|
||||||
|
[jeanlucmakiola.de/calendula/privacy](https://jeanlucmakiola.de/calendula/privacy)
|
||||||
|
|
||||||
|
## Contributing
|
||||||
|
|
||||||
|
Bug reports, ideas and patches are welcome on
|
||||||
|
[Codeberg](https://codeberg.org/jlmakiola/calendula/issues).
|
||||||
|
|
||||||
|
Start with an issue. A feature gets a yes or no before anyone writes code, and
|
||||||
|
features and bugs are assigned a milestone whose `release/vX.Y.Z` branch your
|
||||||
|
pull request targets. Typo and docs fixes can go straight to a pull request.
|
||||||
|
Translations go through [Weblate](#translations), not pull requests.
|
||||||
|
|
||||||
|
Read [CONTRIBUTING.md](CONTRIBUTING.md) before writing code. It covers the
|
||||||
|
workflow, the build (including the `floret-kit` submodule) and the
|
||||||
|
architectural rules changes are reviewed against.
|
||||||
|
|
||||||
|
## Translations
|
||||||
|
|
||||||
|
Calendula is written in English. Translators on Weblate have added Arabic,
|
||||||
|
Belarusian, Chinese (Simplified), Czech, French, German, Hungarian, Italian,
|
||||||
|
Japanese, Polish, Portuguese (Portugal and Brazil), Russian, Slovak and Spanish,
|
||||||
|
some of them partly. Untranslated strings fall back to English, so a partial
|
||||||
|
translation is fine. Translations are managed on a self-hosted Weblate:
|
||||||
|
|
||||||
|
[Help translate Calendula](https://weblate.dev.jeanlucmakiola.de/engage/calendula/)
|
||||||
|
|
||||||
|
You don't need to code. Register on the Weblate server, pick a language (or
|
||||||
|
request one) and translate in your browser. The app links here from the top of
|
||||||
|
*Settings → App language*.
|
||||||
|
|
||||||
|
## Privacy
|
||||||
|
|
||||||
|
Calendula has no analytics, tracking, ads, crash-reporting SDK or third-party
|
||||||
|
services. It doesn't have the internet permission, so it can't send anything
|
||||||
|
anywhere. Your events stay in Android's own calendar store.
|
||||||
|
|
||||||
|
[Privacy policy](https://jeanlucmakiola.de/calendula/privacy), written in
|
||||||
|
[`docs/PRIVACY.md`](docs/PRIVACY.md), which is what that page renders.
|
||||||
|
|
||||||
|
## Support
|
||||||
|
|
||||||
|
Calendula is free and has no ads. If you'd like to support its development,
|
||||||
|
you can tip once on [Ko-fi](https://ko-fi.com/jeanlucmakiola) or donate
|
||||||
|
regularly on [Liberapay](https://liberapay.com/Jean-Luc_Makiola/donate). Both
|
||||||
|
are linked in the app under *Settings → Support development*.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
[MIT](LICENSE), Jean-Luc Makiola, 2026
|
||||||
+31
-8
@@ -26,10 +26,14 @@ android {
|
|||||||
// These committed values ARE the source of truth for a release: merging
|
// These committed values ARE the source of truth for a release: merging
|
||||||
// a bumped versionName into main triggers .gitea/workflows/release.yaml,
|
// a bumped versionName into main triggers .gitea/workflows/release.yaml,
|
||||||
// which builds this version and then creates the matching vX.Y.Z tag +
|
// which builds this version and then creates the matching vX.Y.Z tag +
|
||||||
// release itself (versionCode is pinned to MAJOR*10000 + MINOR*100 +
|
// release itself. A versionName of X.Y.Z-beta.N pushed to a release/*
|
||||||
// PATCH from versionName, e.g. 2.7.2 -> 20702). See docs/RELEASING.md.
|
// branch instead cuts a Codeberg-only pre-release (beta.yaml).
|
||||||
versionCode = 21200
|
// versionCode is derived from versionName by scripts/version_info.sh
|
||||||
versionName = "2.12.0"
|
// (up to 2.22.3: 2.22.3 -> 22203; from 2.22.4: 2.23.0-beta.1 -> 2230001,
|
||||||
|
// 2.22.4 -> 2220499), and CI fails if the committed one doesn't match.
|
||||||
|
// See docs/RELEASING.md.
|
||||||
|
versionCode = 2250001
|
||||||
|
versionName = "2.25.0-beta.1"
|
||||||
|
|
||||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||||
}
|
}
|
||||||
@@ -113,10 +117,17 @@ android {
|
|||||||
lint {
|
lint {
|
||||||
// Community translations are expected to be partial — a missing string
|
// Community translations are expected to be partial — a missing string
|
||||||
// falls back to the English base at runtime — so don't fail the build on
|
// falls back to the English base at runtime — so don't fail the build on
|
||||||
// it. Stale/extra keys (ExtraTranslation) stay fatal; scripts/
|
// it. A translated <plurals> may likewise skip a CLDR quantity form its
|
||||||
// check_translations.py guards the same invariants with clearer,
|
// locale defines (e.g. Arabic "zero"): Android falls back to "other" for
|
||||||
// translator-facing messages.
|
// any form it cannot find, so MissingQuantity is informational too.
|
||||||
informational += "MissingTranslation"
|
// What a translation must NOT skip is "other" itself — nothing falls back
|
||||||
|
// for that one, not even the base locale, so it throws
|
||||||
|
// Resources$NotFoundException at runtime (Codeberg #297/#298).
|
||||||
|
// MissingQuantity doesn't tell the two cases apart, so that invariant is
|
||||||
|
// enforced by scripts/check_translations.py instead, with a clearer
|
||||||
|
// translator-facing message. Stale/extra keys (ExtraTranslation) stay
|
||||||
|
// fatal.
|
||||||
|
informational += listOf("MissingTranslation", "MissingQuantity")
|
||||||
}
|
}
|
||||||
|
|
||||||
testOptions {
|
testOptions {
|
||||||
@@ -161,6 +172,18 @@ dependencies {
|
|||||||
implementation(libs.androidx.glance.material3)
|
implementation(libs.androidx.glance.material3)
|
||||||
|
|
||||||
implementation(libs.kotlinx.datetime)
|
implementation(libs.kotlinx.datetime)
|
||||||
|
implementation("de.jeanlucmakiola.floret:core-time")
|
||||||
|
implementation("de.jeanlucmakiola.floret:core-locale")
|
||||||
|
implementation("de.jeanlucmakiola.floret:core-crash")
|
||||||
|
implementation("de.jeanlucmakiola.floret:core-di")
|
||||||
|
implementation("de.jeanlucmakiola.floret:core-prefs")
|
||||||
|
implementation("de.jeanlucmakiola.floret:core-backup")
|
||||||
|
implementation("de.jeanlucmakiola.floret:core-reminders")
|
||||||
|
implementation("de.jeanlucmakiola.floret:core-android")
|
||||||
|
implementation("de.jeanlucmakiola.floret:identity")
|
||||||
|
implementation("de.jeanlucmakiola.floret:components")
|
||||||
|
implementation("de.jeanlucmakiola.floret:glance")
|
||||||
|
implementation("de.jeanlucmakiola.floret:ring")
|
||||||
implementation(libs.kotlinx.coroutines.core)
|
implementation(libs.kotlinx.coroutines.core)
|
||||||
|
|
||||||
debugImplementation(libs.androidx.ui.tooling)
|
debugImplementation(libs.androidx.ui.tooling)
|
||||||
|
|||||||
Vendored
+18
@@ -38,3 +38,21 @@
|
|||||||
# SessionWorker never ran, and widgets were stuck on their loading layout
|
# SessionWorker never ran, and widgets were stuck on their loading layout
|
||||||
# (a blank spinner) in release builds. Keep every InputMerger's name + ctor.
|
# (a blank spinner) in release builds. Keep every InputMerger's name + ctor.
|
||||||
-keep class * extends androidx.work.InputMerger { <init>(...); }
|
-keep class * extends androidx.work.InputMerger { <init>(...); }
|
||||||
|
|
||||||
|
# Glance identifies a widget by its GlanceAppWidget subclass's *canonical name*:
|
||||||
|
# GlanceAppWidgetManager persists a providerName -> receivers map under that
|
||||||
|
# string, and `updateAll` looks the widget's app-widget ids up through it. Under
|
||||||
|
# R8 full mode (AGP 9 default) MonthWidget and AgendaWidget — same supertype,
|
||||||
|
# same overrides, no distinguishing members — were horizontally merged into one
|
||||||
|
# class, so both receivers registered under the *same* provider name and
|
||||||
|
# `AgendaWidget().updateAll()` resolved the month widget's id too, redrawing a
|
||||||
|
# placed month widget as the agenda one on the next data change (#89). Keeping
|
||||||
|
# the real names also survives app updates, which would otherwise renumber the
|
||||||
|
# obfuscated name and orphan the stored mapping.
|
||||||
|
-keep class * extends androidx.glance.appwidget.GlanceAppWidget
|
||||||
|
|
||||||
|
# Belt and braces one level up: the two receivers are nearly as alike, and the
|
||||||
|
# provider map is keyed off the receiver component too. Redundant today (AGP's
|
||||||
|
# manifest-derived rules cover them), but #89 cost a release to diagnose and the
|
||||||
|
# guarantee should not rest on a component staying in the manifest.
|
||||||
|
-keep class * extends androidx.glance.appwidget.GlanceAppWidgetReceiver
|
||||||
+8
-1
@@ -9,6 +9,7 @@ import androidx.test.platform.app.InstrumentationRegistry
|
|||||||
import androidx.test.rule.GrantPermissionRule
|
import androidx.test.rule.GrantPermissionRule
|
||||||
import com.google.common.truth.Truth.assertThat
|
import com.google.common.truth.Truth.assertThat
|
||||||
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
|
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
|
||||||
|
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.flow.first
|
import kotlinx.coroutines.flow.first
|
||||||
import kotlinx.coroutines.runBlocking
|
import kotlinx.coroutines.runBlocking
|
||||||
@@ -31,7 +32,13 @@ class CalendarRepositorySmokeTest {
|
|||||||
val store: DataStore<Preferences> = PreferenceDataStoreFactory.create(
|
val store: DataStore<Preferences> = PreferenceDataStoreFactory.create(
|
||||||
produceFile = { context.cacheDir.resolve("smoke_test_prefs.preferences_pb") },
|
produceFile = { context.cacheDir.resolve("smoke_test_prefs.preferences_pb") },
|
||||||
)
|
)
|
||||||
return CalendarRepositoryImpl(dataSource, CalendarPrefs(store), Dispatchers.IO)
|
return CalendarRepositoryImpl(
|
||||||
|
dataSource,
|
||||||
|
CalendarPrefs(store),
|
||||||
|
SettingsPrefs(store),
|
||||||
|
Dispatchers.IO,
|
||||||
|
AndroidSyncRequester(context),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
+91
@@ -0,0 +1,91 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.data.calendar
|
||||||
|
|
||||||
|
import android.Manifest
|
||||||
|
import android.content.ContentUris
|
||||||
|
import android.content.ContentValues
|
||||||
|
import android.provider.CalendarContract
|
||||||
|
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||||
|
import androidx.test.platform.app.InstrumentationRegistry
|
||||||
|
import androidx.test.rule.GrantPermissionRule
|
||||||
|
import com.google.common.truth.Truth.assertThat
|
||||||
|
import de.jeanlucmakiola.calendula.domain.toEditForm
|
||||||
|
import kotlinx.datetime.TimeZone
|
||||||
|
import org.junit.Rule
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Moving a synced series keeps its deleted and edited occurrences, although the
|
||||||
|
* moved row has no `_sync_id` for exception rows to attach to.
|
||||||
|
*/
|
||||||
|
@RunWith(AndroidJUnit4::class)
|
||||||
|
class MoveEventExceptionsTest {
|
||||||
|
|
||||||
|
@get:Rule
|
||||||
|
val permissionRule: GrantPermissionRule = GrantPermissionRule.grant(
|
||||||
|
Manifest.permission.READ_CALENDAR,
|
||||||
|
Manifest.permission.WRITE_CALENDAR,
|
||||||
|
)
|
||||||
|
|
||||||
|
private val context = InstrumentationRegistry.getInstrumentation().targetContext
|
||||||
|
private val resolver = context.contentResolver
|
||||||
|
private val ds = AndroidCalendarDataSource(context)
|
||||||
|
private val zone = TimeZone.currentSystemDefault()
|
||||||
|
|
||||||
|
private val day = 86_400_000L
|
||||||
|
private val start = 1_893_492_000_000L // 2030-01-01T10:00Z
|
||||||
|
private val hour = 3_600_000L
|
||||||
|
|
||||||
|
/** "day offset:title" of every instance on [calendarId]. */
|
||||||
|
private fun occurrences(calendarId: Long): List<String> =
|
||||||
|
ds.instances(start - day, start + 10 * day)
|
||||||
|
.filter { it.calendarId == calendarId }
|
||||||
|
.map { "${(it.start.toEpochMilliseconds() - start) / day}:${it.title}" }
|
||||||
|
.sorted()
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun movedSeriesKeepsCancelledAndModifiedOccurrences() {
|
||||||
|
val a = ds.createLocalCalendar("move-test-a", 0xFF336699.toInt(), null)
|
||||||
|
val b = ds.createLocalCalendar("move-test-b", 0xFF993366.toInt(), null)
|
||||||
|
try {
|
||||||
|
val src = insertSyncedSeries(a)
|
||||||
|
ds.deleteOccurrence(src, start + 2 * day)
|
||||||
|
val occurrence = ds.eventDetail(src, 540)!!.toEditForm(start + 3 * day, start + 3 * day + hour, zone)
|
||||||
|
ds.updateOccurrence(src, start + 3 * day, occurrence, occurrence.copy(title = "edited"), 540)
|
||||||
|
val expected = listOf("0:series", "1:series", "3:edited", "4:series")
|
||||||
|
assertThat(occurrences(a)).isEqualTo(expected)
|
||||||
|
|
||||||
|
val form = ds.eventDetail(src, 540)!!.toEditForm(start, start + hour, zone)
|
||||||
|
ds.moveEvent(src, b, form, form, 540)
|
||||||
|
|
||||||
|
assertThat(occurrences(a)).isEmpty()
|
||||||
|
assertThat(occurrences(b)).isEqualTo(expected)
|
||||||
|
} finally {
|
||||||
|
ds.deleteCalendar(a)
|
||||||
|
ds.deleteCalendar(b)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A daily series carrying a `_sync_id`, so its exceptions are real exception rows. */
|
||||||
|
private fun insertSyncedSeries(calendarId: Long): Long {
|
||||||
|
val accountName = resolver.query(
|
||||||
|
ContentUris.withAppendedId(CalendarContract.Calendars.CONTENT_URI, calendarId),
|
||||||
|
arrayOf(CalendarContract.Calendars.ACCOUNT_NAME), null, null, null,
|
||||||
|
)!!.use { it.moveToFirst(); it.getString(0) }
|
||||||
|
val uri = CalendarContract.Events.CONTENT_URI.buildUpon()
|
||||||
|
.appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
|
||||||
|
.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, accountName)
|
||||||
|
.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, CalendarContract.ACCOUNT_TYPE_LOCAL)
|
||||||
|
.build()
|
||||||
|
val values = ContentValues().apply {
|
||||||
|
put(CalendarContract.Events.CALENDAR_ID, calendarId)
|
||||||
|
put(CalendarContract.Events.TITLE, "series")
|
||||||
|
put(CalendarContract.Events.DTSTART, start)
|
||||||
|
put(CalendarContract.Events.DURATION, "P3600S")
|
||||||
|
put(CalendarContract.Events.RRULE, "FREQ=DAILY;COUNT=5")
|
||||||
|
put(CalendarContract.Events.EVENT_TIMEZONE, "UTC")
|
||||||
|
put(CalendarContract.Events._SYNC_ID, "move-test-series")
|
||||||
|
}
|
||||||
|
return ContentUris.parseId(resolver.insert(uri, values)!!)
|
||||||
|
}
|
||||||
|
}
|
||||||
+101
@@ -0,0 +1,101 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.ui.detail
|
||||||
|
|
||||||
|
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||||
|
import com.google.common.truth.Truth.assertThat
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The platform phone matcher on real text. It reads the region off the SIM,
|
||||||
|
* so these stick to international numbers and to text that must never match
|
||||||
|
* anywhere — domestic formats depend on the device they run on.
|
||||||
|
*/
|
||||||
|
@RunWith(AndroidJUnit4::class)
|
||||||
|
class PhoneLinksPlatformTest {
|
||||||
|
|
||||||
|
private fun numbers(text: String) = findPhoneLinks(text).map { it.number }
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun internationalNumbers_areFound() {
|
||||||
|
assertThat(numbers("Call +49 30 1234567 or +1 646-558-8656"))
|
||||||
|
.containsExactly("+49301234567", "+16465588656")
|
||||||
|
.inOrder()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun trunkZero_isDroppedWithOrWithoutSpace() {
|
||||||
|
assertThat(numbers("+49 (0)151 2345678")).containsExactly("+491512345678")
|
||||||
|
assertThat(numbers("+49 (0) 151 2345678")).containsExactly("+491512345678")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun neighbouringNumbers_doNotJoinTheNumber() {
|
||||||
|
assertThat(numbers("Start 10:00 +49 151 2345678")).containsExactly("+491512345678")
|
||||||
|
assertThat(numbers("Call +49 151 2345678 2 times")).containsExactly("+491512345678")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun conferenceDialIn_keepsMeetingId() {
|
||||||
|
assertThat(numbers("One tap mobile: +16465588656,,85012345678# US"))
|
||||||
|
.containsExactly("+16465588656,,85012345678#")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun meetingIds_areNotNumbers() {
|
||||||
|
assertThat(numbers("Meeting ID: 850 1234 5678")).isEmpty()
|
||||||
|
assertThat(numbers("Conference ID: 123 456 789#")).isEmpty()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun datesAndTimes_areNotNumbers() {
|
||||||
|
assertThat(numbers("2026-10-14 10:00")).isEmpty()
|
||||||
|
assertThat(numbers("Am 14.10.2026 10:00 Uhr")).isEmpty()
|
||||||
|
assertThat(numbers("14.10.26 - 16.10.26")).isEmpty()
|
||||||
|
assertThat(numbers("10:00 - 11:30")).isEmpty()
|
||||||
|
assertThat(numbers("Schuljahr 2025/2026, Season 2025-2026")).isEmpty()
|
||||||
|
assertThat(numbers("1.10.2026 - 3.10.2026")).isEmpty()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun amounts_areNotNumbers() {
|
||||||
|
assertThat(numbers("Budget 1.250.000 EUR, 1 250 000 EUR")).isEmpty()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun isbn_isNotANumber() {
|
||||||
|
assertThat(numbers("ISBN 978-3-16-148410-0")).isEmpty()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun extension_becomesAPause() {
|
||||||
|
assertThat(numbers("+1 212 555 1234 ext. 567")).containsExactly("+12125551234,567")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun webexAccessCode_isNotANumber() {
|
||||||
|
assertThat(numbers("Meeting number (access code): 2732 123 4567")).isEmpty()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun commaSeparatedNumbers_stayApart() {
|
||||||
|
assertThat(numbers("+49 30 1234567,+49 151 2345678"))
|
||||||
|
.containsExactly("+49301234567", "+491512345678")
|
||||||
|
.inOrder()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun dottedTimes_areNotNumbers() {
|
||||||
|
assertThat(numbers("Beginn 9.30 – 12.00 Uhr")).isEmpty()
|
||||||
|
assertThat(numbers("10.00-11.30")).isEmpty()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun schemelessUrlDigits_areNotNumbers() {
|
||||||
|
assertThat(numbers("zoom.us/j/85012345678")).isEmpty()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun webLinkDigits_areNotNumbers() {
|
||||||
|
assertThat(numbers("https://zoom.us/j/85012345678?pwd=1")).isEmpty()
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package de.jeanlucmakiola.calendula.ui.permission
|
package de.jeanlucmakiola.calendula.ui.onboarding
|
||||||
|
|
||||||
import androidx.compose.ui.test.assertIsDisplayed
|
import androidx.compose.ui.test.assertIsDisplayed
|
||||||
import androidx.compose.ui.test.junit4.createComposeRule
|
import androidx.compose.ui.test.junit4.createComposeRule
|
||||||
+140
@@ -0,0 +1,140 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.widget.month
|
||||||
|
|
||||||
|
import android.Manifest
|
||||||
|
import android.content.ContentUris
|
||||||
|
import android.content.ContentValues
|
||||||
|
import android.net.Uri
|
||||||
|
import android.os.Parcel
|
||||||
|
import android.provider.CalendarContract
|
||||||
|
import android.util.Log
|
||||||
|
import android.view.View
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import android.widget.FrameLayout
|
||||||
|
import android.widget.TextView
|
||||||
|
import androidx.compose.ui.unit.DpSize
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.glance.ExperimentalGlanceApi
|
||||||
|
import androidx.glance.appwidget.compose
|
||||||
|
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||||
|
import androidx.test.platform.app.InstrumentationRegistry
|
||||||
|
import androidx.test.rule.GrantPermissionRule
|
||||||
|
import com.google.common.truth.Truth.assertThat
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import org.junit.After
|
||||||
|
import org.junit.Before
|
||||||
|
import org.junit.Rule
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
import de.jeanlucmakiola.calendula.R
|
||||||
|
import java.time.LocalDate
|
||||||
|
import java.time.ZoneId
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renders the month widget for a packed month through Glance's own translator
|
||||||
|
* (#372) and checks what one size costs on the wire: the host's binder buffer is
|
||||||
|
* 1 MB for every widget update at once, and Exact sends one copy per size (#214).
|
||||||
|
*/
|
||||||
|
@OptIn(ExperimentalGlanceApi::class)
|
||||||
|
@RunWith(AndroidJUnit4::class)
|
||||||
|
class MonthWidgetPayloadTest {
|
||||||
|
|
||||||
|
@get:Rule
|
||||||
|
val permissionRule: GrantPermissionRule =
|
||||||
|
GrantPermissionRule.grant(Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR)
|
||||||
|
|
||||||
|
private val instrumentation = InstrumentationRegistry.getInstrumentation()
|
||||||
|
private val context = instrumentation.targetContext
|
||||||
|
private var calendarId = -1L
|
||||||
|
|
||||||
|
private fun Uri.asSyncAdapter(): Uri = buildUpon()
|
||||||
|
.appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
|
||||||
|
.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, ACCOUNT)
|
||||||
|
.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, CalendarContract.ACCOUNT_TYPE_LOCAL)
|
||||||
|
.build()
|
||||||
|
|
||||||
|
@Before
|
||||||
|
fun packTheMonth() {
|
||||||
|
val calendar = ContentValues().apply {
|
||||||
|
put(CalendarContract.Calendars.ACCOUNT_NAME, ACCOUNT)
|
||||||
|
put(CalendarContract.Calendars.ACCOUNT_TYPE, CalendarContract.ACCOUNT_TYPE_LOCAL)
|
||||||
|
put(CalendarContract.Calendars.NAME, ACCOUNT)
|
||||||
|
put(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, ACCOUNT)
|
||||||
|
put(CalendarContract.Calendars.CALENDAR_COLOR, 0xFF3F51B5.toInt())
|
||||||
|
put(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, CalendarContract.Calendars.CAL_ACCESS_OWNER)
|
||||||
|
put(CalendarContract.Calendars.OWNER_ACCOUNT, ACCOUNT)
|
||||||
|
put(CalendarContract.Calendars.VISIBLE, 1)
|
||||||
|
put(CalendarContract.Calendars.SYNC_EVENTS, 1)
|
||||||
|
}
|
||||||
|
val uri = context.contentResolver.insert(CalendarContract.Calendars.CONTENT_URI.asSyncAdapter(), calendar)
|
||||||
|
calendarId = ContentUris.parseId(requireNotNull(uri))
|
||||||
|
|
||||||
|
val zone = ZoneId.systemDefault()
|
||||||
|
val first = LocalDate.now(zone).withDayOfMonth(1).minusDays(7)
|
||||||
|
val events = (0 until 49).flatMap { offset ->
|
||||||
|
val day = first.plusDays(offset.toLong())
|
||||||
|
(0 until EVENTS_PER_DAY).map { i ->
|
||||||
|
val start = day.atTime(8 + i, 0).atZone(zone).toInstant().toEpochMilli()
|
||||||
|
ContentValues().apply {
|
||||||
|
put(CalendarContract.Events.CALENDAR_ID, calendarId)
|
||||||
|
put(CalendarContract.Events.TITLE, "Busy $i")
|
||||||
|
put(CalendarContract.Events.DTSTART, start)
|
||||||
|
put(CalendarContract.Events.DTEND, start + 30 * 60_000L)
|
||||||
|
put(CalendarContract.Events.EVENT_TIMEZONE, zone.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
context.contentResolver.bulkInsert(CalendarContract.Events.CONTENT_URI.asSyncAdapter(), events.toTypedArray())
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
fun removeCalendar() {
|
||||||
|
if (calendarId < 0) return
|
||||||
|
context.contentResolver.delete(
|
||||||
|
ContentUris.withAppendedId(CalendarContract.Calendars.CONTENT_URI, calendarId).asSyncAdapter(),
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun aPackedMonthRendersWithinItsPayload() = runBlocking {
|
||||||
|
for (size in listOf(DpSize(250.dp, 250.dp), DpSize(320.dp, 360.dp), DpSize(420.dp, 520.dp), DpSize(600.dp, 1000.dp))) {
|
||||||
|
val views = MonthWidget().compose(context, size = size)
|
||||||
|
val bytes = Parcel.obtain().let { parcel ->
|
||||||
|
try {
|
||||||
|
views.writeToParcel(parcel, 0)
|
||||||
|
parcel.dataSize()
|
||||||
|
} finally {
|
||||||
|
parcel.recycle()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var dayNumbers = 0
|
||||||
|
var bars = 0
|
||||||
|
instrumentation.runOnMainSync {
|
||||||
|
val root = views.apply(context, FrameLayout(context))
|
||||||
|
fun walk(view: View) {
|
||||||
|
if (view.id in DAY_IDS && view is TextView && view.text.isNotEmpty()) dayNumbers += 1
|
||||||
|
if (view.id == R.id.bar_title) bars += 1
|
||||||
|
if (view is ViewGroup) for (i in 0 until view.childCount) walk(view.getChildAt(i))
|
||||||
|
}
|
||||||
|
walk(root)
|
||||||
|
}
|
||||||
|
Log.i(TAG, "size=$size bytes=$bytes days=$dayNumbers bars=$bars")
|
||||||
|
// The grid itself rendered, not Glance's error layout: a number in every day of every week.
|
||||||
|
assertThat(dayNumbers % 7).isEqualTo(0)
|
||||||
|
assertThat(dayNumbers).isAtLeast(28)
|
||||||
|
assertThat(bytes).isAtMost(MAX_BYTES_PER_SIZE)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val TAG = "MonthWidgetPayload"
|
||||||
|
const val ACCOUNT = "calendula-widget-payload-test"
|
||||||
|
const val EVENTS_PER_DAY = 6
|
||||||
|
|
||||||
|
val DAY_IDS = setOf(R.id.day_0, R.id.day_1, R.id.day_2, R.id.day_3, R.id.day_4, R.id.day_5, R.id.day_6)
|
||||||
|
|
||||||
|
/** A quarter of the host's buffer, leaving room for a second size and every other widget. */
|
||||||
|
const val MAX_BYTES_PER_SIZE = 256 * 1024
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,15 @@
|
|||||||
<uses-permission android:name="android.permission.READ_CALENDAR" />
|
<uses-permission android:name="android.permission.READ_CALENDAR" />
|
||||||
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
|
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
|
||||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||||
|
<!--
|
||||||
|
Optional and feature-gated: only the "Contact special dates" feature reads
|
||||||
|
contacts, and only after the user enables it and grants this at runtime
|
||||||
|
(never requested at startup). Everything stays offline — birthdays and
|
||||||
|
other contact dates are mirrored one-way into local calendars; contacts
|
||||||
|
are never written and nothing leaves the device (the app has no INTERNET
|
||||||
|
permission). See docs/design/contact-special-dates.md.
|
||||||
|
-->
|
||||||
|
<uses-permission android:name="android.permission.READ_CONTACTS" />
|
||||||
<!--
|
<!--
|
||||||
Lets the "Reliable delivery" setting open the direct system dialog to
|
Lets the "Reliable delivery" setting open the direct system dialog to
|
||||||
exempt Calendula from battery optimisation (so reminder broadcasts aren't
|
exempt Calendula from battery optimisation (so reminder broadcasts aren't
|
||||||
@@ -24,6 +33,27 @@
|
|||||||
android:maxSdkVersion="32" />
|
android:maxSdkVersion="32" />
|
||||||
<uses-permission android:name="android.permission.USE_EXACT_ALARM" />
|
<uses-permission android:name="android.permission.USE_EXACT_ALARM" />
|
||||||
|
|
||||||
|
<!--
|
||||||
|
A reboot clears every pending alarm, including the one holding the next
|
||||||
|
reminder. Now that the app schedules that alarm itself (#75) rather than
|
||||||
|
leaning on the provider's, it has to hear about the reboot to re-arm it —
|
||||||
|
otherwise reminders simply stop after a restart.
|
||||||
|
-->
|
||||||
|
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||||
|
|
||||||
|
<!-- Lets "Sync now" (#240) follow the sync it asked for: read-only sync state, install-time. -->
|
||||||
|
<uses-permission android:name="android.permission.READ_SYNC_STATS" />
|
||||||
|
|
||||||
|
<!-- WorkManager declares this for network constraints, which the app doesn't use (#448). -->
|
||||||
|
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" tools:node="remove" />
|
||||||
|
|
||||||
|
<!-- Full-screen reminder alerts and their ring (#171), opt-in per calendar. -->
|
||||||
|
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SYSTEM_EXEMPTED" />
|
||||||
|
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||||
|
<uses-permission android:name="android.permission.VIBRATE" />
|
||||||
|
|
||||||
<!-- Package visibility (Android 11+): without this, getLaunchIntentForPackage
|
<!-- Package visibility (Android 11+): without this, getLaunchIntentForPackage
|
||||||
returns null and the calendar manager's per-account "manage" button can't
|
returns null and the calendar manager's per-account "manage" button can't
|
||||||
open the source sync app (DAVx5, ICSx5, Google Calendar, …). The LAUNCHER
|
open the source sync app (DAVx5, ICSx5, Google Calendar, …). The LAUNCHER
|
||||||
@@ -34,6 +64,21 @@
|
|||||||
<action android:name="android.intent.action.MAIN" />
|
<action android:name="android.intent.action.MAIN" />
|
||||||
<category android:name="android.intent.category.LAUNCHER" />
|
<category android:name="android.intent.category.LAUNCHER" />
|
||||||
</intent>
|
</intent>
|
||||||
|
<!-- Sync adapters to ask for a calendar sync (#240, #303). -->
|
||||||
|
<intent>
|
||||||
|
<action android:name="android.content.SyncAdapter" />
|
||||||
|
</intent>
|
||||||
|
<!-- A reminder's "Open link" button only shows when something can open the link (#464). -->
|
||||||
|
<intent>
|
||||||
|
<action android:name="android.intent.action.VIEW" />
|
||||||
|
<category android:name="android.intent.category.BROWSABLE" />
|
||||||
|
<data android:scheme="https" />
|
||||||
|
</intent>
|
||||||
|
<intent>
|
||||||
|
<action android:name="android.intent.action.VIEW" />
|
||||||
|
<category android:name="android.intent.category.BROWSABLE" />
|
||||||
|
<data android:scheme="http" />
|
||||||
|
</intent>
|
||||||
</queries>
|
</queries>
|
||||||
|
|
||||||
<application
|
<application
|
||||||
@@ -54,10 +99,9 @@
|
|||||||
android:exported="true"
|
android:exported="true"
|
||||||
android:launchMode="singleTop"
|
android:launchMode="singleTop"
|
||||||
android:windowSoftInputMode="adjustResize">
|
android:windowSoftInputMode="adjustResize">
|
||||||
<intent-filter>
|
<!-- The MAIN/LAUNCHER entry (the launcher icon + its label) lives on
|
||||||
<action android:name="android.intent.action.MAIN" />
|
the two <activity-alias> below, so the app name can be switched at
|
||||||
<category android:name="android.intent.category.LAUNCHER" />
|
runtime (issue #44). MainActivity keeps every other filter. -->
|
||||||
</intent-filter>
|
|
||||||
|
|
||||||
<!-- Be selectable as the system calendar app. Android has no API for
|
<!-- Be selectable as the system calendar app. Android has no API for
|
||||||
an app to make itself the default, so registering the filters
|
an app to make itself the default, so registering the filters
|
||||||
@@ -88,26 +132,169 @@
|
|||||||
<data android:mimeType="time/epoch" />
|
<data android:mimeType="time/epoch" />
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
|
|
||||||
<!-- Open a .ics file (file manager / email attachment / browser). -->
|
<!-- Open a .ics/.vcs file (file manager / email attachment / browser).
|
||||||
|
The three MIME types cover the common labels the same calendar
|
||||||
|
data arrives under: iCalendar 2.0 (text/calendar), the older
|
||||||
|
vCalendar 1.0 / .vcs (text/x-vcalendar), and application/ics some
|
||||||
|
mail apps emit — Android cross-products the scheme and mimeType
|
||||||
|
tags, so each MIME is accepted on both schemes (matches Etar). -->
|
||||||
<intent-filter>
|
<intent-filter>
|
||||||
<action android:name="android.intent.action.VIEW" />
|
<action android:name="android.intent.action.VIEW" />
|
||||||
<category android:name="android.intent.category.DEFAULT" />
|
<category android:name="android.intent.category.DEFAULT" />
|
||||||
<category android:name="android.intent.category.BROWSABLE" />
|
<category android:name="android.intent.category.BROWSABLE" />
|
||||||
<data android:scheme="content" android:mimeType="text/calendar" />
|
<data android:scheme="content" />
|
||||||
<data android:scheme="file" android:mimeType="text/calendar" />
|
<data android:scheme="file" />
|
||||||
|
<data android:mimeType="text/calendar" />
|
||||||
|
<data android:mimeType="text/x-vcalendar" />
|
||||||
|
<data android:mimeType="application/ics" />
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
<!-- Receive a .ics shared from another app. -->
|
<!-- Same .ics/.vcs data arriving mislabelled as a generic download —
|
||||||
|
application/octet-stream — the way many mail clients, browsers and
|
||||||
|
file managers hand off attachments. Matched by file extension, so
|
||||||
|
this stays a separate filter: a pathPattern here must not narrow
|
||||||
|
the MIME-typed VIEW filter above (that one has no path and must
|
||||||
|
keep matching regardless of name). The import handler ignores the
|
||||||
|
MIME type, so a let-through octet-stream .ics imports normally.
|
||||||
|
Best-effort: pathPattern is reliable for file:// (and content://
|
||||||
|
whose path carries the filename); content:// URIs that expose no
|
||||||
|
name still fall back to the MIME-typed filter above. -->
|
||||||
|
<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="content" />
|
||||||
|
<data android:scheme="file" />
|
||||||
|
<data android:host="*" />
|
||||||
|
<data android:mimeType="application/octet-stream" />
|
||||||
|
<data android:pathPattern=".*\\.ics" />
|
||||||
|
<data android:pathPattern=".*\\.vcs" />
|
||||||
|
</intent-filter>
|
||||||
|
|
||||||
|
<!-- Receive a .ics/.vcs shared from another app (same MIME set). -->
|
||||||
<intent-filter>
|
<intent-filter>
|
||||||
<action android:name="android.intent.action.SEND" />
|
<action android:name="android.intent.action.SEND" />
|
||||||
<category android:name="android.intent.category.DEFAULT" />
|
<category android:name="android.intent.category.DEFAULT" />
|
||||||
<data android:mimeType="text/calendar" />
|
<data android:mimeType="text/calendar" />
|
||||||
|
<data android:mimeType="text/x-vcalendar" />
|
||||||
|
<data android:mimeType="application/ics" />
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
|
|
||||||
<!-- Launcher long-press shortcuts (e.g. "New event"). -->
|
<!-- Text shared or selected in another app opens a prefilled new
|
||||||
|
event (MainActivity.sharedTextRequestOrNull, issue #306). -->
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.SEND" />
|
||||||
|
<category android:name="android.intent.category.DEFAULT" />
|
||||||
|
<data android:mimeType="text/plain" />
|
||||||
|
</intent-filter>
|
||||||
|
<intent-filter android:label="@string/process_text_create_event">
|
||||||
|
<action android:name="android.intent.action.PROCESS_TEXT" />
|
||||||
|
<category android:name="android.intent.category.DEFAULT" />
|
||||||
|
<data android:mimeType="text/plain" />
|
||||||
|
</intent-filter>
|
||||||
|
|
||||||
|
<!-- Let another app or widget (e.g. the Todo Agenda widget) launch us
|
||||||
|
to create a new event, the way the AOSP calendar accepts it:
|
||||||
|
ACTION_INSERT on the events *dir* mime type, carrying the new
|
||||||
|
event's fields as CalendarContract extras
|
||||||
|
(MainActivity.insertFormOrNull, issue #30). ACTION_EDIT on the
|
||||||
|
dir mime is AOSP's "edit a new event" — i.e. create — so it maps
|
||||||
|
to the same prefilled create form. (The far more common *item*-
|
||||||
|
typed INSERT — the form the Android docs' example and apps like
|
||||||
|
DB Navigator use — is the item filter below, issue #74.) -->
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.INSERT" />
|
||||||
|
<action android:name="android.intent.action.EDIT" />
|
||||||
|
<category android:name="android.intent.category.DEFAULT" />
|
||||||
|
<data android:mimeType="vnd.android.cursor.dir/event" />
|
||||||
|
</intent-filter>
|
||||||
|
|
||||||
|
<!-- Create or edit an event another app/assistant/widget points at,
|
||||||
|
addressed by the provider's *item* MIME type. Three actions share
|
||||||
|
this filter, told apart at runtime by the intent's data:
|
||||||
|
|
||||||
|
• ACTION_INSERT — create. This is the form the Android docs'
|
||||||
|
"insert an event" example and many apps use
|
||||||
|
(setType("vnd.android.cursor.item/event")), e.g. DB Navigator's
|
||||||
|
"Save to calendar". The dir-typed filter above alone missed it,
|
||||||
|
so Calendula never showed in the chooser — and, when it was the
|
||||||
|
only calendar app, the intent resolved to nothing (issue #74).
|
||||||
|
• ACTION_INSERT_OR_EDIT — the third "add to calendar" action AOSP
|
||||||
|
and Google Calendar register; a create, or an edit when it
|
||||||
|
carries an event id.
|
||||||
|
• ACTION_EDIT — edit the existing event at
|
||||||
|
content://com.android.calendar/events/<id> (an id-less EDIT is a
|
||||||
|
create). Opens the occurrence in the edit form, not the
|
||||||
|
read-only detail — that's the VIEW filter above.
|
||||||
|
|
||||||
|
Create fields ride as CalendarContract extras; an edit's
|
||||||
|
occurrence times ride as EXTRA_EVENT_BEGIN_TIME /
|
||||||
|
EXTRA_EVENT_END_TIME when supplied (MainActivity.insertFormOrNull
|
||||||
|
/ editEventKeyOrNull). -->
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.INSERT" />
|
||||||
|
<action android:name="android.intent.action.INSERT_OR_EDIT" />
|
||||||
|
<action android:name="android.intent.action.EDIT" />
|
||||||
|
<category android:name="android.intent.category.DEFAULT" />
|
||||||
|
<data android:mimeType="vnd.android.cursor.item/event" />
|
||||||
|
</intent-filter>
|
||||||
|
|
||||||
|
<!-- Open an existing event another app/widget points at (e.g. tapping
|
||||||
|
an event in the Todo Agenda widget): ACTION_VIEW on
|
||||||
|
content://com.android.calendar/events/<id>, the way AOSP fires it.
|
||||||
|
Matched by the provider's item MIME type, not the path — a
|
||||||
|
content: VIEW intent carries the resolved type
|
||||||
|
(vnd.android.cursor.item/event) and a path-only filter wouldn't
|
||||||
|
match it. The occurrence's times ride as EXTRA_EVENT_BEGIN_TIME /
|
||||||
|
EXTRA_EVENT_END_TIME when the launcher supplies them
|
||||||
|
(MainActivity.viewEventKeyOrNull, issue #48). -->
|
||||||
|
<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:mimeType="vnd.android.cursor.item/event" />
|
||||||
|
</intent-filter>
|
||||||
|
|
||||||
|
</activity>
|
||||||
|
|
||||||
|
<!-- Launcher entry for MainActivity, split into two aliases so the app's
|
||||||
|
launcher name can be switched at runtime between "Calendula" and
|
||||||
|
"Calendar" (issue #44). Exactly one is enabled at a time; the app
|
||||||
|
flips them via PackageManager.setComponentEnabledSetting
|
||||||
|
(LauncherNameManager). The shortcuts meta-data lives here, not on
|
||||||
|
MainActivity, because static shortcuts are published by whichever
|
||||||
|
component owns the MAIN/LAUNCHER filter. -->
|
||||||
|
<activity-alias
|
||||||
|
android:name=".DefaultNameAlias"
|
||||||
|
android:enabled="true"
|
||||||
|
android:exported="true"
|
||||||
|
android:icon="@mipmap/ic_launcher"
|
||||||
|
android:label="@string/app_name"
|
||||||
|
android:roundIcon="@mipmap/ic_launcher_round"
|
||||||
|
android:targetActivity=".MainActivity">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.MAIN" />
|
||||||
|
<category android:name="android.intent.category.LAUNCHER" />
|
||||||
|
</intent-filter>
|
||||||
<meta-data
|
<meta-data
|
||||||
android:name="android.app.shortcuts"
|
android:name="android.app.shortcuts"
|
||||||
android:resource="@xml/shortcuts" />
|
android:resource="@xml/shortcuts" />
|
||||||
</activity>
|
</activity-alias>
|
||||||
|
<activity-alias
|
||||||
|
android:name=".CalendarNameAlias"
|
||||||
|
android:enabled="false"
|
||||||
|
android:exported="true"
|
||||||
|
android:icon="@mipmap/ic_launcher"
|
||||||
|
android:label="@string/app_name_calendar_alias"
|
||||||
|
android:roundIcon="@mipmap/ic_launcher_round"
|
||||||
|
android:targetActivity=".MainActivity">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.MAIN" />
|
||||||
|
<category android:name="android.intent.category.LAUNCHER" />
|
||||||
|
</intent-filter>
|
||||||
|
<meta-data
|
||||||
|
android:name="android.app.shortcuts"
|
||||||
|
android:resource="@xml/shortcuts" />
|
||||||
|
</activity-alias>
|
||||||
|
|
||||||
<!-- Standalone surface for a captured crash report. MainActivity routes
|
<!-- Standalone surface for a captured crash report. MainActivity routes
|
||||||
here on a startup crash-loop, so it stays clear of the app's Hilt
|
here on a startup crash-loop, so it stays clear of the app's Hilt
|
||||||
@@ -132,17 +319,28 @@
|
|||||||
</intent-filter>
|
</intent-filter>
|
||||||
</service>
|
</service>
|
||||||
|
|
||||||
<!-- The provider broadcasts EVENT_REMINDER at reminder time but posts
|
<!-- The change watch behind "Also back up after changes" (#516). -->
|
||||||
no notification itself — a calendar app must (v1.4, Etar model).
|
<service
|
||||||
Exported: the broadcast arrives from the provider's process. -->
|
android:name=".data.backup.BackupChangeJob"
|
||||||
|
android:exported="false"
|
||||||
|
android:permission="android.permission.BIND_JOB_SERVICE" />
|
||||||
|
|
||||||
|
<!-- Reminder delivery is the app's own (#75): it plans the alarms from
|
||||||
|
Instances + Reminders instead of waiting for the provider's
|
||||||
|
EVENT_REMINDER broadcast, which OEM-modified providers demonstrably
|
||||||
|
retarget or never send. This receiver takes our scan alarm plus
|
||||||
|
every outside event that invalidates it — boot and package-replace
|
||||||
|
wipe pending alarms, and a clock or timezone change moves every
|
||||||
|
reminder relative to the one that is armed.
|
||||||
|
Exported: the system broadcasts arrive from outside the app. -->
|
||||||
<receiver
|
<receiver
|
||||||
android:name=".data.reminders.EventReminderReceiver"
|
android:name=".data.reminders.ReminderScheduleReceiver"
|
||||||
android:exported="true">
|
android:exported="true">
|
||||||
<intent-filter>
|
<intent-filter>
|
||||||
<action android:name="android.intent.action.EVENT_REMINDER" />
|
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
||||||
<data
|
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
|
||||||
android:host="com.android.calendar"
|
<action android:name="android.intent.action.TIME_SET" />
|
||||||
android:scheme="content" />
|
<action android:name="android.intent.action.TIMEZONE_CHANGED" />
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
</receiver>
|
</receiver>
|
||||||
|
|
||||||
@@ -153,7 +351,31 @@
|
|||||||
android:name=".data.reminders.ReminderActionReceiver"
|
android:name=".data.reminders.ReminderActionReceiver"
|
||||||
android:exported="false" />
|
android:exported="false" />
|
||||||
|
|
||||||
|
<!-- The full-screen reminder alert (#171), in a task of its own. -->
|
||||||
|
<activity
|
||||||
|
android:name=".ui.reminders.ReminderAlertActivity"
|
||||||
|
android:exported="false"
|
||||||
|
android:excludeFromRecents="true"
|
||||||
|
android:launchMode="singleTask"
|
||||||
|
android:taskAffinity="" />
|
||||||
|
|
||||||
|
<!-- Rings a "Ring until dismissed" reminder (#171). -->
|
||||||
|
<service
|
||||||
|
android:name=".data.reminders.ReminderRingService"
|
||||||
|
android:exported="false"
|
||||||
|
android:foregroundServiceType="systemExempted" />
|
||||||
|
|
||||||
<!-- Home-screen widgets (Glance). Exported: the launcher/host binds them. -->
|
<!-- Home-screen widgets (Glance). Exported: the launcher/host binds them. -->
|
||||||
|
<activity
|
||||||
|
android:name=".widget.config.WidgetConfigActivity"
|
||||||
|
android:exported="true"
|
||||||
|
android:excludeFromRecents="true"
|
||||||
|
android:taskAffinity=""
|
||||||
|
android:theme="@style/Theme.Calendula.WidgetConfig">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
|
||||||
|
</intent-filter>
|
||||||
|
</activity>
|
||||||
<receiver
|
<receiver
|
||||||
android:name=".widget.agenda.AgendaWidgetReceiver"
|
android:name=".widget.agenda.AgendaWidgetReceiver"
|
||||||
android:label="@string/widget_agenda_label"
|
android:label="@string/widget_agenda_label"
|
||||||
@@ -178,10 +400,110 @@
|
|||||||
android:resource="@xml/appwidget_info_month" />
|
android:resource="@xml/appwidget_info_month" />
|
||||||
</receiver>
|
</receiver>
|
||||||
|
|
||||||
|
<receiver
|
||||||
|
android:name=".widget.quickadd.QuickAddWidgetReceiver"
|
||||||
|
android:label="@string/widget_quick_add_label"
|
||||||
|
android:exported="true">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
|
||||||
|
</intent-filter>
|
||||||
|
<meta-data
|
||||||
|
android:name="android.appwidget.provider"
|
||||||
|
android:resource="@xml/appwidget_info_quick_add" />
|
||||||
|
</receiver>
|
||||||
|
|
||||||
|
<receiver
|
||||||
|
android:name=".widget.date.DateWidgetReceiver"
|
||||||
|
android:label="@string/widget_date_label"
|
||||||
|
android:exported="true">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
|
||||||
|
</intent-filter>
|
||||||
|
<meta-data
|
||||||
|
android:name="android.appwidget.provider"
|
||||||
|
android:resource="@xml/appwidget_info_date" />
|
||||||
|
</receiver>
|
||||||
|
|
||||||
|
<receiver
|
||||||
|
android:name=".widget.week.WeekStripWidgetReceiver"
|
||||||
|
android:label="@string/widget_week_strip_label"
|
||||||
|
android:exported="true">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
|
||||||
|
</intent-filter>
|
||||||
|
<meta-data
|
||||||
|
android:name="android.appwidget.provider"
|
||||||
|
android:resource="@xml/appwidget_info_week_strip" />
|
||||||
|
</receiver>
|
||||||
|
|
||||||
|
<receiver
|
||||||
|
android:name=".widget.upcoming.UpcomingWidgetReceiver"
|
||||||
|
android:label="@string/widget_upcoming_label"
|
||||||
|
android:exported="true">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
|
||||||
|
</intent-filter>
|
||||||
|
<meta-data
|
||||||
|
android:name="android.appwidget.provider"
|
||||||
|
android:resource="@xml/appwidget_info_upcoming" />
|
||||||
|
</receiver>
|
||||||
|
|
||||||
|
<receiver
|
||||||
|
android:name=".widget.today.TodayWidgetReceiver"
|
||||||
|
android:label="@string/widget_today_label"
|
||||||
|
android:exported="true">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
|
||||||
|
</intent-filter>
|
||||||
|
<meta-data
|
||||||
|
android:name="android.appwidget.provider"
|
||||||
|
android:resource="@xml/appwidget_info_today" />
|
||||||
|
</receiver>
|
||||||
|
|
||||||
|
<receiver
|
||||||
|
android:name=".widget.countdown.CountdownWidgetReceiver"
|
||||||
|
android:label="@string/widget_countdown_label"
|
||||||
|
android:exported="true">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
|
||||||
|
</intent-filter>
|
||||||
|
<meta-data
|
||||||
|
android:name="android.appwidget.provider"
|
||||||
|
android:resource="@xml/appwidget_info_countdown" />
|
||||||
|
</receiver>
|
||||||
|
|
||||||
|
<!-- A countdown widget's redraw for when its label changes (#439). -->
|
||||||
|
<receiver
|
||||||
|
android:name=".widget.WidgetTickReceiver"
|
||||||
|
android:exported="false" />
|
||||||
|
|
||||||
|
<receiver
|
||||||
|
android:name=".widget.split.MonthDayWidgetReceiver"
|
||||||
|
android:label="@string/widget_month_day_label"
|
||||||
|
android:exported="true">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
|
||||||
|
</intent-filter>
|
||||||
|
<meta-data
|
||||||
|
android:name="android.appwidget.provider"
|
||||||
|
android:resource="@xml/appwidget_info_month_day" />
|
||||||
|
</receiver>
|
||||||
|
|
||||||
<!-- Keeps both widgets fresh: the calendar provider broadcasts
|
<!-- Keeps both widgets fresh: the calendar provider broadcasts
|
||||||
PROVIDER_CHANGED on any data change (our writes and external sync),
|
PROVIDER_CHANGED on any data change (external sync; the app's own
|
||||||
and the system broadcasts the date/time ones at midnight / clock
|
writes redraw directly). The day boundary arrives as the app's own
|
||||||
changes so "today" highlighting rolls over. -->
|
ROLLOVER alarm (#228), by explicit PendingIntent, so it needs no
|
||||||
|
filter here; DATE_CHANGED is a free extra only, since Android 8+
|
||||||
|
withholds it from manifest receivers. TIME_SET / TIMEZONE_CHANGED
|
||||||
|
move the boundary, boot / package-replace wipe the alarm, and
|
||||||
|
LOCALE_CHANGED redraws the labels in the new language.
|
||||||
|
Exported: the system broadcasts arrive from outside the app. -->
|
||||||
|
<!-- The app's own redraw request (language change); not exported so
|
||||||
|
other apps can't trigger it. -->
|
||||||
|
<receiver
|
||||||
|
android:name=".widget.WidgetRedrawReceiver"
|
||||||
|
android:exported="false" />
|
||||||
|
|
||||||
<receiver
|
<receiver
|
||||||
android:name=".widget.WidgetUpdateReceiver"
|
android:name=".widget.WidgetUpdateReceiver"
|
||||||
android:exported="true">
|
android:exported="true">
|
||||||
@@ -195,9 +517,24 @@
|
|||||||
<action android:name="android.intent.action.DATE_CHANGED" />
|
<action android:name="android.intent.action.DATE_CHANGED" />
|
||||||
<action android:name="android.intent.action.TIME_SET" />
|
<action android:name="android.intent.action.TIME_SET" />
|
||||||
<action android:name="android.intent.action.TIMEZONE_CHANGED" />
|
<action android:name="android.intent.action.TIMEZONE_CHANGED" />
|
||||||
|
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
||||||
|
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
|
||||||
|
<action android:name="android.intent.action.LOCALE_CHANGED" />
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
</receiver>
|
</receiver>
|
||||||
|
|
||||||
|
<!-- WorkManager initialises on demand from CalendulaApp's configuration. -->
|
||||||
|
<provider
|
||||||
|
android:name="androidx.startup.InitializationProvider"
|
||||||
|
android:authorities="${applicationId}.androidx-startup"
|
||||||
|
android:exported="false"
|
||||||
|
tools:node="merge">
|
||||||
|
<meta-data
|
||||||
|
android:name="androidx.work.WorkManagerInitializer"
|
||||||
|
android:value="androidx.startup"
|
||||||
|
tools:node="remove" />
|
||||||
|
</provider>
|
||||||
|
|
||||||
<!-- Hands .ics files we stage in the cache to other apps via a content
|
<!-- Hands .ics files we stage in the cache to other apps via a content
|
||||||
Uri (single-event share). Authority tracks applicationId so the
|
Uri (single-event share). Authority tracks applicationId so the
|
||||||
debug suffix doesn't break getUriForFile. -->
|
debug suffix doesn't break getUriForFile. -->
|
||||||
|
|||||||
@@ -1,11 +1,23 @@
|
|||||||
package de.jeanlucmakiola.calendula
|
package de.jeanlucmakiola.calendula
|
||||||
|
|
||||||
import android.app.Application
|
import android.app.Application
|
||||||
|
import androidx.work.Configuration
|
||||||
import dagger.hilt.android.EntryPointAccessors
|
import dagger.hilt.android.EntryPointAccessors
|
||||||
import dagger.hilt.android.HiltAndroidApp
|
import dagger.hilt.android.HiltAndroidApp
|
||||||
|
import de.jeanlucmakiola.calendula.data.backup.BackupChangeJob
|
||||||
import de.jeanlucmakiola.calendula.data.backup.BackupScheduler
|
import de.jeanlucmakiola.calendula.data.backup.BackupScheduler
|
||||||
|
import de.jeanlucmakiola.calendula.data.calendar.CalendarVisibilityReconciler
|
||||||
import de.jeanlucmakiola.calendula.data.backup.BackupWorker
|
import de.jeanlucmakiola.calendula.data.backup.BackupWorker
|
||||||
import de.jeanlucmakiola.calendula.data.crash.CrashReporter
|
import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesScheduler
|
||||||
|
import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesSyncWorker
|
||||||
|
import de.jeanlucmakiola.calendula.data.reminders.ReminderMaintenanceScheduler
|
||||||
|
import de.jeanlucmakiola.calendula.data.reminders.ReminderMaintenanceWorker
|
||||||
|
import de.jeanlucmakiola.calendula.widget.publishCalendulaWidgetPreviews
|
||||||
|
import de.jeanlucmakiola.calendula.widget.syncWidgetRollover
|
||||||
|
import de.jeanlucmakiola.calendula.widget.widgetEntryPoint
|
||||||
|
import de.jeanlucmakiola.floret.crash.CrashConfig
|
||||||
|
import de.jeanlucmakiola.floret.crash.CrashReporter
|
||||||
|
import de.jeanlucmakiola.floret.locale.AppLanguage
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.SupervisorJob
|
import kotlinx.coroutines.SupervisorJob
|
||||||
@@ -17,14 +29,82 @@ import kotlinx.coroutines.launch
|
|||||||
* in AndroidManifest.xml. Hilt initializes its component graph here.
|
* in AndroidManifest.xml. Hilt initializes its component graph here.
|
||||||
*/
|
*/
|
||||||
@HiltAndroidApp
|
@HiltAndroidApp
|
||||||
class CalendulaApp : Application() {
|
class CalendulaApp : Application(), Configuration.Provider {
|
||||||
|
|
||||||
|
/** Keeps WorkManager's JobScheduler ids clear of [BackupChangeJob]'s. */
|
||||||
|
override val workManagerConfiguration: Configuration =
|
||||||
|
Configuration.Builder().setJobSchedulerJobIdRange(0, BackupChangeJob.JOB_ID - 1).build()
|
||||||
|
|
||||||
override fun onCreate() {
|
override fun onCreate() {
|
||||||
super.onCreate()
|
super.onCreate()
|
||||||
// Install first thing so startup crashes are captured too (privacy-
|
// Install first thing so startup crashes are captured too (privacy-
|
||||||
// respecting, on-device; the user submits the report by hand).
|
// respecting, on-device; the user submits the report by hand). The
|
||||||
CrashReporter.install(this)
|
// capture/loop-detection/report machinery lives in floret-kit's
|
||||||
|
// core-crash; only the app label + issue-tracker URLs are app-specific.
|
||||||
|
// The prefilled issue's own title and body are the kit's, in English:
|
||||||
|
// they are posted to the tracker, so they don't follow the device
|
||||||
|
// language the way the dialog around them does.
|
||||||
|
CrashReporter.install(
|
||||||
|
this,
|
||||||
|
CrashConfig(
|
||||||
|
appLabel = getString(R.string.app_name),
|
||||||
|
newIssueUrl = getString(R.string.report_issue_url),
|
||||||
|
chooseIssueUrl = getString(R.string.report_issue_choose_url),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
// Below API 33 only AppCompat activities get the app language; a process
|
||||||
|
// woken for a widget formats in it too (#90).
|
||||||
|
AppLanguage.applyDefault(this)
|
||||||
|
// Before anything that writes, so the widgets see every change (#420).
|
||||||
|
widgetEntryPoint().widgetRefreshCoordinator().start()
|
||||||
reconcileAutoBackup()
|
reconcileAutoBackup()
|
||||||
|
reconcileSpecialDates()
|
||||||
|
reconcileCalendarVisibility()
|
||||||
|
startReminderDelivery()
|
||||||
|
reconcileWidgetRollover()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Re-arm the widgets' midnight rollover from whatever is actually placed
|
||||||
|
* (#228). Idempotent, and it covers what no broadcast reaches — an alarm
|
||||||
|
* dropped by a force-stop is armed again the next time the app is opened.
|
||||||
|
* Off the main thread: a handful of binder calls on every process start.
|
||||||
|
* The picker previews are republished here too, once per update.
|
||||||
|
*/
|
||||||
|
private fun reconcileWidgetRollover() {
|
||||||
|
CoroutineScope(SupervisorJob() + Dispatchers.Default).launch {
|
||||||
|
syncWidgetRollover(this@CalendulaApp)
|
||||||
|
publishCalendulaWidgetPreviews(this@CalendulaApp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bring reminder delivery up with the process (#75): a scan re-arms whatever
|
||||||
|
* the system dropped and posts what a missed alarm still owes, then the
|
||||||
|
* provider watch keeps edits re-planned. The daily worker is the backstop.
|
||||||
|
*/
|
||||||
|
private fun startReminderDelivery() {
|
||||||
|
val deps = EntryPointAccessors.fromApplication(
|
||||||
|
this, ReminderMaintenanceWorker.Deps::class.java,
|
||||||
|
)
|
||||||
|
val scanner = deps.reminderScanner()
|
||||||
|
scanner.startWatchingProvider()
|
||||||
|
scanner.scanInBackground()
|
||||||
|
ReminderMaintenanceScheduler.apply(this)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Flush any calendar switch-off not yet written to `Calendars.VISIBLE`,
|
||||||
|
* including the set inherited from the retired app-local model (#75). A
|
||||||
|
* no-op in the steady state; `RootScreen` re-runs it after a later grant.
|
||||||
|
*/
|
||||||
|
private fun reconcileCalendarVisibility() {
|
||||||
|
val deps = EntryPointAccessors.fromApplication(
|
||||||
|
this, CalendarVisibilityReconciler.Deps::class.java,
|
||||||
|
)
|
||||||
|
CoroutineScope(SupervisorJob() + Dispatchers.Default).launch {
|
||||||
|
deps.calendarVisibilityReconciler().run()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -36,11 +116,21 @@ class CalendulaApp : Application() {
|
|||||||
val deps = EntryPointAccessors.fromApplication(this, BackupWorker.Deps::class.java)
|
val deps = EntryPointAccessors.fromApplication(this, BackupWorker.Deps::class.java)
|
||||||
CoroutineScope(SupervisorJob() + Dispatchers.Default).launch {
|
CoroutineScope(SupervisorJob() + Dispatchers.Default).launch {
|
||||||
val prefs = deps.settingsPrefs()
|
val prefs = deps.settingsPrefs()
|
||||||
BackupScheduler.apply(
|
BackupScheduler.reconcile(this@CalendulaApp, prefs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Re-arm (or cancel) the daily special-dates reconcile from the saved
|
||||||
|
* settings, like [reconcileAutoBackup]. The on-open refresh is RootScreen's
|
||||||
|
* ON_RESUME trigger, so no immediate run is needed here.
|
||||||
|
*/
|
||||||
|
private fun reconcileSpecialDates() {
|
||||||
|
val deps = EntryPointAccessors.fromApplication(this, SpecialDatesSyncWorker.Deps::class.java)
|
||||||
|
CoroutineScope(SupervisorJob() + Dispatchers.Default).launch {
|
||||||
|
SpecialDatesScheduler.apply(
|
||||||
context = this@CalendulaApp,
|
context = this@CalendulaApp,
|
||||||
enabled = prefs.autoBackupEnabled.first(),
|
enabled = deps.settingsPrefs().specialDatesEnabled.first(),
|
||||||
intervalMinutes = prefs.autoBackupIntervalMinutes.first(),
|
|
||||||
hasFolder = prefs.autoBackupFolderUri.first() != null,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,8 +2,12 @@ package de.jeanlucmakiola.calendula
|
|||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
|
import android.content.res.Configuration
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
|
import android.provider.CalendarContract
|
||||||
|
import android.provider.OpenableColumns
|
||||||
|
import androidx.activity.SystemBarStyle
|
||||||
import androidx.activity.compose.setContent
|
import androidx.activity.compose.setContent
|
||||||
import androidx.activity.enableEdgeToEdge
|
import androidx.activity.enableEdgeToEdge
|
||||||
import androidx.appcompat.app.AppCompatActivity
|
import androidx.appcompat.app.AppCompatActivity
|
||||||
@@ -11,6 +15,7 @@ import androidx.compose.foundation.isSystemInDarkTheme
|
|||||||
import androidx.compose.foundation.layout.Box
|
import androidx.compose.foundation.layout.Box
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.runtime.CompositionLocalProvider
|
import androidx.compose.runtime.CompositionLocalProvider
|
||||||
|
import androidx.compose.runtime.DisposableEffect
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
@@ -21,44 +26,81 @@ import androidx.core.content.IntentCompat
|
|||||||
import androidx.core.net.toUri
|
import androidx.core.net.toUri
|
||||||
import androidx.hilt.navigation.compose.hiltViewModel
|
import androidx.hilt.navigation.compose.hiltViewModel
|
||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import androidx.lifecycle.lifecycleScope
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
import de.jeanlucmakiola.calendula.data.crash.CrashReporter
|
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
|
||||||
import de.jeanlucmakiola.calendula.data.prefs.ThemeMode
|
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||||
|
import de.jeanlucmakiola.floret.locale.AppLanguage
|
||||||
|
import de.jeanlucmakiola.floret.prefs.ThemeMode
|
||||||
|
import de.jeanlucmakiola.floret.prefs.isDark
|
||||||
|
import de.jeanlucmakiola.floret.prefs.isPureBlack
|
||||||
import de.jeanlucmakiola.calendula.data.prefs.is24Hour
|
import de.jeanlucmakiola.calendula.data.prefs.is24Hour
|
||||||
|
import de.jeanlucmakiola.calendula.domain.EventForm
|
||||||
|
import de.jeanlucmakiola.calendula.domain.buildInsertEventForm
|
||||||
|
import de.jeanlucmakiola.calendula.domain.sharedTextOrNull
|
||||||
|
import de.jeanlucmakiola.calendula.ui.ExternalRequests
|
||||||
|
import de.jeanlucmakiola.calendula.ui.InsertRequest
|
||||||
import de.jeanlucmakiola.calendula.ui.RootScreen
|
import de.jeanlucmakiola.calendula.ui.RootScreen
|
||||||
import de.jeanlucmakiola.calendula.ui.common.LocalShowHourLines
|
import de.jeanlucmakiola.calendula.ui.common.LocalShowHourGrid
|
||||||
|
import de.jeanlucmakiola.calendula.ui.common.LocalMultiDayCount
|
||||||
|
import de.jeanlucmakiola.calendula.ui.common.LocalTimelineZoom
|
||||||
|
import de.jeanlucmakiola.calendula.ui.common.rememberTimelineZoom
|
||||||
|
import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors
|
||||||
import de.jeanlucmakiola.calendula.ui.common.LocalUse24HourFormat
|
import de.jeanlucmakiola.calendula.ui.common.LocalUse24HourFormat
|
||||||
import de.jeanlucmakiola.calendula.ui.WidgetNavRequest
|
import de.jeanlucmakiola.calendula.ui.WidgetNavRequest
|
||||||
import de.jeanlucmakiola.calendula.ui.common.CalendarView
|
import de.jeanlucmakiola.calendula.ui.common.CalendarView
|
||||||
import de.jeanlucmakiola.calendula.ui.common.DebugRibbon
|
import de.jeanlucmakiola.calendula.ui.detail.EventDetailViewModel.Companion.NO_OCCURRENCE_TIME
|
||||||
|
import de.jeanlucmakiola.calendula.ui.edit.ImportSource
|
||||||
|
import de.jeanlucmakiola.floret.components.DebugRibbon
|
||||||
import de.jeanlucmakiola.calendula.ui.crash.CrashReportActivity
|
import de.jeanlucmakiola.calendula.ui.crash.CrashReportActivity
|
||||||
import de.jeanlucmakiola.calendula.ui.crash.CrashReportDialog
|
|
||||||
import de.jeanlucmakiola.calendula.ui.crash.submitCrashReport
|
|
||||||
import de.jeanlucmakiola.calendula.domain.FontRole
|
import de.jeanlucmakiola.calendula.domain.FontRole
|
||||||
import de.jeanlucmakiola.calendula.ui.settings.SettingsViewModel
|
import de.jeanlucmakiola.calendula.ui.settings.SettingsViewModel
|
||||||
|
import de.jeanlucmakiola.floret.crash.CrashReportDialog
|
||||||
|
import de.jeanlucmakiola.floret.crash.CrashReporter
|
||||||
|
import de.jeanlucmakiola.floret.crash.submitCrashReport
|
||||||
import de.jeanlucmakiola.calendula.ui.theme.CalendulaTheme
|
import de.jeanlucmakiola.calendula.ui.theme.CalendulaTheme
|
||||||
|
import de.jeanlucmakiola.calendula.ui.theme.WindowThemeCache
|
||||||
|
import de.jeanlucmakiola.calendula.ui.theme.windowBackgroundRes
|
||||||
import de.jeanlucmakiola.calendula.ui.theme.calendulaTypography
|
import de.jeanlucmakiola.calendula.ui.theme.calendulaTypography
|
||||||
import de.jeanlucmakiola.calendula.ui.theme.resolveFontFamily
|
import de.jeanlucmakiola.calendula.ui.theme.resolveFontFamily
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.combine
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.datetime.LocalDate
|
import kotlinx.datetime.LocalDate
|
||||||
|
import kotlinx.datetime.LocalDateTime
|
||||||
|
import kotlinx.datetime.LocalTime
|
||||||
import kotlinx.datetime.TimeZone
|
import kotlinx.datetime.TimeZone
|
||||||
|
import kotlinx.datetime.toInstant
|
||||||
import kotlinx.datetime.toLocalDateTime
|
import kotlinx.datetime.toLocalDateTime
|
||||||
|
import kotlin.time.Clock
|
||||||
import kotlin.time.Instant
|
import kotlin.time.Instant
|
||||||
|
import javax.inject.Inject
|
||||||
|
|
||||||
@AndroidEntryPoint
|
@AndroidEntryPoint
|
||||||
class MainActivity : AppCompatActivity() {
|
class MainActivity : AppCompatActivity() {
|
||||||
|
|
||||||
// The occurrence a reminder notification was tapped for (eventId, begin,
|
@Inject lateinit var calendarRepository: CalendarRepository
|
||||||
// end — the detail screen's key shape). singleTop + onNewIntent route a
|
@Inject lateinit var settingsPrefs: SettingsPrefs
|
||||||
// tap into the running activity; CalendarHost consumes and clears it.
|
|
||||||
private var requestedDetailKey by mutableStateOf<LongArray?>(null)
|
|
||||||
|
|
||||||
// A navigation a home-screen widget asked for (open a date / start a
|
// Which of light/dark the system bars are drawn for. The styles installed
|
||||||
// create). Consumed once by CalendarHost, same pattern as the detail key.
|
// in onCreate read this field live, so androidx's config-change replay
|
||||||
private var requestedNav by mutableStateOf<WidgetNavRequest?>(null)
|
// picks up the in-app override instead of the night resource qualifier.
|
||||||
|
private var systemBarsDark = false
|
||||||
|
|
||||||
// An .ics file opened/shared into the app (ACTION_VIEW/SEND). Consumed once
|
private val requests = ExternalRequests(
|
||||||
// by CalendarHost's import flow.
|
onExternalFormClosed = {
|
||||||
private var requestedImportUri by mutableStateOf<Uri?>(null)
|
insertFormOpen = false
|
||||||
|
if (launchedForInsert) finish()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
// Whether such a form is still open. Only then does a recreation re-read the
|
||||||
|
// intent to bring it back; a saved or dismissed one stays closed.
|
||||||
|
private var insertFormOpen = false
|
||||||
|
|
||||||
|
// Started just for an external create, so closing its form returns to the
|
||||||
|
// app that asked instead of leaving the calendar on top of it.
|
||||||
|
private var launchedForInsert = false
|
||||||
|
|
||||||
// A captured crash report awaiting the user's decision, surfaced as a dialog
|
// A captured crash report awaiting the user's decision, surfaced as a dialog
|
||||||
// over the calendar on the next launch (the single-crash path). A startup
|
// over the calendar on the next launch (the single-crash path). A startup
|
||||||
@@ -80,20 +122,72 @@ class MainActivity : AppCompatActivity() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
enableEdgeToEdge()
|
val systemDark = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK ==
|
||||||
requestedDetailKey = intent.detailKeyOrNull()
|
Configuration.UI_MODE_NIGHT_YES
|
||||||
requestedNav = intent.navRequestOrNull()
|
// The stored theme only arrives after the first frame, so a Light, Dark
|
||||||
requestedImportUri = intent.importUriOrNull()
|
// or Black override starts from its last mirrored copy: the matching
|
||||||
|
// backdrop and bar icons instead of the night qualifier's (#181).
|
||||||
|
val cachedTheme = WindowThemeCache.read(this)
|
||||||
|
cachedTheme?.windowBackgroundRes()?.let { window.setBackgroundDrawableResource(it) }
|
||||||
|
systemBarsDark = (cachedTheme ?: ThemeMode.SYSTEM).isDark(systemDark)
|
||||||
|
applyEdgeToEdge()
|
||||||
|
val appearance = MutableStateFlow(
|
||||||
|
Appearance(
|
||||||
|
themeMode = cachedTheme ?: ThemeMode.SYSTEM,
|
||||||
|
dynamicColor = WindowThemeCache.readDynamicColor(this),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
lifecycleScope.launch {
|
||||||
|
combine(settingsPrefs.themeMode, settingsPrefs.dynamicColor, ::Appearance).collect { stored ->
|
||||||
|
WindowThemeCache.write(this@MainActivity, stored.themeMode, stored.dynamicColor ?: true)
|
||||||
|
window.setBackgroundDrawableResource(stored.themeMode.windowBackgroundRes() ?: R.color.window_background)
|
||||||
|
appearance.value = stored
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Android hands the intent that started the task back to onCreate every
|
||||||
|
// time the activity is recreated — on a rotation, or on a restart after
|
||||||
|
// the system reclaimed the process. Re-running a launch that opens one
|
||||||
|
// specific event is what made a single reminder or widget tap re-open
|
||||||
|
// that event on every later launch, an error screen once the event had
|
||||||
|
// been deleted (#309); the user left it long ago, and the activity
|
||||||
|
// restores where they actually were along with its saved state.
|
||||||
|
//
|
||||||
|
// Only those channels are held back. An .ics import or a prefilled
|
||||||
|
// create form keeps no saved state of its own, so re-reading the intent
|
||||||
|
// is what carries one through a recreation — the create form only while
|
||||||
|
// it's still open.
|
||||||
|
val replaying = savedInstanceState != null || intent.isRelaunch()
|
||||||
|
requests.replayed = savedInstanceState != null
|
||||||
|
if (!replaying) {
|
||||||
|
requests.detailKey = intent.detailKeyOrNull() ?: intent.viewEventKeyOrNull()
|
||||||
|
requests.editKey = intent.editEventKeyOrNull()
|
||||||
|
}
|
||||||
|
requests.nav = intent.navRequestOrNull()
|
||||||
|
?.takeUnless { replaying && it is WidgetNavRequest.OpenEvent }
|
||||||
|
requests.importUri = intent.importUriOrNull()
|
||||||
|
val insertOpenBefore = savedInstanceState?.getBoolean(KEY_INSERT_FORM_OPEN) == true
|
||||||
|
requests.insert = intent.createRequestOrNull()?.takeIf { !replaying || insertOpenBefore }
|
||||||
|
insertFormOpen = requests.insert != null
|
||||||
|
launchedForInsert = savedInstanceState?.getBoolean(KEY_LAUNCHED_FOR_INSERT)
|
||||||
|
?: (requests.insert != null)
|
||||||
if (CrashReporter.shouldPrompt(this)) pendingCrashReport = CrashReporter.pendingReport(this)
|
if (CrashReporter.shouldPrompt(this)) pendingCrashReport = CrashReporter.pendingReport(this)
|
||||||
setContent {
|
setContent {
|
||||||
// One activity-scoped SettingsViewModel drives both the theme here
|
// One activity-scoped SettingsViewModel drives both the theme here
|
||||||
// and the Settings screen, so a theme change applies app-wide at once.
|
// and the Settings screen, so a theme change applies app-wide at once.
|
||||||
val settingsViewModel: SettingsViewModel = hiltViewModel()
|
val settingsViewModel: SettingsViewModel = hiltViewModel()
|
||||||
val settings by settingsViewModel.state.collectAsStateWithLifecycle()
|
val settings by settingsViewModel.state.collectAsStateWithLifecycle()
|
||||||
val darkTheme = when (settings.themeMode) {
|
// Seeded from the cache, so the first frame doesn't draw the default
|
||||||
ThemeMode.SYSTEM -> isSystemInDarkTheme()
|
// theme and palette before the stored choices arrive.
|
||||||
ThemeMode.LIGHT -> false
|
val shownAppearance by appearance.collectAsStateWithLifecycle()
|
||||||
ThemeMode.DARK -> true
|
val themeMode = shownAppearance.themeMode
|
||||||
|
val darkTheme = themeMode.isDark(isSystemInDarkTheme())
|
||||||
|
// onCreate can only see the night resource qualifier, not the in-app
|
||||||
|
// override — re-apply from the resolved theme so the bar icons follow
|
||||||
|
// the app's light/dark choice.
|
||||||
|
DisposableEffect(darkTheme) {
|
||||||
|
systemBarsDark = darkTheme
|
||||||
|
applyEdgeToEdge()
|
||||||
|
onDispose {}
|
||||||
}
|
}
|
||||||
// The app-wide clock convention: the time-format preference resolved
|
// The app-wide clock convention: the time-format preference resolved
|
||||||
// against the device's 24-hour system setting, provided once here so
|
// against the device's 24-hour system setting, provided once here so
|
||||||
@@ -107,6 +201,14 @@ class MainActivity : AppCompatActivity() {
|
|||||||
// re-import stamp AppFontSettings carries, so replacing the file
|
// re-import stamp AppFontSettings carries, so replacing the file
|
||||||
// behind an active "custom" token still refreshes — changes;
|
// behind an active "custom" token still refreshes — changes;
|
||||||
// "system for both" returns the default scale untouched.
|
// "system for both" returns the default scale untouched.
|
||||||
|
// The timeline scale plus the pinch in flight over it (#56). Held
|
||||||
|
// here, above the calendar views, so a zoom survives paging between
|
||||||
|
// weeks and switching between the week and day view.
|
||||||
|
val timelineZoom = rememberTimelineZoom(
|
||||||
|
stored = settings.timelineScale,
|
||||||
|
hours = settings.timelineHours,
|
||||||
|
onPersist = settingsViewModel::setTimelineScale,
|
||||||
|
)
|
||||||
val fonts by settingsViewModel.fontState.collectAsStateWithLifecycle()
|
val fonts by settingsViewModel.fontState.collectAsStateWithLifecycle()
|
||||||
val typography = remember(fonts, context) {
|
val typography = remember(fonts, context) {
|
||||||
calendulaTypography(
|
calendulaTypography(
|
||||||
@@ -116,22 +218,21 @@ class MainActivity : AppCompatActivity() {
|
|||||||
}
|
}
|
||||||
CalendulaTheme(
|
CalendulaTheme(
|
||||||
darkTheme = darkTheme,
|
darkTheme = darkTheme,
|
||||||
dynamicColor = settings.dynamicColor,
|
dynamicColor = shownAppearance.dynamicColor ?: settings.dynamicColor,
|
||||||
|
pureBlack = themeMode.isPureBlack,
|
||||||
typography = typography,
|
typography = typography,
|
||||||
) {
|
) {
|
||||||
Box(modifier = Modifier.fillMaxSize()) {
|
Box(modifier = Modifier.fillMaxSize()) {
|
||||||
CompositionLocalProvider(
|
CompositionLocalProvider(
|
||||||
LocalUse24HourFormat provides use24Hour,
|
LocalUse24HourFormat provides use24Hour,
|
||||||
LocalShowHourLines provides settings.showHourLines,
|
LocalShowHourGrid provides settings.showHourGrid,
|
||||||
|
LocalTimelineZoom provides timelineZoom,
|
||||||
|
LocalMultiDayCount provides settings.multiDayCount,
|
||||||
|
LocalSoftenColors provides settings.softenColors,
|
||||||
) {
|
) {
|
||||||
RootScreen(
|
RootScreen(
|
||||||
modifier = Modifier.fillMaxSize(),
|
modifier = Modifier.fillMaxSize(),
|
||||||
requestedDetailKey = requestedDetailKey,
|
requests = requests,
|
||||||
onDetailKeyConsumed = { requestedDetailKey = null },
|
|
||||||
widgetNavRequest = requestedNav,
|
|
||||||
onWidgetNavConsumed = { requestedNav = null },
|
|
||||||
requestedImportUri = requestedImportUri,
|
|
||||||
onImportConsumed = { requestedImportUri = null },
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
// A persistent corner marker so a debug build is never
|
// A persistent corner marker so a debug build is never
|
||||||
@@ -158,18 +259,67 @@ class MainActivity : AppCompatActivity() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Applies the transparent edge-to-edge bars for the current [systemBarsDark].
|
||||||
|
* Both scrims are transparent because API 29+ enforces its own contrast and
|
||||||
|
* ignores them anyway.
|
||||||
|
*/
|
||||||
|
private fun applyEdgeToEdge() {
|
||||||
|
val transparent = android.graphics.Color.TRANSPARENT
|
||||||
|
enableEdgeToEdge(
|
||||||
|
statusBarStyle = SystemBarStyle.auto(transparent, transparent) { systemBarsDark },
|
||||||
|
navigationBarStyle = SystemBarStyle.auto(transparent, transparent) { systemBarsDark },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onStart() {
|
||||||
|
super.onStart()
|
||||||
|
// Changes made while we were away may never have notified us (#364).
|
||||||
|
calendarRepository.refresh()
|
||||||
|
}
|
||||||
|
|
||||||
override fun onResume() {
|
override fun onResume() {
|
||||||
super.onResume()
|
super.onResume()
|
||||||
// Reaching a running UI means startup succeeded; reset the loop trail.
|
// Reaching a running UI means startup succeeded; reset the loop trail.
|
||||||
CrashReporter.markHealthy(this)
|
CrashReporter.markHealthy(this)
|
||||||
|
AppLanguage.syncMirror(this)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onSaveInstanceState(outState: Bundle) {
|
||||||
|
super.onSaveInstanceState(outState)
|
||||||
|
outState.putBoolean(KEY_INSERT_FORM_OPEN, insertFormOpen)
|
||||||
|
outState.putBoolean(KEY_LAUNCHED_FOR_INSERT, launchedForInsert)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onNewIntent(intent: Intent) {
|
override fun onNewIntent(intent: Intent) {
|
||||||
super.onNewIntent(intent)
|
super.onNewIntent(intent)
|
||||||
intent.detailKeyOrNull()?.let { requestedDetailKey = it }
|
requests.replayed = false
|
||||||
intent.navRequestOrNull()?.let { requestedNav = it }
|
(intent.detailKeyOrNull() ?: intent.viewEventKeyOrNull())?.let { requests.detailKey = it }
|
||||||
intent.importUriOrNull()?.let { requestedImportUri = it }
|
intent.navRequestOrNull()?.let { requests.nav = it }
|
||||||
|
intent.importUriOrNull()?.let { requests.importUri = it }
|
||||||
|
intent.createRequestOrNull()?.let {
|
||||||
|
requests.insert = it
|
||||||
|
insertFormOpen = true
|
||||||
}
|
}
|
||||||
|
intent.editEventKeyOrNull()?.let { requests.editKey = it }
|
||||||
|
// The user moved on into the app, so closing the create form no longer
|
||||||
|
// hands control back to the app that started it.
|
||||||
|
if (requests.detailKey != null || requests.nav != null || requests.importUri != null ||
|
||||||
|
requests.editKey != null
|
||||||
|
) {
|
||||||
|
launchedForInsert = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether this launch is the task being resumed rather than a fresh
|
||||||
|
* delivery — Android sets the flag when an activity is started from the
|
||||||
|
* recents list, where the intent it carries is the one the task was started
|
||||||
|
* with however long ago. `onNewIntent` is the channel a real new request
|
||||||
|
* arrives on while the task lives, so nothing is lost by ignoring these.
|
||||||
|
*/
|
||||||
|
private fun Intent.isRelaunch(): Boolean =
|
||||||
|
flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY != 0
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The `.ics` Uri an external app asked us to open (file manager `ACTION_VIEW`)
|
* The `.ics` Uri an external app asked us to open (file manager `ACTION_VIEW`)
|
||||||
@@ -179,7 +329,10 @@ class MainActivity : AppCompatActivity() {
|
|||||||
private fun Intent.importUriOrNull(): Uri? {
|
private fun Intent.importUriOrNull(): Uri? {
|
||||||
val uri = when (action) {
|
val uri = when (action) {
|
||||||
Intent.ACTION_VIEW -> data
|
Intent.ACTION_VIEW -> data
|
||||||
Intent.ACTION_SEND -> IntentCompat.getParcelableExtra(this, Intent.EXTRA_STREAM, Uri::class.java)
|
// Shared text is a create (#306); a text/plain file is imported only
|
||||||
|
// when it is calendar data, e.g. an .ics attachment labelled text/plain.
|
||||||
|
Intent.ACTION_SEND -> sharedStreamOrNull()
|
||||||
|
?.takeUnless { type == SHARED_TEXT_TYPE && !it.isCalendarFile() }
|
||||||
else -> null
|
else -> null
|
||||||
} ?: return null
|
} ?: return null
|
||||||
// The calendar "view time" Uri (a date tap) is also ACTION_VIEW/content;
|
// The calendar "view time" Uri (a date tap) is also ACTION_VIEW/content;
|
||||||
@@ -188,6 +341,103 @@ class MainActivity : AppCompatActivity() {
|
|||||||
return uri.takeIf { it.scheme == "content" || it.scheme == "file" }
|
return uri.takeIf { it.scheme == "content" || it.scheme == "file" }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A prefilled new-event form from an external launch asking us to create an
|
||||||
|
* event — another app or widget (e.g. Todo Agenda) firing `ACTION_INSERT`
|
||||||
|
* (issue #30), or `ACTION_EDIT` with no concrete event id (AOSP's "edit a new
|
||||||
|
* event", i.e. create). The new event's fields ride as CalendarContract
|
||||||
|
* extras; anything omitted falls back to the in-app "new event" defaults in
|
||||||
|
* [buildInsertEventForm]. An intent that names no end time leaves the length
|
||||||
|
* to the default-duration setting ([ImportSource.InsertOpenEnded], #54).
|
||||||
|
*/
|
||||||
|
private fun Intent.insertRequestOrNull(): InsertRequest? {
|
||||||
|
// ACTION_EDIT / ACTION_INSERT_OR_EDIT on an existing event route to the
|
||||||
|
// edit form instead ([editEventKeyOrNull]); an id-less one is a create,
|
||||||
|
// as is any plain ACTION_INSERT.
|
||||||
|
val isCreate = action == Intent.ACTION_INSERT ||
|
||||||
|
((action == Intent.ACTION_EDIT || action == Intent.ACTION_INSERT_OR_EDIT) &&
|
||||||
|
editEventKeyOrNull() == null)
|
||||||
|
if (!isCreate) return null
|
||||||
|
val beginMillis = longExtraOrNull(CalendarContract.EXTRA_EVENT_BEGIN_TIME)
|
||||||
|
val endMillis = longExtraOrNull(CalendarContract.EXTRA_EVENT_END_TIME)
|
||||||
|
val form = buildInsertEventForm(
|
||||||
|
beginMillis = beginMillis,
|
||||||
|
endMillis = endMillis,
|
||||||
|
isAllDay = getBooleanExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, false),
|
||||||
|
title = getStringExtra(CalendarContract.Events.TITLE),
|
||||||
|
description = getStringExtra(CalendarContract.Events.DESCRIPTION),
|
||||||
|
location = getStringExtra(CalendarContract.Events.EVENT_LOCATION),
|
||||||
|
rrule = getStringExtra(CalendarContract.Events.RRULE),
|
||||||
|
calendarId = calendarIdExtraOrNull(),
|
||||||
|
zone = TimeZone.currentSystemDefault(),
|
||||||
|
now = Clock.System.now(),
|
||||||
|
)
|
||||||
|
// An end the intent didn't name — or one [buildInsertEventForm] drops for
|
||||||
|
// landing before the start — leaves the length to the setting.
|
||||||
|
val namesEnd = beginMillis != null && endMillis != null && endMillis >= beginMillis
|
||||||
|
return InsertRequest(form, if (namesEnd) ImportSource.Insert else ImportSource.InsertOpenEnded)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Any external request to create an event: shared text or an insert intent. */
|
||||||
|
private fun Intent.createRequestOrNull(): InsertRequest? = sharedTextRequestOrNull() ?: insertRequestOrNull()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Plain text shared into us (`ACTION_SEND`) or picked from a text-selection
|
||||||
|
* menu (`ACTION_PROCESS_TEXT`), as a new event at the default time (#306).
|
||||||
|
*/
|
||||||
|
private fun Intent.sharedTextRequestOrNull(): InsertRequest? {
|
||||||
|
val shared = when (action) {
|
||||||
|
Intent.ACTION_SEND -> if (type == SHARED_TEXT_TYPE && sharedStreamOrNull()?.isCalendarFile() != true) {
|
||||||
|
sharedTextOrNull(
|
||||||
|
subject = getCharSequenceExtra(Intent.EXTRA_SUBJECT)?.toString(),
|
||||||
|
text = getCharSequenceExtra(Intent.EXTRA_TEXT)?.toString(),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
Intent.ACTION_PROCESS_TEXT ->
|
||||||
|
sharedTextOrNull(subject = null, text = getCharSequenceExtra(Intent.EXTRA_PROCESS_TEXT)?.toString())
|
||||||
|
else -> null
|
||||||
|
} ?: return null
|
||||||
|
val form = buildInsertEventForm(
|
||||||
|
title = shared.title,
|
||||||
|
description = shared.description,
|
||||||
|
zone = TimeZone.currentSystemDefault(),
|
||||||
|
now = Clock.System.now(),
|
||||||
|
)
|
||||||
|
return InsertRequest(form, ImportSource.InsertOpenEnded)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun Intent.sharedStreamOrNull(): Uri? =
|
||||||
|
IntentCompat.getParcelableExtra(this, Intent.EXTRA_STREAM, Uri::class.java)
|
||||||
|
|
||||||
|
/** Whether a shared file is iCalendar/vCalendar data, by its resolved type or its name. */
|
||||||
|
private fun Uri.isCalendarFile(): Boolean {
|
||||||
|
val resolvedType = runCatching { contentResolver.getType(this) }.getOrNull()
|
||||||
|
if (resolvedType in CALENDAR_TYPES) return true
|
||||||
|
val name = when (scheme) {
|
||||||
|
"content" -> runCatching {
|
||||||
|
contentResolver.query(this, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)
|
||||||
|
?.use { c -> if (c.moveToFirst()) c.getString(0) else null }
|
||||||
|
}.getOrNull()
|
||||||
|
else -> lastPathSegment
|
||||||
|
} ?: return false
|
||||||
|
return CALENDAR_EXTENSIONS.any { name.endsWith(it, ignoreCase = true) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A Long extra's value, or null when the extra is absent. */
|
||||||
|
private fun Intent.longExtraOrNull(key: String): Long? =
|
||||||
|
if (hasExtra(key)) getLongExtra(key, 0L) else null
|
||||||
|
|
||||||
|
/** The calendar an insert intent names (#429); callers pass it as an int, a long or a string. */
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
private fun Intent.calendarIdExtraOrNull(): Long? =
|
||||||
|
when (val value = extras?.get(CalendarContract.Events.CALENDAR_ID)) {
|
||||||
|
is Number -> value.toLong()
|
||||||
|
is String -> value.trim().toLongOrNull()
|
||||||
|
else -> null
|
||||||
|
}?.takeIf { it > 0 }
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The date a launcher/clock date tap points at, parsed from the AOSP calendar
|
* The date a launcher/clock date tap points at, parsed from the AOSP calendar
|
||||||
* "view time" intent: ACTION_VIEW on `content://com.android.calendar/time/
|
* "view time" intent: ACTION_VIEW on `content://com.android.calendar/time/
|
||||||
@@ -255,10 +505,65 @@ class MainActivity : AppCompatActivity() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The detail key for an external "open this event" — ACTION_VIEW on
|
||||||
|
* `content://com.android.calendar/events/<id>`, the way AOSP fires it (e.g.
|
||||||
|
* tapping an existing event in the Todo Agenda widget, issue #48). Reuses the
|
||||||
|
* same occurrence-key channel as reminder taps. The launcher passes the
|
||||||
|
* occurrence's times as `EXTRA_EVENT_BEGIN_TIME` / `EXTRA_EVENT_END_TIME` when
|
||||||
|
* it has them; a bare URI omits them, so we carry [NO_OCCURRENCE_TIME] and
|
||||||
|
* [EventDetailViewModel] falls back to the event row's own DTSTART/DTEND
|
||||||
|
* rather than rendering at the epoch.
|
||||||
|
*/
|
||||||
|
private fun Intent.viewEventKeyOrNull(): LongArray? {
|
||||||
|
if (action != Intent.ACTION_VIEW) return null
|
||||||
|
val uri = data ?: return null
|
||||||
|
if (uri.host != CALENDAR_PROVIDER_HOST) return null
|
||||||
|
val segments = uri.pathSegments
|
||||||
|
if (segments.firstOrNull() != "events") return null
|
||||||
|
val eventId = segments.getOrNull(1)?.toLongOrNull() ?: return null
|
||||||
|
return longArrayOf(
|
||||||
|
eventId,
|
||||||
|
longExtraOrNull(CalendarContract.EXTRA_EVENT_BEGIN_TIME) ?: NO_OCCURRENCE_TIME,
|
||||||
|
longExtraOrNull(CalendarContract.EXTRA_EVENT_END_TIME) ?: NO_OCCURRENCE_TIME,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The occurrence key for an external "edit this event" — `ACTION_EDIT` on
|
||||||
|
* `content://com.android.calendar/events/<id>`, the way AOSP fires it (e.g.
|
||||||
|
* an assistant, task app, or widget that wants to open the event for editing
|
||||||
|
* rather than viewing). Opens it in the edit form. Reuses the same
|
||||||
|
* occurrence-key channel as reminder/view taps; the caller passes the
|
||||||
|
* occurrence's times as `EXTRA_EVENT_BEGIN_TIME` / `EXTRA_EVENT_END_TIME`
|
||||||
|
* when it has them, otherwise we carry [NO_OCCURRENCE_TIME] and
|
||||||
|
* [EventEditViewModel.openForEdit] falls back to the event row's own
|
||||||
|
* DTSTART/DTEND. An id-less `ACTION_EDIT` — or `ACTION_INSERT_OR_EDIT`, which
|
||||||
|
* some apps fire — is a create instead ([insertFormOrNull]).
|
||||||
|
*/
|
||||||
|
private fun Intent.editEventKeyOrNull(): LongArray? {
|
||||||
|
if (action != Intent.ACTION_EDIT && action != Intent.ACTION_INSERT_OR_EDIT) return null
|
||||||
|
val uri = data ?: return null
|
||||||
|
if (uri.host != CALENDAR_PROVIDER_HOST) return null
|
||||||
|
val segments = uri.pathSegments
|
||||||
|
if (segments.firstOrNull() != "events") return null
|
||||||
|
val eventId = segments.getOrNull(1)?.toLongOrNull() ?: return null
|
||||||
|
return longArrayOf(
|
||||||
|
eventId,
|
||||||
|
longExtraOrNull(CalendarContract.EXTRA_EVENT_BEGIN_TIME) ?: NO_OCCURRENCE_TIME,
|
||||||
|
longExtraOrNull(CalendarContract.EXTRA_EVENT_END_TIME) ?: NO_OCCURRENCE_TIME,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
// The calendar provider's authority/host. A date tap arrives as
|
// The calendar provider's authority/host. A date tap arrives as
|
||||||
// ACTION_VIEW on content://com.android.calendar/time/<epochMillis>.
|
// ACTION_VIEW on content://com.android.calendar/time/<epochMillis>.
|
||||||
private const val CALENDAR_PROVIDER_HOST = "com.android.calendar"
|
private const val CALENDAR_PROVIDER_HOST = "com.android.calendar"
|
||||||
|
private const val SHARED_TEXT_TYPE = "text/plain"
|
||||||
|
private val CALENDAR_TYPES = setOf("text/calendar", "text/x-vcalendar", "application/ics")
|
||||||
|
private val CALENDAR_EXTENSIONS = listOf(".ics", ".vcs")
|
||||||
|
private const val KEY_INSERT_FORM_OPEN = "insert_form_open"
|
||||||
|
private const val KEY_LAUNCHED_FOR_INSERT = "launched_for_insert"
|
||||||
|
|
||||||
private const val EXTRA_EVENT_ID = "de.jeanlucmakiola.calendula.extra.EVENT_ID"
|
private const val EXTRA_EVENT_ID = "de.jeanlucmakiola.calendula.extra.EVENT_ID"
|
||||||
private const val EXTRA_BEGIN_MILLIS = "de.jeanlucmakiola.calendula.extra.BEGIN"
|
private const val EXTRA_BEGIN_MILLIS = "de.jeanlucmakiola.calendula.extra.BEGIN"
|
||||||
@@ -303,7 +608,9 @@ class MainActivity : AppCompatActivity() {
|
|||||||
*/
|
*/
|
||||||
fun openDateIntent(context: Context, date: LocalDate, source: CalendarView): Intent =
|
fun openDateIntent(context: Context, date: LocalDate, source: CalendarView): Intent =
|
||||||
Intent(context, MainActivity::class.java).apply {
|
Intent(context, MainActivity::class.java).apply {
|
||||||
data = "calendula://date/$date".toUri()
|
// The source is part of the URI so widgets of different kinds
|
||||||
|
// tapping the same date don't share one PendingIntent.
|
||||||
|
data = "calendula://date/$date/${source.name}".toUri()
|
||||||
putExtra(EXTRA_DATE_ISO, date.toString())
|
putExtra(EXTRA_DATE_ISO, date.toString())
|
||||||
putExtra(EXTRA_SOURCE_VIEW, source.name)
|
putExtra(EXTRA_SOURCE_VIEW, source.name)
|
||||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||||
@@ -322,9 +629,24 @@ class MainActivity : AppCompatActivity() {
|
|||||||
endMillis: Long,
|
endMillis: Long,
|
||||||
source: CalendarView,
|
source: CalendarView,
|
||||||
): Intent = eventDetailIntent(context, eventId, beginMillis, endMillis).apply {
|
): Intent = eventDetailIntent(context, eventId, beginMillis, endMillis).apply {
|
||||||
|
data = "calendula://event/$eventId/$beginMillis/${source.name}".toUri()
|
||||||
putExtra(EXTRA_SOURCE_VIEW, source.name)
|
putExtra(EXTRA_SOURCE_VIEW, source.name)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Open the day view on [date] over the default home view — the daily
|
||||||
|
* summary's tap (#459). Spoken as the system's own "view time" intent,
|
||||||
|
* at the day's local noon, so it lands on the path a clock tap takes.
|
||||||
|
*/
|
||||||
|
fun openDayIntent(context: Context, date: LocalDate): Intent {
|
||||||
|
val noon = LocalDateTime(date, LocalTime(12, 0))
|
||||||
|
.toInstant(TimeZone.currentSystemDefault())
|
||||||
|
.toEpochMilliseconds()
|
||||||
|
return Intent(Intent.ACTION_VIEW, "content://$CALENDAR_PROVIDER_HOST/time/$noon".toUri())
|
||||||
|
.setClass(context, MainActivity::class.java)
|
||||||
|
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||||
|
}
|
||||||
|
|
||||||
/** Open the create-event form prefilled for [date] (home-screen widgets). */
|
/** Open the create-event form prefilled for [date] (home-screen widgets). */
|
||||||
fun openCreateIntent(context: Context, date: LocalDate): Intent =
|
fun openCreateIntent(context: Context, date: LocalDate): Intent =
|
||||||
Intent(context, MainActivity::class.java).apply {
|
Intent(context, MainActivity::class.java).apply {
|
||||||
@@ -349,3 +671,6 @@ class MainActivity : AppCompatActivity() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The theme choices the window needs before the settings screen's state loads. */
|
||||||
|
private data class Appearance(val themeMode: ThemeMode, val dynamicColor: Boolean?)
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.data.appname
|
||||||
|
|
||||||
|
import android.content.ComponentName
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
/** The launcher label the app shows for itself (issue #44). */
|
||||||
|
enum class LauncherName { CALENDULA, CALENDAR }
|
||||||
|
|
||||||
|
/** The two launcher aliases declared in the manifest. */
|
||||||
|
enum class LauncherAlias { DEFAULT, CALENDAR }
|
||||||
|
|
||||||
|
/** One component-enable change in a [aliasWritePlan]. */
|
||||||
|
data class AliasStateChange(val alias: LauncherAlias, val enabled: Boolean)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Interpret the `CalendarNameAlias` component-enabled state as a [LauncherName].
|
||||||
|
* Only [PackageManager.COMPONENT_ENABLED_STATE_ENABLED] means the "Calendar"
|
||||||
|
* name is active; `DEFAULT` (never toggled) and `DISABLED` both resolve to the
|
||||||
|
* manifest default, "Calendula".
|
||||||
|
*/
|
||||||
|
fun launcherNameFor(calendarAliasState: Int): LauncherName =
|
||||||
|
if (calendarAliasState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
|
||||||
|
LauncherName.CALENDAR
|
||||||
|
} else {
|
||||||
|
LauncherName.CALENDULA
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The ordered enable/disable steps to switch the launcher name to [target].
|
||||||
|
* Always **enables the target alias first, then disables the other** — the two
|
||||||
|
* `setComponentEnabledSetting` calls are not atomic, and this ordering means the
|
||||||
|
* only transient the launcher can observe is a harmless two-entry state, never a
|
||||||
|
* zero-entry one (which would briefly drop the app from the launcher).
|
||||||
|
*/
|
||||||
|
fun aliasWritePlan(target: LauncherName): List<AliasStateChange> = when (target) {
|
||||||
|
LauncherName.CALENDAR -> listOf(
|
||||||
|
AliasStateChange(LauncherAlias.CALENDAR, enabled = true),
|
||||||
|
AliasStateChange(LauncherAlias.DEFAULT, enabled = false),
|
||||||
|
)
|
||||||
|
LauncherName.CALENDULA -> listOf(
|
||||||
|
AliasStateChange(LauncherAlias.DEFAULT, enabled = true),
|
||||||
|
AliasStateChange(LauncherAlias.CALENDAR, enabled = false),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Switches the app's launcher label between "Calendula" and "Calendar" by
|
||||||
|
* enabling/disabling the two `<activity-alias>` components (issue #44). The
|
||||||
|
* component-enabled state is the single source of truth — there is no persisted
|
||||||
|
* preference — so [current] reads it straight from [PackageManager] and the two
|
||||||
|
* always agree.
|
||||||
|
*
|
||||||
|
* The decision logic lives in the pure [launcherNameFor] / [aliasWritePlan]
|
||||||
|
* functions above (JVM-tested); this class is only the thin framework seam.
|
||||||
|
*/
|
||||||
|
@Singleton
|
||||||
|
class LauncherNameManager @Inject constructor(
|
||||||
|
@ApplicationContext private val context: Context,
|
||||||
|
) {
|
||||||
|
private val packageManager: PackageManager get() = context.packageManager
|
||||||
|
|
||||||
|
// The class portion is namespace-qualified (suffix-free), the package portion
|
||||||
|
// is the applicationId (which carries the .debug / .releasetest suffix). The
|
||||||
|
// manifest's ".CalendarNameAlias" resolves its class against the namespace, so
|
||||||
|
// the real component is <namespace>.CalendarNameAlias registered under the
|
||||||
|
// suffixed applicationId. Do NOT use ComponentName(context, ".CalendarNameAlias")
|
||||||
|
// — its leading-dot form prepends the applicationId to the class too, producing
|
||||||
|
// "<appId>.CalendarNameAlias" and failing on every debug / releaseTest build.
|
||||||
|
private fun component(alias: LauncherAlias): ComponentName {
|
||||||
|
val simpleName = when (alias) {
|
||||||
|
LauncherAlias.DEFAULT -> "DefaultNameAlias"
|
||||||
|
LauncherAlias.CALENDAR -> "CalendarNameAlias"
|
||||||
|
}
|
||||||
|
return ComponentName(context.packageName, "$NAMESPACE.$simpleName")
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The launcher name currently in effect. */
|
||||||
|
fun current(): LauncherName =
|
||||||
|
launcherNameFor(packageManager.getComponentEnabledSetting(component(LauncherAlias.CALENDAR)))
|
||||||
|
|
||||||
|
/** Switch the launcher name to [name] (no-op cost if already active). */
|
||||||
|
fun set(name: LauncherName) {
|
||||||
|
for (change in aliasWritePlan(name)) {
|
||||||
|
val state = if (change.enabled) {
|
||||||
|
PackageManager.COMPONENT_ENABLED_STATE_ENABLED
|
||||||
|
} else {
|
||||||
|
PackageManager.COMPONENT_ENABLED_STATE_DISABLED
|
||||||
|
}
|
||||||
|
packageManager.setComponentEnabledSetting(
|
||||||
|
component(change.alias),
|
||||||
|
state,
|
||||||
|
PackageManager.DONT_KILL_APP,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
/**
|
||||||
|
* The app's namespace (R-class package) — NOT `applicationId`, which
|
||||||
|
* carries the build-type suffix. Kept in sync with `namespace` in
|
||||||
|
* `app/build.gradle.kts`.
|
||||||
|
*/
|
||||||
|
const val NAMESPACE = "de.jeanlucmakiola.calendula"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,20 +5,23 @@ import android.app.NotificationChannel
|
|||||||
import android.app.NotificationManager
|
import android.app.NotificationManager
|
||||||
import android.app.PendingIntent
|
import android.app.PendingIntent
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.pm.PackageManager
|
import android.net.Uri
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import androidx.core.app.NotificationCompat
|
import androidx.core.app.NotificationCompat
|
||||||
import androidx.core.app.NotificationManagerCompat
|
import androidx.core.app.NotificationManagerCompat
|
||||||
import androidx.core.content.ContextCompat
|
|
||||||
import androidx.core.net.toUri
|
import androidx.core.net.toUri
|
||||||
|
import androidx.work.Constraints
|
||||||
import androidx.work.CoroutineWorker
|
import androidx.work.CoroutineWorker
|
||||||
import androidx.work.ExistingPeriodicWorkPolicy
|
import androidx.work.ExistingPeriodicWorkPolicy
|
||||||
import androidx.work.ExistingWorkPolicy
|
import androidx.work.ExistingWorkPolicy
|
||||||
import androidx.work.OneTimeWorkRequestBuilder
|
import androidx.work.OneTimeWorkRequestBuilder
|
||||||
import androidx.work.PeriodicWorkRequestBuilder
|
import androidx.work.PeriodicWorkRequestBuilder
|
||||||
|
import androidx.work.WorkInfo
|
||||||
import androidx.work.WorkManager
|
import androidx.work.WorkManager
|
||||||
import androidx.work.WorkerParameters
|
import androidx.work.WorkerParameters
|
||||||
|
import androidx.work.await
|
||||||
|
import androidx.work.workDataOf
|
||||||
import dagger.hilt.EntryPoint
|
import dagger.hilt.EntryPoint
|
||||||
import dagger.hilt.InstallIn
|
import dagger.hilt.InstallIn
|
||||||
import dagger.hilt.android.EntryPointAccessors
|
import dagger.hilt.android.EntryPointAccessors
|
||||||
@@ -27,41 +30,87 @@ import de.jeanlucmakiola.calendula.R
|
|||||||
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
|
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
|
||||||
import de.jeanlucmakiola.calendula.data.ics.IcsExporter
|
import de.jeanlucmakiola.calendula.data.ics.IcsExporter
|
||||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||||
|
import de.jeanlucmakiola.calendula.domain.backup.BackupFilePlan
|
||||||
|
import de.jeanlucmakiola.calendula.domain.backup.BackupTarget
|
||||||
|
import de.jeanlucmakiola.calendula.domain.backup.backupFingerprint
|
||||||
|
import de.jeanlucmakiola.calendula.domain.backup.backupTargets
|
||||||
|
import de.jeanlucmakiola.calendula.domain.backup.inBackupOrder
|
||||||
|
import de.jeanlucmakiola.calendula.domain.backup.latestHeldElsewhere
|
||||||
|
import de.jeanlucmakiola.calendula.domain.backup.latestFileName
|
||||||
|
import de.jeanlucmakiola.calendula.domain.backup.latestLedgerKey
|
||||||
|
import de.jeanlucmakiola.calendula.domain.backup.needsRefresh
|
||||||
|
import de.jeanlucmakiola.calendula.domain.backup.planBackupFiles
|
||||||
|
import de.jeanlucmakiola.calendula.domain.backup.replacedLatestCopies
|
||||||
|
import de.jeanlucmakiola.calendula.domain.backup.withFingerprint
|
||||||
|
import de.jeanlucmakiola.calendula.domain.backup.withLedgerEntry
|
||||||
import de.jeanlucmakiola.calendula.domain.ics.IcsWriter
|
import de.jeanlucmakiola.calendula.domain.ics.IcsWriter
|
||||||
|
import de.jeanlucmakiola.floret.android.hasPermission
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.NonCancellable
|
||||||
import kotlinx.coroutines.flow.first
|
import kotlinx.coroutines.flow.first
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import java.time.LocalDateTime
|
||||||
import java.util.concurrent.TimeUnit
|
import java.util.concurrent.TimeUnit
|
||||||
|
import kotlin.coroutines.cancellation.CancellationException
|
||||||
import kotlin.time.Clock
|
import kotlin.time.Clock
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Schedules and runs the automatic periodic `.ics` backup of local calendars
|
* Schedules and runs the automatic periodic `.ics` backup (issue #8) of the
|
||||||
* (issue #8). One-way export only — it mirrors the manual "Back up" into a
|
* calendars the user picked (#147). One-way export only — it mirrors the manual
|
||||||
* user-chosen folder on an interval; it is not a sync. Stays INTERNET-free:
|
* "Back up" into a user-chosen folder on an interval; it is not a sync. Stays
|
||||||
* everything is local provider reads + a local file write.
|
* INTERNET-free: everything is local provider reads + local file writes.
|
||||||
*/
|
*/
|
||||||
object BackupScheduler {
|
object BackupScheduler {
|
||||||
|
|
||||||
private const val WORK_NAME = "auto-backup"
|
private const val WORK_NAME = "auto-backup"
|
||||||
private const val WORK_NAME_NOW = "auto-backup-now"
|
private const val WORK_NAME_NOW = "auto-backup-now"
|
||||||
|
private const val WORK_NAME_CHANGE = "auto-backup-change"
|
||||||
|
internal const val KEY_CHANGE_RUN = "change_run"
|
||||||
|
|
||||||
|
private val reconcileLock = Mutex()
|
||||||
|
|
||||||
|
/** A watch that fired while the option was off: still pending until it finishes, but not re-armed. */
|
||||||
|
private var watchDropped = false
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reconcile the scheduled work with the current settings: enqueue a unique
|
* Reconcile the scheduled work with the saved settings: enqueue a unique
|
||||||
* periodic request when backup is on and a folder is set, otherwise cancel
|
* periodic request when backup is on and a folder is set, otherwise cancel
|
||||||
* it. WorkManager persists the request across reboots on its own.
|
* it. WorkManager persists the request across reboots on its own.
|
||||||
*
|
*
|
||||||
* The first run is delayed by one interval so it never overlaps an immediate
|
* The first run is delayed by one interval so it doesn't follow an immediate
|
||||||
* [runNow] (two simultaneous writes would race and leave a "(1)" duplicate).
|
* [runNow] with a near-identical copy. With backing up after changes on
|
||||||
|
* (#516), the change watch ([BackupChangeJob]) is armed unless it already
|
||||||
|
* waits; it doesn't survive a reboot, and this runs on every process start.
|
||||||
|
* Serialised and not cancellable, so quick toggles settle on the last one.
|
||||||
*/
|
*/
|
||||||
fun apply(context: Context, enabled: Boolean, intervalMinutes: Long, hasFolder: Boolean) {
|
suspend fun reconcile(context: Context, prefs: SettingsPrefs) = withContext(NonCancellable + Dispatchers.IO) {
|
||||||
|
reconcileLock.withLock {
|
||||||
|
try {
|
||||||
|
apply(context, prefs)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "Scheduling the automatic backup failed", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun apply(context: Context, prefs: SettingsPrefs) {
|
||||||
val workManager = WorkManager.getInstance(context)
|
val workManager = WorkManager.getInstance(context)
|
||||||
if (!enabled || !hasFolder) {
|
fun stopWatching() {
|
||||||
|
BackupChangeJob.cancel(context)
|
||||||
|
workManager.cancelUniqueWork(WORK_NAME_CHANGE)
|
||||||
|
}
|
||||||
|
if (!prefs.autoBackupEnabled.first() || prefs.autoBackupFolderUri.first() == null) {
|
||||||
workManager.cancelUniqueWork(WORK_NAME)
|
workManager.cancelUniqueWork(WORK_NAME)
|
||||||
// Also cancel any pending immediate run — otherwise a failing run-now
|
// Also cancel any pending immediate run — otherwise a failing run-now
|
||||||
// keeps retrying after the user has turned backup off.
|
// keeps retrying after the user has turned backup off.
|
||||||
workManager.cancelUniqueWork(WORK_NAME_NOW)
|
workManager.cancelUniqueWork(WORK_NAME_NOW)
|
||||||
|
stopWatching()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// WorkManager's own floor is 15 min; the UI floors the user choice at 30.
|
// WorkManager's own floor is 15 min; the UI floors the user choice at 30.
|
||||||
val interval = intervalMinutes.coerceAtLeast(15L)
|
val interval = prefs.autoBackupIntervalMinutes.first().coerceAtLeast(15L)
|
||||||
val request = PeriodicWorkRequestBuilder<BackupWorker>(interval, TimeUnit.MINUTES)
|
val request = PeriodicWorkRequestBuilder<BackupWorker>(interval, TimeUnit.MINUTES)
|
||||||
.setInitialDelay(interval, TimeUnit.MINUTES)
|
.setInitialDelay(interval, TimeUnit.MINUTES)
|
||||||
.build()
|
.build()
|
||||||
@@ -70,6 +119,44 @@ object BackupScheduler {
|
|||||||
ExistingPeriodicWorkPolicy.UPDATE,
|
ExistingPeriodicWorkPolicy.UPDATE,
|
||||||
request,
|
request,
|
||||||
)
|
)
|
||||||
|
if (!prefs.autoBackupOnChange.first()) {
|
||||||
|
stopWatching()
|
||||||
|
} else if (watchDropped || !BackupChangeJob.isPending(context)) {
|
||||||
|
// Replacing a waiting watch would drop the changes it has seen.
|
||||||
|
BackupChangeJob.schedule(context)
|
||||||
|
watchDropped = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The watch fired: queue a change run and arm the next watch, unless the
|
||||||
|
* option went off meanwhile. Under [reconcileLock], so it can't re-arm
|
||||||
|
* after a switch-off.
|
||||||
|
*/
|
||||||
|
internal suspend fun changed(context: Context, prefs: SettingsPrefs) = withContext(NonCancellable) {
|
||||||
|
reconcileLock.withLock {
|
||||||
|
// Re-armed even when queueing the run fails: a trigger fires only once.
|
||||||
|
var wanted = true
|
||||||
|
try {
|
||||||
|
wanted = prefs.autoBackupEnabled.first() && prefs.autoBackupFolderUri.first() != null &&
|
||||||
|
prefs.autoBackupOnChange.first()
|
||||||
|
if (wanted) queueChangeRun(context)
|
||||||
|
} finally {
|
||||||
|
if (wanted) BackupChangeJob.schedule(context)
|
||||||
|
watchDropped = !wanted
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun queueChangeRun(context: Context) {
|
||||||
|
val workManager = WorkManager.getInstance(context)
|
||||||
|
val states = workManager.getWorkInfosForUniqueWorkFlow(WORK_NAME_CHANGE).first().map { it.state }
|
||||||
|
val policy = changeRunPolicy(states) ?: return
|
||||||
|
val run = OneTimeWorkRequestBuilder<BackupWorker>()
|
||||||
|
.setConstraints(Constraints.Builder().setRequiresBatteryNotLow(true).build())
|
||||||
|
.setInputData(workDataOf(KEY_CHANGE_RUN to true))
|
||||||
|
.build()
|
||||||
|
workManager.enqueueUniqueWork(WORK_NAME_CHANGE, policy, run).await()
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -84,11 +171,25 @@ object BackupScheduler {
|
|||||||
OneTimeWorkRequestBuilder<BackupWorker>().build(),
|
OneTimeWorkRequestBuilder<BackupWorker>().build(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private const val TAG = "BackupScheduler"
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Exports the local calendars to `calendula-backup.ics` in the configured folder,
|
* How a fired change watch queues its run (#516), from the change runs' work
|
||||||
* overwriting the previous file. Pulls its collaborators through a Hilt
|
* [states]: a run that hasn't started yet will see the change anyway (null);
|
||||||
|
* one already going may have read too early, so the new one queues behind it.
|
||||||
|
*/
|
||||||
|
internal fun changeRunPolicy(states: List<WorkInfo.State>): ExistingWorkPolicy? = when {
|
||||||
|
states.any { it == WorkInfo.State.ENQUEUED || it == WorkInfo.State.BLOCKED } -> null
|
||||||
|
WorkInfo.State.RUNNING in states -> ExistingWorkPolicy.APPEND_OR_REPLACE
|
||||||
|
else -> ExistingWorkPolicy.REPLACE
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Exports the selected calendars into the configured folder — one dated file
|
||||||
|
* per calendar, or one combined file (#411) — then prunes each series down to
|
||||||
|
* the retention count. Pulls its collaborators through a Hilt
|
||||||
* [EntryPoint] so it works under WorkManager's default (no-arg) worker factory —
|
* [EntryPoint] so it works under WorkManager's default (no-arg) worker factory —
|
||||||
* no custom factory / Application wiring needed. Records the outcome for the
|
* no custom factory / Application wiring needed. Records the outcome for the
|
||||||
* settings status line, and notifies after repeated failures.
|
* settings status line, and notifies after repeated failures.
|
||||||
@@ -108,33 +209,237 @@ class BackupWorker(
|
|||||||
|
|
||||||
override suspend fun doWork(): Result {
|
override suspend fun doWork(): Result {
|
||||||
val deps = EntryPointAccessors.fromApplication(applicationContext, Deps::class.java)
|
val deps = EntryPointAccessors.fromApplication(applicationContext, Deps::class.java)
|
||||||
val prefs = deps.settingsPrefs()
|
val changeRun = inputData.getBoolean(BackupScheduler.KEY_CHANGE_RUN, false)
|
||||||
// Respect the toggle even for already-queued work: if backup was turned
|
if (!changeRun) return backUp(deps, deps.settingsPrefs(), changeRun = false)
|
||||||
// off, no-op (and don't retry) so a lingering run can't revive itself.
|
// A failed change run would fail the one queued behind it too.
|
||||||
if (!prefs.autoBackupEnabled.first()) return Result.success()
|
try {
|
||||||
val folder = prefs.autoBackupFolderUri.first()
|
backUp(deps, deps.settingsPrefs(), changeRun = true)
|
||||||
?: return Result.failure() // nothing to write to — leave scheduling to settings
|
} catch (e: CancellationException) {
|
||||||
val now = System.currentTimeMillis()
|
throw e
|
||||||
return try {
|
|
||||||
val events = deps.repository().exportEvents()
|
|
||||||
val content = IcsWriter().writeCalendar(events, Clock.System.now())
|
|
||||||
deps.exporter().writeToFolder(folder.toUri(), BACKUP_FILE_NAME, content)
|
|
||||||
prefs.recordAutoBackupRun(success = true, atMillis = now)
|
|
||||||
Result.success()
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
prefs.recordAutoBackupRun(success = false, atMillis = now)
|
Log.w(TAG, "Backup after a change failed", e)
|
||||||
if (prefs.autoBackupStatus.first().consecutiveFailures >= FAILURE_NOTIFY_THRESHOLD) {
|
}
|
||||||
|
return Result.success()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One run under the shared lock, recorded for the status line. A change
|
||||||
|
* run (#516) refreshes only the stable copies and never retries. The
|
||||||
|
* failure notification comes once per failure streak, when it reaches
|
||||||
|
* [FAILURE_NOTIFY_THRESHOLD], and goes with the next success of any run.
|
||||||
|
*/
|
||||||
|
private suspend fun backUp(deps: Deps, prefs: SettingsPrefs, changeRun: Boolean): Result {
|
||||||
|
// One run at a time, or each would overwrite the other's ledger.
|
||||||
|
val outcome = runLock.withLock {
|
||||||
|
val now = System.currentTimeMillis()
|
||||||
|
// Respect the toggles even for already-queued work, so a lingering
|
||||||
|
// run can't revive itself.
|
||||||
|
if (!prefs.autoBackupEnabled.first()) return Result.success()
|
||||||
|
if (changeRun && !prefs.autoBackupOnChange.first()) return Result.success()
|
||||||
|
val folder = prefs.autoBackupFolderUri.first() ?: return Result.failure()
|
||||||
|
val outcome = try {
|
||||||
|
runBackup(deps, prefs, folder.toUri(), latestOnly = changeRun)
|
||||||
|
} catch (e: CancellationException) {
|
||||||
|
throw e
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "Automatic backup failed", e)
|
||||||
|
RunOutcome.Failed
|
||||||
|
}
|
||||||
|
if (outcome != RunOutcome.NothingToDo) {
|
||||||
|
withContext(NonCancellable) {
|
||||||
|
prefs.recordAutoBackupRun(success = outcome == RunOutcome.Written, atMillis = now)
|
||||||
|
when {
|
||||||
|
outcome == RunOutcome.Written -> clearFailureNotification(applicationContext)
|
||||||
|
prefs.autoBackupStatus.first().consecutiveFailures == FAILURE_NOTIFY_THRESHOLD ->
|
||||||
notifyFailure(applicationContext)
|
notifyFailure(applicationContext)
|
||||||
}
|
}
|
||||||
Log.w(TAG, "Automatic backup failed", e)
|
|
||||||
Result.retry()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
outcome
|
||||||
|
}
|
||||||
|
// Only a run that wrote nothing retries: a retry rewrites every series.
|
||||||
|
return if (outcome == RunOutcome.Failed && !changeRun) Result.retry() else Result.success()
|
||||||
|
}
|
||||||
|
|
||||||
|
private enum class RunOutcome { Written, PartlyFailed, Failed, NothingToDo }
|
||||||
|
|
||||||
|
/** How a stable copy's write went: under its own name, under one the provider picked, or not at all. */
|
||||||
|
private enum class LatestWrite { Landed, Renamed, Failed }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Writes each series and prunes it only once its new file has landed. A
|
||||||
|
* [latestOnly] run (#516) leaves the dated files and their retention to the
|
||||||
|
* schedule and rewrites only the stable copies whose calendars changed.
|
||||||
|
*/
|
||||||
|
private suspend fun runBackup(deps: Deps, prefs: SettingsPrefs, folder: Uri, latestOnly: Boolean): RunOutcome {
|
||||||
|
val repository = deps.repository()
|
||||||
|
val exporter = deps.exporter()
|
||||||
|
if (!applicationContext.hasPermission(Manifest.permission.READ_CALENDAR)) return RunOutcome.Failed
|
||||||
|
val all = repository.calendars().first()
|
||||||
|
val selection = prefs.autoBackupSelection.first()
|
||||||
|
val combined = prefs.autoBackupCombined.first()
|
||||||
|
if (all.none(selection::selects)) return RunOutcome.NothingToDo
|
||||||
|
prefs.adoptLegacyBackupFile()
|
||||||
|
val listing = exporter.listFolder(folder)
|
||||||
|
val ledger = prefs.autoBackupLedger.first()
|
||||||
|
// A listing still loading can't tell a gone file from a late one.
|
||||||
|
val existing = if (listing.complete) listing.files.keys else listing.files.keys + ledger.values.flatten()
|
||||||
|
val targets = backupTargets(all.filter(selection::selects), combined, ledger, existing)
|
||||||
|
if (targets.isEmpty()) return RunOutcome.NothingToDo
|
||||||
|
val stamp = Clock.System.now()
|
||||||
|
val fingerprints = prefs.autoBackupFingerprints.first()
|
||||||
|
suspend fun export(target: BackupTarget): String? = try {
|
||||||
|
val events = repository.exportEvents(target.calendarIds).inBackupOrder()
|
||||||
|
IcsWriter().writeCalendar(events, stamp, target.calendarName)
|
||||||
|
} catch (e: CancellationException) {
|
||||||
|
throw e
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "Reading one series failed", e)
|
||||||
|
null
|
||||||
|
}
|
||||||
|
fun fingerprintOf(target: BackupTarget, text: String) =
|
||||||
|
backupFingerprint(text, latestFileName(target.baseName))
|
||||||
|
// Hashes only serve change runs; without them a stale one could pass later.
|
||||||
|
val trackHashes = prefs.autoBackupOnChange.first()
|
||||||
|
if (!trackHashes && fingerprints.isNotEmpty()) prefs.updateAutoBackupFingerprints(folder.toString()) { emptyMap() }
|
||||||
|
// A change run hashes first (null: unreadable) and leaves the folder alone when nothing moved.
|
||||||
|
val preHashes: Map<String, String?> = if (latestOnly) {
|
||||||
|
targets.associate { target -> target.key to export(target)?.let { fingerprintOf(target, it) } }
|
||||||
|
} else {
|
||||||
|
emptyMap()
|
||||||
|
}
|
||||||
|
if (latestOnly && targets.all { preHashes[it.key].let { hash -> hash != null && hash == fingerprints[it.key] } }) {
|
||||||
|
return RunOutcome.NothingToDo
|
||||||
|
}
|
||||||
|
val plans = planBackupFiles(
|
||||||
|
targets = targets,
|
||||||
|
ledger = ledger,
|
||||||
|
existing = existing,
|
||||||
|
at = LocalDateTime.now(),
|
||||||
|
keep = prefs.autoBackupKeep.first(),
|
||||||
|
)
|
||||||
|
val liveKeys = all.map { it.id.toString() }.toSet()
|
||||||
|
suspend fun record(key: String, files: List<String>) =
|
||||||
|
prefs.updateAutoBackupLedger(folder.toString()) { withLedgerEntry(it, key, files, liveKeys) }
|
||||||
|
|
||||||
|
suspend fun writeDated(plan: BackupFilePlan, bytes: ByteArray): Boolean = try {
|
||||||
|
val name = exporter.writeToFolder(folder, listing, plan.fileName, bytes)
|
||||||
|
record(plan.target.key, plan.prune + plan.keep + name)
|
||||||
|
val undeleted = exporter.deleteFromFolder(listing, plan.prune)
|
||||||
|
record(plan.target.key, plan.prune.filter { it in undeleted } + plan.keep + name)
|
||||||
|
true
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "Backup of one series failed", e)
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
// An old copy goes only once the new one has landed.
|
||||||
|
suspend fun writeLatest(plan: BackupFilePlan, bytes: ByteArray, fingerprint: String): LatestWrite {
|
||||||
|
val target = plan.target
|
||||||
|
val latest = checkNotNull(plan.latestName)
|
||||||
|
var landed: String? = null
|
||||||
|
try {
|
||||||
|
val latestKey = latestLedgerKey(target.key)
|
||||||
|
if (trackHashes && target.key in fingerprints) {
|
||||||
|
prefs.updateAutoBackupFingerprints(folder.toString()) { it - target.key }
|
||||||
|
}
|
||||||
|
landed = exporter.writeToFolder(folder, listing, latest, bytes)
|
||||||
|
// A provider that renamed it leaves a copy to clean up next
|
||||||
|
// run; the intended name stays ours only if it already was.
|
||||||
|
val ownsLatest = landed == latest || latest in ledger[latestKey].orEmpty()
|
||||||
|
val current = listOfNotNull(landed, latest.takeIf { ownsLatest })
|
||||||
|
// A hand-off stays on record only until its new owner claimed it.
|
||||||
|
suspend fun recordLatest(stale: List<String>, landedFingerprint: String? = null) =
|
||||||
|
prefs.updateAutoBackupLedger(
|
||||||
|
folder.toString(),
|
||||||
|
fingerprints = landedFingerprint?.let { hash ->
|
||||||
|
{ old -> withFingerprint(old, target.key, hash, liveKeys) }
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
val pending = plan.handOff - it.latestHeldElsewhere(target.key)
|
||||||
|
withLedgerEntry(it, latestKey, stale + pending + current, liveKeys)
|
||||||
|
}
|
||||||
|
recordLatest(plan.staleLatest, fingerprint.takeIf { trackHashes })
|
||||||
|
val staleLeft = exporter.deleteFromFolder(listing, plan.staleLatest)
|
||||||
|
recordLatest(plan.staleLatest.filter { it in staleLeft })
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "Stable copy of one series failed", e)
|
||||||
|
}
|
||||||
|
return when (landed) {
|
||||||
|
null -> LatestWrite.Failed
|
||||||
|
latest -> LatestWrite.Landed
|
||||||
|
else -> LatestWrite.Renamed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A copy blocked by a file of the user's keeps its hash, so a later change run can stop early.
|
||||||
|
suspend fun rememberBlocked(plan: BackupFilePlan, hash: String) {
|
||||||
|
val key = plan.target.key
|
||||||
|
if (plan.latestName == null && trackHashes && fingerprints[key] != hash) {
|
||||||
|
prefs.updateAutoBackupFingerprints(folder.toString()) { withFingerprint(it, key, hash, liveKeys) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var written = 0
|
||||||
|
var failed = 0
|
||||||
|
val landedLatest = mutableSetOf<String>()
|
||||||
|
for (plan in plans) {
|
||||||
|
val target = plan.target
|
||||||
|
if (latestOnly) {
|
||||||
|
val hash = preHashes[target.key] ?: run {
|
||||||
|
failed++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
rememberBlocked(plan, hash)
|
||||||
|
if (!plan.needsRefresh(hash, fingerprints, listing.files.keys, listing.complete)) {
|
||||||
|
if (plan.latestName in listing.files) landedLatest += target.key
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Read again rather than held since the pre-pass: one series' text in memory at a time.
|
||||||
|
val text = export(target) ?: run {
|
||||||
|
failed++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
val fingerprint = fingerprintOf(target, text)
|
||||||
|
if (!latestOnly) rememberBlocked(plan, fingerprint)
|
||||||
|
val bytes = text.toByteArray(Charsets.UTF_8)
|
||||||
|
// Not cancellable once a file exists: it must reach the ledger.
|
||||||
|
withContext(NonCancellable) {
|
||||||
|
val dated = if (latestOnly) null else writeDated(plan, bytes)
|
||||||
|
val latest = plan.latestName?.let { writeLatest(plan, bytes, fingerprint) }
|
||||||
|
if (latest == LatestWrite.Landed) landedLatest += target.key
|
||||||
|
// A full run's status follows its dated file; the stable copy is best-effort there.
|
||||||
|
val ok = dated ?: (latest != LatestWrite.Failed)
|
||||||
|
if (ok) written++ else failed++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A layout switch retires the other layout's copies once every new one is there.
|
||||||
|
if (landedLatest.size == plans.size) {
|
||||||
|
replacedLatestCopies(targets, prefs.autoBackupLedger.first(), existing).forEach { (key, names) ->
|
||||||
|
withContext(NonCancellable) {
|
||||||
|
val left = exporter.deleteFromFolder(listing, names)
|
||||||
|
record(latestLedgerKey(key), names.filter { it in left })
|
||||||
|
// Its copy is gone, so its hash mustn't let a change run stop early.
|
||||||
|
prefs.updateAutoBackupFingerprints(folder.toString()) { it - key }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return when {
|
||||||
|
failed == 0 && written == 0 -> RunOutcome.NothingToDo
|
||||||
|
failed == 0 -> RunOutcome.Written
|
||||||
|
written == 0 -> RunOutcome.Failed
|
||||||
|
else -> RunOutcome.PartlyFailed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun clearFailureNotification(context: Context) {
|
||||||
|
NotificationManagerCompat.from(context).cancel(NOTIFICATION_ID)
|
||||||
|
}
|
||||||
|
|
||||||
private fun notifyFailure(context: Context) {
|
private fun notifyFailure(context: Context) {
|
||||||
val canPost = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
|
val canPost = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
|
||||||
ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) ==
|
context.hasPermission(Manifest.permission.POST_NOTIFICATIONS)
|
||||||
PackageManager.PERMISSION_GRANTED
|
|
||||||
if (!canPost) return
|
if (!canPost) return
|
||||||
val manager = NotificationManagerCompat.from(context)
|
val manager = NotificationManagerCompat.from(context)
|
||||||
manager.createNotificationChannel(
|
manager.createNotificationChannel(
|
||||||
@@ -167,10 +472,10 @@ class BackupWorker(
|
|||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
const val BACKUP_FILE_NAME = "calendula-backup.ics"
|
|
||||||
private const val FAILURE_NOTIFY_THRESHOLD = 2
|
private const val FAILURE_NOTIFY_THRESHOLD = 2
|
||||||
private const val CHANNEL_ID = "backup"
|
private const val CHANNEL_ID = "backup"
|
||||||
private const val NOTIFICATION_ID = 2
|
private const val NOTIFICATION_ID = 2
|
||||||
private const val TAG = "BackupWorker"
|
private const val TAG = "BackupWorker"
|
||||||
|
private val runLock = Mutex()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.data.backup
|
||||||
|
|
||||||
|
import android.app.job.JobInfo
|
||||||
|
import android.app.job.JobParameters
|
||||||
|
import android.app.job.JobScheduler
|
||||||
|
import android.app.job.JobService
|
||||||
|
import android.content.ComponentName
|
||||||
|
import android.content.Context
|
||||||
|
import android.provider.CalendarContract
|
||||||
|
import android.util.Log
|
||||||
|
import dagger.hilt.android.EntryPointAccessors
|
||||||
|
import kotlinx.coroutines.CancellationException
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.SupervisorJob
|
||||||
|
import kotlinx.coroutines.cancel
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The watch behind "Also back up after changes" (#516): a JobScheduler job
|
||||||
|
* with a content trigger on the provider's root URI, where it reports every
|
||||||
|
* change, whoever made it (this app, a sync adapter or another app). It waits
|
||||||
|
* for [SETTLE_MINUTES] of quiet, at most [MAX_WAIT_MINUTES], so a burst makes
|
||||||
|
* one run. A trigger fires once; each firing queues a change run and schedules
|
||||||
|
* the next watch under the same id before finishing, which hands over the
|
||||||
|
* changes seen meanwhile, so exactly one watch exists and none are lost.
|
||||||
|
*/
|
||||||
|
class BackupChangeJob : JobService() {
|
||||||
|
|
||||||
|
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||||
|
|
||||||
|
override fun onStartJob(params: JobParameters): Boolean {
|
||||||
|
scope.launch {
|
||||||
|
// Retried when it failed early, so the watch isn't lost; once re-armed, the retry is moot.
|
||||||
|
val failed = try {
|
||||||
|
val deps = EntryPointAccessors.fromApplication(applicationContext, BackupWorker.Deps::class.java)
|
||||||
|
BackupScheduler.changed(applicationContext, deps.settingsPrefs())
|
||||||
|
false
|
||||||
|
} catch (e: CancellationException) {
|
||||||
|
throw e
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "Queueing a backup after a change failed", e)
|
||||||
|
true
|
||||||
|
}
|
||||||
|
jobFinished(params, failed)
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Stopped before it could re-arm: run again rather than leave the provider unwatched. */
|
||||||
|
override fun onStopJob(params: JobParameters): Boolean = true
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
scope.cancel()
|
||||||
|
super.onDestroy()
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
/** Above the range WorkManager is given (see CalendulaApp). */
|
||||||
|
const val JOB_ID = 0x0516_0001
|
||||||
|
private const val SETTLE_MINUTES = 2L
|
||||||
|
private const val MAX_WAIT_MINUTES = 15L
|
||||||
|
private const val TAG = "BackupChangeJob"
|
||||||
|
|
||||||
|
fun schedule(context: Context) {
|
||||||
|
val job = JobInfo.Builder(JOB_ID, ComponentName(context, BackupChangeJob::class.java))
|
||||||
|
.addTriggerContentUri(
|
||||||
|
JobInfo.TriggerContentUri(
|
||||||
|
CalendarContract.CONTENT_URI,
|
||||||
|
JobInfo.TriggerContentUri.FLAG_NOTIFY_FOR_DESCENDANTS,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.setTriggerContentUpdateDelay(TimeUnit.MINUTES.toMillis(SETTLE_MINUTES))
|
||||||
|
.setTriggerContentMaxDelay(TimeUnit.MINUTES.toMillis(MAX_WAIT_MINUTES))
|
||||||
|
.build()
|
||||||
|
if (context.getSystemService(JobScheduler::class.java).schedule(job) != JobScheduler.RESULT_SUCCESS) {
|
||||||
|
Log.w(TAG, "The change watch could not be scheduled")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isPending(context: Context): Boolean =
|
||||||
|
context.getSystemService(JobScheduler::class.java).getPendingJob(JOB_ID) != null
|
||||||
|
|
||||||
|
fun cancel(context: Context) = context.getSystemService(JobScheduler::class.java).cancel(JOB_ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,265 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.data.backup
|
||||||
|
|
||||||
|
import androidx.datastore.preferences.core.Preferences
|
||||||
|
import de.jeanlucmakiola.calendula.data.appname.LauncherName
|
||||||
|
import de.jeanlucmakiola.calendula.data.calendar.ManagedCalendarRow
|
||||||
|
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefKeys
|
||||||
|
import de.jeanlucmakiola.calendula.data.prefs.FixedTimeOverride
|
||||||
|
import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys
|
||||||
|
import de.jeanlucmakiola.calendula.data.prefs.fixedTimeOverrideFor
|
||||||
|
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||||
|
import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType
|
||||||
|
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
|
||||||
|
import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle
|
||||||
|
import de.jeanlucmakiola.calendula.ui.common.CalendarView
|
||||||
|
import de.jeanlucmakiola.floret.backup.BackupDocument
|
||||||
|
import de.jeanlucmakiola.floret.backup.BackupResult
|
||||||
|
import de.jeanlucmakiola.floret.backup.PrefsSection
|
||||||
|
import de.jeanlucmakiola.floret.backup.invalidBackup
|
||||||
|
import de.jeanlucmakiola.floret.backup.optBoolean
|
||||||
|
import de.jeanlucmakiola.floret.backup.optIntList
|
||||||
|
import de.jeanlucmakiola.floret.backup.optObject
|
||||||
|
import de.jeanlucmakiola.floret.backup.optObjectList
|
||||||
|
import de.jeanlucmakiola.floret.backup.optInt
|
||||||
|
import de.jeanlucmakiola.floret.backup.optString
|
||||||
|
import de.jeanlucmakiola.floret.backup.optStringList
|
||||||
|
import de.jeanlucmakiola.floret.backup.readBackup
|
||||||
|
import de.jeanlucmakiola.floret.backup.requireString
|
||||||
|
import de.jeanlucmakiola.floret.prefs.Pref
|
||||||
|
import de.jeanlucmakiola.floret.prefs.get
|
||||||
|
import kotlinx.serialization.json.JsonArray
|
||||||
|
import kotlinx.serialization.json.JsonNull
|
||||||
|
import kotlinx.serialization.json.JsonObject
|
||||||
|
import kotlinx.serialization.json.JsonPrimitive
|
||||||
|
import kotlinx.serialization.json.buildJsonObject
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A calendar as another device can find it again: provider ids are per
|
||||||
|
* device, so a calendar is named by its account and display name, and a
|
||||||
|
* special-dates mirror by the date type it mirrors.
|
||||||
|
*/
|
||||||
|
data class CalendarIdentity(
|
||||||
|
val accountName: String,
|
||||||
|
val accountType: String,
|
||||||
|
val displayName: String,
|
||||||
|
val specialDates: SpecialDateType? = null,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** The per-calendar settings of one calendar; null fields inherit the global default. */
|
||||||
|
data class CalendarSettings(
|
||||||
|
val calendar: CalendarIdentity,
|
||||||
|
val hidden: Boolean = false,
|
||||||
|
val lastUsed: Boolean = false,
|
||||||
|
val eventDurationMinutes: Int? = null,
|
||||||
|
/** Timed reminder override; an empty list is "no reminder". */
|
||||||
|
val reminders: List<Int>? = null,
|
||||||
|
val allDayReminders: List<Int>? = null,
|
||||||
|
/** The views it is hidden in only (#270). */
|
||||||
|
val hiddenInViews: Set<CalendarView> = emptySet(),
|
||||||
|
/** False when Calendula posts none of its reminders (#272). */
|
||||||
|
val notifications: Boolean = true,
|
||||||
|
/** Its alert style (#171); null is a plain notification. */
|
||||||
|
val alertStyle: ReminderAlertStyle? = null,
|
||||||
|
/** Its set-time reminder override (#459). */
|
||||||
|
val fixedTimeReminder: FixedTimeOverride = FixedTimeOverride.Inherit,
|
||||||
|
/** False when the daily summary leaves it out (#459). */
|
||||||
|
val inDailyDigest: Boolean = true,
|
||||||
|
/** The automatic backup's choice for it (#147); null follows the default for its kind. */
|
||||||
|
val autoBackup: Boolean? = null,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** The app language a file carries; [tag] null follows the system. */
|
||||||
|
data class LanguageChoice(val tag: String?)
|
||||||
|
|
||||||
|
/** Everything a settings backup holds. Null [language]/[launcherName]: the file didn't say. */
|
||||||
|
data class SettingsBackup(
|
||||||
|
val prefs: Map<Pref<*>, Any>,
|
||||||
|
val calendars: List<CalendarSettings>,
|
||||||
|
val language: LanguageChoice? = null,
|
||||||
|
val launcherName: LauncherName? = null,
|
||||||
|
)
|
||||||
|
|
||||||
|
internal val plainSection = PrefsSection(SettingsBackupSchema.plain)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The backup of [snapshot]. Per-calendar entries are named through
|
||||||
|
* [calendars] and [managed]; an id neither knows (a deleted calendar's
|
||||||
|
* leftover) is dropped.
|
||||||
|
*/
|
||||||
|
fun buildSettingsBackup(
|
||||||
|
snapshot: Preferences,
|
||||||
|
calendars: List<CalendarSource>,
|
||||||
|
managed: List<ManagedCalendarRow>,
|
||||||
|
language: LanguageChoice?,
|
||||||
|
launcherName: LauncherName?,
|
||||||
|
): SettingsBackup {
|
||||||
|
val hidden = snapshot[CalendarPrefKeys.hiddenCalendarIds]
|
||||||
|
val lastUsed = snapshot[CalendarPrefKeys.lastUsedCalendarId]
|
||||||
|
val durations = snapshot[SettingsKeys.perCalendarEventDuration]
|
||||||
|
val reminders = snapshot[SettingsKeys.perCalendarReminderOverride]
|
||||||
|
val allDay = snapshot[SettingsKeys.perCalendarAllDayReminderOverride]
|
||||||
|
val hiddenViews = snapshot[SettingsKeys.perCalendarHiddenViews]
|
||||||
|
val muted = snapshot[SettingsKeys.mutedReminderCalendarIds]
|
||||||
|
val alertStyles = snapshot[SettingsKeys.reminderAlertStyles]
|
||||||
|
val fixedTime = snapshot[SettingsKeys.perCalendarFixedTimeReminderOverride]
|
||||||
|
val notInDigest = snapshot[SettingsKeys.digestExcludedCalendarIds]
|
||||||
|
val backupIncluded = snapshot[SettingsKeys.autoBackupIncluded]
|
||||||
|
val backupExcluded = snapshot[SettingsKeys.autoBackupExcluded]
|
||||||
|
val ids = hidden + listOfNotNull(lastUsed) + durations.keys + reminders.keys + allDay.keys +
|
||||||
|
hiddenViews.keys + muted + alertStyles.keys + fixedTime.keys + notInDigest + backupIncluded + backupExcluded
|
||||||
|
val byId = calendars.associateBy { it.id }
|
||||||
|
val managedType = managed.associate { it.id to it.type }
|
||||||
|
val entries = ids.sorted().mapNotNull { id ->
|
||||||
|
val calendar = byId[id] ?: return@mapNotNull null
|
||||||
|
CalendarSettings(
|
||||||
|
calendar = CalendarIdentity(
|
||||||
|
accountName = calendar.accountName,
|
||||||
|
accountType = calendar.accountType,
|
||||||
|
displayName = calendar.displayName,
|
||||||
|
specialDates = managedType[id],
|
||||||
|
),
|
||||||
|
hidden = id in hidden,
|
||||||
|
lastUsed = id == lastUsed,
|
||||||
|
eventDurationMinutes = durations[id],
|
||||||
|
reminders = reminders[id],
|
||||||
|
allDayReminders = allDay[id],
|
||||||
|
hiddenInViews = hiddenViews[id].orEmpty(),
|
||||||
|
notifications = id !in muted,
|
||||||
|
alertStyle = alertStyles[id]?.takeUnless { it == ReminderAlertStyle.Notification },
|
||||||
|
fixedTimeReminder = fixedTime.fixedTimeOverrideFor(id),
|
||||||
|
inDailyDigest = id !in notInDigest,
|
||||||
|
autoBackup = when (id) {
|
||||||
|
in backupIncluded -> true
|
||||||
|
in backupExcluded -> false
|
||||||
|
else -> null
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return SettingsBackup(
|
||||||
|
prefs = plainSection.snapshot(snapshot),
|
||||||
|
calendars = entries,
|
||||||
|
language = language,
|
||||||
|
launcherName = launcherName,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun encodeSettingsBackup(backup: SettingsBackup, exportedAtMillis: Long, appVersion: String?): String {
|
||||||
|
val body = buildJsonObject {
|
||||||
|
put(KEY_SETTINGS, plainSection.encode(backup.prefs))
|
||||||
|
put(KEY_CALENDARS, JsonArray(backup.calendars.map { it.toJson() }))
|
||||||
|
put(
|
||||||
|
KEY_APP,
|
||||||
|
buildJsonObject {
|
||||||
|
backup.language?.let { put(KEY_LANGUAGE, it.tag?.let(::JsonPrimitive) ?: JsonNull) }
|
||||||
|
backup.launcherName?.let { put(KEY_LAUNCHER_NAME, JsonPrimitive(it.name)) }
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
val document = BackupDocument(
|
||||||
|
version = SettingsBackupSchema.format.version,
|
||||||
|
exportedAtMillis = exportedAtMillis,
|
||||||
|
appVersion = appVersion,
|
||||||
|
body = body,
|
||||||
|
)
|
||||||
|
return SettingsBackupSchema.format.encode(document)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Validates the whole file before anything is applied; see docs/SETTINGS_BACKUP.md. */
|
||||||
|
fun decodeSettingsBackup(text: String): BackupResult<SettingsBackup> {
|
||||||
|
val document = when (val decoded = SettingsBackupSchema.format.decode(text)) {
|
||||||
|
is BackupResult.Failure -> return decoded
|
||||||
|
is BackupResult.Success -> decoded.value
|
||||||
|
}
|
||||||
|
return readBackup {
|
||||||
|
val body = document.body
|
||||||
|
val app = body.optObject(KEY_APP)
|
||||||
|
SettingsBackup(
|
||||||
|
prefs = plainSection.read(body.optObject(KEY_SETTINGS) ?: invalidBackup("$KEY_SETTINGS: missing")),
|
||||||
|
calendars = body.optObjectList(KEY_CALENDARS).orEmpty().map { it.toCalendarSettings() },
|
||||||
|
language = app?.takeIf { KEY_LANGUAGE in it }?.let { LanguageChoice(it.optString(KEY_LANGUAGE)) },
|
||||||
|
launcherName = app?.optString(KEY_LAUNCHER_NAME)
|
||||||
|
?.let { name -> LauncherName.entries.firstOrNull { it.name == name } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun CalendarSettings.toJson(): JsonObject = buildJsonObject {
|
||||||
|
put(KEY_ACCOUNT_NAME, JsonPrimitive(calendar.accountName))
|
||||||
|
put(KEY_ACCOUNT_TYPE, JsonPrimitive(calendar.accountType))
|
||||||
|
put(KEY_DISPLAY_NAME, JsonPrimitive(calendar.displayName))
|
||||||
|
calendar.specialDates?.let { put(KEY_SPECIAL_DATES, JsonPrimitive(it.name)) }
|
||||||
|
if (hidden) put(KEY_HIDDEN, JsonPrimitive(true))
|
||||||
|
if (lastUsed) put(KEY_LAST_USED, JsonPrimitive(true))
|
||||||
|
eventDurationMinutes?.let { put(KEY_EVENT_DURATION, JsonPrimitive(it)) }
|
||||||
|
reminders?.let { put(KEY_REMINDERS, JsonArray(it.map(::JsonPrimitive))) }
|
||||||
|
allDayReminders?.let { put(KEY_ALL_DAY_REMINDERS, JsonArray(it.map(::JsonPrimitive))) }
|
||||||
|
if (hiddenInViews.isNotEmpty()) {
|
||||||
|
put(KEY_HIDDEN_IN_VIEWS, JsonArray(hiddenInViews.sortedBy { it.ordinal }.map { JsonPrimitive(it.name) }))
|
||||||
|
}
|
||||||
|
if (!notifications) put(KEY_NOTIFICATIONS, JsonPrimitive(false))
|
||||||
|
alertStyle?.let { put(KEY_ALERT_STYLE, JsonPrimitive(it.storageValue)) }
|
||||||
|
when (val fixed = fixedTimeReminder) {
|
||||||
|
FixedTimeOverride.Inherit -> Unit
|
||||||
|
FixedTimeOverride.Off -> put(KEY_FIXED_TIME_REMINDER, JsonPrimitive(FIXED_TIME_OFF))
|
||||||
|
is FixedTimeOverride.At -> put(KEY_FIXED_TIME_REMINDER, JsonPrimitive(fixed.reminder.toToken()))
|
||||||
|
}
|
||||||
|
if (!inDailyDigest) put(KEY_IN_DAILY_DIGEST, JsonPrimitive(false))
|
||||||
|
autoBackup?.let { put(KEY_AUTO_BACKUP, JsonPrimitive(it)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Strict about what it reads. A special-dates type this build doesn't know
|
||||||
|
* reads as an ordinary calendar, which then simply finds no match.
|
||||||
|
*/
|
||||||
|
private fun JsonObject.toCalendarSettings(): CalendarSettings {
|
||||||
|
return CalendarSettings(
|
||||||
|
calendar = CalendarIdentity(
|
||||||
|
accountName = requireString(KEY_ACCOUNT_NAME),
|
||||||
|
accountType = requireString(KEY_ACCOUNT_TYPE),
|
||||||
|
displayName = requireString(KEY_DISPLAY_NAME),
|
||||||
|
specialDates = optString(KEY_SPECIAL_DATES)?.let { name -> SpecialDateType.entries.firstOrNull { it.name == name } },
|
||||||
|
),
|
||||||
|
hidden = optBoolean(KEY_HIDDEN) ?: false,
|
||||||
|
lastUsed = optBoolean(KEY_LAST_USED) ?: false,
|
||||||
|
eventDurationMinutes = optInt(KEY_EVENT_DURATION),
|
||||||
|
reminders = optIntList(KEY_REMINDERS)?.cleanReminders(),
|
||||||
|
allDayReminders = optIntList(KEY_ALL_DAY_REMINDERS)?.cleanReminders(),
|
||||||
|
hiddenInViews = optStringList(KEY_HIDDEN_IN_VIEWS).orEmpty()
|
||||||
|
.mapNotNullTo(mutableSetOf()) { name -> CalendarView.entries.firstOrNull { it.name == name } },
|
||||||
|
notifications = optBoolean(KEY_NOTIFICATIONS) ?: true,
|
||||||
|
alertStyle = optString(KEY_ALERT_STYLE)?.let(ReminderAlertStyle::fromStorage)
|
||||||
|
?.takeUnless { it == ReminderAlertStyle.Notification },
|
||||||
|
fixedTimeReminder = when (val token = optString(KEY_FIXED_TIME_REMINDER)) {
|
||||||
|
null -> FixedTimeOverride.Inherit
|
||||||
|
FIXED_TIME_OFF -> FixedTimeOverride.Off
|
||||||
|
else -> FixedTimeReminder.parse(token)?.let(FixedTimeOverride::At) ?: FixedTimeOverride.Inherit
|
||||||
|
},
|
||||||
|
inDailyDigest = optBoolean(KEY_IN_DAILY_DIGEST) ?: true,
|
||||||
|
autoBackup = optBoolean(KEY_AUTO_BACKUP),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** As the reminder setters store them: no negative leads, each once, ascending. */
|
||||||
|
private fun List<Int>.cleanReminders(): List<Int> = filter { it >= 0 }.distinct().sorted()
|
||||||
|
|
||||||
|
private const val KEY_SETTINGS = "settings"
|
||||||
|
private const val KEY_CALENDARS = "calendars"
|
||||||
|
private const val KEY_APP = "app"
|
||||||
|
private const val KEY_LANGUAGE = "language"
|
||||||
|
private const val KEY_LAUNCHER_NAME = "launcher_name"
|
||||||
|
private const val KEY_ACCOUNT_NAME = "account_name"
|
||||||
|
private const val KEY_ACCOUNT_TYPE = "account_type"
|
||||||
|
private const val KEY_DISPLAY_NAME = "display_name"
|
||||||
|
private const val KEY_SPECIAL_DATES = "special_dates"
|
||||||
|
private const val KEY_HIDDEN = "hidden"
|
||||||
|
private const val KEY_LAST_USED = "last_used"
|
||||||
|
private const val KEY_EVENT_DURATION = "event_duration_minutes"
|
||||||
|
private const val KEY_REMINDERS = "reminders"
|
||||||
|
private const val KEY_ALL_DAY_REMINDERS = "all_day_reminders"
|
||||||
|
private const val KEY_HIDDEN_IN_VIEWS = "hidden_in_views"
|
||||||
|
private const val KEY_NOTIFICATIONS = "notifications"
|
||||||
|
private const val KEY_ALERT_STYLE = "alert_style"
|
||||||
|
private const val KEY_FIXED_TIME_REMINDER = "fixed_time_reminder"
|
||||||
|
private const val FIXED_TIME_OFF = "off"
|
||||||
|
private const val KEY_IN_DAILY_DIGEST = "in_daily_digest"
|
||||||
|
private const val KEY_AUTO_BACKUP = "auto_backup"
|
||||||
@@ -0,0 +1,233 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.data.backup
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.util.Log
|
||||||
|
import androidx.datastore.core.DataStore
|
||||||
|
import androidx.datastore.preferences.core.Preferences
|
||||||
|
import androidx.datastore.preferences.core.edit
|
||||||
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
|
import de.jeanlucmakiola.calendula.BuildConfig
|
||||||
|
import de.jeanlucmakiola.calendula.R
|
||||||
|
import de.jeanlucmakiola.calendula.data.appname.LauncherNameManager
|
||||||
|
import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource
|
||||||
|
import de.jeanlucmakiola.calendula.data.contacts.ContactSpecialDatesDataSource
|
||||||
|
import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesScheduler
|
||||||
|
import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesSyncEngine
|
||||||
|
import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesSyncResult
|
||||||
|
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||||
|
import de.jeanlucmakiola.calendula.data.prefs.SpecialDatesStalledReason
|
||||||
|
import de.jeanlucmakiola.calendula.data.fonts.CustomFontStore
|
||||||
|
import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys
|
||||||
|
import de.jeanlucmakiola.calendula.data.reminders.ReminderScanner
|
||||||
|
import de.jeanlucmakiola.calendula.domain.FontRole
|
||||||
|
import de.jeanlucmakiola.calendula.widget.requestWidgetRedraw
|
||||||
|
import de.jeanlucmakiola.floret.backup.BackupProblem
|
||||||
|
import de.jeanlucmakiola.floret.backup.BackupResult
|
||||||
|
import de.jeanlucmakiola.floret.di.IoDispatcher
|
||||||
|
import de.jeanlucmakiola.floret.locale.AppLanguage
|
||||||
|
import de.jeanlucmakiola.floret.prefs.get
|
||||||
|
import de.jeanlucmakiola.floret.prefs.rawValue
|
||||||
|
import de.jeanlucmakiola.floret.reminders.reminderOverrideFor
|
||||||
|
import kotlinx.coroutines.CancellationException
|
||||||
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.NonCancellable
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Exports and imports Calendula's settings (#481). The file format and what
|
||||||
|
* it holds are [SettingsBackupSchema]'s; the import is planned purely by
|
||||||
|
* [planSettingsImport], written in one DataStore edit, and then followed by
|
||||||
|
* the side effects the settings screens would have run themselves.
|
||||||
|
*/
|
||||||
|
@Singleton
|
||||||
|
class SettingsBackupEngine @Inject constructor(
|
||||||
|
private val store: DataStore<Preferences>,
|
||||||
|
private val calendars: CalendarDataSource,
|
||||||
|
private val contacts: ContactSpecialDatesDataSource,
|
||||||
|
private val specialDates: SpecialDatesSyncEngine,
|
||||||
|
private val settingsPrefs: SettingsPrefs,
|
||||||
|
private val reminderScanner: ReminderScanner,
|
||||||
|
private val launcherNames: LauncherNameManager,
|
||||||
|
@ApplicationContext private val context: Context,
|
||||||
|
@IoDispatcher private val io: CoroutineDispatcher,
|
||||||
|
) {
|
||||||
|
|
||||||
|
suspend fun export(): String = withContext(io) {
|
||||||
|
val supported = supportedLanguages()
|
||||||
|
val snapshot = store.data.first()
|
||||||
|
// Without the list the per-calendar settings would silently drop out of the file.
|
||||||
|
val list = if (snapshot.hasCalendarSettings()) calendars.calendars() else emptyList()
|
||||||
|
val backup = buildSettingsBackup(
|
||||||
|
snapshot = snapshot,
|
||||||
|
calendars = list,
|
||||||
|
managed = if (list.any { it.isManaged }) calendars.findManagedCalendars() else emptyList(),
|
||||||
|
language = LanguageChoice(AppLanguage.currentTag(context, supported)),
|
||||||
|
launcherName = launcherNames.current(),
|
||||||
|
)
|
||||||
|
encodeSettingsBackup(backup, System.currentTimeMillis(), BuildConfig.VERSION_NAME)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Validates [text] in full, then replaces the settings; nothing is written for an invalid file. */
|
||||||
|
suspend fun import(text: String): BackupResult<SettingsImportSummary> = withContext(io) {
|
||||||
|
val backup = when (val decoded = decodeSettingsBackup(text)) {
|
||||||
|
is BackupResult.Failure -> return@withContext decoded
|
||||||
|
is BackupResult.Success -> decoded.value
|
||||||
|
}
|
||||||
|
val current = store.data.first()
|
||||||
|
val supported = supportedLanguages()
|
||||||
|
val environment = environment(current, backup, supported)
|
||||||
|
val plan = planSettingsImport(backup, current, environment)
|
||||||
|
val existingMirrors = environment.managed.map { it.id }.toSet()
|
||||||
|
// Once the write starts, the side effects have to follow it, whoever cancels.
|
||||||
|
withContext(NonCancellable) {
|
||||||
|
try {
|
||||||
|
store.edit { plan.applyTo(it) }
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "Settings import could not be written", e)
|
||||||
|
return@withContext BackupResult.Failure(BackupProblem.NOT_APPLIED, e.message.orEmpty())
|
||||||
|
}
|
||||||
|
val lateSkips = afterImport(plan, current, supported, existingMirrors)
|
||||||
|
BackupResult.Success(plan.summary(plan.calendars.orEmpty().size + lateSkips.matched, lateSkips.skipped))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private class LateMatches(val matched: Int, val skipped: List<SkippedSetting>)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Brings what reads the settings outside DataStore in line: the mirror,
|
||||||
|
* reminder alarms, scheduled backups, the launcher alias and the language.
|
||||||
|
* Each step stands alone, so one failing never undoes the import.
|
||||||
|
*/
|
||||||
|
private suspend fun afterImport(
|
||||||
|
plan: SettingsImportPlan,
|
||||||
|
before: Preferences,
|
||||||
|
supported: List<String>,
|
||||||
|
existingMirrors: Set<Long>,
|
||||||
|
): LateMatches {
|
||||||
|
val after = store.data.first()
|
||||||
|
val wasMirroring = before[SettingsKeys.specialDatesEnabled]
|
||||||
|
val mirroring = after[SettingsKeys.specialDatesEnabled]
|
||||||
|
var late = LateMatches(0, plan.pendingSpecialDates.map { it.calendar.skipped() })
|
||||||
|
step("special dates") {
|
||||||
|
if (mirroring) {
|
||||||
|
SpecialDatesScheduler.apply(context, enabled = true)
|
||||||
|
val result = specialDates.sync()
|
||||||
|
if (result != SpecialDatesSyncResult.Disabled) {
|
||||||
|
val stalled = SpecialDatesStalledReason.PermissionRevoked
|
||||||
|
.takeIf { result == SpecialDatesSyncResult.PermissionMissing }
|
||||||
|
settingsPrefs.recordSpecialDatesRun(System.currentTimeMillis(), stalled)
|
||||||
|
}
|
||||||
|
late = matchSpecialDates(plan, before, existingMirrors, synced = result == SpecialDatesSyncResult.Success)
|
||||||
|
} else if (wasMirroring) {
|
||||||
|
SpecialDatesScheduler.apply(context, enabled = false)
|
||||||
|
specialDates.teardown()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
step("reminders") { reminderScanner.scan() }
|
||||||
|
step("auto backup") { BackupScheduler.reconcile(context, settingsPrefs) }
|
||||||
|
plan.launcherName?.let { name ->
|
||||||
|
step("launcher name") { if (launcherNames.current() != name) launcherNames.set(name) }
|
||||||
|
}
|
||||||
|
plan.language?.let { choice ->
|
||||||
|
step("language") {
|
||||||
|
if (AppLanguage.currentTag(context, supported) != choice.tag) {
|
||||||
|
withContext(Dispatchers.Main) { AppLanguage.apply(context, choice.tag) }
|
||||||
|
requestWidgetRedraw(context)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return late
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gives late-created mirror calendars their entries (only after a
|
||||||
|
* successful [synced] run), then rewrites each mirror whose all-day
|
||||||
|
* reminders differ from what its events carry: the pre-import override for
|
||||||
|
* a calendar that already existed, the sync's seed for a new one. A mirror
|
||||||
|
* the file doesn't override inherits again.
|
||||||
|
*/
|
||||||
|
private suspend fun matchSpecialDates(
|
||||||
|
plan: SettingsImportPlan,
|
||||||
|
before: Preferences,
|
||||||
|
existingMirrors: Set<Long>,
|
||||||
|
synced: Boolean,
|
||||||
|
): LateMatches {
|
||||||
|
val managed = calendars.findManagedCalendars()
|
||||||
|
val skipped = mutableListOf<SkippedSetting>()
|
||||||
|
var matched = 0
|
||||||
|
val resolved = if (!synced) {
|
||||||
|
skipped += plan.pendingSpecialDates.map { it.calendar.skipped() }
|
||||||
|
emptyList()
|
||||||
|
} else {
|
||||||
|
plan.pendingSpecialDates.mapNotNull { entry ->
|
||||||
|
val id = managed.firstOrNull { it.type == entry.calendar.specialDates }?.id
|
||||||
|
if (id == null) skipped += entry.calendar.skipped() else matched++
|
||||||
|
id?.let { it to entry }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (resolved.isNotEmpty()) {
|
||||||
|
store.edit { prefs ->
|
||||||
|
resolved.forEach { (id, entry) -> prefs.addCalendarSettings(id, entry.copy(allDayReminders = null)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (plan.calendars != null) {
|
||||||
|
val wanted = (plan.calendars.values + resolved.map { it.second })
|
||||||
|
.mapNotNull { entry -> entry.calendar.specialDates?.let { it to entry.allDayReminders } }
|
||||||
|
.toMap()
|
||||||
|
val carried = before[SettingsKeys.perCalendarAllDayReminderOverride]
|
||||||
|
val seeded = store.data.first()[SettingsKeys.perCalendarAllDayReminderOverride]
|
||||||
|
managed.distinctBy { it.type }.forEach { (id, type) ->
|
||||||
|
val minutes = wanted[type]
|
||||||
|
val onEvents = if (id in existingMirrors) carried[id] else seeded[id]
|
||||||
|
if (onEvents == minutes) return@forEach
|
||||||
|
val desired = minutes?.let { mapOf(id to it) }.orEmpty()
|
||||||
|
specialDates.applyReminders(type, desired.reminderOverrideFor(id))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return LateMatches(matched, skipped)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The highest byte count [import] is worth reading. */
|
||||||
|
val maxImportBytes: Int get() = SettingsBackupSchema.format.maxChars
|
||||||
|
|
||||||
|
private fun environment(
|
||||||
|
current: Preferences,
|
||||||
|
backup: SettingsBackup,
|
||||||
|
supported: List<String>,
|
||||||
|
): ImportEnvironment = ImportEnvironment(
|
||||||
|
// An empty list here is a failed read as far as the import can tell, never "wipe them all".
|
||||||
|
calendars = if (backup.calendars.isEmpty()) {
|
||||||
|
emptyList()
|
||||||
|
} else {
|
||||||
|
runCatching { calendars.calendars() }.getOrNull()?.takeIf { it.isNotEmpty() }
|
||||||
|
},
|
||||||
|
managed = runCatching { calendars.findManagedCalendars() }.getOrDefault(emptyList()),
|
||||||
|
contactsPermission = contacts.hasPermission(),
|
||||||
|
customFonts = FontRole.entries.filter { CustomFontStore.exists(context, it) }.toSet(),
|
||||||
|
hasBackupFolder = current[SettingsKeys.autoBackupFolderUri] != null,
|
||||||
|
supportedLanguages = supported,
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun Preferences.hasCalendarSettings(): Boolean =
|
||||||
|
SettingsBackupSchema.perCalendar.any { rawValue(it) != null }
|
||||||
|
|
||||||
|
private fun supportedLanguages(): List<String> = AppLanguage.supportedTags(context, R.xml.locales_config)
|
||||||
|
|
||||||
|
private suspend fun step(name: String, block: suspend () -> Unit) {
|
||||||
|
try {
|
||||||
|
block()
|
||||||
|
} catch (e: CancellationException) {
|
||||||
|
throw e
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "Settings import: $name could not be refreshed", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val TAG = "SettingsBackup"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.data.backup
|
||||||
|
|
||||||
|
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefKeys
|
||||||
|
import de.jeanlucmakiola.calendula.data.prefs.ReminderStateKeys
|
||||||
|
import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys
|
||||||
|
import de.jeanlucmakiola.floret.backup.BackupFormat
|
||||||
|
import de.jeanlucmakiola.floret.prefs.Pref
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Which stored keys a settings backup carries (#481), and how. Every key of
|
||||||
|
* the settings store is in exactly one of the three lists; a test holds that,
|
||||||
|
* so a new setting cannot ship without deciding. See docs/SETTINGS_BACKUP.md.
|
||||||
|
*/
|
||||||
|
internal object SettingsBackupSchema {
|
||||||
|
|
||||||
|
val format = BackupFormat(name = "calendula-settings", version = 1)
|
||||||
|
|
||||||
|
/** Carried as stored and restored over the current value; an absent key restores the default. */
|
||||||
|
val plain: List<Pref<*>> = listOf(
|
||||||
|
SettingsKeys.themeMode,
|
||||||
|
SettingsKeys.dynamicColor,
|
||||||
|
SettingsKeys.weekStart,
|
||||||
|
SettingsKeys.softenCalendarColors,
|
||||||
|
SettingsKeys.brandFont,
|
||||||
|
SettingsKeys.plainFont,
|
||||||
|
SettingsKeys.timeFormat,
|
||||||
|
SettingsKeys.showHourGrid,
|
||||||
|
SettingsKeys.pastEventDisplay,
|
||||||
|
SettingsKeys.dimCompletedEvents,
|
||||||
|
SettingsKeys.showWeekNumbers,
|
||||||
|
SettingsKeys.monthShowStartTimes,
|
||||||
|
SettingsKeys.monthViewStyle,
|
||||||
|
SettingsKeys.timelineScale,
|
||||||
|
SettingsKeys.multiDayCount,
|
||||||
|
SettingsKeys.timelineHoursEnabled,
|
||||||
|
SettingsKeys.timelineHoursStart,
|
||||||
|
SettingsKeys.timelineHoursEnd,
|
||||||
|
SettingsKeys.todayButtonInToolbar,
|
||||||
|
SettingsKeys.dragToReschedule,
|
||||||
|
SettingsKeys.tapOpensEditor,
|
||||||
|
SettingsKeys.agendaScreenRange,
|
||||||
|
SettingsKeys.agendaShowRangeBar,
|
||||||
|
SettingsKeys.agendaShowToday,
|
||||||
|
SettingsKeys.defaultView,
|
||||||
|
SettingsKeys.quickSwitchConfig,
|
||||||
|
SettingsKeys.drawerViewOrder,
|
||||||
|
SettingsKeys.defaultFormFields,
|
||||||
|
SettingsKeys.autofocusEventTitle,
|
||||||
|
// Names its calendar by account and display name, so it finds it again on another device.
|
||||||
|
SettingsKeys.defaultNewEventCalendar,
|
||||||
|
SettingsKeys.defaultEventDurationMinutes,
|
||||||
|
SettingsKeys.remindersEnabled,
|
||||||
|
SettingsKeys.allowColorOnUnsupportedCalendars,
|
||||||
|
SettingsKeys.defaultReminderMinutes,
|
||||||
|
SettingsKeys.defaultAllDayReminderMinutes,
|
||||||
|
SettingsKeys.allDayReminderTimeMinutes,
|
||||||
|
SettingsKeys.snoozeMinutes,
|
||||||
|
SettingsKeys.defaultFixedTimeReminder,
|
||||||
|
SettingsKeys.dailyDigestEnabled,
|
||||||
|
SettingsKeys.dailyDigestTimeMinutes,
|
||||||
|
SettingsKeys.dailyDigestDay,
|
||||||
|
SettingsKeys.autoBackupEnabled,
|
||||||
|
SettingsKeys.autoBackupIntervalMinutes,
|
||||||
|
SettingsKeys.autoBackupCombinedStored,
|
||||||
|
SettingsKeys.autoBackupKeep,
|
||||||
|
SettingsKeys.autoBackupOnChange,
|
||||||
|
SettingsKeys.specialDatesEnabled,
|
||||||
|
SettingsKeys.specialDatesShowYear,
|
||||||
|
) + SettingsKeys.specialDateTypeEnabled.values + SettingsKeys.specialDatesTitleTemplate.values
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keyed by calendar id on disk, so carried per calendar under a portable
|
||||||
|
* identity instead ([CalendarSettings]) and re-keyed to this device's ids.
|
||||||
|
*/
|
||||||
|
val perCalendar: List<Pref<*>> = listOf(
|
||||||
|
CalendarPrefKeys.hiddenCalendarIds,
|
||||||
|
CalendarPrefKeys.lastUsedCalendarId,
|
||||||
|
SettingsKeys.perCalendarEventDuration,
|
||||||
|
SettingsKeys.perCalendarReminderOverride,
|
||||||
|
SettingsKeys.perCalendarAllDayReminderOverride,
|
||||||
|
SettingsKeys.perCalendarHiddenViews,
|
||||||
|
SettingsKeys.mutedReminderCalendarIds,
|
||||||
|
SettingsKeys.reminderAlertStyles,
|
||||||
|
SettingsKeys.perCalendarFixedTimeReminderOverride,
|
||||||
|
SettingsKeys.digestExcludedCalendarIds,
|
||||||
|
SettingsKeys.autoBackupIncluded,
|
||||||
|
SettingsKeys.autoBackupExcluded,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Never exported: this install's own state, bookkeeping, or meaningless on another device. */
|
||||||
|
val excluded: List<Pref<*>> = (
|
||||||
|
listOf(
|
||||||
|
// Cache-busting counters for the locally imported font file.
|
||||||
|
SettingsKeys.brandFontStamp,
|
||||||
|
SettingsKeys.plainFontStamp,
|
||||||
|
// Legacy defaults for unconfigured widgets; widget configuration stays out.
|
||||||
|
SettingsKeys.agendaWidgetRange,
|
||||||
|
SettingsKeys.widgetSize,
|
||||||
|
// Usage history, not a setting.
|
||||||
|
SettingsKeys.recentTimeZones,
|
||||||
|
SettingsKeys.recentFixedTimeReminders,
|
||||||
|
// A dismissed hint of this install.
|
||||||
|
SettingsKeys.notificationCategoryHintDismissed,
|
||||||
|
// This device's notification channels.
|
||||||
|
SettingsKeys.reminderChannelVersions,
|
||||||
|
// Sync-request grants of this device's accounts.
|
||||||
|
CalendarPrefKeys.syncAccessDismissed,
|
||||||
|
// First-run wizard progress of this install.
|
||||||
|
SettingsKeys.onboardingWizardArmed,
|
||||||
|
CalendarPrefKeys.visibilityNoticePending,
|
||||||
|
// A SAF grant, which does not survive a reinstall or another device.
|
||||||
|
SettingsKeys.autoBackupFolderUri,
|
||||||
|
// Run status.
|
||||||
|
SettingsKeys.autoBackupLastRun,
|
||||||
|
SettingsKeys.autoBackupLastSuccess,
|
||||||
|
SettingsKeys.autoBackupFailures,
|
||||||
|
SettingsKeys.specialDatesLastRun,
|
||||||
|
SettingsKeys.specialDatesStalled,
|
||||||
|
SettingsKeys.specialDatesLastForegroundSync,
|
||||||
|
SettingsKeys.dailyDigestArmedAt,
|
||||||
|
ReminderStateKeys.lastDigestDay,
|
||||||
|
// What the automatic backup wrote to this install's folder.
|
||||||
|
SettingsKeys.autoBackupLedger,
|
||||||
|
SettingsKeys.autoBackupFingerprints,
|
||||||
|
// Switch-offs still owed to the provider on this device.
|
||||||
|
CalendarPrefKeys.pendingDisabledCalendarIds,
|
||||||
|
// The reminder delivery watermark.
|
||||||
|
ReminderStateKeys.lastScanMillis,
|
||||||
|
) +
|
||||||
|
SettingsKeys.onboardingDone.values +
|
||||||
|
// The mirror re-adopts its calendars by their provider marker.
|
||||||
|
SettingsKeys.specialDatesCalendarId.values
|
||||||
|
).distinct()
|
||||||
|
}
|
||||||
@@ -0,0 +1,234 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.data.backup
|
||||||
|
|
||||||
|
import androidx.datastore.preferences.core.MutablePreferences
|
||||||
|
import androidx.datastore.preferences.core.Preferences
|
||||||
|
import de.jeanlucmakiola.calendula.data.appname.LauncherName
|
||||||
|
import de.jeanlucmakiola.calendula.data.calendar.ManagedCalendarRow
|
||||||
|
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefKeys
|
||||||
|
import de.jeanlucmakiola.calendula.data.prefs.FixedTimeOverride
|
||||||
|
import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys
|
||||||
|
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||||
|
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||||
|
import de.jeanlucmakiola.calendula.domain.FontRole
|
||||||
|
import de.jeanlucmakiola.calendula.ui.theme.FONT_CUSTOM_TOKEN
|
||||||
|
import de.jeanlucmakiola.floret.locale.AppLanguage
|
||||||
|
import de.jeanlucmakiola.floret.prefs.Pref
|
||||||
|
import de.jeanlucmakiola.floret.prefs.get
|
||||||
|
import de.jeanlucmakiola.floret.prefs.rawValue
|
||||||
|
import de.jeanlucmakiola.floret.prefs.set
|
||||||
|
import de.jeanlucmakiola.floret.prefs.setRawValue
|
||||||
|
|
||||||
|
/** What this device can take of a backup, read before planning. */
|
||||||
|
data class ImportEnvironment(
|
||||||
|
/** Null when the calendar list can't be read: the per-calendar settings are then left alone. */
|
||||||
|
val calendars: List<CalendarSource>?,
|
||||||
|
val managed: List<ManagedCalendarRow>,
|
||||||
|
val contactsPermission: Boolean,
|
||||||
|
val customFonts: Set<FontRole>,
|
||||||
|
val hasBackupFolder: Boolean,
|
||||||
|
val supportedLanguages: List<String>,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Something in the file this device could not take, for the import summary. */
|
||||||
|
sealed interface SkippedSetting {
|
||||||
|
/** No calendar on this device matches the file's, or [ambiguous]ly more than one does. */
|
||||||
|
data class Calendar(
|
||||||
|
val displayName: String,
|
||||||
|
val accountName: String,
|
||||||
|
val ambiguous: Boolean = false,
|
||||||
|
) : SkippedSetting
|
||||||
|
|
||||||
|
/** The calendars couldn't be read, so the per-calendar settings were left as they are. */
|
||||||
|
data object CalendarsUnavailable : SkippedSetting
|
||||||
|
|
||||||
|
/** A custom font: the font file itself is not part of the backup. */
|
||||||
|
data class CustomFont(val role: FontRole) : SkippedSetting
|
||||||
|
|
||||||
|
/** Contact special dates were on, but this device hasn't granted the contacts permission. */
|
||||||
|
data object SpecialDates : SkippedSetting
|
||||||
|
|
||||||
|
/** Automatic backup was on, but its folder has to be chosen again here. */
|
||||||
|
data object AutoBackupFolder : SkippedSetting
|
||||||
|
|
||||||
|
/** The file's app language isn't one this build ships. */
|
||||||
|
data class Language(val tag: String) : SkippedSetting
|
||||||
|
}
|
||||||
|
|
||||||
|
data class SettingsImportSummary(
|
||||||
|
val calendarsMatched: Int,
|
||||||
|
val skipped: List<SkippedSetting>,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A validated backup laid onto this device: the stored values to write in one
|
||||||
|
* edit, the side effects the engine runs after it, and the summary.
|
||||||
|
* [calendars] null leaves the per-calendar keys untouched.
|
||||||
|
* [pendingSpecialDates] are mirror calendars that don't exist yet; the engine
|
||||||
|
* matches them once the mirror's sync has created them.
|
||||||
|
*/
|
||||||
|
data class SettingsImportPlan(
|
||||||
|
val prefs: Map<Pref<*>, Any?>,
|
||||||
|
val calendars: Map<Long, CalendarSettings>?,
|
||||||
|
val pendingSpecialDates: List<CalendarSettings>,
|
||||||
|
val language: LanguageChoice?,
|
||||||
|
val launcherName: LauncherName?,
|
||||||
|
val skipped: List<SkippedSetting>,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Plans an import that replaces every backed-up setting; see docs/SETTINGS_BACKUP.md. */
|
||||||
|
fun planSettingsImport(
|
||||||
|
backup: SettingsBackup,
|
||||||
|
current: Preferences,
|
||||||
|
environment: ImportEnvironment,
|
||||||
|
): SettingsImportPlan {
|
||||||
|
val skipped = mutableListOf<SkippedSetting>()
|
||||||
|
val prefs = backup.prefs.toMutableMap<Pref<*>, Any?>()
|
||||||
|
|
||||||
|
fun keepCurrent(pref: Pref<*>) {
|
||||||
|
prefs[pref] = current.rawValue(pref)
|
||||||
|
}
|
||||||
|
|
||||||
|
FontRole.entries.forEach { role ->
|
||||||
|
val pref = role.fontPref()
|
||||||
|
if (prefs[pref] == FONT_CUSTOM_TOKEN && role !in environment.customFonts) {
|
||||||
|
keepCurrent(pref)
|
||||||
|
skipped += SkippedSetting.CustomFont(role)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (prefs[SettingsKeys.specialDatesEnabled] == true && !environment.contactsPermission) {
|
||||||
|
keepCurrent(SettingsKeys.specialDatesEnabled)
|
||||||
|
skipped += SkippedSetting.SpecialDates
|
||||||
|
}
|
||||||
|
if (prefs[SettingsKeys.autoBackupEnabled] == true && !environment.hasBackupFolder) {
|
||||||
|
keepCurrent(SettingsKeys.autoBackupEnabled)
|
||||||
|
skipped += SkippedSetting.AutoBackupFolder
|
||||||
|
}
|
||||||
|
|
||||||
|
val language = backup.language?.let { choice ->
|
||||||
|
val tag = choice.tag ?: return@let choice
|
||||||
|
val resolved = AppLanguage.resolveTag(tag, environment.supportedLanguages)
|
||||||
|
if (resolved in environment.supportedLanguages) {
|
||||||
|
LanguageChoice(resolved)
|
||||||
|
} else {
|
||||||
|
skipped += SkippedSetting.Language(tag)
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The mirror's calendars are torn down when the imported settings leave it off.
|
||||||
|
val mirroring = prefs[SettingsKeys.specialDatesEnabled] == true
|
||||||
|
val available = environment.calendars
|
||||||
|
val calendars = linkedMapOf<Long, CalendarSettings>()
|
||||||
|
val pending = mutableListOf<CalendarSettings>()
|
||||||
|
if (available == null) {
|
||||||
|
if (backup.calendars.isNotEmpty()) skipped += SkippedSetting.CalendarsUnavailable
|
||||||
|
} else {
|
||||||
|
val repeated = backup.calendars.groupingBy { it.calendar }.eachCount().filterValues { it > 1 }.keys
|
||||||
|
backup.calendars.forEach { entry ->
|
||||||
|
val type = entry.calendar.specialDates
|
||||||
|
if (type != null) {
|
||||||
|
// The mirror only keeps calendars for the types the imported settings switch on.
|
||||||
|
val typeOn = prefs[SettingsKeys.specialDateTypeEnabled.getValue(type)] != false
|
||||||
|
if (!mirroring || !typeOn) return@forEach
|
||||||
|
val id = environment.managed.firstOrNull { it.type == type }?.id
|
||||||
|
if (id != null) calendars[id] = entry else pending += entry
|
||||||
|
return@forEach
|
||||||
|
}
|
||||||
|
if (entry.calendar in repeated) {
|
||||||
|
// Two calendars on the exporting phone that this one can't tell apart.
|
||||||
|
val reported = SkippedSetting.Calendar(entry.calendar.displayName, entry.calendar.accountName, ambiguous = true)
|
||||||
|
if (reported !in skipped) skipped += reported
|
||||||
|
return@forEach
|
||||||
|
}
|
||||||
|
val candidates = available.filter { !it.isManaged && it.matches(entry.calendar) }
|
||||||
|
when (candidates.size) {
|
||||||
|
1 -> calendars[candidates.single().id] = entry
|
||||||
|
else -> skipped += entry.calendar.skipped(ambiguous = candidates.size > 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return SettingsImportPlan(
|
||||||
|
prefs = prefs,
|
||||||
|
calendars = calendars.takeIf { available != null },
|
||||||
|
pendingSpecialDates = pending,
|
||||||
|
language = language,
|
||||||
|
launcherName = backup.launcherName,
|
||||||
|
skipped = skipped,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Writes the plan's stored values, replacing every backed-up setting and all per-calendar ones. */
|
||||||
|
fun SettingsImportPlan.applyTo(target: MutablePreferences) {
|
||||||
|
plainSection.apply(target, prefs)
|
||||||
|
calendars?.let(target::writeCalendarSettings)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Replaces the per-calendar keys with [calendars], by this device's ids. A
|
||||||
|
* last-used calendar only counts from the first entry claiming it.
|
||||||
|
*/
|
||||||
|
fun MutablePreferences.writeCalendarSettings(calendars: Map<Long, CalendarSettings>) {
|
||||||
|
SettingsBackupSchema.perCalendar.forEach { setRawValue(it, null) }
|
||||||
|
calendars.forEach { (id, entry) -> addCalendarSettings(id, entry) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Adds one late-matched calendar's settings to what [writeCalendarSettings] stored. */
|
||||||
|
fun MutablePreferences.addCalendarSettings(id: Long, entry: CalendarSettings) {
|
||||||
|
if (entry.hidden) this[CalendarPrefKeys.hiddenCalendarIds] = this[CalendarPrefKeys.hiddenCalendarIds] + id
|
||||||
|
if (entry.lastUsed && this[CalendarPrefKeys.lastUsedCalendarId] == null) {
|
||||||
|
this[CalendarPrefKeys.lastUsedCalendarId] = id
|
||||||
|
}
|
||||||
|
entry.eventDurationMinutes?.let {
|
||||||
|
this[SettingsKeys.perCalendarEventDuration] =
|
||||||
|
this[SettingsKeys.perCalendarEventDuration] + (id to it.clampDuration())
|
||||||
|
}
|
||||||
|
entry.reminders?.let {
|
||||||
|
this[SettingsKeys.perCalendarReminderOverride] = this[SettingsKeys.perCalendarReminderOverride] + (id to it)
|
||||||
|
}
|
||||||
|
entry.allDayReminders?.let {
|
||||||
|
this[SettingsKeys.perCalendarAllDayReminderOverride] =
|
||||||
|
this[SettingsKeys.perCalendarAllDayReminderOverride] + (id to it)
|
||||||
|
}
|
||||||
|
if (entry.hiddenInViews.isNotEmpty()) {
|
||||||
|
this[SettingsKeys.perCalendarHiddenViews] = this[SettingsKeys.perCalendarHiddenViews] + (id to entry.hiddenInViews)
|
||||||
|
}
|
||||||
|
if (!entry.notifications) this[SettingsKeys.mutedReminderCalendarIds] = this[SettingsKeys.mutedReminderCalendarIds] + id
|
||||||
|
entry.alertStyle?.let { this[SettingsKeys.reminderAlertStyles] = this[SettingsKeys.reminderAlertStyles] + (id to it) }
|
||||||
|
val fixed = when (val override = entry.fixedTimeReminder) {
|
||||||
|
FixedTimeOverride.Inherit -> null
|
||||||
|
FixedTimeOverride.Off -> id to null
|
||||||
|
is FixedTimeOverride.At -> id to override.reminder
|
||||||
|
}
|
||||||
|
fixed?.let {
|
||||||
|
this[SettingsKeys.perCalendarFixedTimeReminderOverride] = this[SettingsKeys.perCalendarFixedTimeReminderOverride] + it
|
||||||
|
}
|
||||||
|
if (!entry.inDailyDigest) this[SettingsKeys.digestExcludedCalendarIds] = this[SettingsKeys.digestExcludedCalendarIds] + id
|
||||||
|
when (entry.autoBackup) {
|
||||||
|
true -> this[SettingsKeys.autoBackupIncluded] = this[SettingsKeys.autoBackupIncluded] + id
|
||||||
|
false -> this[SettingsKeys.autoBackupExcluded] = this[SettingsKeys.autoBackupExcluded] + id
|
||||||
|
null -> Unit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun CalendarIdentity.skipped(ambiguous: Boolean = false): SkippedSetting =
|
||||||
|
SkippedSetting.Calendar(displayName, accountName, ambiguous)
|
||||||
|
|
||||||
|
fun SettingsImportPlan.summary(calendarsMatched: Int, more: List<SkippedSetting> = emptyList()) =
|
||||||
|
SettingsImportSummary(
|
||||||
|
calendarsMatched = calendarsMatched,
|
||||||
|
skipped = skipped + more,
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun CalendarSource.matches(identity: CalendarIdentity): Boolean =
|
||||||
|
accountType == identity.accountType &&
|
||||||
|
accountName == identity.accountName &&
|
||||||
|
displayName == identity.displayName
|
||||||
|
|
||||||
|
/** The same range the per-calendar duration setter clamps to. */
|
||||||
|
private fun Int.clampDuration(): Int = coerceIn(SettingsPrefs.MIN_EVENT_DURATION, SettingsPrefs.MAX_EVENT_DURATION)
|
||||||
|
|
||||||
|
private fun FontRole.fontPref(): Pref<String> = when (this) {
|
||||||
|
FontRole.BRAND -> SettingsKeys.brandFont
|
||||||
|
FontRole.PLAIN -> SettingsKeys.plainFont
|
||||||
|
}
|
||||||
+85
-17
@@ -1,11 +1,10 @@
|
|||||||
package de.jeanlucmakiola.calendula.data.calendar
|
package de.jeanlucmakiola.calendula.data.calendar
|
||||||
|
|
||||||
import java.time.Instant
|
import de.jeanlucmakiola.calendula.domain.reminders.allDayLeadDays
|
||||||
import java.time.LocalDate
|
import java.time.LocalDate
|
||||||
import java.time.LocalTime
|
import java.time.LocalTime
|
||||||
import java.time.ZoneId
|
import java.time.ZoneId
|
||||||
import java.time.ZoneOffset
|
import java.time.ZoneOffset
|
||||||
import java.time.temporal.ChronoUnit
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Translates an all-day reminder between the **semantic** lead time the UI
|
* Translates an all-day reminder between the **semantic** lead time the UI
|
||||||
@@ -32,9 +31,13 @@ private const val MILLIS_PER_MINUTE = 60_000L
|
|||||||
* event (a whole-day multiple; sub-day remainders are dropped), so it fires at
|
* event (a whole-day multiple; sub-day remainders are dropped), so it fires at
|
||||||
* [timeOfDayMinutes] (minutes from local midnight) in [zone]. The result may be
|
* [timeOfDayMinutes] (minutes from local midnight) in [zone]. The result may be
|
||||||
* **negative** — e.g. "at time of event" at 09:00 CEST encodes to −420, meaning
|
* **negative** — e.g. "at time of event" at 09:00 CEST encodes to −420, meaning
|
||||||
* the provider fires *after* DTSTART; this is valid and must not be clamped.
|
* the provider fires *after* DTSTART; this is valid and must not be clamped. The
|
||||||
* A negative [semanticMinutes] is the "provider default" sentinel and passes
|
* one negative it never is is [MINUTES_DEFAULT]: the sentinel and the encoding
|
||||||
* through unchanged.
|
* share a value space, so an encoding that lands on it is nudged one minute past
|
||||||
|
* it rather than being read back as "use the account default". That sentinel is
|
||||||
|
* also the one [semanticMinutes] that passes through unencoded — a lead time may
|
||||||
|
* itself be negative (a foreign row firing the day *after* the event), and
|
||||||
|
* waving those through would change when they fire.
|
||||||
*/
|
*/
|
||||||
internal fun toProviderAllDayMinutes(
|
internal fun toProviderAllDayMinutes(
|
||||||
semanticMinutes: Int,
|
semanticMinutes: Int,
|
||||||
@@ -42,29 +45,94 @@ internal fun toProviderAllDayMinutes(
|
|||||||
zone: ZoneId,
|
zone: ZoneId,
|
||||||
timeOfDayMinutes: Int,
|
timeOfDayMinutes: Int,
|
||||||
): Int {
|
): Int {
|
||||||
if (semanticMinutes < 0) return semanticMinutes
|
if (semanticMinutes == MINUTES_DEFAULT) return semanticMinutes
|
||||||
val utcMidnight = startDate.atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli()
|
val utcMidnight = startDate.atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli()
|
||||||
val fire = startDate.minusDays((semanticMinutes / MINUTES_PER_DAY).toLong())
|
val fire = startDate.minusDays((semanticMinutes / MINUTES_PER_DAY).toLong())
|
||||||
.atTime(LocalTime.of(timeOfDayMinutes / 60, timeOfDayMinutes % 60))
|
.atTime(LocalTime.of(timeOfDayMinutes / 60, timeOfDayMinutes % 60))
|
||||||
.atZone(zone).toInstant().toEpochMilli()
|
.atZone(zone).toInstant().toEpochMilli()
|
||||||
return ((utcMidnight - fire) / MILLIS_PER_MINUTE).toInt()
|
val raw = ((utcMidnight - fire) / MILLIS_PER_MINUTE).toInt()
|
||||||
|
return if (raw == MINUTES_DEFAULT) MINUTES_DEFAULT - 1 else raw
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A lead time as the whole days an all-day reminder actually fires at: the
|
||||||
|
* sub-day part is dropped, matching [toProviderAllDayMinutes]'s day count.
|
||||||
|
* [MINUTES_DEFAULT] passes through.
|
||||||
|
*/
|
||||||
|
internal fun wholeDayLeadMinutes(minutes: Int): Int =
|
||||||
|
if (minutes == MINUTES_DEFAULT) minutes else minutes / MINUTES_PER_DAY * MINUTES_PER_DAY
|
||||||
|
|
||||||
|
/** [wholeDayLeadMinutes] for a reminder list, merging lead times that land on the same day. */
|
||||||
|
internal fun wholeDayLeadTimes(minutes: List<Int>): List<Int> =
|
||||||
|
minutes.map(::wholeDayLeadMinutes).distinct().sorted()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The next date on or after [today] carrying [month]/[day] — the date to sample
|
||||||
|
* a yearly all-day reminder's UTC offset at. A managed birthday's DTSTART is an
|
||||||
|
* ancient anchor (1972 for year-less dates), a year whose timezone rules
|
||||||
|
* (pre-DST offsets) differ from today's; sampling the offset there skews every
|
||||||
|
* modern occurrence by hours. Sampling at the upcoming occurrence makes the
|
||||||
|
* stored offset correct for it and its neighbours (only ±1h DST drift remains,
|
||||||
|
* the inherent limit). Feb-29 skips forward to the next leap year.
|
||||||
|
*/
|
||||||
|
internal fun nextYearlyOccurrence(month: Int, day: Int, today: LocalDate): LocalDate {
|
||||||
|
var year = today.year
|
||||||
|
// A Feb-29 date is valid only every ~4 years; 8 tries always reaches one.
|
||||||
|
repeat(8) {
|
||||||
|
val candidate = runCatching { LocalDate.of(year, month, day) }.getOrNull()
|
||||||
|
if (candidate != null && !candidate.isBefore(today)) return candidate
|
||||||
|
year++
|
||||||
|
}
|
||||||
|
// Unreachable for real month/day inputs; fall back to the raw anchor.
|
||||||
|
return LocalDate.of(today.year, month, day)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The date an **imported** all-day event's reminder offset is sampled at.
|
||||||
|
*
|
||||||
|
* A one-off fires once, on its own date. A series' `DTSTART` is only an anchor
|
||||||
|
* and may be ancient — Fossify writes a year-less contact birthday at 1970, a
|
||||||
|
* year whose rules predate DST across most of Europe, and a real birth year is
|
||||||
|
* usually older still — so sampling there skews every modern occurrence by the
|
||||||
|
* offset delta (the same trap [nextYearlyOccurrence] exists for). A yearly
|
||||||
|
* series is therefore sampled at its next occurrence of the anchor's month/day,
|
||||||
|
* which shares the season; any other series at [today], which its upcoming
|
||||||
|
* occurrences are near.
|
||||||
|
*
|
||||||
|
* The decode side ([fromProviderAllDayMinutes]) only asks which local *day* the
|
||||||
|
* encoded instant falls on, so it still reads the lead time back correctly from
|
||||||
|
* the anchor's own date.
|
||||||
|
*/
|
||||||
|
internal fun importedAllDayReminderDate(
|
||||||
|
startDate: LocalDate,
|
||||||
|
recurrenceRule: String?,
|
||||||
|
today: LocalDate,
|
||||||
|
): LocalDate = when {
|
||||||
|
recurrenceRule.isNullOrBlank() -> startDate
|
||||||
|
recurrenceRule.contains("FREQ=YEARLY", ignoreCase = true) ->
|
||||||
|
nextYearlyOccurrence(startDate.monthValue, startDate.dayOfMonth, today)
|
||||||
|
startDate.isBefore(today) -> today
|
||||||
|
else -> startDate
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Recover the semantic whole-day lead time from a raw all-day reminder
|
* Recover the semantic whole-day lead time from a raw all-day reminder
|
||||||
* [rawMinutes]. Keys off the **local date** of the encoded fire instant, so it
|
* [rawMinutes] — the inverse of [toProviderAllDayMinutes], for the form and the
|
||||||
* returns the right day count regardless of which [timeOfDayMinutes] wrote the
|
* detail screen. Delegates to [allDayLeadDays], so the day displayed is the day
|
||||||
* row — including pre-feature rows (raw multiples of 1440, fired at UTC midnight)
|
* the reminder actually fires on.
|
||||||
* and rows written under a different timezone. A negative [rawMinutes] (fire
|
*
|
||||||
* after DTSTART) folds to day 0.
|
* [MINUTES_DEFAULT] passes through unchanged, the mirror of the encode side. A
|
||||||
|
* real encoding is often negative, so only that exact value may be treated as the
|
||||||
|
* sentinel — decoding it would land it on the start date and turn "use the
|
||||||
|
* account default" into a concrete at-start alarm.
|
||||||
*/
|
*/
|
||||||
internal fun fromProviderAllDayMinutes(
|
internal fun fromProviderAllDayMinutes(
|
||||||
rawMinutes: Int,
|
rawMinutes: Int,
|
||||||
startDate: LocalDate,
|
startDate: LocalDate,
|
||||||
zone: ZoneId,
|
zone: ZoneId,
|
||||||
): Int {
|
timeOfDayMinutes: Int,
|
||||||
val utcMidnight = startDate.atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli()
|
): Int = if (rawMinutes == MINUTES_DEFAULT) {
|
||||||
val fireLocalDate = Instant.ofEpochMilli(utcMidnight - rawMinutes * MILLIS_PER_MINUTE)
|
rawMinutes
|
||||||
.atZone(zone).toLocalDate()
|
} else {
|
||||||
return ChronoUnit.DAYS.between(fireLocalDate, startDate).toInt() * MINUTES_PER_DAY
|
allDayLeadDays(rawMinutes, startDate, zone, timeOfDayMinutes).toInt() * MINUTES_PER_DAY
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.data.calendar
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The colours offered when creating or editing a calendar; ARGB ints for a raw
|
||||||
|
* `CALENDAR_COLOR` / `EVENT_COLOR`.
|
||||||
|
*
|
||||||
|
* Hues rather than final fills: every surface that draws a calendar colour runs
|
||||||
|
* it through the app's own tone pass first, so these are chosen to stay
|
||||||
|
* distinguishable after it. Shared with Agendula, whose list palette these are —
|
||||||
|
* the two apps are the same family and a calendar and a task list picked from
|
||||||
|
* different-looking sets read as different products.
|
||||||
|
*
|
||||||
|
* The named entries exist for callers that need one specific hue (the managed
|
||||||
|
* special-dates calendars), so they can't drift from the swatches on offer.
|
||||||
|
*/
|
||||||
|
object CalendarColorPalette {
|
||||||
|
val Mauve = 0xFF7A5C6B.toInt()
|
||||||
|
val Red = 0xFFD7484A.toInt()
|
||||||
|
val Orange = 0xFFE8743B.toInt()
|
||||||
|
val Amber = 0xFFE0A32E.toInt()
|
||||||
|
val Olive = 0xFF7CA83E.toInt()
|
||||||
|
val Green = 0xFF35A06A.toInt()
|
||||||
|
val Teal = 0xFF19938C.toInt()
|
||||||
|
val Cyan = 0xFF2A9BC4.toInt()
|
||||||
|
val Blue = 0xFF3C74C8.toInt()
|
||||||
|
val Indigo = 0xFF6A5CC0.toInt()
|
||||||
|
val Purple = 0xFF9455B8.toInt()
|
||||||
|
val Pink = 0xFFC94F8E.toInt()
|
||||||
|
|
||||||
|
/** The full palette, in swatch-grid order. */
|
||||||
|
val all: List<Int> = listOf(
|
||||||
|
Mauve, Red, Orange, Amber, Olive, Green,
|
||||||
|
Teal, Cyan, Blue, Indigo, Purple, Pink,
|
||||||
|
)
|
||||||
|
}
|
||||||
+1082
-269
File diff suppressed because it is too large.
Load diff
@@ -8,8 +8,9 @@ internal fun ColumnReader.toCalendarSource(): CalendarSource {
|
|||||||
val isLocal = accountType == CalendarContract.ACCOUNT_TYPE_LOCAL
|
val isLocal = accountType == CalendarContract.ACCOUNT_TYPE_LOCAL
|
||||||
return CalendarSource(
|
return CalendarSource(
|
||||||
id = getLong(CalendarProjection.IDX_ID),
|
id = getLong(CalendarProjection.IDX_ID),
|
||||||
displayName = getString(CalendarProjection.IDX_DISPLAY_NAME)
|
// Blank when the provider row has no name: the placeholder is a display
|
||||||
?: Fallbacks.UNNAMED_CALENDAR,
|
// string and belongs to the UI, where it can be localised (#329).
|
||||||
|
displayName = getString(CalendarProjection.IDX_DISPLAY_NAME).orEmpty(),
|
||||||
accountName = getString(CalendarProjection.IDX_ACCOUNT_NAME).orEmpty(),
|
accountName = getString(CalendarProjection.IDX_ACCOUNT_NAME).orEmpty(),
|
||||||
accountType = accountType,
|
accountType = accountType,
|
||||||
color = getInt(CalendarProjection.IDX_COLOR),
|
color = getInt(CalendarProjection.IDX_COLOR),
|
||||||
@@ -24,5 +25,15 @@ internal fun ColumnReader.toCalendarSource(): CalendarSource {
|
|||||||
} else {
|
} else {
|
||||||
null
|
null
|
||||||
},
|
},
|
||||||
|
// A special-dates mirror calendar, recognised by its durable CAL_SYNC2
|
||||||
|
// marker (only meaningful on the local calendars the app owns). This is
|
||||||
|
// the source of truth for the editor lock — independent of any stored
|
||||||
|
// preference that a backup restore could have wiped.
|
||||||
|
isManaged = isLocal &&
|
||||||
|
getString(CalendarProjection.IDX_MANAGED_MARKER)
|
||||||
|
?.startsWith(CalendarProjection.MANAGED_MARKER_PREFIX) == true,
|
||||||
|
// NULL is treated as syncing — the harmless default.
|
||||||
|
syncsEvents = isNull(CalendarProjection.IDX_SYNC_EVENTS) ||
|
||||||
|
getInt(CalendarProjection.IDX_SYNC_EVENTS) != 0,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
+114
-13
@@ -5,27 +5,40 @@ import de.jeanlucmakiola.calendula.domain.EventColorOption
|
|||||||
import de.jeanlucmakiola.calendula.domain.EventDetail
|
import de.jeanlucmakiola.calendula.domain.EventDetail
|
||||||
import de.jeanlucmakiola.calendula.domain.EventForm
|
import de.jeanlucmakiola.calendula.domain.EventForm
|
||||||
import de.jeanlucmakiola.calendula.domain.EventInstance
|
import de.jeanlucmakiola.calendula.domain.EventInstance
|
||||||
|
import de.jeanlucmakiola.calendula.domain.SearchCandidate
|
||||||
import de.jeanlucmakiola.calendula.domain.ics.IcsEvent
|
import de.jeanlucmakiola.calendula.domain.ics.IcsEvent
|
||||||
import de.jeanlucmakiola.calendula.domain.ics.IcsImportSummary
|
import de.jeanlucmakiola.calendula.domain.ics.IcsImportSummary
|
||||||
import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent
|
import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
import kotlinx.coroutines.flow.emptyFlow
|
||||||
|
import kotlinx.coroutines.flow.flowOf
|
||||||
import kotlin.time.Instant
|
import kotlin.time.Instant
|
||||||
|
|
||||||
interface CalendarRepository {
|
interface CalendarRepository {
|
||||||
fun calendars(): Flow<List<CalendarSource>>
|
fun calendars(): Flow<List<CalendarSource>>
|
||||||
fun instances(range: ClosedRange<Instant>): Flow<List<EventInstance>>
|
fun instances(range: ClosedRange<Instant>): Flow<List<EventInstance>>
|
||||||
|
|
||||||
|
/** One read of event [eventId]'s occurrences overlapping [range], soonest first, whatever calendar it is in. */
|
||||||
|
suspend fun eventOccurrences(eventId: Long, range: ClosedRange<Instant>): List<EventInstance>
|
||||||
|
|
||||||
|
/** Re-query every open [calendars] / [instances] flow. */
|
||||||
|
fun refresh()
|
||||||
|
|
||||||
|
/** Emits on the app's own writes and visibility changes; not on provider notifications or [refresh]. */
|
||||||
|
val localChanges: Flow<Unit>
|
||||||
|
|
||||||
suspend fun eventDetail(eventId: Long): EventDetail
|
suspend fun eventDetail(eventId: Long): EventDetail
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Events whose title, description or location contains [query], with hidden
|
* Candidate matches for [query] with hidden calendars removed; empty when
|
||||||
* calendars removed and newest first. Empty when [query] is blank. Searches
|
* [query] is blank. Searches the whole history/future and leaves matching
|
||||||
* the whole history/future (see [CalendarDataSource.searchEvents]).
|
* and ranking to [de.jeanlucmakiola.calendula.domain.EventSearch].
|
||||||
*/
|
*/
|
||||||
suspend fun searchEvents(query: String): List<EventInstance>
|
suspend fun searchEvents(query: String): List<SearchCandidate>
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The event-colour palette a calendar's account publishes; empty when it
|
* The event-colour palette a calendar's account publishes; empty when it
|
||||||
* exposes none (see [CalendarDataSource.eventColorPalette]).
|
* exposes none (see [CalendarDataSource.publishedEventColors]).
|
||||||
*/
|
*/
|
||||||
suspend fun eventColorPalette(calendarId: Long): List<EventColorOption>
|
suspend fun eventColorPalette(calendarId: Long): List<EventColorOption>
|
||||||
|
|
||||||
@@ -39,17 +52,51 @@ interface CalendarRepository {
|
|||||||
suspend fun deleteCalendar(id: Long)
|
suspend fun deleteCalendar(id: Long)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Every event of the writable local calendars, ready to serialise into a
|
* Show or hide [ids] device-wide (`Calendars.VISIBLE`), which also gates
|
||||||
* whole-calendar `.ics` backup (see [CalendarDataSource.exportableEvents]).
|
* their reminders — see [CalendarDataSource.setCalendarVisible]. Written one
|
||||||
|
* at a time, in order; a failure part-way leaves the earlier writes standing.
|
||||||
|
*
|
||||||
|
* Without `WRITE_CALENDAR` the choice is kept app-side instead (see
|
||||||
|
* [de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs.pendingDisabledCalendarIds]).
|
||||||
*/
|
*/
|
||||||
suspend fun exportEvents(): List<IcsEvent>
|
suspend fun setCalendarsVisible(ids: Collection<Long>, visible: Boolean)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Every event of [calendarIds], ready to serialise into an `.ics` backup
|
||||||
|
* (see [CalendarDataSource.calendarRows]). Any calendar can be read,
|
||||||
|
* synced and read-only ones included (#147). Exception rows come out
|
||||||
|
* flattened ([de.jeanlucmakiola.calendula.domain.ics.flattenOverrides]),
|
||||||
|
* so a restore keeps moved and deleted occurrences of a series.
|
||||||
|
*/
|
||||||
|
suspend fun exportEvents(calendarIds: Set<Long>): List<IcsEvent>
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Bulk-import parsed `.ics` [events] into [targetCalendarId]. Events whose
|
* Bulk-import parsed `.ics` [events] into [targetCalendarId]. Events whose
|
||||||
* UID already exists in the target are skipped (idempotent restore); the
|
* UID already exists in the target are skipped (idempotent restore); the
|
||||||
* rest are inserted. See [CalendarDataSource.insertImportedEvent].
|
* rest are inserted, as is a standalone occurrence whose series is already
|
||||||
|
* there ([ParsedIcsEvent.overrideOf]). See [CalendarDataSource.insertImportedEvent].
|
||||||
|
* [onProgress] gets the count of events handled so far before each event
|
||||||
|
* after the first and once more when all were handled; it may throw to stop
|
||||||
|
* the import between events.
|
||||||
*/
|
*/
|
||||||
suspend fun importEvents(targetCalendarId: Long, events: List<ParsedIcsEvent>): IcsImportSummary
|
suspend fun importEvents(
|
||||||
|
targetCalendarId: Long,
|
||||||
|
events: List<ParsedIcsEvent>,
|
||||||
|
onProgress: (done: Int) -> Unit = {},
|
||||||
|
): IcsImportSummary
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Copy every event of [sourceCalendarId] into [targetCalendarId] (#325),
|
||||||
|
* exceptions included (see
|
||||||
|
* [de.jeanlucmakiola.calendula.domain.ics.planCalendarCopy]). The source is only read. Runs
|
||||||
|
* through [importEvents], so a re-run skips what an earlier one copied.
|
||||||
|
* [onProgress] gets (done, total) once the source is read and after each event.
|
||||||
|
*/
|
||||||
|
suspend fun copyEvents(
|
||||||
|
sourceCalendarId: Long,
|
||||||
|
targetCalendarId: Long,
|
||||||
|
onProgress: (done: Int, total: Int) -> Unit = { _, _ -> },
|
||||||
|
): IcsImportSummary
|
||||||
|
|
||||||
/** Create a new event from a validated form; returns the new `Events._ID`. */
|
/** Create a new event from a validated form; returns the new `Events._ID`. */
|
||||||
suspend fun createEvent(form: EventForm): Long
|
suspend fun createEvent(form: EventForm): Long
|
||||||
@@ -61,10 +108,36 @@ interface CalendarRepository {
|
|||||||
suspend fun updateEvent(eventId: Long, original: EventForm, updated: EventForm)
|
suspend fun updateEvent(eventId: Long, original: EventForm, updated: EventForm)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Change a single occurrence of a recurring event (exception row with the
|
* Move an event (recurring: the whole series, with its exceptions) to
|
||||||
* form's values); returns the exception's `Events._ID`.
|
* [targetCalendarId] and apply the [original]→[updated] field edits; returns
|
||||||
|
* the new event's `Events._ID`. Copy+delete under the hood
|
||||||
|
* (see [CalendarDataSource.moveEvent]) — `CALENDAR_ID` can't be updated in
|
||||||
|
* place.
|
||||||
*/
|
*/
|
||||||
suspend fun updateOccurrence(eventId: Long, beginMillis: Long, form: EventForm): Long
|
suspend fun moveEvent(
|
||||||
|
eventId: Long,
|
||||||
|
targetCalendarId: Long,
|
||||||
|
original: EventForm,
|
||||||
|
updated: EventForm,
|
||||||
|
): Long
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Change a single occurrence of a recurring event (exception row with the
|
||||||
|
* form's values); returns the exception's `Events._ID`. [original] is what
|
||||||
|
* the row holds now, for the case where it turns out not to recur.
|
||||||
|
*/
|
||||||
|
suspend fun updateOccurrence(
|
||||||
|
eventId: Long,
|
||||||
|
beginMillis: Long,
|
||||||
|
original: EventForm,
|
||||||
|
form: EventForm,
|
||||||
|
): Long
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Every series split the app makes ([updateEventFromOccurrence]), so what
|
||||||
|
* follows a series by id can move on to the part that continues it.
|
||||||
|
*/
|
||||||
|
val seriesSplits: Flow<SeriesSplit> get() = emptyFlow()
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Change a recurring event from [beginMillis] onwards (series split);
|
* Change a recurring event from [beginMillis] onwards (series split);
|
||||||
@@ -85,6 +158,31 @@ interface CalendarRepository {
|
|||||||
|
|
||||||
/** Delete a recurring event from the occurrence at [beginMillis] onwards. */
|
/** Delete a recurring event from the occurrence at [beginMillis] onwards. */
|
||||||
suspend fun deleteEventFromOccurrence(eventId: Long, beginMillis: Long)
|
suspend fun deleteEventFromOccurrence(eventId: Long, beginMillis: Long)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ask every account behind a visible synced calendar to sync now (#240).
|
||||||
|
* Only a request: the adapter may still run it late, or fail.
|
||||||
|
*/
|
||||||
|
suspend fun requestSync(): SyncRequest = SyncRequest(SyncRequestResult.NothingToSync)
|
||||||
|
|
||||||
|
/** Wait for the syncs a [requestSync] reached to run, see [awaitSyncs]. */
|
||||||
|
suspend fun awaitSyncs(accounts: Set<SyncAccount>): SyncWait = SyncWait.Unconfirmed
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The accounts behind visible calendars with a sync adapter, split by
|
||||||
|
* whether [requestSync] can reach them yet. Account access isn't observable:
|
||||||
|
* it is re-read on each collection and on every [refreshSyncAccess].
|
||||||
|
*/
|
||||||
|
val syncTargets: Flow<SyncTargets> get() = flowOf(SyncTargets.None)
|
||||||
|
|
||||||
|
/** Re-read account access for every [syncTargets] collector; it can change outside the app. */
|
||||||
|
fun refreshSyncAccess() {}
|
||||||
|
|
||||||
|
/** Stop or resume asking for [account]'s sync-request access. */
|
||||||
|
suspend fun setSyncAccessDismissed(account: SyncAccount, dismissed: Boolean) {}
|
||||||
|
|
||||||
|
/** Every provider notification and [refresh], including the app's own writes. */
|
||||||
|
val providerChanges: Flow<Unit> get() = emptyFlow()
|
||||||
}
|
}
|
||||||
|
|
||||||
class NoSuchEventException(eventId: Long) :
|
class NoSuchEventException(eventId: Long) :
|
||||||
@@ -93,3 +191,6 @@ class NoSuchEventException(eventId: Long) :
|
|||||||
/** A ContentResolver write affected no rows or returned no URI. */
|
/** A ContentResolver write affected no rows or returned no URI. */
|
||||||
class WriteFailedException(operation: String) :
|
class WriteFailedException(operation: String) :
|
||||||
RuntimeException("Calendar write failed: $operation")
|
RuntimeException("Calendar write failed: $operation")
|
||||||
|
|
||||||
|
/** A "this and following" edit: [oldEventId] now ends where [newEventId] picks up. */
|
||||||
|
data class SeriesSplit(val oldEventId: Long, val newEventId: Long)
|
||||||
+453
-56
@@ -1,25 +1,43 @@
|
|||||||
package de.jeanlucmakiola.calendula.data.calendar
|
package de.jeanlucmakiola.calendula.data.calendar
|
||||||
|
|
||||||
import de.jeanlucmakiola.calendula.data.di.IoDispatcher
|
import android.util.Log
|
||||||
|
import de.jeanlucmakiola.floret.di.IoDispatcher
|
||||||
|
import de.jeanlucmakiola.floret.time.toEpochMillis
|
||||||
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
|
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
|
||||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||||
|
import de.jeanlucmakiola.calendula.domain.curatedForPicker
|
||||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||||
import de.jeanlucmakiola.calendula.domain.EventColorOption
|
import de.jeanlucmakiola.calendula.domain.EventColorOption
|
||||||
import de.jeanlucmakiola.calendula.domain.EventDetail
|
import de.jeanlucmakiola.calendula.domain.EventDetail
|
||||||
import de.jeanlucmakiola.calendula.domain.EventForm
|
import de.jeanlucmakiola.calendula.domain.EventForm
|
||||||
import de.jeanlucmakiola.calendula.domain.EventInstance
|
import de.jeanlucmakiola.calendula.domain.EventInstance
|
||||||
|
import de.jeanlucmakiola.calendula.domain.SearchCandidate
|
||||||
import de.jeanlucmakiola.calendula.domain.ics.IcsImportSummary
|
import de.jeanlucmakiola.calendula.domain.ics.IcsImportSummary
|
||||||
import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent
|
import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent
|
||||||
|
import de.jeanlucmakiola.calendula.domain.ics.flattenOverrides
|
||||||
|
import de.jeanlucmakiola.calendula.domain.ics.planCalendarCopy
|
||||||
import kotlinx.coroutines.CoroutineDispatcher
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
|
import kotlinx.coroutines.channels.BufferOverflow
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||||
|
import kotlinx.coroutines.flow.update
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.combine
|
import kotlinx.coroutines.flow.combine
|
||||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||||
|
import kotlinx.coroutines.flow.drop
|
||||||
import kotlinx.coroutines.flow.first
|
import kotlinx.coroutines.flow.first
|
||||||
import kotlinx.coroutines.flow.flow
|
import kotlinx.coroutines.flow.flow
|
||||||
import kotlinx.coroutines.flow.flowOn
|
import kotlinx.coroutines.flow.flowOn
|
||||||
|
import kotlinx.coroutines.flow.map
|
||||||
|
import kotlinx.coroutines.flow.merge
|
||||||
import kotlinx.coroutines.flow.onStart
|
import kotlinx.coroutines.flow.onStart
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
import kotlinx.coroutines.CancellationException
|
||||||
|
import kotlinx.coroutines.currentCoroutineContext
|
||||||
|
import kotlinx.coroutines.ensureActive
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
|
import java.util.concurrent.atomic.AtomicLong
|
||||||
import kotlin.time.Instant
|
import kotlin.time.Instant
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
@@ -35,75 +53,335 @@ class CalendarRepositoryImpl @Inject constructor(
|
|||||||
private val prefs: CalendarPrefs,
|
private val prefs: CalendarPrefs,
|
||||||
private val settingsPrefs: SettingsPrefs,
|
private val settingsPrefs: SettingsPrefs,
|
||||||
@IoDispatcher private val io: CoroutineDispatcher,
|
@IoDispatcher private val io: CoroutineDispatcher,
|
||||||
|
private val syncRequester: SyncRequester,
|
||||||
) : CalendarRepository {
|
) : CalendarRepository {
|
||||||
|
|
||||||
/** The configured wall-clock fire time for all-day reminders, read per write. */
|
/** The configured wall-clock fire time for all-day reminders, read per write. */
|
||||||
private suspend fun allDayReminderTimeMinutes(): Int =
|
private suspend fun allDayReminderTimeMinutes(): Int =
|
||||||
settingsPrefs.allDayReminderTimeMinutes.first()
|
settingsPrefs.allDayReminderTimeMinutes.first()
|
||||||
|
|
||||||
|
// DROP_OLDEST: tryEmit never fails, so a tick that lands while a subscriber
|
||||||
|
// still holds the previous one is never lost (#364).
|
||||||
private val ticks = MutableSharedFlow<Unit>(
|
private val ticks = MutableSharedFlow<Unit>(
|
||||||
replay = 0,
|
replay = 0,
|
||||||
extraBufferCapacity = 1,
|
extraBufferCapacity = 1,
|
||||||
|
onBufferOverflow = BufferOverflow.DROP_OLDEST,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bumped on every [refresh], so one tick's calendar read can be
|
||||||
|
* shared by everything that needs it (see [calendarsSnapshot]).
|
||||||
|
*/
|
||||||
|
private val generation = AtomicLong(0L)
|
||||||
|
|
||||||
init {
|
init {
|
||||||
dataSource.registerChangeListener { ticks.tryEmit(Unit) }
|
dataSource.registerChangeListener(::refresh)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun calendars(): Flow<List<CalendarSource>> =
|
// Writes re-query on their own too: some providers never notify the
|
||||||
ticks
|
// observer, which left every view stale until a restart (#364).
|
||||||
.onStart { emit(Unit) }
|
override fun refresh() {
|
||||||
.reQuery { dataSource.calendars() }
|
generation.incrementAndGet()
|
||||||
.flowOn(io)
|
ticks.tryEmit(Unit)
|
||||||
|
}
|
||||||
|
|
||||||
// Instances are filtered by the app-side hidden ∪ disabled calendar sets
|
private val writes = MutableSharedFlow<Unit>(
|
||||||
// (M3): an event is dropped whenever the user has hidden *or* disabled its
|
replay = 0,
|
||||||
// calendar. Re-runs when the provider ticks *or* either set changes —
|
extraBufferCapacity = 1,
|
||||||
// toggling a calendar in the filter sheet or the calendar manager updates
|
onBufferOverflow = BufferOverflow.DROP_OLDEST,
|
||||||
// every view immediately. [calendars] stays unfiltered so those screens can
|
|
||||||
// list and re-enable hidden/disabled calendars.
|
|
||||||
override fun instances(range: ClosedRange<Instant>): Flow<List<EventInstance>> =
|
|
||||||
combine(
|
|
||||||
ticks
|
|
||||||
.onStart { emit(Unit) }
|
|
||||||
.reQuery {
|
|
||||||
dataSource.instances(
|
|
||||||
beginMillis = range.start.toEpochMillis(),
|
|
||||||
endMillis = range.endInclusive.toEpochMillis(),
|
|
||||||
)
|
)
|
||||||
},
|
|
||||||
prefs.hiddenCalendarIds,
|
override val providerChanges: Flow<Unit> get() = ticks
|
||||||
prefs.disabledCalendarIds,
|
|
||||||
) { instances, hidden, disabled ->
|
/**
|
||||||
val excluded = hidden + disabled
|
* Run a provider write on [io], then re-query whether or not it threw. The
|
||||||
if (excluded.isEmpty()) instances
|
* accounts behind [syncCalendars] (read before the write, which may delete
|
||||||
else instances.filterNot { it.calendarId in excluded }
|
* the row) then get one sync nudge each (#303), also after a failure, which
|
||||||
|
* may have landed part of a multi-row write. Once per write, so a multi-row
|
||||||
|
* save or a whole import asks once per account.
|
||||||
|
*/
|
||||||
|
private suspend fun <T> write(
|
||||||
|
syncCalendars: suspend () -> Collection<Long?>,
|
||||||
|
block: suspend () -> T,
|
||||||
|
): T = withContext(io) {
|
||||||
|
val accounts = syncAccountsOf(syncCalendars)
|
||||||
|
try {
|
||||||
|
block()
|
||||||
|
} finally {
|
||||||
|
refresh()
|
||||||
|
writes.tryEmit(Unit)
|
||||||
|
requestSyncs(accounts, userInitiated = false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private val noSync: suspend () -> Collection<Long?> = { emptyList() }
|
||||||
|
|
||||||
|
private suspend fun syncAccountsOf(calendarIds: suspend () -> Collection<Long?>): Set<SyncAccount> =
|
||||||
|
try {
|
||||||
|
calendarIds().filterNotNull().distinct()
|
||||||
|
.mapNotNull { accountOf(it) }
|
||||||
|
.withAdapter()
|
||||||
|
} catch (e: CancellationException) {
|
||||||
|
throw e
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "No sync nudge: the calendar account could not be read", e)
|
||||||
|
emptySet()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** From the shared per-tick read; a calendar newer than it is read on its own. */
|
||||||
|
private suspend fun accountOf(calendarId: Long): SyncAccount? =
|
||||||
|
calendarsSnapshot().firstOrNull { it.id == calendarId }
|
||||||
|
?.let { SyncAccount(it.accountName, it.accountType) }
|
||||||
|
?: dataSource.calendarAccount(calendarId)
|
||||||
|
|
||||||
|
/** The syncable accounts among these whose type has a calendar sync adapter. */
|
||||||
|
private fun Collection<SyncAccount>.withAdapter(): Set<SyncAccount> {
|
||||||
|
val candidates = filter { it.isSyncable }
|
||||||
|
if (candidates.isEmpty()) return emptySet()
|
||||||
|
val adapterTypes = try {
|
||||||
|
syncRequester.adapterAccountTypes()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "Sync adapters unreadable", e)
|
||||||
|
return emptySet()
|
||||||
|
}
|
||||||
|
return candidates.filterTo(linkedSetOf()) { it.type in adapterTypes }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Splits [accounts] by whether a request may name them (see
|
||||||
|
* [SyncRequester.addressableAccounts]). The rest wait for the user's grant:
|
||||||
|
* an account-less request would reach them, but also every other calendar
|
||||||
|
* account on the device, so none is sent.
|
||||||
|
*/
|
||||||
|
private fun reach(accounts: Set<SyncAccount>): SyncTargets {
|
||||||
|
if (accounts.isEmpty()) return SyncTargets.None
|
||||||
|
// Unreadable access counts as reachable: a grant can't fix a failing read.
|
||||||
|
val addressable = try {
|
||||||
|
syncRequester.addressableAccounts(accounts.mapTo(mutableSetOf()) { it.type })
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "Account visibility unreadable", e)
|
||||||
|
null
|
||||||
|
}
|
||||||
|
if (addressable == null) return SyncTargets(reachable = accounts, needsAccess = emptySet())
|
||||||
|
val (reachable, hidden) = accounts.partition { it in addressable }
|
||||||
|
return SyncTargets(reachable.toSet(), hidden.toSet())
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ask each reachable one of [accounts] once. */
|
||||||
|
private fun requestSyncs(accounts: Set<SyncAccount>, userInitiated: Boolean) {
|
||||||
|
reach(accounts).reachable.forEach { requestSync(it, userInitiated) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun requestSync(account: SyncAccount, userInitiated: Boolean): Boolean = try {
|
||||||
|
syncRequester.requestSync(account, userInitiated)
|
||||||
|
true
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "Sync request refused", e)
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The event's own calendar (from [original] when given, else read), plus [others]. */
|
||||||
|
private fun eventCalendar(
|
||||||
|
eventId: Long,
|
||||||
|
original: EventForm? = null,
|
||||||
|
vararg others: Long?,
|
||||||
|
): suspend () -> Collection<Long?> =
|
||||||
|
{ listOf(original?.calendarId ?: dataSource.eventCalendarId(eventId), *others) }
|
||||||
|
|
||||||
|
private fun targetsOf(calendars: List<CalendarSource>, dismissed: Set<SyncAccount>): SyncTargets =
|
||||||
|
reach(
|
||||||
|
calendars.syncAccounts().withAdapter()
|
||||||
|
.sortedWith(compareBy({ it.name.lowercase() }, { it.type }))
|
||||||
|
.toSet(),
|
||||||
|
).let {
|
||||||
|
if (dismissed.isEmpty()) {
|
||||||
|
it
|
||||||
|
} else {
|
||||||
|
it.copy(needsAccess = it.needsAccess - dismissed, dismissed = it.needsAccess intersect dismissed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private val accessChecks = MutableStateFlow(0)
|
||||||
|
|
||||||
|
override val syncTargets: Flow<SyncTargets>
|
||||||
|
get() = combine(calendars(), prefs.syncAccessDismissed, accessChecks) { calendars, dismissed, _ ->
|
||||||
|
// One failed read leaves the rows off until the next change, not for good.
|
||||||
|
try {
|
||||||
|
targetsOf(calendars, dismissed)
|
||||||
|
} catch (e: CancellationException) {
|
||||||
|
throw e
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "Sync targets unreadable", e)
|
||||||
|
SyncTargets.None
|
||||||
|
}
|
||||||
|
}.flowOn(io)
|
||||||
|
|
||||||
|
override fun refreshSyncAccess() {
|
||||||
|
accessChecks.update { it + 1 }
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun setSyncAccessDismissed(account: SyncAccount, dismissed: Boolean) {
|
||||||
|
try {
|
||||||
|
prefs.setSyncAccessDismissed(account, dismissed)
|
||||||
|
} catch (e: CancellationException) {
|
||||||
|
throw e
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "Sync access dismissal not saved", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun requestSync(): SyncRequest = withContext(io) {
|
||||||
|
val targets = try {
|
||||||
|
targetsOf(calendars().first(), prefs.syncAccessDismissed.first())
|
||||||
|
} catch (e: CancellationException) {
|
||||||
|
throw e
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "Sync request skipped: calendars unreadable", e)
|
||||||
|
return@withContext SyncRequest(SyncRequestResult.Failed)
|
||||||
|
}
|
||||||
|
if (targets.reachable.isEmpty()) {
|
||||||
|
return@withContext SyncRequest(
|
||||||
|
if (targets.needsAccess.isEmpty()) SyncRequestResult.NothingToSync else SyncRequestResult.NeedsAccess,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
val sent = targets.reachable.filterTo(linkedSetOf()) { requestSync(it, userInitiated = true) }
|
||||||
|
val result = when {
|
||||||
|
sent.isEmpty() -> SyncRequestResult.Failed
|
||||||
|
sent.size < targets.reachable.size -> SyncRequestResult.PartlyFailed
|
||||||
|
targets.needsAccess.isNotEmpty() -> SyncRequestResult.SomeNeedAccess
|
||||||
|
else -> SyncRequestResult.Requested
|
||||||
|
}
|
||||||
|
SyncRequest(result, sent)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun awaitSyncs(accounts: Set<SyncAccount>): SyncWait =
|
||||||
|
withContext(io) { syncRequester.awaitSyncs(accounts) }
|
||||||
|
|
||||||
|
override val localChanges: Flow<Unit> = merge(
|
||||||
|
writes,
|
||||||
|
prefs.pendingDisabledCalendarIds.distinctUntilChanged().drop(1).map {},
|
||||||
|
prefs.hiddenCalendarIds.distinctUntilChanged().drop(1).map {},
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Re-query signal for everything filtered by visibility: the provider's own
|
||||||
|
* notifications, plus every change to the pending switch-off set.
|
||||||
|
*/
|
||||||
|
private fun visibilityTicks(): Flow<Unit> = merge(
|
||||||
|
ticks.onStart { emit(Unit) },
|
||||||
|
// drop(1): the current value is already covered by the tick above.
|
||||||
|
prefs.pendingDisabledCalendarIds.drop(1).map {},
|
||||||
|
)
|
||||||
|
|
||||||
|
// A switch-off not yet written to the provider is folded into the flag
|
||||||
|
// itself, so every consumer reads one visibility (#75). The reconciler goes
|
||||||
|
// to the data source directly — it needs the provider's own answer.
|
||||||
|
override fun calendars(): Flow<List<CalendarSource>> =
|
||||||
|
visibilityTicks().reQuery {
|
||||||
|
val calendars = calendarsSnapshot()
|
||||||
|
val pendingDisabled = prefs.pendingDisabledCalendarIds.first()
|
||||||
|
if (pendingDisabled.isEmpty()) calendars
|
||||||
|
else calendars.map {
|
||||||
|
if (it.id in pendingDisabled) it.copy(isVisibleInSystem = false) else it
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// hidden and disabled both derive from one DataStore, so toggling
|
|
||||||
// either makes both re-emit and combine briefly surfaces the same
|
|
||||||
// list twice — collapse the duplicate so views don't re-render for it.
|
|
||||||
.distinctUntilChanged()
|
.distinctUntilChanged()
|
||||||
.flowOn(io)
|
.flowOn(io)
|
||||||
|
|
||||||
override suspend fun eventDetail(eventId: Long): EventDetail = withContext(io) {
|
// Instances are filtered by the system's VISIBLE flag ∪ the switch-offs
|
||||||
dataSource.eventDetail(eventId) ?: throw NoSuchEventException(eventId)
|
// still waiting to be written to it ∪ the app-side hidden set from the
|
||||||
|
// filter sheet. [calendars] stays unfiltered so those screens can list and
|
||||||
|
// re-enable invisible calendars.
|
||||||
|
override fun instances(range: ClosedRange<Instant>): Flow<List<EventInstance>> =
|
||||||
|
combine(
|
||||||
|
visibilityTicks().reQuery {
|
||||||
|
// All three reads in one pass, so a list of instances is never
|
||||||
|
// filtered against a visibility snapshot from another tick.
|
||||||
|
QueriedInstances(
|
||||||
|
instances = dataSource.instances(
|
||||||
|
beginMillis = range.start.toEpochMillis(),
|
||||||
|
endMillis = range.endInclusive.toEpochMillis(),
|
||||||
|
),
|
||||||
|
switchedOffCalendarIds = switchedOffCalendarIds(),
|
||||||
|
)
|
||||||
|
},
|
||||||
|
prefs.hiddenCalendarIds,
|
||||||
|
) { queried, hidden ->
|
||||||
|
val excluded = hidden + queried.switchedOffCalendarIds
|
||||||
|
if (excluded.isEmpty()) queried.instances
|
||||||
|
else queried.instances.filterNot { it.calendarId in excluded }
|
||||||
|
}
|
||||||
|
// Any DataStore edit re-emits the hidden set even when unchanged;
|
||||||
|
// collapse those so views don't re-render for them.
|
||||||
|
.distinctUntilChanged()
|
||||||
|
.flowOn(io)
|
||||||
|
|
||||||
|
/** One instances query plus the visibility it must be filtered against. */
|
||||||
|
private data class QueriedInstances(
|
||||||
|
val instances: List<EventInstance>,
|
||||||
|
val switchedOffCalendarIds: Set<Long>,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Calendars switched off at system level — hidden, and never reminded about. */
|
||||||
|
private suspend fun invisibleCalendarIds(): Set<Long> = calendarsSnapshot()
|
||||||
|
.filterNot { it.isVisibleInSystem }
|
||||||
|
.mapTo(mutableSetOf()) { it.id }
|
||||||
|
|
||||||
|
/** [invisibleCalendarIds] plus the switch-offs still waiting to be written. */
|
||||||
|
private suspend fun switchedOffCalendarIds(): Set<Long> =
|
||||||
|
invisibleCalendarIds() + prefs.pendingDisabledCalendarIds.first()
|
||||||
|
|
||||||
|
private val calendarsLock = Mutex()
|
||||||
|
private var cachedGeneration = -1L
|
||||||
|
private var cachedPending: Set<Long>? = null
|
||||||
|
private var cachedCalendars: List<CalendarSource> = emptyList()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The calendar list for the current tick, queried once and shared, so every
|
||||||
|
* open view doesn't pay for its own `Calendars` query and all of them see
|
||||||
|
* one snapshot.
|
||||||
|
*
|
||||||
|
* An empty result is never cached — that is what a read without the calendar
|
||||||
|
* permission returns, and the grant itself doesn't notify the provider. The
|
||||||
|
* pending switch-off set keys the cache alongside the tick, because an id
|
||||||
|
* leaves it before the invalidating observer is dispatched.
|
||||||
|
*/
|
||||||
|
private suspend fun calendarsSnapshot(): List<CalendarSource> = calendarsLock.withLock {
|
||||||
|
val current = generation.get()
|
||||||
|
val pending = prefs.pendingDisabledCalendarIds.first()
|
||||||
|
if (current != cachedGeneration || pending != cachedPending || cachedCalendars.isEmpty()) {
|
||||||
|
cachedCalendars = dataSource.calendars()
|
||||||
|
cachedGeneration = current
|
||||||
|
cachedPending = pending
|
||||||
|
}
|
||||||
|
cachedCalendars
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun searchEvents(query: String): List<EventInstance> = withContext(io) {
|
override suspend fun eventOccurrences(eventId: Long, range: ClosedRange<Instant>): List<EventInstance> =
|
||||||
|
withContext(io) {
|
||||||
|
dataSource.eventInstances(eventId, range.start.toEpochMillis(), range.endInclusive.toEpochMillis())
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun eventDetail(eventId: Long): EventDetail = withContext(io) {
|
||||||
|
dataSource.eventDetail(eventId, allDayReminderTimeMinutes())
|
||||||
|
?: throw NoSuchEventException(eventId)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun searchEvents(query: String): List<SearchCandidate> = withContext(io) {
|
||||||
if (query.isBlank()) return@withContext emptyList()
|
if (query.isBlank()) return@withContext emptyList()
|
||||||
val excluded = prefs.hiddenCalendarIds.first() + prefs.disabledCalendarIds.first()
|
val excluded = prefs.hiddenCalendarIds.first() + switchedOffCalendarIds()
|
||||||
dataSource.searchEvents(query)
|
dataSource.searchEvents(query)
|
||||||
.let { if (excluded.isEmpty()) it else it.filterNot { e -> e.calendarId in excluded } }
|
.let { if (excluded.isEmpty()) it else it.filterNot { c -> c.event.calendarId in excluded } }
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun eventColorPalette(calendarId: Long): List<EventColorOption> =
|
override suspend fun eventColorPalette(calendarId: Long): List<EventColorOption> =
|
||||||
withContext(io) { dataSource.eventColorPalette(calendarId) }
|
withContext(io) { dataSource.publishedEventColors(calendarId).curatedForPicker() }
|
||||||
|
|
||||||
override suspend fun createLocalCalendar(
|
override suspend fun createLocalCalendar(
|
||||||
displayName: String,
|
displayName: String,
|
||||||
color: Int,
|
color: Int,
|
||||||
description: String?,
|
description: String?,
|
||||||
): Long = withContext(io) {
|
): Long = write(noSync) {
|
||||||
dataSource.createLocalCalendar(displayName, color, description)
|
dataSource.createLocalCalendar(displayName, color, description)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -112,34 +390,116 @@ class CalendarRepositoryImpl @Inject constructor(
|
|||||||
displayName: String,
|
displayName: String,
|
||||||
color: Int,
|
color: Int,
|
||||||
description: String?,
|
description: String?,
|
||||||
) = withContext(io) { dataSource.updateCalendar(id, displayName, color, description) }
|
) = write(noSync) { dataSource.updateCalendar(id, displayName, color, description) }
|
||||||
|
|
||||||
override suspend fun deleteCalendar(id: Long) =
|
override suspend fun deleteCalendar(id: Long) =
|
||||||
withContext(io) { dataSource.deleteCalendar(id) }
|
write(noSync) { dataSource.deleteCalendar(id) }
|
||||||
|
|
||||||
override suspend fun exportEvents() = withContext(io) { dataSource.exportableEvents() }
|
override suspend fun setCalendarsVisible(ids: Collection<Long>, visible: Boolean) =
|
||||||
|
// VISIBLE is device-local: nothing for an adapter to upload.
|
||||||
|
write(noSync) {
|
||||||
|
val canWrite = dataSource.canWriteCalendars()
|
||||||
|
if (canWrite) ids.forEach { dataSource.setCalendarVisible(it, visible) }
|
||||||
|
// Nothing of ours is left waiting for the provider once the write
|
||||||
|
// lands, and switching one back on retires its entry. With read-only
|
||||||
|
// permission a switch-off still works, app-side, and the reconciler
|
||||||
|
// flushes it if WRITE_CALENDAR ever arrives.
|
||||||
|
if (canWrite || visible) {
|
||||||
|
prefs.removePendingDisabledCalendarIds(ids)
|
||||||
|
} else {
|
||||||
|
prefs.addPendingDisabledCalendarIds(ids)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun exportEvents(calendarIds: Set<Long>) = withContext(io) {
|
||||||
|
flattenOverrides(dataSource.calendarRows(calendarIds, allDayReminderTimeMinutes()), ::formatExdateStamp)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun copyEvents(
|
||||||
|
sourceCalendarId: Long,
|
||||||
|
targetCalendarId: Long,
|
||||||
|
onProgress: (done: Int, total: Int) -> Unit,
|
||||||
|
): IcsImportSummary {
|
||||||
|
val events = withContext(io) {
|
||||||
|
planCalendarCopy(
|
||||||
|
dataSource.calendarRows(setOf(sourceCalendarId), allDayReminderTimeMinutes()),
|
||||||
|
::formatExdateStamp,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
onProgress(0, events.size)
|
||||||
|
val context = currentCoroutineContext()
|
||||||
|
return importEvents(targetCalendarId, events) { done ->
|
||||||
|
if (done < events.size) context.ensureActive()
|
||||||
|
onProgress(done, events.size)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override suspend fun importEvents(
|
override suspend fun importEvents(
|
||||||
targetCalendarId: Long,
|
targetCalendarId: Long,
|
||||||
events: List<ParsedIcsEvent>,
|
events: List<ParsedIcsEvent>,
|
||||||
): IcsImportSummary = withContext(io) {
|
onProgress: (done: Int) -> Unit,
|
||||||
|
): IcsImportSummary = write({ listOf(targetCalendarId) }) {
|
||||||
val existing = dataSource.existingUids(targetCalendarId)
|
val existing = dataSource.existingUids(targetCalendarId)
|
||||||
|
// Both are per-calendar, not per-event: looking them up once keeps a
|
||||||
|
// thousand-event restore to two extra queries. The palette is the
|
||||||
|
// uncurated one — an imported colour is matched against every key the
|
||||||
|
// account accepts, not the subset the picker shows.
|
||||||
|
val palette = dataSource.publishedEventColors(targetCalendarId)
|
||||||
|
val allDayMinutes = allDayReminderTimeMinutes()
|
||||||
var imported = 0
|
var imported = 0
|
||||||
var skipped = 0
|
var skipped = 0
|
||||||
for (event in events) {
|
var failed = 0
|
||||||
|
var notAttempted = 0
|
||||||
|
// Occurrences whose standalone copy didn't land, by series UID: the series
|
||||||
|
// keeps them instead of excluding them for good.
|
||||||
|
val unexcluded = mutableMapOf<String, MutableList<Instant>>()
|
||||||
|
// Standalone occurrences ahead of the series they were cut from, however the file is ordered.
|
||||||
|
val ordered = events.sortedBy { it.overrideOf == null }
|
||||||
|
for ((index, event) in ordered.withIndex()) {
|
||||||
|
if (index > 0) onProgress(index)
|
||||||
// A known UID means the event is already in this calendar — skip,
|
// A known UID means the event is already in this calendar — skip,
|
||||||
// keeping a restore idempotent (no overwrite this pass).
|
// keeping a restore idempotent (no overwrite this pass).
|
||||||
if (event.uid != null && event.uid in existing) {
|
if (event.isAlreadyIn(existing)) {
|
||||||
skipped++
|
skipped++
|
||||||
} else {
|
continue
|
||||||
dataSource.insertImportedEvent(event, targetCalendarId)
|
}
|
||||||
|
try {
|
||||||
|
dataSource.insertImportedEvent(event.keeping(unexcluded), targetCalendarId, allDayMinutes, palette)
|
||||||
imported++
|
imported++
|
||||||
|
} catch (e: CancellationException) {
|
||||||
|
throw e
|
||||||
|
} catch (e: SecurityException) {
|
||||||
|
// Not this event's fault: the permission or the target calendar is
|
||||||
|
// gone, so every remaining insert would fail the same way.
|
||||||
|
Log.w(TAG, "Import stopped: the calendar is no longer writable", e)
|
||||||
|
// A known UID would have been skipped whatever happened, so it is
|
||||||
|
// no part of what a retry still has to import.
|
||||||
|
val remaining = ordered.drop(index)
|
||||||
|
val duplicates = remaining.count { it.isAlreadyIn(existing) }
|
||||||
|
skipped += duplicates
|
||||||
|
notAttempted = remaining.size - duplicates
|
||||||
|
break
|
||||||
|
} catch (e: Exception) {
|
||||||
|
// One event the provider won't take must not cost the user the
|
||||||
|
// rest of the file — foreign exports do carry rows it rejects
|
||||||
|
// outright (a malformed RRULE throws straight out of insert).
|
||||||
|
failed++
|
||||||
|
if (event.overrideOf != null && event.overrideAt != null) {
|
||||||
|
unexcluded.getOrPut(event.overrideOf) { mutableListOf() } += event.overrideAt
|
||||||
|
}
|
||||||
|
Log.w(TAG, "Skipped an unimportable event", e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
IcsImportSummary(imported = imported, skippedDuplicate = skipped)
|
if (notAttempted == 0) onProgress(events.size)
|
||||||
|
IcsImportSummary(
|
||||||
|
imported = imported,
|
||||||
|
skippedDuplicate = skipped,
|
||||||
|
failed = failed,
|
||||||
|
notAttempted = notAttempted,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun createEvent(form: EventForm): Long = withContext(io) {
|
override suspend fun createEvent(form: EventForm): Long = write({ listOf(form.calendarId) }) {
|
||||||
dataSource.insertEvent(form, allDayReminderTimeMinutes())
|
dataSource.insertEvent(form, allDayReminderTimeMinutes())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -147,20 +507,34 @@ class CalendarRepositoryImpl @Inject constructor(
|
|||||||
eventId: Long,
|
eventId: Long,
|
||||||
original: EventForm,
|
original: EventForm,
|
||||||
updated: EventForm,
|
updated: EventForm,
|
||||||
) = withContext(io) {
|
) = write(eventCalendar(eventId, original, updated.calendarId)) {
|
||||||
dataSource.updateEvent(eventId, original, updated, allDayReminderTimeMinutes())
|
dataSource.updateEvent(eventId, original, updated, allDayReminderTimeMinutes())
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun deleteEvent(eventId: Long) = withContext(io) {
|
override suspend fun deleteEvent(eventId: Long) = write(eventCalendar(eventId)) {
|
||||||
dataSource.deleteEvent(eventId)
|
dataSource.deleteEvent(eventId)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override suspend fun moveEvent(
|
||||||
|
eventId: Long,
|
||||||
|
targetCalendarId: Long,
|
||||||
|
original: EventForm,
|
||||||
|
updated: EventForm,
|
||||||
|
): Long = write(eventCalendar(eventId, original, targetCalendarId)) {
|
||||||
|
dataSource.moveEvent(
|
||||||
|
eventId, targetCalendarId, original, updated, allDayReminderTimeMinutes(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
override suspend fun updateOccurrence(
|
override suspend fun updateOccurrence(
|
||||||
eventId: Long,
|
eventId: Long,
|
||||||
beginMillis: Long,
|
beginMillis: Long,
|
||||||
|
original: EventForm,
|
||||||
form: EventForm,
|
form: EventForm,
|
||||||
): Long = withContext(io) {
|
): Long = write(eventCalendar(eventId, original)) {
|
||||||
dataSource.updateOccurrence(eventId, beginMillis, form, allDayReminderTimeMinutes())
|
dataSource.updateOccurrence(
|
||||||
|
eventId, beginMillis, original, form, allDayReminderTimeMinutes(),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun updateEventFromOccurrence(
|
override suspend fun updateEventFromOccurrence(
|
||||||
@@ -168,24 +542,47 @@ class CalendarRepositoryImpl @Inject constructor(
|
|||||||
beginMillis: Long,
|
beginMillis: Long,
|
||||||
original: EventForm,
|
original: EventForm,
|
||||||
updated: EventForm,
|
updated: EventForm,
|
||||||
): Long = withContext(io) {
|
): Long = write(eventCalendar(eventId, original)) {
|
||||||
dataSource.updateEventFromOccurrence(
|
dataSource.updateEventFromOccurrence(
|
||||||
eventId, beginMillis, original, updated, allDayReminderTimeMinutes(),
|
eventId, beginMillis, original, updated, allDayReminderTimeMinutes(),
|
||||||
)
|
)
|
||||||
}
|
}.also { newId -> if (newId != eventId) splits.tryEmit(SeriesSplit(eventId, newId)) }
|
||||||
|
|
||||||
override suspend fun deleteOccurrence(eventId: Long, beginMillis: Long) = withContext(io) {
|
private val splits = MutableSharedFlow<SeriesSplit>(extraBufferCapacity = 8)
|
||||||
|
|
||||||
|
override val seriesSplits: Flow<SeriesSplit> = splits
|
||||||
|
|
||||||
|
override suspend fun deleteOccurrence(eventId: Long, beginMillis: Long) = write(eventCalendar(eventId)) {
|
||||||
dataSource.deleteOccurrence(eventId, beginMillis)
|
dataSource.deleteOccurrence(eventId, beginMillis)
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun deleteEventFromOccurrence(
|
override suspend fun deleteEventFromOccurrence(
|
||||||
eventId: Long,
|
eventId: Long,
|
||||||
beginMillis: Long,
|
beginMillis: Long,
|
||||||
) = withContext(io) {
|
) = write(eventCalendar(eventId)) {
|
||||||
dataSource.deleteEventFromOccurrence(eventId, beginMillis)
|
dataSource.deleteEventFromOccurrence(eventId, beginMillis)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val TAG = "CalendarRepository"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun <T> Flow<Unit>.reQuery(block: suspend () -> T): Flow<T> = flow {
|
private fun <T> Flow<Unit>.reQuery(block: suspend () -> T): Flow<T> = flow {
|
||||||
collect { emit(block()) }
|
collect { emit(block()) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether [existing] UIDs already hold this event: its own UID, or — for a
|
||||||
|
* standalone occurrence of a backed-up or copied series — the series, which
|
||||||
|
* there carries the override itself.
|
||||||
|
*/
|
||||||
|
private fun ParsedIcsEvent.isAlreadyIn(existing: Set<String>): Boolean =
|
||||||
|
(uid != null && uid in existing) || (overrideOf != null && overrideOf in existing)
|
||||||
|
|
||||||
|
/** This series without the exclusions of [unexcluded] occurrences whose standalone copy failed. */
|
||||||
|
private fun ParsedIcsEvent.keeping(unexcluded: Map<String, List<Instant>>): ParsedIcsEvent {
|
||||||
|
val kept = uid?.let(unexcluded::get) ?: return this
|
||||||
|
val stamps = kept.map { formatExdateStamp(it.toEpochMilliseconds(), isAllDay) }.toSet()
|
||||||
|
return copy(exDates = exDates.filterNot { it in stamps })
|
||||||
|
}
|
||||||
+110
@@ -0,0 +1,110 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.data.calendar
|
||||||
|
|
||||||
|
import android.Manifest
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import android.util.Log
|
||||||
|
import dagger.hilt.EntryPoint
|
||||||
|
import dagger.hilt.InstallIn
|
||||||
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
|
import dagger.hilt.components.SingletonComponent
|
||||||
|
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
|
||||||
|
import de.jeanlucmakiola.calendula.domain.calendarVisibilityPlan
|
||||||
|
import de.jeanlucmakiola.calendula.domain.hasSystemHiddenCalendars
|
||||||
|
import de.jeanlucmakiola.floret.android.hasPermission
|
||||||
|
import de.jeanlucmakiola.floret.di.IoDispatcher
|
||||||
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import kotlin.coroutines.cancellation.CancellationException
|
||||||
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keeps [CalendarPrefs.pendingDisabledCalendarIds] and the system's
|
||||||
|
* `Calendars.VISIBLE` in step (#75): the fold-in of the retired app-local
|
||||||
|
* visibility model, and the standing drain for switch-offs made without
|
||||||
|
* `WRITE_CALENDAR`.
|
||||||
|
*
|
||||||
|
* Runs on every launch and on every calendar-permission grant; a no-op once the
|
||||||
|
* pending set is empty and the notice is settled. Only ever hides (see
|
||||||
|
* [calendarVisibilityPlan]); on an upgraded install the first run that sees a
|
||||||
|
* system-hidden calendar arms the one-time explanatory notice.
|
||||||
|
*/
|
||||||
|
@Singleton
|
||||||
|
class CalendarVisibilityReconciler @Inject constructor(
|
||||||
|
@ApplicationContext private val context: Context,
|
||||||
|
private val dataSource: CalendarDataSource,
|
||||||
|
private val prefs: CalendarPrefs,
|
||||||
|
@IoDispatcher private val io: CoroutineDispatcher,
|
||||||
|
) {
|
||||||
|
|
||||||
|
suspend fun run() = withContext(io) {
|
||||||
|
// The DataStore reads sit inside the guard too: this runs in a bare
|
||||||
|
// application-scope coroutine, so an IOException from a damaged
|
||||||
|
// preferences file would take the process down on every launch.
|
||||||
|
try {
|
||||||
|
// Settled ahead of the permission gate, so an update installed
|
||||||
|
// before the first grant can't later look like an upgrade.
|
||||||
|
if (!isUpgradeInstall()) settleNoticeOnce(pending = false)
|
||||||
|
if (!context.hasPermission(Manifest.permission.READ_CALENDAR)) return@withContext
|
||||||
|
val pending = prefs.pendingDisabledCalendarIds.first()
|
||||||
|
val noticeSettled = prefs.visibilityNoticePending.first() != null
|
||||||
|
if (pending.isEmpty() && noticeSettled) return@withContext
|
||||||
|
val calendars = dataSource.calendars()
|
||||||
|
// Empty means "couldn't read" (null cursor), not "no calendars".
|
||||||
|
// Both decisions below are one-way, so leave them to the next run.
|
||||||
|
if (calendars.isEmpty()) return@withContext
|
||||||
|
settleNoticeOnce(hasSystemHiddenCalendars(calendars, pending))
|
||||||
|
if (pending.isEmpty() || !context.hasPermission(Manifest.permission.WRITE_CALENDAR)) {
|
||||||
|
return@withContext
|
||||||
|
}
|
||||||
|
val plan = calendarVisibilityPlan(calendars, pending)
|
||||||
|
prefs.removePendingDisabledCalendarIds(plan.settled)
|
||||||
|
// One calendar per write: the provider skips its reminder-alarm
|
||||||
|
// reschedule for anything but a single-id update (see
|
||||||
|
// [CalendarDataSource.setCalendarVisible]).
|
||||||
|
for (id in plan.hide) {
|
||||||
|
dataSource.setCalendarVisible(id, false)
|
||||||
|
prefs.removePendingDisabledCalendarIds(setOf(id))
|
||||||
|
}
|
||||||
|
} catch (e: CancellationException) {
|
||||||
|
throw e
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "Calendar visibility reconcile failed; will retry", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Settle the one-time notice: [pending] arms it, false retires it unshown.
|
||||||
|
* Answered once and stored either way, so it can't resurface later.
|
||||||
|
*/
|
||||||
|
private suspend fun settleNoticeOnce(pending: Boolean) {
|
||||||
|
if (prefs.visibilityNoticePending.first() != null) return
|
||||||
|
prefs.setVisibilityNoticePending(pending)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether this install has ever run an earlier version. The notice explains
|
||||||
|
* a behaviour change, so a first install has nothing to announce.
|
||||||
|
*/
|
||||||
|
private fun isUpgradeInstall(): Boolean = try {
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
val info = context.packageManager.getPackageInfo(context.packageName, 0)
|
||||||
|
info.lastUpdateTime > info.firstInstallTime
|
||||||
|
} catch (e: PackageManager.NameNotFoundException) {
|
||||||
|
Log.w(TAG, "Own package info unavailable; treating as a fresh install", e)
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Lets non-injectable entry points (the Application) reach the reconciler. */
|
||||||
|
@EntryPoint
|
||||||
|
@InstallIn(SingletonComponent::class)
|
||||||
|
interface Deps {
|
||||||
|
fun calendarVisibilityReconciler(): CalendarVisibilityReconciler
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val TAG = "CalendarVisibility"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,11 @@
|
|||||||
package de.jeanlucmakiola.calendula.data.calendar
|
package de.jeanlucmakiola.calendula.data.calendar
|
||||||
|
|
||||||
import android.database.Cursor
|
import android.database.Cursor
|
||||||
|
import de.jeanlucmakiola.calendula.domain.EventStatus
|
||||||
|
import de.jeanlucmakiola.calendula.domain.ics.parseRfc2445DurationMillis
|
||||||
|
import java.time.Instant
|
||||||
|
import java.time.LocalDate
|
||||||
|
import java.time.ZoneOffset
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Read-only view over a single row's columns by index. Lets the mappers work
|
* Read-only view over a single row's columns by index. Lets the mappers work
|
||||||
@@ -20,3 +25,33 @@ internal class CursorColumnReader(private val cursor: Cursor) : ColumnReader {
|
|||||||
override fun getInt(index: Int): Int = cursor.getInt(index)
|
override fun getInt(index: Int): Int = cursor.getInt(index)
|
||||||
override fun isNull(index: Int): Boolean = cursor.isNull(index)
|
override fun isNull(index: Int): Boolean = cursor.isNull(index)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal fun ColumnReader.getIntOrNull(index: Int): Int? = if (isNull(index)) null else getInt(index)
|
||||||
|
|
||||||
|
internal fun ColumnReader.getLongOrNull(index: Int): Long? = if (isNull(index)) null else getLong(index)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The row's end: DTEND, or DTSTART + DURATION for a recurring row, which stores
|
||||||
|
* no DTEND. Unclamped; a missing/blank both means a zero-length event.
|
||||||
|
*/
|
||||||
|
internal fun ColumnReader.endMillis(dtStartMillis: Long, dtEndIndex: Int, durationIndex: Int): Long =
|
||||||
|
getLongOrNull(dtEndIndex) ?: (dtStartMillis + parseRfc2445DurationMillis(getString(durationIndex)))
|
||||||
|
|
||||||
|
/** STATUS shares value 0 with TENTATIVE, so an absent column must read as Confirmed. */
|
||||||
|
internal fun ColumnReader.eventStatus(index: Int): EventStatus =
|
||||||
|
getIntOrNull(index)?.let(::mapEventStatus) ?: EventStatus.Confirmed
|
||||||
|
|
||||||
|
/** Map every row, reading each through one [CursorColumnReader]. */
|
||||||
|
internal inline fun <T> Cursor.mapRows(map: ColumnReader.() -> T): List<T> {
|
||||||
|
val reader = CursorColumnReader(this)
|
||||||
|
return buildList { while (moveToNext()) add(reader.map()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** [mapRows], dropping the rows [map] returns null for. */
|
||||||
|
internal inline fun <T : Any> Cursor.mapRowsNotNull(map: ColumnReader.() -> T?): List<T> {
|
||||||
|
val reader = CursorColumnReader(this)
|
||||||
|
return buildList { while (moveToNext()) reader.map()?.let(::add) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The UTC calendar day of [millis] — an all-day row's date, since it sits at UTC midnight. */
|
||||||
|
internal fun utcDate(millis: Long): LocalDate = Instant.ofEpochMilli(millis).atZone(ZoneOffset.UTC).toLocalDate()
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package de.jeanlucmakiola.calendula.data.calendar
|
package de.jeanlucmakiola.calendula.data.calendar
|
||||||
|
|
||||||
|
import de.jeanlucmakiola.floret.time.toKotlinInstantFromEpochMillis
|
||||||
import android.provider.CalendarContract
|
import android.provider.CalendarContract
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import de.jeanlucmakiola.calendula.domain.AccessLevel
|
import de.jeanlucmakiola.calendula.domain.AccessLevel
|
||||||
@@ -13,37 +14,40 @@ import de.jeanlucmakiola.calendula.domain.EventInstance
|
|||||||
import de.jeanlucmakiola.calendula.domain.EventStatus
|
import de.jeanlucmakiola.calendula.domain.EventStatus
|
||||||
import de.jeanlucmakiola.calendula.domain.Reminder
|
import de.jeanlucmakiola.calendula.domain.Reminder
|
||||||
import de.jeanlucmakiola.calendula.domain.ReminderMethod
|
import de.jeanlucmakiola.calendula.domain.ReminderMethod
|
||||||
import java.time.Instant
|
import de.jeanlucmakiola.calendula.domain.ics.parseRfc2445DurationMillis
|
||||||
import java.time.ZoneId
|
import java.time.ZoneId
|
||||||
import java.time.ZoneOffset
|
|
||||||
|
|
||||||
private const val TAG = "EventDetailMapper"
|
private const val TAG = "EventDetailMapper"
|
||||||
|
|
||||||
internal fun ColumnReader.toEventDetailCore(
|
internal fun ColumnReader.toEventDetailCore(
|
||||||
attendees: List<Attendee>,
|
attendees: List<Attendee>,
|
||||||
reminders: List<Reminder>,
|
reminders: List<Reminder>,
|
||||||
|
allDayReminderTimeMinutes: Int,
|
||||||
): EventDetail? {
|
): EventDetail? {
|
||||||
|
// DTSTART is epoch millis in UTC, so a series anchored before 1970 (common
|
||||||
|
// for yearly birthdays/anniversaries synced over CalDAV) is legitimately
|
||||||
|
// negative — only an *absent* DTSTART marks a malformed row worth dropping.
|
||||||
|
// Dropping negatives made every occurrence of such a series un-openable
|
||||||
|
// (the detail loads the ancient series-master DTSTART), see issue #34.
|
||||||
|
if (isNull(EventDetailProjection.IDX_DTSTART)) {
|
||||||
|
Log.w(TAG, "Dropping event with missing dtstart")
|
||||||
|
return null
|
||||||
|
}
|
||||||
val begin = getLong(EventDetailProjection.IDX_DTSTART)
|
val begin = getLong(EventDetailProjection.IDX_DTSTART)
|
||||||
|
|
||||||
if (begin < 0L) {
|
|
||||||
Log.w(TAG, "Dropping event with negative dtstart=$begin")
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
// Recurring events store DURATION instead of DTEND, so the series row's
|
// Recurring events store DURATION instead of DTEND, so the series row's
|
||||||
// DTEND is null. Keep the event (end == begin); callers that opened a
|
// DTEND is null — derive the length from DURATION (as SearchMapper and
|
||||||
// specific occurrence supply the real per-occurrence times from
|
// IcsExportMapper do). Callers that opened a specific occurrence overwrite
|
||||||
// CalendarContract.Instances. Only a present-but-backwards DTEND is malformed.
|
// both times with the per-occurrence values from CalendarContract.Instances;
|
||||||
val end = if (isNull(EventDetailProjection.IDX_DTEND)) {
|
// a caller that names no occurrence (a bare content://.../events/<id> VIEW
|
||||||
begin
|
// intent, issue #48) keeps this row's own times, so the length has to be
|
||||||
} else {
|
// right here or the series renders zero-length. A present-but-backwards
|
||||||
val rawEnd = getLong(EventDetailProjection.IDX_DTEND)
|
// DTEND is malformed, but dropping the row would make the event un-openable
|
||||||
if (rawEnd < begin) {
|
// — the same trap as the pre-1970 DTSTART bug above (issue #34): it would
|
||||||
Log.w(TAG, "Dropping event with dtend=$rawEnd < dtstart=$begin")
|
// surface as the generic error screen with no way to open the event and fix
|
||||||
return null
|
// it. Clamp to a zero-length event instead (matching SearchMapper).
|
||||||
}
|
val end = getLongOrNull(EventDetailProjection.IDX_DTEND)?.coerceAtLeast(begin)
|
||||||
rawEnd
|
?: (begin + parseRfc2445DurationMillis(getString(EventDetailProjection.IDX_DURATION)))
|
||||||
}
|
|
||||||
|
|
||||||
// Kept raw (no untitled fallback): the detail screen substitutes its own
|
// Kept raw (no untitled fallback): the detail screen substitutes its own
|
||||||
// localized placeholder, and the edit form must prefill the true value.
|
// localized placeholder, and the edit form must prefill the true value.
|
||||||
@@ -52,11 +56,7 @@ internal fun ColumnReader.toEventDetailCore(
|
|||||||
// The event's own colour (null = inherits the calendar's) is kept apart
|
// The event's own colour (null = inherits the calendar's) is kept apart
|
||||||
// from the resolved display colour: the edit form needs to tell the two
|
// from the resolved display colour: the edit form needs to tell the two
|
||||||
// cases apart, while the instance carries the calendar fallback for display.
|
// cases apart, while the instance carries the calendar fallback for display.
|
||||||
val eventColor = if (isNull(EventDetailProjection.IDX_EVENT_COLOR)) {
|
val eventColor = getIntOrNull(EventDetailProjection.IDX_EVENT_COLOR)
|
||||||
null
|
|
||||||
} else {
|
|
||||||
getInt(EventDetailProjection.IDX_EVENT_COLOR)
|
|
||||||
}
|
|
||||||
val eventColorKey = getString(EventDetailProjection.IDX_EVENT_COLOR_KEY)
|
val eventColorKey = getString(EventDetailProjection.IDX_EVENT_COLOR_KEY)
|
||||||
val color = eventColor ?: getInt(EventDetailProjection.IDX_CALENDAR_COLOR)
|
val color = eventColor ?: getInt(EventDetailProjection.IDX_CALENDAR_COLOR)
|
||||||
|
|
||||||
@@ -79,21 +79,19 @@ internal fun ColumnReader.toEventDetailCore(
|
|||||||
// and detail screen speak. DTSTART is UTC midnight for all-day events, so the
|
// and detail screen speak. DTSTART is UTC midnight for all-day events, so the
|
||||||
// event's date is its UTC date.
|
// event's date is its UTC date.
|
||||||
val displayReminders = if (isAllDay) {
|
val displayReminders = if (isAllDay) {
|
||||||
val startDate = Instant.ofEpochMilli(begin).atZone(ZoneOffset.UTC).toLocalDate()
|
val startDate = utcDate(begin)
|
||||||
val zone = ZoneId.systemDefault()
|
val zone = ZoneId.systemDefault()
|
||||||
reminders.map { it.copy(minutes = fromProviderAllDayMinutes(it.minutes, startDate, zone)) }
|
reminders.map {
|
||||||
|
it.copy(
|
||||||
|
minutes = fromProviderAllDayMinutes(
|
||||||
|
it.minutes, startDate, zone, allDayReminderTimeMinutes,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
reminders
|
reminders
|
||||||
}
|
}
|
||||||
|
|
||||||
// STATUS shares its 0 value with STATUS_TENTATIVE, so a missing column must
|
|
||||||
// be distinguished from a present 0 — an absent status means "just confirmed".
|
|
||||||
val status = if (isNull(EventDetailProjection.IDX_STATUS)) {
|
|
||||||
EventStatus.Confirmed
|
|
||||||
} else {
|
|
||||||
mapEventStatus(getInt(EventDetailProjection.IDX_STATUS))
|
|
||||||
}
|
|
||||||
|
|
||||||
return EventDetail(
|
return EventDetail(
|
||||||
instance = instance,
|
instance = instance,
|
||||||
description = getString(EventDetailProjection.IDX_DESCRIPTION),
|
description = getString(EventDetailProjection.IDX_DESCRIPTION),
|
||||||
@@ -101,7 +99,7 @@ internal fun ColumnReader.toEventDetailCore(
|
|||||||
attendees = attendees,
|
attendees = attendees,
|
||||||
rrule = getString(EventDetailProjection.IDX_RRULE),
|
rrule = getString(EventDetailProjection.IDX_RRULE),
|
||||||
reminders = displayReminders,
|
reminders = displayReminders,
|
||||||
status = status,
|
status = eventStatus(EventDetailProjection.IDX_STATUS),
|
||||||
// BUSY and DEFAULT are both 0, so a null column folds into the same
|
// BUSY and DEFAULT are both 0, so a null column folds into the same
|
||||||
// default these mappers already return — no isNull guard needed.
|
// default these mappers already return — no isNull guard needed.
|
||||||
availability = mapAvailability(getInt(EventDetailProjection.IDX_AVAILABILITY)),
|
availability = mapAvailability(getInt(EventDetailProjection.IDX_AVAILABILITY)),
|
||||||
@@ -110,6 +108,7 @@ internal fun ColumnReader.toEventDetailCore(
|
|||||||
selfStatus = mapAttendeeStatus(getInt(EventDetailProjection.IDX_SELF_ATTENDEE_STATUS)),
|
selfStatus = mapAttendeeStatus(getInt(EventDetailProjection.IDX_SELF_ATTENDEE_STATUS)),
|
||||||
eventColor = eventColor,
|
eventColor = eventColor,
|
||||||
eventColorKey = eventColorKey,
|
eventColorKey = eventColorKey,
|
||||||
|
isException = !isNull(EventDetailProjection.IDX_ORIGINAL_ID),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,14 +1,30 @@
|
|||||||
package de.jeanlucmakiola.calendula.data.calendar
|
package de.jeanlucmakiola.calendula.data.calendar
|
||||||
|
|
||||||
|
import de.jeanlucmakiola.calendula.domain.instantIn
|
||||||
|
import kotlinx.datetime.toKotlinTimeZone
|
||||||
import android.provider.CalendarContract
|
import android.provider.CalendarContract
|
||||||
import de.jeanlucmakiola.calendula.domain.AccessLevel
|
import de.jeanlucmakiola.calendula.domain.AccessLevel
|
||||||
import de.jeanlucmakiola.calendula.domain.Availability
|
import de.jeanlucmakiola.calendula.domain.Availability
|
||||||
|
import de.jeanlucmakiola.calendula.domain.EventColorOption
|
||||||
import de.jeanlucmakiola.calendula.domain.EventForm
|
import de.jeanlucmakiola.calendula.domain.EventForm
|
||||||
|
import de.jeanlucmakiola.calendula.domain.FormTime
|
||||||
|
import de.jeanlucmakiola.calendula.domain.EventStatus
|
||||||
|
import de.jeanlucmakiola.calendula.domain.forNewEvent
|
||||||
|
import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent
|
||||||
|
import de.jeanlucmakiola.calendula.domain.nearestTo
|
||||||
import kotlinx.datetime.toJavaLocalDate
|
import kotlinx.datetime.toJavaLocalDate
|
||||||
import kotlinx.datetime.toJavaLocalDateTime
|
import kotlinx.datetime.toJavaLocalDateTime
|
||||||
|
import kotlinx.datetime.toJavaZoneOffset
|
||||||
|
import java.time.Duration
|
||||||
import java.time.Instant
|
import java.time.Instant
|
||||||
import java.time.ZoneId
|
import java.time.ZoneId
|
||||||
import java.time.ZoneOffset
|
import java.time.ZoneOffset
|
||||||
|
import java.time.ZonedDateTime
|
||||||
|
import java.time.format.DateTimeFormatter
|
||||||
|
import java.time.format.ResolverStyle
|
||||||
|
import java.time.LocalDate as JavaLocalDate
|
||||||
|
import java.time.LocalDateTime as JavaLocalDateTime
|
||||||
|
import java.time.LocalTime as JavaLocalTime
|
||||||
|
|
||||||
/** Provider-ready DTSTART / DTEND / EVENT_TIMEZONE for an event write. */
|
/** Provider-ready DTSTART / DTEND / EVENT_TIMEZONE for an event write. */
|
||||||
internal data class EventWriteTimes(
|
internal data class EventWriteTimes(
|
||||||
@@ -20,7 +36,11 @@ internal data class EventWriteTimes(
|
|||||||
/**
|
/**
|
||||||
* All-day events live at UTC midnights with an exclusive DTEND (the
|
* All-day events live at UTC midnights with an exclusive DTEND (the
|
||||||
* CalendarContract convention — a one-day event ends at the next midnight);
|
* CalendarContract convention — a one-day event ends at the next midnight);
|
||||||
* timed events resolve their wall-clock values in [zone].
|
* timed events resolve their wall-clock values in the form's own
|
||||||
|
* [EventForm.timezone], falling back to [zone] (the device) when it doesn't pin
|
||||||
|
* one. Passing the device zone is therefore still correct for an unpinned form —
|
||||||
|
* but it no longer overrides a pinned event's zone, which is what used to
|
||||||
|
* silently re-anchor a foreign-zone event to the device on any time edit.
|
||||||
*/
|
*/
|
||||||
internal fun EventForm.toWriteTimes(zone: ZoneId): EventWriteTimes = if (isAllDay) {
|
internal fun EventForm.toWriteTimes(zone: ZoneId): EventWriteTimes = if (isAllDay) {
|
||||||
EventWriteTimes(
|
EventWriteTimes(
|
||||||
@@ -31,22 +51,94 @@ internal fun EventForm.toWriteTimes(zone: ZoneId): EventWriteTimes = if (isAllDa
|
|||||||
timezone = "UTC",
|
timezone = "UTC",
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
|
val writeZone = writeZone(zone)
|
||||||
EventWriteTimes(
|
EventWriteTimes(
|
||||||
dtStartMillis = start.toJavaLocalDateTime().atZone(zone).toInstant().toEpochMilli(),
|
dtStartMillis = start.instantIn(writeZone.toKotlinTimeZone()).toEpochMilliseconds(),
|
||||||
dtEndMillis = end.toJavaLocalDateTime().atZone(zone).toInstant().toEpochMilli(),
|
dtEndMillis = end.instantIn(writeZone.toKotlinTimeZone()).toEpochMilliseconds(),
|
||||||
timezone = zone.id,
|
timezone = writeZone.id,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The zone this form's DTSTART is expressed in: UTC for an all-day event (the
|
||||||
|
* provider's date anchor), otherwise the form's own pinned zone, falling back to
|
||||||
|
* [deviceZone] when it doesn't pin one or pins something the tz database can't
|
||||||
|
* parse.
|
||||||
|
*/
|
||||||
|
private fun EventForm.writeZone(deviceZone: ZoneId): ZoneId = if (isAllDay) {
|
||||||
|
ZoneOffset.UTC
|
||||||
|
} else {
|
||||||
|
timezone?.let { runCatching { ZoneId.of(it) }.getOrNull() } ?: deviceZone
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The form's start as a bare wall-clock value — what the user sees on the form,
|
||||||
|
* stripped of any zone. All-day events use their date's midnight rather than
|
||||||
|
* [EventForm.start]'s placeholder time-of-day, which exists only so switching the
|
||||||
|
* event back to timed has something to show.
|
||||||
|
*/
|
||||||
|
private fun EventForm.anchorLocal(): JavaLocalDateTime = if (isAllDay) {
|
||||||
|
start.date.toJavaLocalDate().atStartOfDay()
|
||||||
|
} else {
|
||||||
|
start.dateTime.toJavaLocalDateTime()
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* RFC 2445 duration for a recurring event's row (the provider requires
|
* RFC 2445 duration for a recurring event's row (the provider requires
|
||||||
* DURATION instead of DTEND when an RRULE is set): whole days for all-day
|
* DURATION instead of DTEND when an RRULE is set): whole days for all-day
|
||||||
* events, seconds otherwise.
|
* events, seconds otherwise.
|
||||||
*/
|
*/
|
||||||
internal fun EventWriteTimes.toRfc2445Duration(isAllDay: Boolean): String = if (isAllDay) {
|
internal fun EventWriteTimes.toRfc2445Duration(isAllDay: Boolean): String =
|
||||||
"P${(dtEndMillis - dtStartMillis) / MILLIS_PER_DAY}D"
|
rfc2445Duration(dtEndMillis - dtStartMillis, isAllDay)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* RFC 2445 duration for a [spanMillis]-long event: whole days for all-day
|
||||||
|
* events (the provider's convention), seconds otherwise. Shared by the write
|
||||||
|
* paths that need a DURATION but start from a raw millisecond span (the series
|
||||||
|
* copy and exception replay of a calendar move) rather than [EventWriteTimes].
|
||||||
|
*/
|
||||||
|
internal fun rfc2445Duration(spanMillis: Long, isAllDay: Boolean): String = if (isAllDay) {
|
||||||
|
"P${spanMillis / MILLIS_PER_DAY}D"
|
||||||
} else {
|
} else {
|
||||||
"P${(dtEndMillis - dtStartMillis) / 1_000L}S"
|
"P${spanMillis / 1_000L}S"
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Column values for a brand-new Events row: identity, times (the provider's
|
||||||
|
* invariant — recurring rows carry RRULE+DURATION and no DTEND, one-off rows
|
||||||
|
* carry DTEND), availability/access level and trimmed optional text. Shared by
|
||||||
|
* the user-event and managed-event insert paths, which differ only in the
|
||||||
|
* [uid] they stamp; colour and attendees are user-event concerns the caller
|
||||||
|
* layers on top.
|
||||||
|
*/
|
||||||
|
internal fun buildEventInsertValues(
|
||||||
|
form: EventForm,
|
||||||
|
uid: String,
|
||||||
|
times: EventWriteTimes,
|
||||||
|
): Map<String, Any?> = buildMap {
|
||||||
|
put(
|
||||||
|
CalendarContract.Events.CALENDAR_ID,
|
||||||
|
requireNotNull(form.calendarId) { "EventForm.calendarId is required" },
|
||||||
|
)
|
||||||
|
put(CalendarContract.Events.UID_2445, uid)
|
||||||
|
put(CalendarContract.Events.TITLE, form.title.trim())
|
||||||
|
put(CalendarContract.Events.ALL_DAY, if (form.isAllDay) 1 else 0)
|
||||||
|
put(CalendarContract.Events.DTSTART, times.dtStartMillis)
|
||||||
|
if (form.rrule == null) {
|
||||||
|
put(CalendarContract.Events.DTEND, times.dtEndMillis)
|
||||||
|
} else {
|
||||||
|
put(CalendarContract.Events.RRULE, form.rrule)
|
||||||
|
put(CalendarContract.Events.DURATION, times.toRfc2445Duration(form.isAllDay))
|
||||||
|
}
|
||||||
|
put(CalendarContract.Events.EVENT_TIMEZONE, times.timezone)
|
||||||
|
put(CalendarContract.Events.AVAILABILITY, form.availability.toProviderValue())
|
||||||
|
put(CalendarContract.Events.ACCESS_LEVEL, form.accessLevel.toProviderValue())
|
||||||
|
form.status.forNewEvent().takeIf { it != EventStatus.Confirmed }
|
||||||
|
?.let { put(CalendarContract.Events.STATUS, it.toProviderStatus()) }
|
||||||
|
form.location.trim().takeIf { it.isNotEmpty() }
|
||||||
|
?.let { put(CalendarContract.Events.EVENT_LOCATION, it) }
|
||||||
|
form.description.trim().takeIf { it.isNotEmpty() }
|
||||||
|
?.let { put(CalendarContract.Events.DESCRIPTION, it) }
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -58,16 +150,21 @@ internal fun EventWriteTimes.toRfc2445Duration(isAllDay: Boolean): String = if (
|
|||||||
*
|
*
|
||||||
* Time fields travel together (the provider validates them as a unit):
|
* Time fields travel together (the provider validates them as a unit):
|
||||||
* - unchanged times, all-day flag and rrule → no time columns at all;
|
* - unchanged times, all-day flag and rrule → no time columns at all;
|
||||||
* - non-recurring result → DTSTART/DTEND, DURATION and RRULE cleared;
|
* - non-recurring result → DTSTART/DTEND, DURATION, RRULE and EXDATE cleared;
|
||||||
* - recurring result → the *series* DTSTART moves by the same delta the user
|
* - recurring result → the *series* DTSTART moves by the same **wall-clock**
|
||||||
* applied to the displayed occurrence ([seriesDtStartMillis] is the row's
|
* shift the user applied to the displayed occurrence and is re-resolved in the
|
||||||
* current DTSTART), DURATION replaces DTEND, RRULE is written. This keeps
|
* event's zone ([seriesDtStartMillis] is the row's current DTSTART), DURATION
|
||||||
* past occurrences intact when someone edits a later occurrence's time.
|
* replaces DTEND, RRULE is written, and the row's exclusions
|
||||||
|
* ([seriesExdate], the current EXDATE) travel with the anchor. This keeps past
|
||||||
|
* occurrences intact when someone edits a later occurrence's time, and keeps
|
||||||
|
* the anchor's time-of-day stable across a DST boundary or a zone change
|
||||||
|
* between the two.
|
||||||
*/
|
*/
|
||||||
internal fun buildEventUpdateValues(
|
internal fun buildEventUpdateValues(
|
||||||
original: EventForm,
|
original: EventForm,
|
||||||
updated: EventForm,
|
updated: EventForm,
|
||||||
seriesDtStartMillis: Long,
|
seriesDtStartMillis: Long,
|
||||||
|
seriesExdate: String?,
|
||||||
zone: ZoneId,
|
zone: ZoneId,
|
||||||
): Map<String, Any?> = buildMap {
|
): Map<String, Any?> = buildMap {
|
||||||
if (updated.title.trim() != original.title.trim()) {
|
if (updated.title.trim() != original.title.trim()) {
|
||||||
@@ -85,14 +182,22 @@ internal fun buildEventUpdateValues(
|
|||||||
if (updated.accessLevel != original.accessLevel) {
|
if (updated.accessLevel != original.accessLevel) {
|
||||||
put(CalendarContract.Events.ACCESS_LEVEL, updated.accessLevel.toProviderValue())
|
put(CalendarContract.Events.ACCESS_LEVEL, updated.accessLevel.toProviderValue())
|
||||||
}
|
}
|
||||||
|
if (updated.status != original.status) {
|
||||||
|
put(CalendarContract.Events.STATUS, updated.status.toProviderStatus())
|
||||||
|
}
|
||||||
if (updated.colorKey != original.colorKey || updated.color != original.color) {
|
if (updated.colorKey != original.colorKey || updated.color != original.color) {
|
||||||
putAll(eventColorColumns(updated.colorKey, updated.color))
|
putAll(eventColorColumns(updated.colorKey, updated.color))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A zone change counts as a time change even when the wall-clock is
|
||||||
|
// untouched: the same 09:00 in another zone is a different instant, so
|
||||||
|
// DTSTART has to move with it. So does a switch between the two passes of
|
||||||
|
// the fall-back hour, which each [FormTime] carries (#387).
|
||||||
val timesChanged = updated.start != original.start ||
|
val timesChanged = updated.start != original.start ||
|
||||||
updated.end != original.end ||
|
updated.end != original.end ||
|
||||||
updated.isAllDay != original.isAllDay ||
|
updated.isAllDay != original.isAllDay ||
|
||||||
updated.rrule != original.rrule
|
updated.rrule != original.rrule ||
|
||||||
|
updated.timezone != original.timezone
|
||||||
if (!timesChanged) return@buildMap
|
if (!timesChanged) return@buildMap
|
||||||
|
|
||||||
val newTimes = updated.toWriteTimes(zone)
|
val newTimes = updated.toWriteTimes(zone)
|
||||||
@@ -103,12 +208,47 @@ internal fun buildEventUpdateValues(
|
|||||||
put(CalendarContract.Events.DTEND, newTimes.dtEndMillis)
|
put(CalendarContract.Events.DTEND, newTimes.dtEndMillis)
|
||||||
put(CalendarContract.Events.RRULE, null)
|
put(CalendarContract.Events.RRULE, null)
|
||||||
put(CalendarContract.Events.DURATION, null)
|
put(CalendarContract.Events.DURATION, null)
|
||||||
|
// The exclusions named occurrences of a series that no longer exists.
|
||||||
|
// Left behind they are dormant rather than harmless: adding a recurrence
|
||||||
|
// back later would punch the old holes into the new one.
|
||||||
|
put(CalendarContract.Events.EXDATE, null)
|
||||||
} else {
|
} else {
|
||||||
val startDelta = newTimes.dtStartMillis - original.toWriteTimes(zone).dtStartMillis
|
// Move the series anchor by the *wall-clock* shift the user applied to the
|
||||||
put(CalendarContract.Events.DTSTART, seriesDtStartMillis + startDelta)
|
// displayed occurrence, then re-resolve it in the event's (possibly new)
|
||||||
|
// zone — never by a millisecond delta. An instant delta silently bakes in
|
||||||
|
// the offset that happened to apply on the edited occurrence's date, which
|
||||||
|
// is a different offset from the series anchor's whenever a DST boundary
|
||||||
|
// sits between them, or whenever the zone itself changed. Working in wall
|
||||||
|
// clock keeps "09:00" meaning 09:00 at both ends.
|
||||||
|
val seriesZoned = Instant.ofEpochMilli(seriesDtStartMillis).atZone(original.writeZone(zone))
|
||||||
|
val seriesLocal = seriesZoned.toLocalDateTime()
|
||||||
|
val wallClockShift = Duration.between(original.anchorLocal(), updated.anchorLocal())
|
||||||
|
val shifted = seriesLocal.plus(wallClockShift)
|
||||||
|
// An all-day series anchor must sit on a UTC midnight. A pure day move
|
||||||
|
// already lands there (both ends are midnights), but *switching* a
|
||||||
|
// recurring event to all-day shifts by a time-of-day too, so snap.
|
||||||
|
val newSeriesLocal = if (updated.isAllDay) shifted.toLocalDate().atStartOfDay() else shifted
|
||||||
|
// A wall clock the fall-back hour repeats keeps the anchor's own pass, or,
|
||||||
|
// when the anchor is the edited occurrence itself, the pass the form now
|
||||||
|
// holds: a bare wall clock would always take the earlier one (#387).
|
||||||
|
val pass = if (seriesLocal == original.anchorLocal()) {
|
||||||
|
updated.start.offset?.toJavaZoneOffset()
|
||||||
|
} else {
|
||||||
|
seriesZoned.offset
|
||||||
|
}
|
||||||
|
val newSeriesStart = ZonedDateTime.ofLocal(newSeriesLocal, updated.writeZone(zone), pass)
|
||||||
|
put(CalendarContract.Events.DTSTART, newSeriesStart.toInstant().toEpochMilli())
|
||||||
put(CalendarContract.Events.DTEND, null)
|
put(CalendarContract.Events.DTEND, null)
|
||||||
put(CalendarContract.Events.RRULE, updated.rrule)
|
put(CalendarContract.Events.RRULE, updated.rrule)
|
||||||
put(CalendarContract.Events.DURATION, newTimes.toRfc2445Duration(updated.isAllDay))
|
put(CalendarContract.Events.DURATION, newTimes.toRfc2445Duration(updated.isAllDay))
|
||||||
|
// An EXDATE stamp is an absolute instant, so it excludes an occurrence
|
||||||
|
// only while the series keeps generating one at exactly that instant. The
|
||||||
|
// anchor has just moved, so every occurrence regenerates elsewhere and a
|
||||||
|
// stamp left behind matches none of them — the occurrence the user deleted
|
||||||
|
// comes back. Move the stamps the same way the anchor moved.
|
||||||
|
shiftedExdate(seriesExdate, original, updated, zone)
|
||||||
|
?.takeIf { it != seriesExdate }
|
||||||
|
?.let { put(CalendarContract.Events.EXDATE, it) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -126,6 +266,10 @@ internal fun buildEventUpdateValues(
|
|||||||
* DTSTART + DURATION itself, clearing the inherited RRULE in the process. This
|
* DTSTART + DURATION itself, clearing the inherited RRULE in the process. This
|
||||||
* matches how AOSP Calendar/Etar write exceptions; sending DTEND is what made
|
* matches how AOSP Calendar/Etar write exceptions; sending DTEND is what made
|
||||||
* "only this event" fail on-device (Codeberg #16).
|
* "only this event" fail on-device (Codeberg #16).
|
||||||
|
*
|
||||||
|
* A palette key is left out: the provider crashes on an exception insert that
|
||||||
|
* carries `EVENT_COLOR_KEY` (Codeberg #338), so the caller sets it with a plain
|
||||||
|
* update once the row exists.
|
||||||
*/
|
*/
|
||||||
internal fun buildOccurrenceExceptionValues(
|
internal fun buildOccurrenceExceptionValues(
|
||||||
form: EventForm,
|
form: EventForm,
|
||||||
@@ -141,11 +285,499 @@ internal fun buildOccurrenceExceptionValues(
|
|||||||
put(CalendarContract.Events.EVENT_TIMEZONE, times.timezone)
|
put(CalendarContract.Events.EVENT_TIMEZONE, times.timezone)
|
||||||
put(CalendarContract.Events.AVAILABILITY, form.availability.toProviderValue())
|
put(CalendarContract.Events.AVAILABILITY, form.availability.toProviderValue())
|
||||||
put(CalendarContract.Events.ACCESS_LEVEL, form.accessLevel.toProviderValue())
|
put(CalendarContract.Events.ACCESS_LEVEL, form.accessLevel.toProviderValue())
|
||||||
|
put(CalendarContract.Events.STATUS, form.status.forNewEvent().toProviderStatus())
|
||||||
put(CalendarContract.Events.EVENT_LOCATION, form.location.trim().ifEmpty { null })
|
put(CalendarContract.Events.EVENT_LOCATION, form.location.trim().ifEmpty { null })
|
||||||
put(CalendarContract.Events.DESCRIPTION, form.description.trim().ifEmpty { null })
|
put(CalendarContract.Events.DESCRIPTION, form.description.trim().ifEmpty { null })
|
||||||
putAll(eventColorColumns(form.colorKey, form.color))
|
if (form.colorKey == null) putAll(eventColorColumns(null, form.color))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The form as a **detached occurrence**: the same edited values, with the
|
||||||
|
* series rule dropped so [buildEventInsertValues] writes a standalone one-off
|
||||||
|
* row (DTSTART + DTEND, no RRULE/DURATION) at the occurrence's own times.
|
||||||
|
*
|
||||||
|
* The "edit only this event" shape for a series with **no `_sync_id`**, where an
|
||||||
|
* exception row can't attach to its parent at all (Codeberg #234).
|
||||||
|
*
|
||||||
|
* The exception path gets the rule dropped for free — the provider clears the
|
||||||
|
* RRULE it cloned when an exception carries DTSTART + DURATION
|
||||||
|
* ([buildOccurrenceExceptionValues]). Here nothing is cloned, so it is stripped
|
||||||
|
* by hand; leaving it on would insert a second *series* overlapping the first.
|
||||||
|
*/
|
||||||
|
internal fun EventForm.toDetachedOccurrence(): EventForm = copy(rrule = null)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Raw provider snapshot of a master/one-off Events row, enough to re-insert it
|
||||||
|
* verbatim on another calendar (a calendar move is copy+delete — `CALENDAR_ID`
|
||||||
|
* is sync-adapter-owned and can't be updated in place). Recurring rows carry
|
||||||
|
* [rrule]/[duration] (and any [rdate]/[exdate]) with a null [dtEndMillis];
|
||||||
|
* one-off rows carry [dtEndMillis]. Colour is deliberately absent: a raw
|
||||||
|
* `EVENT_COLOR` or account-scoped `EVENT_COLOR_KEY` may be invalid on the target
|
||||||
|
* account, so the moved copy inherits the target calendar's colour instead.
|
||||||
|
*/
|
||||||
|
internal data class MasterEventSnapshot(
|
||||||
|
val title: String,
|
||||||
|
val isAllDay: Boolean,
|
||||||
|
val dtStartMillis: Long,
|
||||||
|
val dtEndMillis: Long?,
|
||||||
|
val duration: String?,
|
||||||
|
val rrule: String?,
|
||||||
|
val rdate: String?,
|
||||||
|
val exdate: String?,
|
||||||
|
val timezone: String?,
|
||||||
|
val availability: Int,
|
||||||
|
val accessLevel: Int,
|
||||||
|
val status: Int?,
|
||||||
|
val location: String?,
|
||||||
|
val description: String?,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Column values re-creating [snapshot] as a fresh Events row on
|
||||||
|
* [targetCalendarId], keeping its [uid] so `.ics` backup dedup and sync identity
|
||||||
|
* survive the move. Preserves the recurrence skeleton (DTSTART/RRULE/DURATION,
|
||||||
|
* RDATE/EXDATE) so the series' generated instances — and therefore the
|
||||||
|
* ORIGINAL_INSTANCE_TIME of every copied exception — line up unchanged. The
|
||||||
|
* caller layers the user's field edits on top with a normal series update.
|
||||||
|
*/
|
||||||
|
internal fun buildMovedMasterValues(
|
||||||
|
snapshot: MasterEventSnapshot,
|
||||||
|
targetCalendarId: Long,
|
||||||
|
uid: String,
|
||||||
|
): Map<String, Any?> = buildMap {
|
||||||
|
put(CalendarContract.Events.CALENDAR_ID, targetCalendarId)
|
||||||
|
put(CalendarContract.Events.UID_2445, uid)
|
||||||
|
put(CalendarContract.Events.TITLE, snapshot.title)
|
||||||
|
put(CalendarContract.Events.ALL_DAY, if (snapshot.isAllDay) 1 else 0)
|
||||||
|
put(CalendarContract.Events.DTSTART, snapshot.dtStartMillis)
|
||||||
|
put(CalendarContract.Events.EVENT_TIMEZONE, snapshot.timezone ?: "UTC")
|
||||||
|
if (snapshot.rrule != null) {
|
||||||
|
put(CalendarContract.Events.RRULE, snapshot.rrule)
|
||||||
|
snapshot.rdate?.takeIf { it.isNotBlank() }?.let { put(CalendarContract.Events.RDATE, it) }
|
||||||
|
snapshot.exdate?.takeIf { it.isNotBlank() }?.let { put(CalendarContract.Events.EXDATE, it) }
|
||||||
|
put(CalendarContract.Events.DURATION, snapshot.movedDuration())
|
||||||
|
} else {
|
||||||
|
snapshot.dtEndMillis?.let { put(CalendarContract.Events.DTEND, it) }
|
||||||
|
}
|
||||||
|
put(CalendarContract.Events.AVAILABILITY, snapshot.availability)
|
||||||
|
put(CalendarContract.Events.ACCESS_LEVEL, snapshot.accessLevel)
|
||||||
|
snapshot.status?.takeIf { it != CalendarContract.Events.STATUS_CANCELED }
|
||||||
|
?.let { put(CalendarContract.Events.STATUS, it) }
|
||||||
|
put(CalendarContract.Events.EVENT_LOCATION, snapshot.location?.ifEmpty { null })
|
||||||
|
put(CalendarContract.Events.DESCRIPTION, snapshot.description?.ifEmpty { null })
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The recurring copy's DURATION: its own if present, else derived from DTEND. */
|
||||||
|
private fun MasterEventSnapshot.movedDuration(): String = duration?.takeIf { it.isNotBlank() }
|
||||||
|
?: rfc2445Duration((dtEndMillis ?: dtStartMillis) - dtStartMillis, isAllDay)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Raw provider snapshot of one exception row of a recurring series (a modified
|
||||||
|
* or cancelled occurrence, `ORIGINAL_ID` = the series). [originalInstanceMillis]
|
||||||
|
* ties it to the occurrence it overrides; a [isCancelled] row only needs that.
|
||||||
|
*/
|
||||||
|
internal data class ExceptionRowSnapshot(
|
||||||
|
val exceptionEventId: Long,
|
||||||
|
val originalInstanceMillis: Long,
|
||||||
|
val isCancelled: Boolean,
|
||||||
|
val dtStartMillis: Long,
|
||||||
|
val dtEndMillis: Long?,
|
||||||
|
val duration: String?,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Column values for a *cancelled*-occurrence exception row ("delete only this
|
||||||
|
* event"): inserting them at `Events.CONTENT_EXCEPTION_URI/<id>` makes the
|
||||||
|
* provider clone the series row and cancel exactly this one instance.
|
||||||
|
*
|
||||||
|
* As with [buildOccurrenceExceptionValues], the occurrence must be anchored with
|
||||||
|
* DTSTART + DURATION so the provider derives a single instance and clears the
|
||||||
|
* inherited RRULE. A STATUS-only cancel skips that: the clone keeps the RRULE, so
|
||||||
|
* the *whole series* is cancelled and every other occurrence disappears
|
||||||
|
* (Codeberg #47). The occurrence's length/zone come straight from the series row
|
||||||
|
* — cancelling never changes them.
|
||||||
|
*/
|
||||||
|
internal fun buildOccurrenceCancelValues(
|
||||||
|
originalInstanceMillis: Long,
|
||||||
|
dtStartMillis: Long,
|
||||||
|
duration: String?,
|
||||||
|
timezone: String?,
|
||||||
|
allDay: Int,
|
||||||
|
): Map<String, Any?> = buildMap {
|
||||||
|
put(CalendarContract.Events.ORIGINAL_INSTANCE_TIME, originalInstanceMillis)
|
||||||
|
put(CalendarContract.Events.DTSTART, dtStartMillis)
|
||||||
|
put(CalendarContract.Events.DURATION, duration)
|
||||||
|
put(CalendarContract.Events.EVENT_TIMEZONE, timezone)
|
||||||
|
put(CalendarContract.Events.ALL_DAY, allDay)
|
||||||
|
put(CalendarContract.Events.STATUS, CalendarContract.Events.STATUS_CANCELED)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The master-row columns that drop the occurrence at [occurrenceMillis] from a
|
||||||
|
* series by adding it to `EXDATE` — the path for events that have **no
|
||||||
|
* `_sync_id`** (a local calendar, or a synced event not yet pushed).
|
||||||
|
*
|
||||||
|
* A cancelled exception row (see [buildOccurrenceCancelValues]) only attaches to
|
||||||
|
* its parent through `ORIGINAL_SYNC_ID`. Without a `_sync_id` the link never
|
||||||
|
* forms, and the provider's expansion of the *parent* collapses — every other
|
||||||
|
* occurrence disappears (Codeberg #47, reproduced on a local calendar). EXDATE
|
||||||
|
* needs no link, and is the canonical iCalendar way to drop an occurrence, so a
|
||||||
|
* sync adapter carries it upstream unchanged if the calendar later syncs.
|
||||||
|
*
|
||||||
|
* The whole time/recurrence set is rewritten alongside it on purpose. The
|
||||||
|
* provider does **not** treat an EXDATE-only update as a recurrence change: it
|
||||||
|
* leaves the expanded `Instances` rows untouched, so the occurrence stays visible
|
||||||
|
* (and, symmetrically, un-excluding one leaves it hidden). Writing DTSTART with
|
||||||
|
* it forces the re-expansion — but DTSTART *alone* makes the provider recompute
|
||||||
|
* `lastDate` as if the event were a single instance, collapsing the series to its
|
||||||
|
* first occurrence. Passing DTSTART + DURATION + RRULE + zone together is what
|
||||||
|
* re-expands it correctly. All observed on a Pixel; see the #47 notes.
|
||||||
|
*
|
||||||
|
* [rdate] travels with [rrule]: a sync adapter may list a series' occurrences
|
||||||
|
* instead of naming a rule, and rewriting the recurrence set without it would
|
||||||
|
* leave the provider nothing but DTSTART to re-expand from — the collapse this
|
||||||
|
* values map exists to avoid.
|
||||||
|
*
|
||||||
|
* EXDATE is a comma-separated list, so an existing one is appended to (a repeat
|
||||||
|
* of the same occurrence is folded away — [mergedExdate]).
|
||||||
|
*/
|
||||||
|
internal fun buildOccurrenceExdateValues(
|
||||||
|
existingExdate: String?,
|
||||||
|
occurrenceMillis: Long,
|
||||||
|
dtStartMillis: Long,
|
||||||
|
rrule: String?,
|
||||||
|
rdate: String?,
|
||||||
|
duration: String?,
|
||||||
|
timezone: String?,
|
||||||
|
allDay: Int,
|
||||||
|
): Map<String, Any?> = buildOccurrencesExdateValues(
|
||||||
|
existingExdate, listOf(occurrenceMillis), dtStartMillis, rrule, rdate, duration, timezone, allDay,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** [buildOccurrenceExdateValues] excluding every one of [occurrences] in one write. */
|
||||||
|
internal fun buildOccurrencesExdateValues(
|
||||||
|
existingExdate: String?,
|
||||||
|
occurrences: List<Long>,
|
||||||
|
dtStartMillis: Long,
|
||||||
|
rrule: String?,
|
||||||
|
rdate: String?,
|
||||||
|
duration: String?,
|
||||||
|
timezone: String?,
|
||||||
|
allDay: Int,
|
||||||
|
): Map<String, Any?> = mapOf(
|
||||||
|
CalendarContract.Events.EXDATE to occurrences.fold(existingExdate) { exdate, millis ->
|
||||||
|
mergedExdate(exdate, millis, allDay != 0, timezone)
|
||||||
|
},
|
||||||
|
CalendarContract.Events.DTSTART to dtStartMillis,
|
||||||
|
CalendarContract.Events.RRULE to rrule,
|
||||||
|
CalendarContract.Events.RDATE to rdate,
|
||||||
|
CalendarContract.Events.DURATION to duration,
|
||||||
|
CalendarContract.Events.EVENT_TIMEZONE to timezone,
|
||||||
|
CalendarContract.Events.ALL_DAY to allDay,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [existingExdate] with the occurrence at [occurrenceMillis] excluded as well.
|
||||||
|
*
|
||||||
|
* Existing stamps are canonicalised first — all-day series take the `VALUE=DATE`
|
||||||
|
* form (`yyyyMMdd`), timed ones the UTC date-time form (`yyyyMMddTHHmmssZ`) — so
|
||||||
|
* appending to a list a sync adapter wrote in the other accepted form folds the
|
||||||
|
* repeat away instead of leaving the same day excluded twice in two spellings.
|
||||||
|
*
|
||||||
|
* A stamp in no form Calendula reads makes the whole list untouchable: it is kept
|
||||||
|
* exactly as it is, behind the parameter prefix that tells a reader how to
|
||||||
|
* resolve it, and the new exclusion joins it in the list's own form.
|
||||||
|
* Canonicalising the readable stamps around it would leave absolute stamps under
|
||||||
|
* a prefix claiming a zone for all of them — which is how the unreadable one
|
||||||
|
* quietly changes instant.
|
||||||
|
*/
|
||||||
|
private fun mergedExdate(
|
||||||
|
existingExdate: String?,
|
||||||
|
occurrenceMillis: Long,
|
||||||
|
isAllDay: Boolean,
|
||||||
|
timezone: String?,
|
||||||
|
): String {
|
||||||
|
val listZone = exdateListZone(existingExdate, timezone)
|
||||||
|
val stamps = exdateStamps(existingExdate)
|
||||||
|
val canonical = stamps.map { canonicalExdateStamp(it, isAllDay, listZone) }
|
||||||
|
if (canonical.all { it != null }) {
|
||||||
|
val stamp = formatExdateStamp(occurrenceMillis, isAllDay)
|
||||||
|
return (canonical.filterNotNull() + stamp).distinct().joinToString(",")
|
||||||
|
}
|
||||||
|
val prefix = existingExdate?.exdateParameterPrefix().orEmpty()
|
||||||
|
val stamp = if (isAllDay || prefix.isEmpty()) {
|
||||||
|
formatExdateStamp(occurrenceMillis, isAllDay)
|
||||||
|
} else {
|
||||||
|
Instant.ofEpochMilli(occurrenceMillis).atZone(listZone).format(FLOATING_EXDATE)
|
||||||
|
}
|
||||||
|
return prefix + (stamps + stamp).distinct().joinToString(",")
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether [existingExdate] already excludes the occurrence at [occurrenceMillis]
|
||||||
|
* — i.e. it has already been dropped from the series, deleted or detached.
|
||||||
|
*
|
||||||
|
* Guards the detach path against running twice from a stale screen: the EXDATE
|
||||||
|
* merge folds the repeat away silently and the update still reports one row
|
||||||
|
* changed, so a second save would leave a second standalone copy.
|
||||||
|
*/
|
||||||
|
internal fun exdateContains(
|
||||||
|
existingExdate: String?,
|
||||||
|
occurrenceMillis: Long,
|
||||||
|
isAllDay: Boolean,
|
||||||
|
timezone: String?,
|
||||||
|
): Boolean {
|
||||||
|
val stamp = formatExdateStamp(occurrenceMillis, isAllDay)
|
||||||
|
val listZone = exdateListZone(existingExdate, timezone)
|
||||||
|
// Canonicalised rather than compared verbatim: a sync adapter may spell the
|
||||||
|
// same exclusion differently to Calendula, and a guard that misses it lets
|
||||||
|
// the detach run a second time and leave a second standalone copy.
|
||||||
|
return exdateStamps(existingExdate)
|
||||||
|
.any { canonicalExdateStamp(it, isAllDay, listZone) == stamp }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [existingExdate] with every stamp re-timed by the same **wall-clock** shift the
|
||||||
|
* series anchor takes from [original] to [updated] — the exclusions' half of the
|
||||||
|
* anchor move [buildEventUpdateValues] performs, and what carries them onto the
|
||||||
|
* new series when "this and following" splits one.
|
||||||
|
*
|
||||||
|
* A stamp is an absolute instant, so it keeps naming its occurrence only if it
|
||||||
|
* moves exactly as the occurrence does: shifted in wall clock and re-resolved in
|
||||||
|
* the event's (possibly new) zone. A millisecond delta would instead bake in the
|
||||||
|
* offset that happened to apply at the edited occurrence — an hour off for any
|
||||||
|
* exclusion on the far side of a DST boundary. All-day-ness is read from
|
||||||
|
* [original] and written from [updated], so the `VALUE=DATE` and date-time forms
|
||||||
|
* convert into each other when the event switches.
|
||||||
|
*
|
||||||
|
* A zoned list is read in the zone its prefix names ([exdateListZone]). Null
|
||||||
|
* when there is nothing to carry: no stamps, or a stamp in a form Calendula
|
||||||
|
* cannot read at all. Those are left exactly as they are rather than guessed at —
|
||||||
|
* a stale stamp excludes nothing, but a mangled one could exclude the wrong
|
||||||
|
* occurrence.
|
||||||
|
*/
|
||||||
|
internal fun shiftedExdate(
|
||||||
|
existingExdate: String?,
|
||||||
|
original: EventForm,
|
||||||
|
updated: EventForm,
|
||||||
|
zone: ZoneId,
|
||||||
|
): String? {
|
||||||
|
val stamps = exdateStamps(existingExdate)
|
||||||
|
if (stamps.isEmpty()) return null
|
||||||
|
val fromZone = original.writeZone(zone)
|
||||||
|
val toZone = updated.writeZone(zone)
|
||||||
|
val listZone = exdateListZone(existingExdate, fromZone.id)
|
||||||
|
val wallClockShift = Duration.between(original.anchorLocal(), updated.anchorLocal())
|
||||||
|
return stamps
|
||||||
|
.map { stamp ->
|
||||||
|
val local = parseExdateStamp(stamp, original.isAllDay, fromZone, listZone)
|
||||||
|
?: return null
|
||||||
|
formatExdateStamp(local.plus(wallClockShift), updated.isAllDay, toZone)
|
||||||
|
}
|
||||||
|
.distinct()
|
||||||
|
.joinToString(",")
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The stamps of [existingExdate] naming occurrences after [beginMillis] — the ones
|
||||||
|
* that belong to the *new* series once "this and following" splits a recurring
|
||||||
|
* event there. The parent keeps the full list; its stamps past the split point are
|
||||||
|
* simply inert once it stops generating those occurrences.
|
||||||
|
*
|
||||||
|
* The occurrence at [beginMillis] itself is never carried. It is the one the user
|
||||||
|
* is editing, so it exists by definition, and honouring a stale exclusion for it
|
||||||
|
* would swallow the edit whole.
|
||||||
|
*
|
||||||
|
* The stamps that qualify come back canonicalised, since the zone prefix that
|
||||||
|
* told the reader how to resolve them does not survive the filter.
|
||||||
|
*
|
||||||
|
* Null when nothing qualifies, or when a stamp can't be read (see [shiftedExdate]).
|
||||||
|
*/
|
||||||
|
internal fun exdateAfter(
|
||||||
|
existingExdate: String?,
|
||||||
|
beginMillis: Long,
|
||||||
|
isAllDay: Boolean,
|
||||||
|
timezone: String?,
|
||||||
|
): String? {
|
||||||
|
val stamps = exdateStamps(existingExdate)
|
||||||
|
if (stamps.isEmpty()) return null
|
||||||
|
val listZone = exdateListZone(existingExdate, timezone)
|
||||||
|
return stamps
|
||||||
|
.mapNotNull { stamp ->
|
||||||
|
val utc = parseExdateStamp(stamp, isAllDay, ZoneOffset.UTC, listZone) ?: return null
|
||||||
|
utc.takeIf { it.toInstant(ZoneOffset.UTC).toEpochMilli() > beginMillis }
|
||||||
|
}
|
||||||
|
.map { formatExdateStamp(it, isAllDay, ZoneOffset.UTC) }
|
||||||
|
.takeIf { it.isNotEmpty() }
|
||||||
|
?.joinToString(",")
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The individual stamps of an EXDATE column value; it is a comma-separated list,
|
||||||
|
* optionally behind the parameter prefix AOSP's `RecurrenceSet` puts in front of
|
||||||
|
* a zoned one ([exdateListZone] reads that half).
|
||||||
|
*/
|
||||||
|
internal fun exdateStamps(exdate: String?): List<String> = exdate
|
||||||
|
?.withoutExdateParameters()
|
||||||
|
?.split(',')
|
||||||
|
?.map { it.trim() }
|
||||||
|
?.filter { it.isNotEmpty() }
|
||||||
|
.orEmpty()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An EXDATE column value with the parameter section its stamps sit behind taken
|
||||||
|
* off.
|
||||||
|
*/
|
||||||
|
internal fun String.withoutExdateParameters(): String = substring(exdateParameterPrefix().length)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The parameter section an EXDATE list's stamps sit behind, its `;` included, or
|
||||||
|
* empty when it has none. Only a `;` before the first stamp separator is one —
|
||||||
|
* anything later belongs to a stamp, and cutting there would drop every stamp in
|
||||||
|
* front of it.
|
||||||
|
*/
|
||||||
|
private fun String.exdateParameterPrefix(): String {
|
||||||
|
val semicolon = indexOf(';')
|
||||||
|
val comma = indexOf(',')
|
||||||
|
return if (semicolon >= 0 && (comma < 0 || semicolon < comma)) {
|
||||||
|
substring(0, semicolon + 1)
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The zone the floating stamps of [exdate] are wall clock in: the one its
|
||||||
|
* parameter prefix names, or [fallback] — the event's own `EVENT_TIMEZONE` —
|
||||||
|
* when there is no prefix, or the device's tz database doesn't know the name it
|
||||||
|
* uses (Exchange spells zones its own way). The series' own zone is the right
|
||||||
|
* guess, since a zoned exclusion list is written in it. UTC last, for a row that
|
||||||
|
* carries no zone either. Stamps already written as UTC instants ignore all this.
|
||||||
|
*
|
||||||
|
* Both spellings of the prefix are read. AOSP's `RecurrenceSet` stores the TZID
|
||||||
|
* parameter's *value* alone (`Europe/Berlin;<stamps>`), and so does DAVx5; the
|
||||||
|
* iCalendar `TZID=<zone>;` some writers keep is the other one. Only matching the
|
||||||
|
* second would miss every list the provider itself wrote.
|
||||||
|
*/
|
||||||
|
internal fun exdateListZone(exdate: String?, fallback: String?): ZoneId =
|
||||||
|
exdate?.exdateZoneName()?.toZoneIdOrNull()
|
||||||
|
?: fallback?.toZoneIdOrNull()
|
||||||
|
?: ZoneOffset.UTC
|
||||||
|
|
||||||
|
/** The zone id an EXDATE list's parameter prefix names, with or without `TZID=`. */
|
||||||
|
private fun String.exdateZoneName(): String {
|
||||||
|
val prefix = exdateParameterPrefix().dropLast(1)
|
||||||
|
return if (prefix.startsWith(TZID_PREFIX, ignoreCase = true)) {
|
||||||
|
prefix.drop(TZID_PREFIX.length)
|
||||||
|
} else {
|
||||||
|
prefix
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun String.toZoneIdOrNull(): ZoneId? = runCatching { ZoneId.of(this) }.getOrNull()
|
||||||
|
|
||||||
|
/** The optional `TZID=` a zoned EXDATE list's zone id may sit behind. */
|
||||||
|
private const val TZID_PREFIX = "TZID="
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One EXDATE entry for the occurrence starting at [occurrenceMillis]. Both forms
|
||||||
|
* are UTC: the provider stores an all-day DTSTART at UTC midnight, so its date
|
||||||
|
* reads off the UTC calendar day.
|
||||||
|
*/
|
||||||
|
internal fun formatExdateStamp(occurrenceMillis: Long, isAllDay: Boolean): String =
|
||||||
|
formatExdateStamp(
|
||||||
|
local = Instant.ofEpochMilli(occurrenceMillis).atZone(ZoneOffset.UTC).toLocalDateTime(),
|
||||||
|
isAllDay = isAllDay,
|
||||||
|
zone = ZoneOffset.UTC,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One EXDATE entry for the occurrence whose wall clock in [zone] is [local]. An
|
||||||
|
* all-day entry keeps only the date (its time-of-day is the anchor's, not the
|
||||||
|
* occurrence's); a timed one is resolved in [zone] and written as a UTC instant.
|
||||||
|
*/
|
||||||
|
private fun formatExdateStamp(local: JavaLocalDateTime, isAllDay: Boolean, zone: ZoneId): String =
|
||||||
|
if (isAllDay) {
|
||||||
|
local.toLocalDate().format(ALL_DAY_EXDATE)
|
||||||
|
} else {
|
||||||
|
local.atZone(zone).withZoneSameInstant(ZoneOffset.UTC).format(TIMED_EXDATE)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [stamp] as the wall clock it names in [zone] — the inverse of
|
||||||
|
* [formatExdateStamp]. Null for anything Calendula cannot read, so a caller can
|
||||||
|
* tell "not ours, leave it alone" from a value it may safely re-time.
|
||||||
|
*
|
||||||
|
* A timed exclusion is read both as the UTC instant Calendula writes and as a
|
||||||
|
* floating stamp, which [listZone] then resolves. An all-day one is read both
|
||||||
|
* bare (`yyyyMMdd`, what Calendula writes) and padded to a midnight stamp, in
|
||||||
|
* either spelling: sync adapters are inconsistent about which they store — the
|
||||||
|
* same forms [exportExDates] reshapes on the way out — and refusing one would
|
||||||
|
* drop every exclusion of a foreign all-day series the moment it is re-timed.
|
||||||
|
*/
|
||||||
|
private fun parseExdateStamp(
|
||||||
|
stamp: String,
|
||||||
|
isAllDay: Boolean,
|
||||||
|
zone: ZoneId,
|
||||||
|
listZone: ZoneId,
|
||||||
|
): JavaLocalDateTime? =
|
||||||
|
if (isAllDay) {
|
||||||
|
parseAllDayExdate(stamp)?.atStartOfDay()
|
||||||
|
} else {
|
||||||
|
parseTimedExdate(stamp, listZone)?.withZoneSameInstant(zone)?.toLocalDateTime()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A timed EXDATE stamp as the instant it names: the trailing `Z` form resolved in
|
||||||
|
* UTC, or the floating one resolved in [listZone].
|
||||||
|
*/
|
||||||
|
private fun parseTimedExdate(stamp: String, listZone: ZoneId): ZonedDateTime? =
|
||||||
|
runCatching { JavaLocalDateTime.parse(stamp, TIMED_EXDATE).atZone(ZoneOffset.UTC) }.getOrNull()
|
||||||
|
?: runCatching {
|
||||||
|
JavaLocalDateTime.parse(stamp, FLOATING_EXDATE).atZone(listZone)
|
||||||
|
}.getOrNull()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The calendar day an all-day EXDATE stamp names, bare or padded to a midnight
|
||||||
|
* stamp. A padded stamp naming any other time of day is refused rather than
|
||||||
|
* rounded: it is not a form an all-day series is written in, so it could be
|
||||||
|
* naming something else entirely. Midnight is midnight in any zone, so the
|
||||||
|
* padding's own spelling — trailing `Z` or floating — makes no difference.
|
||||||
|
*/
|
||||||
|
private fun parseAllDayExdate(stamp: String): JavaLocalDate? {
|
||||||
|
runCatching { JavaLocalDate.parse(stamp, ALL_DAY_EXDATE) }.getOrNull()?.let { return it }
|
||||||
|
val padded = parsePaddedExdate(stamp) ?: return null
|
||||||
|
return padded.toLocalDate().takeIf { padded.toLocalTime() == JavaLocalTime.MIDNIGHT }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** An `uuuuMMddTHHmmss` stamp, with or without the trailing `Z`, as its own wall clock. */
|
||||||
|
private fun parsePaddedExdate(stamp: String): JavaLocalDateTime? =
|
||||||
|
runCatching { JavaLocalDateTime.parse(stamp, TIMED_EXDATE) }.getOrNull()
|
||||||
|
?: runCatching { JavaLocalDateTime.parse(stamp, FLOATING_EXDATE) }.getOrNull()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [stamp] in the form Calendula writes, so two spellings of the same exclusion
|
||||||
|
* compare equal. Null for a stamp in no form it reads.
|
||||||
|
*/
|
||||||
|
internal fun canonicalExdateStamp(
|
||||||
|
stamp: String,
|
||||||
|
isAllDay: Boolean,
|
||||||
|
listZone: ZoneId,
|
||||||
|
): String? = parseExdateStamp(stamp, isAllDay, ZoneOffset.UTC, listZone)
|
||||||
|
?.let { formatExdateStamp(it, isAllDay, ZoneOffset.UTC) }
|
||||||
|
|
||||||
|
/** `VALUE=DATE` EXDATE form, for an all-day series. */
|
||||||
|
private val ALL_DAY_EXDATE: DateTimeFormatter =
|
||||||
|
DateTimeFormatter.ofPattern("uuuuMMdd").withResolverStyle(ResolverStyle.STRICT)
|
||||||
|
|
||||||
|
/** UTC date-time EXDATE form, for a timed series. */
|
||||||
|
private val TIMED_EXDATE: DateTimeFormatter =
|
||||||
|
DateTimeFormatter.ofPattern("uuuuMMdd'T'HHmmss'Z'").withResolverStyle(ResolverStyle.STRICT)
|
||||||
|
|
||||||
|
/** The same form without the `Z`, wall clock in the list's zone rather than UTC. */
|
||||||
|
private val FLOATING_EXDATE: DateTimeFormatter =
|
||||||
|
DateTimeFormatter.ofPattern("uuuuMMdd'T'HHmmss").withResolverStyle(ResolverStyle.STRICT)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The `EVENT_COLOR` / `EVENT_COLOR_KEY` columns for a colour selection. A
|
* The `EVENT_COLOR` / `EVENT_COLOR_KEY` columns for a colour selection. A
|
||||||
* [colorKey] writes the key alone (the provider derives `EVENT_COLOR` from the
|
* [colorKey] writes the key alone (the provider derives `EVENT_COLOR` from the
|
||||||
@@ -193,3 +825,78 @@ internal fun AccessLevel.toProviderValue(): Int = when (this) {
|
|||||||
AccessLevel.Private -> CalendarContract.Events.ACCESS_PRIVATE
|
AccessLevel.Private -> CalendarContract.Events.ACCESS_PRIVATE
|
||||||
AccessLevel.Public -> CalendarContract.Events.ACCESS_PUBLIC
|
AccessLevel.Public -> CalendarContract.Events.ACCESS_PUBLIC
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The `Events` row for a `.ics` event being imported into [calendarId].
|
||||||
|
*
|
||||||
|
* A recurring row carries RRULE + DURATION (and any EXDATE) with no DTEND; a
|
||||||
|
* one-off carries DTEND. All-day rows live at UTC midnights, exactly as the
|
||||||
|
* parser hands them over.
|
||||||
|
*
|
||||||
|
* [palette] is the target account's published event colours. A calendar that
|
||||||
|
* publishes one rejects a raw `EVENT_COLOR`, so an imported colour — which is
|
||||||
|
* an arbitrary ARGB from a foreign app — is snapped to the nearest key it does
|
||||||
|
* accept; accounts with no palette take the raw value (see [eventColorColumns]).
|
||||||
|
*/
|
||||||
|
internal fun buildImportedEventValues(
|
||||||
|
event: ParsedIcsEvent,
|
||||||
|
calendarId: Long,
|
||||||
|
uid: String,
|
||||||
|
palette: List<EventColorOption>,
|
||||||
|
): Map<String, Any?> = buildMap {
|
||||||
|
val startMillis = event.start.toEpochMilliseconds()
|
||||||
|
val endMillis = event.end.toEpochMilliseconds()
|
||||||
|
put(CalendarContract.Events.CALENDAR_ID, calendarId)
|
||||||
|
put(CalendarContract.Events.UID_2445, uid)
|
||||||
|
put(CalendarContract.Events.TITLE, event.summary.trim())
|
||||||
|
put(CalendarContract.Events.ALL_DAY, if (event.isAllDay) 1 else 0)
|
||||||
|
put(CalendarContract.Events.DTSTART, startMillis)
|
||||||
|
if (event.recurrenceRule == null && event.recurrenceDates.isEmpty()) {
|
||||||
|
put(CalendarContract.Events.DTEND, endMillis)
|
||||||
|
} else {
|
||||||
|
event.recurrenceRule?.let { put(CalendarContract.Events.RRULE, it) }
|
||||||
|
event.recurrenceDates.takeIf { it.isNotEmpty() }
|
||||||
|
?.let { put(CalendarContract.Events.RDATE, it.joinToString(",")) }
|
||||||
|
put(
|
||||||
|
CalendarContract.Events.DURATION,
|
||||||
|
importDuration(startMillis, endMillis, event.isAllDay),
|
||||||
|
)
|
||||||
|
event.exDates.takeIf { it.isNotEmpty() }
|
||||||
|
?.let { put(CalendarContract.Events.EXDATE, it.joinToString(",")) }
|
||||||
|
}
|
||||||
|
// All-day rows live at UTC midnights (the file already encodes them so);
|
||||||
|
// timed rows keep the event's own zone.
|
||||||
|
put(CalendarContract.Events.EVENT_TIMEZONE, if (event.isAllDay) "UTC" else event.zoneId)
|
||||||
|
put(CalendarContract.Events.AVAILABILITY, event.availability.toProviderValue())
|
||||||
|
if (event.accessLevel != AccessLevel.Default) {
|
||||||
|
put(CalendarContract.Events.ACCESS_LEVEL, event.accessLevel.toProviderValue())
|
||||||
|
}
|
||||||
|
put(CalendarContract.Events.STATUS, event.status.forNewEvent().toProviderStatus())
|
||||||
|
event.location?.trim()?.takeIf { it.isNotEmpty() }
|
||||||
|
?.let { put(CalendarContract.Events.EVENT_LOCATION, it) }
|
||||||
|
event.description?.trim()?.takeIf { it.isNotEmpty() }
|
||||||
|
?.let { put(CalendarContract.Events.DESCRIPTION, it) }
|
||||||
|
event.color?.let { color ->
|
||||||
|
val key = palette.nearestTo(color)?.key
|
||||||
|
putAll(eventColorColumns(colorKey = key, color = if (key == null) color else null))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Provider `DURATION` for an imported recurring row: whole days for an all-day
|
||||||
|
* series, seconds otherwise. An all-day series is never shorter than a day —
|
||||||
|
* the provider expands a zero-length one into no instances at all, so the
|
||||||
|
* series would vanish (which is what a literal read of the Fossify family's
|
||||||
|
* inclusive DTEND used to produce; see "Importing foreign .ics" in
|
||||||
|
* docs/ARCHITECTURE.md).
|
||||||
|
*/
|
||||||
|
private fun importDuration(startMillis: Long, endMillis: Long, isAllDay: Boolean): String {
|
||||||
|
val span = (endMillis - startMillis).coerceAtLeast(0)
|
||||||
|
return rfc2445Duration(if (isAllDay) span.coerceAtLeast(MILLIS_PER_DAY) else span, isAllDay)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun EventStatus.toProviderStatus(): Int = when (this) {
|
||||||
|
EventStatus.Confirmed -> CalendarContract.Events.STATUS_CONFIRMED
|
||||||
|
EventStatus.Tentative -> CalendarContract.Events.STATUS_TENTATIVE
|
||||||
|
EventStatus.Cancelled -> CalendarContract.Events.STATUS_CANCELED
|
||||||
|
}
|
||||||
@@ -1,9 +1,13 @@
|
|||||||
package de.jeanlucmakiola.calendula.data.calendar
|
package de.jeanlucmakiola.calendula.data.calendar
|
||||||
|
|
||||||
import de.jeanlucmakiola.calendula.domain.EventStatus
|
import de.jeanlucmakiola.floret.time.toKotlinInstantFromEpochMillis
|
||||||
|
import de.jeanlucmakiola.calendula.domain.AccessLevel
|
||||||
import de.jeanlucmakiola.calendula.domain.ics.IcsEvent
|
import de.jeanlucmakiola.calendula.domain.ics.IcsEvent
|
||||||
import de.jeanlucmakiola.calendula.domain.ics.deriveIcsUid
|
import de.jeanlucmakiola.calendula.domain.ics.deriveIcsUid
|
||||||
import de.jeanlucmakiola.calendula.domain.ics.parseRfc2445DurationMillis
|
import java.time.Instant
|
||||||
|
import java.time.LocalDate
|
||||||
|
import java.time.ZoneId
|
||||||
|
import java.time.format.DateTimeFormatter
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Map one Events row (read through [EventExportProjection]) into an [IcsEvent]
|
* Map one Events row (read through [EventExportProjection]) into an [IcsEvent]
|
||||||
@@ -11,44 +15,135 @@ import de.jeanlucmakiola.calendula.domain.ics.parseRfc2445DurationMillis
|
|||||||
* [calendarName] the display name of its calendar (emitted as
|
* [calendarName] the display name of its calendar (emitted as
|
||||||
* `X-CALENDULA-CALENDAR`). Pure given a [ColumnReader] — JVM-tested with
|
* `X-CALENDULA-CALENDAR`). Pure given a [ColumnReader] — JVM-tested with
|
||||||
* MapColumnReader.
|
* MapColumnReader.
|
||||||
|
*
|
||||||
|
* An all-day row's raw offset has the firing time of day encoded into it and is
|
||||||
|
* normally *negative* (see [AllDayReminderEncoding]); written out literally it
|
||||||
|
* would be dropped as a trigger that fires after the event, losing the reminder.
|
||||||
|
* [allDayReminderTimeMinutes] and [zone] decode it back to the whole-day lead
|
||||||
|
* time the file should carry, which an import re-encodes for its own device.
|
||||||
*/
|
*/
|
||||||
internal fun ColumnReader.toIcsEvent(
|
internal fun ColumnReader.toIcsEvent(
|
||||||
reminderMinutes: List<Int>,
|
reminderMinutes: List<Int>,
|
||||||
calendarName: String?,
|
calendarName: String?,
|
||||||
|
allDayReminderTimeMinutes: Int,
|
||||||
|
zone: ZoneId = ZoneId.systemDefault(),
|
||||||
): IcsEvent {
|
): IcsEvent {
|
||||||
val eventId = getLong(EventExportProjection.IDX_ID)
|
val eventId = getLong(EventExportProjection.IDX_ID)
|
||||||
val dtStart = getLong(EventExportProjection.IDX_DTSTART)
|
val dtStart = getLong(EventExportProjection.IDX_DTSTART)
|
||||||
val rrule = getString(EventExportProjection.IDX_RRULE)?.takeIf { it.isNotBlank() }
|
val rrule = getString(EventExportProjection.IDX_RRULE)?.takeIf { it.isNotBlank() }
|
||||||
|
val isAllDay = getInt(EventExportProjection.IDX_ALL_DAY) != 0
|
||||||
|
val timezone = getString(EventExportProjection.IDX_EVENT_TIMEZONE)
|
||||||
|
val rdates = exportRecurrenceDates(getString(EventExportProjection.IDX_RDATE), isAllDay, timezone, dtStart)
|
||||||
|
|
||||||
// Recurring rows store DURATION instead of DTEND; reconstruct the end from it
|
// Unclamped: the writer renders DTEND as stored.
|
||||||
// so the writer can render DTEND. A missing/blank both means a zero-length event.
|
val end = endMillis(dtStart, EventExportProjection.IDX_DTEND, EventExportProjection.IDX_DURATION)
|
||||||
val end = when {
|
|
||||||
!isNull(EventExportProjection.IDX_DTEND) -> getLong(EventExportProjection.IDX_DTEND)
|
|
||||||
else -> dtStart + parseRfc2445DurationMillis(getString(EventExportProjection.IDX_DURATION))
|
|
||||||
}
|
|
||||||
|
|
||||||
// STATUS shares value 0 with TENTATIVE, so an absent column must read as Confirmed.
|
|
||||||
val status = if (isNull(EventExportProjection.IDX_STATUS)) {
|
|
||||||
EventStatus.Confirmed
|
|
||||||
} else {
|
|
||||||
mapEventStatus(getInt(EventExportProjection.IDX_STATUS))
|
|
||||||
}
|
|
||||||
|
|
||||||
return IcsEvent(
|
return IcsEvent(
|
||||||
uid = deriveIcsUid(getString(EventExportProjection.IDX_UID), eventId, dtStart),
|
uid = deriveIcsUid(getString(EventExportProjection.IDX_UID), eventId, dtStart),
|
||||||
summary = getString(EventExportProjection.IDX_TITLE).orEmpty(),
|
summary = getString(EventExportProjection.IDX_TITLE).orEmpty(),
|
||||||
start = dtStart.toKotlinInstantFromEpochMillis(),
|
start = dtStart.toKotlinInstantFromEpochMillis(),
|
||||||
end = end.toKotlinInstantFromEpochMillis(),
|
end = end.toKotlinInstantFromEpochMillis(),
|
||||||
isAllDay = getInt(EventExportProjection.IDX_ALL_DAY) != 0,
|
isAllDay = isAllDay,
|
||||||
zoneId = getString(EventExportProjection.IDX_EVENT_TIMEZONE)?.takeIf { it.isNotBlank() }
|
zoneId = timezone?.takeIf { it.isNotBlank() } ?: "UTC",
|
||||||
?: "UTC",
|
|
||||||
recurrenceRule = rrule,
|
recurrenceRule = rrule,
|
||||||
|
exDates = if (rrule == null && rdates.isEmpty()) {
|
||||||
|
emptyList()
|
||||||
|
} else {
|
||||||
|
exportExDates(getString(EventExportProjection.IDX_EXDATE), isAllDay, timezone, dtStart)
|
||||||
|
},
|
||||||
location = getString(EventExportProjection.IDX_LOCATION),
|
location = getString(EventExportProjection.IDX_LOCATION),
|
||||||
description = getString(EventExportProjection.IDX_DESCRIPTION),
|
description = getString(EventExportProjection.IDX_DESCRIPTION),
|
||||||
reminderMinutes = reminderMinutes,
|
reminderMinutes = if (isAllDay) {
|
||||||
status = status,
|
val startDate = utcDate(dtStart)
|
||||||
|
reminderMinutes.map {
|
||||||
|
fromProviderAllDayMinutes(it, startDate, zone, allDayReminderTimeMinutes)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
reminderMinutes
|
||||||
|
},
|
||||||
|
status = eventStatus(EventExportProjection.IDX_STATUS),
|
||||||
availability = mapAvailability(getInt(EventExportProjection.IDX_AVAILABILITY)),
|
availability = mapAvailability(getInt(EventExportProjection.IDX_AVAILABILITY)),
|
||||||
calendarName = calendarName,
|
calendarName = calendarName,
|
||||||
|
recurrenceDates = rdates,
|
||||||
|
accessLevel = getIntOrNull(EventExportProjection.IDX_ACCESS_LEVEL)?.let(::mapAccessLevel) ?: AccessLevel.Default,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The row's `EXDATE` as the writer wants it: one stamp per entry, empties
|
||||||
|
* dropped.
|
||||||
|
*
|
||||||
|
* An all-day exclusion names a calendar day, and sync adapters are inconsistent
|
||||||
|
* about whether they write it as a bare `yyyyMMdd` or pad it to a midnight
|
||||||
|
* stamp; the time part is dropped so the exported value is the day either way.
|
||||||
|
* Calendula's own writes ([buildOccurrenceExdateValues]) are already bare.
|
||||||
|
*
|
||||||
|
* A zoned exclusion arrives in AOSP's `RecurrenceSet` form, `<zone>;<stamps>`,
|
||||||
|
* where the prefix names the zone the whole list is wall clock in. [IcsWriter]
|
||||||
|
* emits one bare `EXDATE:` line, and a parameter belongs before that colon, not
|
||||||
|
* inside the value — passed on as-is it would make the line unparseable. The
|
||||||
|
* prefix is therefore taken off and its stamps resolved to UTC instants
|
||||||
|
* ([canonicalExdateStamp], the same reading the write path does), the form every
|
||||||
|
* reader accepts.
|
||||||
|
*
|
||||||
|
* Which zone that resolution uses is [exdateListZone]'s call, the same one the
|
||||||
|
* write path makes: the `TZID=` when this device's tz database knows the name,
|
||||||
|
* else the row's own [eventTimezone]. A stamp is never emitted floating just
|
||||||
|
* because the prefix named a zone we couldn't place — against a `DTSTART;TZID=…`
|
||||||
|
* line every reader would resolve it in its own zone and the exclusion would stop
|
||||||
|
* matching its occurrence.
|
||||||
|
*/
|
||||||
|
internal fun exportExDates(
|
||||||
|
exdate: String?,
|
||||||
|
isAllDay: Boolean,
|
||||||
|
eventTimezone: String? = null,
|
||||||
|
seriesStartMillis: Long? = null,
|
||||||
|
): List<String> {
|
||||||
|
if (exdate.isNullOrBlank()) return emptyList()
|
||||||
|
// Several properties are stored one per line, each with its own zone prefix.
|
||||||
|
return exdate.lines().filter { it.isNotBlank() }.flatMap { line ->
|
||||||
|
val zone = exdateListZone(line, eventTimezone)
|
||||||
|
exdateStamps(line).mapNotNull { stamp ->
|
||||||
|
when {
|
||||||
|
isAllDay -> stamp.substringBefore('T')
|
||||||
|
// A bare day on a timed series means the occurrence at the series' time of day.
|
||||||
|
seriesStartMillis != null && BARE_DAY.matches(stamp) -> atSeriesTime(stamp, seriesStartMillis, zone)
|
||||||
|
else -> canonicalExdateStamp(stamp, isAllDay = false, listZone = zone) ?: stamp
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.filter { (if (isAllDay) BARE_DAY else UTC_STAMP).matches(it) }
|
||||||
|
.distinct()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The row's `RDATE` in the same shape [exportExDates] gives `EXDATE` — the list
|
||||||
|
* shares its `<zone>;<stamps>` form. A `PERIOD` entry (`start/end`) keeps only its
|
||||||
|
* start: the occurrence then runs the series' own length. Anything that still
|
||||||
|
* isn't a date or a UTC stamp is dropped, since a file can't name it.
|
||||||
|
*/
|
||||||
|
internal fun exportRecurrenceDates(
|
||||||
|
rdate: String?,
|
||||||
|
isAllDay: Boolean,
|
||||||
|
eventTimezone: String? = null,
|
||||||
|
seriesStartMillis: Long? = null,
|
||||||
|
): List<String> {
|
||||||
|
if (rdate.isNullOrBlank()) return emptyList()
|
||||||
|
// The zone prefix may hold a '/' of its own (Europe/Berlin), so only the stamps lose their period end.
|
||||||
|
val starts = rdate.lines().joinToString("\n") { line ->
|
||||||
|
val stamps = line.withoutExdateParameters()
|
||||||
|
line.dropLast(stamps.length) + stamps.split(',').joinToString(",") { it.substringBefore('/') }
|
||||||
|
}
|
||||||
|
return exportExDates(starts, isAllDay, eventTimezone, seriesStartMillis)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** [day] (`yyyyMMdd`) at the wall-clock time the series starts at in [zone], as a UTC stamp. */
|
||||||
|
private fun atSeriesTime(day: String, seriesStartMillis: Long, zone: ZoneId): String? {
|
||||||
|
val date = runCatching { LocalDate.parse(day, DateTimeFormatter.BASIC_ISO_DATE) }.getOrNull() ?: return null
|
||||||
|
val time = Instant.ofEpochMilli(seriesStartMillis).atZone(zone).toLocalTime()
|
||||||
|
return formatExdateStamp(date.atTime(time).atZone(zone).toInstant().toEpochMilli(), isAllDay = false)
|
||||||
|
}
|
||||||
|
|
||||||
|
private val BARE_DAY = Regex("""\d{8}""")
|
||||||
|
private val UTC_STAMP = Regex("""\d{8}T\d{6}Z""")
|
||||||
|
|
||||||
@@ -1,7 +1,10 @@
|
|||||||
package de.jeanlucmakiola.calendula.data.calendar
|
package de.jeanlucmakiola.calendula.data.calendar
|
||||||
|
|
||||||
|
import de.jeanlucmakiola.floret.time.toKotlinInstantFromEpochMillis
|
||||||
|
import android.provider.CalendarContract
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import de.jeanlucmakiola.calendula.domain.EventInstance
|
import de.jeanlucmakiola.calendula.domain.EventInstance
|
||||||
|
import de.jeanlucmakiola.calendula.domain.EventResponse
|
||||||
|
|
||||||
private const val TAG = "InstanceMapper"
|
private const val TAG = "InstanceMapper"
|
||||||
|
|
||||||
@@ -18,14 +21,11 @@ internal fun ColumnReader.toEventInstance(): EventInstance? {
|
|||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
val rawTitle = getString(InstanceProjection.IDX_TITLE)
|
// Left blank when the event has no title: the placeholder is a display
|
||||||
val title = if (rawTitle.isNullOrEmpty()) Fallbacks.UNTITLED_EVENT else rawTitle
|
// string, so it belongs to the UI layer where it can be localised (#321).
|
||||||
|
val title = getString(InstanceProjection.IDX_TITLE).orEmpty()
|
||||||
|
|
||||||
val color = if (isNull(InstanceProjection.IDX_EVENT_COLOR)) {
|
val color = getIntOrNull(InstanceProjection.IDX_EVENT_COLOR) ?: getInt(InstanceProjection.IDX_CALENDAR_COLOR)
|
||||||
getInt(InstanceProjection.IDX_CALENDAR_COLOR)
|
|
||||||
} else {
|
|
||||||
getInt(InstanceProjection.IDX_EVENT_COLOR)
|
|
||||||
}
|
|
||||||
|
|
||||||
return EventInstance(
|
return EventInstance(
|
||||||
instanceId = getLong(InstanceProjection.IDX_INSTANCE_ID),
|
instanceId = getLong(InstanceProjection.IDX_INSTANCE_ID),
|
||||||
@@ -37,5 +37,25 @@ internal fun ColumnReader.toEventInstance(): EventInstance? {
|
|||||||
isAllDay = getInt(InstanceProjection.IDX_ALL_DAY) != 0,
|
isAllDay = getInt(InstanceProjection.IDX_ALL_DAY) != 0,
|
||||||
color = color,
|
color = color,
|
||||||
location = getString(InstanceProjection.IDX_LOCATION),
|
location = getString(InstanceProjection.IDX_LOCATION),
|
||||||
|
response = mapEventResponse(getInt(InstanceProjection.IDX_SELF_ATTENDEE_STATUS)),
|
||||||
|
status = eventStatus(InstanceProjection.IDX_STATUS),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A [CancelledEventProjection] row as an instance. Its id is the negated event
|
||||||
|
* id, so it can't collide with a provider instance id.
|
||||||
|
*/
|
||||||
|
internal fun ColumnReader.toCancelledOneOff(): EventInstance? =
|
||||||
|
toEventInstance()?.let { it.copy(instanceId = -it.eventId) }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `SELF_ATTENDEE_STATUS` as the calendar surfaces read it: a tentative "maybe"
|
||||||
|
* counts as going, and everything that is not an open or refused invitation —
|
||||||
|
* your own events included — falls through to [EventResponse.Going].
|
||||||
|
*/
|
||||||
|
internal fun mapEventResponse(raw: Int): EventResponse = when (raw) {
|
||||||
|
CalendarContract.Attendees.ATTENDEE_STATUS_DECLINED -> EventResponse.Declined
|
||||||
|
CalendarContract.Attendees.ATTENDEE_STATUS_INVITED -> EventResponse.Invited
|
||||||
|
else -> EventResponse.Going
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.data.calendar
|
||||||
|
|
||||||
|
import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One of the app's special-dates calendars, discovered by the marker stamped in
|
||||||
|
* its `CAL_SYNC2` column — so the mirror can re-adopt its calendars even if the
|
||||||
|
* stored ids in preferences were lost (e.g. an app-data wipe).
|
||||||
|
*/
|
||||||
|
data class ManagedCalendarRow(val id: Long, val type: SpecialDateType)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A managed event as read back for the sync diff. [uid] is the deterministic
|
||||||
|
* `Events.UID_2445` (`contact-<type>:<lookupKey>@calendula`) the mirror keys on;
|
||||||
|
* [title], [dtStartMillis] and [rrule] are the managed columns compared against
|
||||||
|
* the desired state to decide whether a targeted update is needed.
|
||||||
|
*/
|
||||||
|
data class ManagedEventRow(
|
||||||
|
val eventId: Long,
|
||||||
|
val uid: String,
|
||||||
|
val title: String,
|
||||||
|
val dtStartMillis: Long,
|
||||||
|
val rrule: String?,
|
||||||
|
)
|
||||||
@@ -1,7 +1,16 @@
|
|||||||
package de.jeanlucmakiola.calendula.data.calendar
|
package de.jeanlucmakiola.calendula.data.calendar
|
||||||
|
|
||||||
|
import android.content.ContentUris
|
||||||
|
import android.net.Uri
|
||||||
import android.provider.CalendarContract
|
import android.provider.CalendarContract
|
||||||
|
|
||||||
|
/** The `Instances` table over the window [beginMillis]..[endMillis]. */
|
||||||
|
internal fun instancesUri(beginMillis: Long, endMillis: Long): Uri =
|
||||||
|
CalendarContract.Instances.CONTENT_URI.buildUpon().apply {
|
||||||
|
ContentUris.appendId(this, beginMillis)
|
||||||
|
ContentUris.appendId(this, endMillis)
|
||||||
|
}.build()
|
||||||
|
|
||||||
internal object CalendarProjection {
|
internal object CalendarProjection {
|
||||||
val COLUMNS: Array<String> = arrayOf(
|
val COLUMNS: Array<String> = arrayOf(
|
||||||
CalendarContract.Calendars._ID,
|
CalendarContract.Calendars._ID,
|
||||||
@@ -15,9 +24,18 @@ internal object CalendarProjection {
|
|||||||
// own we stash one in CAL_SYNC1 (synced rows put their sync token here,
|
// own we stash one in CAL_SYNC1 (synced rows put their sync token here,
|
||||||
// so the mapper only reads it for local calendars).
|
// so the mapper only reads it for local calendars).
|
||||||
DESCRIPTION_COLUMN,
|
DESCRIPTION_COLUMN,
|
||||||
|
// The special-dates marker (CAL_SYNC2) — the durable identity the app
|
||||||
|
// uses to recognise its own managed calendars, independent of any
|
||||||
|
// stored preference id (which a backup restore / data wipe can lose).
|
||||||
|
MANAGED_MARKER_COLUMN,
|
||||||
|
CalendarContract.Calendars.SYNC_EVENTS,
|
||||||
)
|
)
|
||||||
|
|
||||||
const val DESCRIPTION_COLUMN: String = CalendarContract.Calendars.CAL_SYNC1
|
const val DESCRIPTION_COLUMN: String = CalendarContract.Calendars.CAL_SYNC1
|
||||||
|
const val MANAGED_MARKER_COLUMN: String = CalendarContract.Calendars.CAL_SYNC2
|
||||||
|
|
||||||
|
/** Namespace prefix of every managed-calendar [MANAGED_MARKER_COLUMN] value. */
|
||||||
|
const val MANAGED_MARKER_PREFIX = "calendula.specialdates"
|
||||||
|
|
||||||
const val IDX_ID = 0
|
const val IDX_ID = 0
|
||||||
const val IDX_DISPLAY_NAME = 1
|
const val IDX_DISPLAY_NAME = 1
|
||||||
@@ -27,6 +45,8 @@ internal object CalendarProjection {
|
|||||||
const val IDX_VISIBLE = 5
|
const val IDX_VISIBLE = 5
|
||||||
const val IDX_ACCESS_LEVEL = 6
|
const val IDX_ACCESS_LEVEL = 6
|
||||||
const val IDX_DESCRIPTION = 7
|
const val IDX_DESCRIPTION = 7
|
||||||
|
const val IDX_MANAGED_MARKER = 8
|
||||||
|
const val IDX_SYNC_EVENTS = 9
|
||||||
}
|
}
|
||||||
|
|
||||||
internal object InstanceProjection {
|
internal object InstanceProjection {
|
||||||
@@ -41,6 +61,8 @@ internal object InstanceProjection {
|
|||||||
CalendarContract.Instances.EVENT_COLOR,
|
CalendarContract.Instances.EVENT_COLOR,
|
||||||
CalendarContract.Instances.CALENDAR_COLOR,
|
CalendarContract.Instances.CALENDAR_COLOR,
|
||||||
CalendarContract.Instances.EVENT_LOCATION,
|
CalendarContract.Instances.EVENT_LOCATION,
|
||||||
|
CalendarContract.Instances.SELF_ATTENDEE_STATUS,
|
||||||
|
CalendarContract.Instances.STATUS,
|
||||||
)
|
)
|
||||||
|
|
||||||
const val IDX_INSTANCE_ID = 0
|
const val IDX_INSTANCE_ID = 0
|
||||||
@@ -53,6 +75,30 @@ internal object InstanceProjection {
|
|||||||
const val IDX_EVENT_COLOR = 7
|
const val IDX_EVENT_COLOR = 7
|
||||||
const val IDX_CALENDAR_COLOR = 8
|
const val IDX_CALENDAR_COLOR = 8
|
||||||
const val IDX_LOCATION = 9
|
const val IDX_LOCATION = 9
|
||||||
|
const val IDX_SELF_ATTENDEE_STATUS = 10
|
||||||
|
const val IDX_STATUS = 11
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A cancelled one-off straight from the Events table, laid out on
|
||||||
|
* [InstanceProjection]'s indices so [toCancelledOneOff] reuses its mapper. AOSP
|
||||||
|
* writes no Instances rows for a cancelled event (#388).
|
||||||
|
*/
|
||||||
|
internal object CancelledEventProjection {
|
||||||
|
val COLUMNS: Array<String> = arrayOf(
|
||||||
|
CalendarContract.Events._ID,
|
||||||
|
CalendarContract.Events._ID,
|
||||||
|
CalendarContract.Events.CALENDAR_ID,
|
||||||
|
CalendarContract.Events.TITLE,
|
||||||
|
CalendarContract.Events.DTSTART,
|
||||||
|
CalendarContract.Events.DTEND,
|
||||||
|
CalendarContract.Events.ALL_DAY,
|
||||||
|
CalendarContract.Events.EVENT_COLOR,
|
||||||
|
CalendarContract.Events.CALENDAR_COLOR,
|
||||||
|
CalendarContract.Events.EVENT_LOCATION,
|
||||||
|
CalendarContract.Events.SELF_ATTENDEE_STATUS,
|
||||||
|
CalendarContract.Events.STATUS,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
internal object EventDetailProjection {
|
internal object EventDetailProjection {
|
||||||
@@ -75,6 +121,12 @@ internal object EventDetailProjection {
|
|||||||
CalendarContract.Events.EVENT_TIMEZONE,
|
CalendarContract.Events.EVENT_TIMEZONE,
|
||||||
CalendarContract.Events.SELF_ATTENDEE_STATUS,
|
CalendarContract.Events.SELF_ATTENDEE_STATUS,
|
||||||
CalendarContract.Events.EVENT_COLOR_KEY,
|
CalendarContract.Events.EVENT_COLOR_KEY,
|
||||||
|
// Recurring rows carry DURATION instead of DTEND; the detail screen
|
||||||
|
// needs it to render a series opened without a named occurrence.
|
||||||
|
CalendarContract.Events.DURATION,
|
||||||
|
// Non-null on a modified-occurrence exception row; "no RRULE" alone
|
||||||
|
// can't tell an exception from a master (#68).
|
||||||
|
CalendarContract.Events.ORIGINAL_ID,
|
||||||
)
|
)
|
||||||
|
|
||||||
const val IDX_EVENT_ID = 0
|
const val IDX_EVENT_ID = 0
|
||||||
@@ -95,15 +147,18 @@ internal object EventDetailProjection {
|
|||||||
const val IDX_EVENT_TIMEZONE = 15
|
const val IDX_EVENT_TIMEZONE = 15
|
||||||
const val IDX_SELF_ATTENDEE_STATUS = 16
|
const val IDX_SELF_ATTENDEE_STATUS = 16
|
||||||
const val IDX_EVENT_COLOR_KEY = 17
|
const val IDX_EVENT_COLOR_KEY = 17
|
||||||
|
const val IDX_DURATION = 18
|
||||||
|
const val IDX_ORIGINAL_ID = 19
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Master/one-off Events rows for a whole-calendar backup. Unlike
|
* Every Events row of a whole-calendar backup or copy. Unlike
|
||||||
* [EventDetailProjection] this reads `UID_2445` (to keep a row's identity across
|
* [EventDetailProjection] this reads `UID_2445` (to keep a row's identity across
|
||||||
* backups) and `DURATION` (recurring rows carry it instead of DTEND). Modified-
|
* backups) and `DURATION` (recurring rows carry it instead of DTEND), plus
|
||||||
* occurrence and cancelled-exception rows are filtered out by the query
|
* `EXDATE` so a series exports the occurrences deleted from it. Exception rows
|
||||||
* (`ORIGINAL_ID IS NULL`), so RECURRENCE-ID overrides and EXDATEs aren't
|
* are read too and told apart by their series-link columns; see
|
||||||
* exported yet — a documented v1 limit (import skips them too).
|
* [de.jeanlucmakiola.calendula.domain.ics.flattenOverrides] for how they are
|
||||||
|
* written out.
|
||||||
*/
|
*/
|
||||||
internal object EventExportProjection {
|
internal object EventExportProjection {
|
||||||
val COLUMNS: Array<String> = arrayOf(
|
val COLUMNS: Array<String> = arrayOf(
|
||||||
@@ -116,11 +171,21 @@ internal object EventExportProjection {
|
|||||||
CalendarContract.Events.ALL_DAY,
|
CalendarContract.Events.ALL_DAY,
|
||||||
CalendarContract.Events.EVENT_TIMEZONE,
|
CalendarContract.Events.EVENT_TIMEZONE,
|
||||||
CalendarContract.Events.RRULE,
|
CalendarContract.Events.RRULE,
|
||||||
|
CalendarContract.Events.EXDATE,
|
||||||
CalendarContract.Events.EVENT_LOCATION,
|
CalendarContract.Events.EVENT_LOCATION,
|
||||||
CalendarContract.Events.DESCRIPTION,
|
CalendarContract.Events.DESCRIPTION,
|
||||||
CalendarContract.Events.STATUS,
|
CalendarContract.Events.STATUS,
|
||||||
CalendarContract.Events.AVAILABILITY,
|
CalendarContract.Events.AVAILABILITY,
|
||||||
CalendarContract.Events.CALENDAR_ID,
|
CalendarContract.Events.CALENDAR_ID,
|
||||||
|
CalendarContract.Events.EVENT_COLOR,
|
||||||
|
CalendarContract.Events._SYNC_ID,
|
||||||
|
CalendarContract.Events.ORIGINAL_ID,
|
||||||
|
CalendarContract.Events.ORIGINAL_SYNC_ID,
|
||||||
|
CalendarContract.Events.ORIGINAL_INSTANCE_TIME,
|
||||||
|
CalendarContract.Events.RDATE,
|
||||||
|
CalendarContract.Events.ACCESS_LEVEL,
|
||||||
|
CalendarContract.Events.EVENT_COLOR_KEY,
|
||||||
|
CalendarContract.Events.SELF_ATTENDEE_STATUS,
|
||||||
)
|
)
|
||||||
|
|
||||||
const val IDX_ID = 0
|
const val IDX_ID = 0
|
||||||
@@ -132,11 +197,21 @@ internal object EventExportProjection {
|
|||||||
const val IDX_ALL_DAY = 6
|
const val IDX_ALL_DAY = 6
|
||||||
const val IDX_EVENT_TIMEZONE = 7
|
const val IDX_EVENT_TIMEZONE = 7
|
||||||
const val IDX_RRULE = 8
|
const val IDX_RRULE = 8
|
||||||
const val IDX_LOCATION = 9
|
const val IDX_EXDATE = 9
|
||||||
const val IDX_DESCRIPTION = 10
|
const val IDX_LOCATION = 10
|
||||||
const val IDX_STATUS = 11
|
const val IDX_DESCRIPTION = 11
|
||||||
const val IDX_AVAILABILITY = 12
|
const val IDX_STATUS = 12
|
||||||
const val IDX_CALENDAR_ID = 13
|
const val IDX_AVAILABILITY = 13
|
||||||
|
const val IDX_CALENDAR_ID = 14
|
||||||
|
const val IDX_EVENT_COLOR = 15
|
||||||
|
const val IDX_SYNC_ID = 16
|
||||||
|
const val IDX_ORIGINAL_ID = 17
|
||||||
|
const val IDX_ORIGINAL_SYNC_ID = 18
|
||||||
|
const val IDX_ORIGINAL_INSTANCE_TIME = 19
|
||||||
|
const val IDX_RDATE = 20
|
||||||
|
const val IDX_ACCESS_LEVEL = 21
|
||||||
|
const val IDX_EVENT_COLOR_KEY = 22
|
||||||
|
const val IDX_SELF_ATTENDEE_STATUS = 23
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -161,6 +236,10 @@ internal object SearchProjection {
|
|||||||
// display its nearest occurrence, not the series-start DTSTART.
|
// display its nearest occurrence, not the series-start DTSTART.
|
||||||
CalendarContract.Events.RRULE,
|
CalendarContract.Events.RRULE,
|
||||||
CalendarContract.Events.RDATE,
|
CalendarContract.Events.RDATE,
|
||||||
|
// Excerpted, not just filtered on: a hit has to show what it matched.
|
||||||
|
CalendarContract.Events.DESCRIPTION,
|
||||||
|
CalendarContract.Events.SELF_ATTENDEE_STATUS,
|
||||||
|
CalendarContract.Events.STATUS,
|
||||||
)
|
)
|
||||||
|
|
||||||
const val IDX_ID = 0
|
const val IDX_ID = 0
|
||||||
@@ -175,6 +254,75 @@ internal object SearchProjection {
|
|||||||
const val IDX_LOCATION = 9
|
const val IDX_LOCATION = 9
|
||||||
const val IDX_RRULE = 10
|
const val IDX_RRULE = 10
|
||||||
const val IDX_RDATE = 11
|
const val IDX_RDATE = 11
|
||||||
|
const val IDX_DESCRIPTION = 12
|
||||||
|
const val IDX_SELF_ATTENDEE_STATUS = 13
|
||||||
|
const val IDX_STATUS = 14
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The master/one-off Events row of an event about to be moved to another
|
||||||
|
* calendar, read for a verbatim re-insert (see [MasterEventSnapshot]). Carries
|
||||||
|
* the full recurrence skeleton (RRULE/DURATION, RDATE/EXDATE) so the moved copy
|
||||||
|
* generates the same instances, and `UID_2445` so identity survives the move.
|
||||||
|
*/
|
||||||
|
internal object MoveMasterProjection {
|
||||||
|
val COLUMNS: Array<String> = arrayOf(
|
||||||
|
CalendarContract.Events.UID_2445,
|
||||||
|
CalendarContract.Events.TITLE,
|
||||||
|
CalendarContract.Events.DTSTART,
|
||||||
|
CalendarContract.Events.DTEND,
|
||||||
|
CalendarContract.Events.DURATION,
|
||||||
|
CalendarContract.Events.RRULE,
|
||||||
|
CalendarContract.Events.RDATE,
|
||||||
|
CalendarContract.Events.EXDATE,
|
||||||
|
CalendarContract.Events.EVENT_TIMEZONE,
|
||||||
|
CalendarContract.Events.ALL_DAY,
|
||||||
|
CalendarContract.Events.AVAILABILITY,
|
||||||
|
CalendarContract.Events.ACCESS_LEVEL,
|
||||||
|
CalendarContract.Events.STATUS,
|
||||||
|
CalendarContract.Events.EVENT_LOCATION,
|
||||||
|
CalendarContract.Events.DESCRIPTION,
|
||||||
|
)
|
||||||
|
|
||||||
|
const val IDX_UID = 0
|
||||||
|
const val IDX_TITLE = 1
|
||||||
|
const val IDX_DTSTART = 2
|
||||||
|
const val IDX_DTEND = 3
|
||||||
|
const val IDX_DURATION = 4
|
||||||
|
const val IDX_RRULE = 5
|
||||||
|
const val IDX_RDATE = 6
|
||||||
|
const val IDX_EXDATE = 7
|
||||||
|
const val IDX_EVENT_TIMEZONE = 8
|
||||||
|
const val IDX_ALL_DAY = 9
|
||||||
|
const val IDX_AVAILABILITY = 10
|
||||||
|
const val IDX_ACCESS_LEVEL = 11
|
||||||
|
const val IDX_STATUS = 12
|
||||||
|
const val IDX_LOCATION = 13
|
||||||
|
const val IDX_DESCRIPTION = 14
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The exception rows of a recurring series (`ORIGINAL_ID` = the series), read to
|
||||||
|
* carry them over to a moved copy (see [ExceptionRowSnapshot]). Both modified
|
||||||
|
* occurrences and cancellations (`STATUS_CANCELED`) are read; the query filters
|
||||||
|
* `DELETED = 0` so provider tombstones aren't carried over.
|
||||||
|
*/
|
||||||
|
internal object ExceptionProjection {
|
||||||
|
val COLUMNS: Array<String> = arrayOf(
|
||||||
|
CalendarContract.Events._ID,
|
||||||
|
CalendarContract.Events.ORIGINAL_INSTANCE_TIME,
|
||||||
|
CalendarContract.Events.STATUS,
|
||||||
|
CalendarContract.Events.DTSTART,
|
||||||
|
CalendarContract.Events.DTEND,
|
||||||
|
CalendarContract.Events.DURATION,
|
||||||
|
)
|
||||||
|
|
||||||
|
const val IDX_ID = 0
|
||||||
|
const val IDX_ORIGINAL_INSTANCE_TIME = 1
|
||||||
|
const val IDX_STATUS = 2
|
||||||
|
const val IDX_DTSTART = 3
|
||||||
|
const val IDX_DTEND = 4
|
||||||
|
const val IDX_DURATION = 5
|
||||||
}
|
}
|
||||||
|
|
||||||
internal object AttendeeProjection {
|
internal object AttendeeProjection {
|
||||||
@@ -202,8 +350,3 @@ internal object ReminderProjection {
|
|||||||
const val IDX_MINUTES = 0
|
const val IDX_MINUTES = 0
|
||||||
const val IDX_METHOD = 1
|
const val IDX_METHOD = 1
|
||||||
}
|
}
|
||||||
|
|
||||||
internal object Fallbacks {
|
|
||||||
const val UNNAMED_CALENDAR = "(Unbenannter Kalender)"
|
|
||||||
const val UNTITLED_EVENT = "(Ohne Titel)"
|
|
||||||
}
|
|
||||||
+24
@@ -0,0 +1,24 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.data.calendar
|
||||||
|
|
||||||
|
import android.provider.CalendarContract
|
||||||
|
|
||||||
|
/**
|
||||||
|
* "Fire at whatever lead time this account defaults to" — a sentinel in the
|
||||||
|
* `Reminders.MINUTES` column, not an offset, so nothing may do arithmetic on it.
|
||||||
|
* `CalendarContract` never exposes what an account resolves it to, so Calendula
|
||||||
|
* neither fires such a row ([withoutProviderDefaults]) nor decodes it
|
||||||
|
* ([fromProviderAllDayMinutes]); the detail screen names it instead.
|
||||||
|
*
|
||||||
|
* It is the **only** negative that means this. A real all-day offset is often
|
||||||
|
* negative too — the firing time of day is encoded into it — so a `< 0` test
|
||||||
|
* would silence reminders that do fire.
|
||||||
|
*/
|
||||||
|
internal const val MINUTES_DEFAULT = CalendarContract.Reminders.MINUTES_DEFAULT
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Raw provider offsets with the account-default rows dropped, so the pure
|
||||||
|
* planner ([de.jeanlucmakiola.calendula.domain.reminders.planReminders]) only
|
||||||
|
* ever sees offsets it can resolve.
|
||||||
|
*/
|
||||||
|
internal fun Map<Long, List<Int>>.withoutProviderDefaults(): Map<Long, List<Int>> =
|
||||||
|
mapValues { (_, minutes) -> minutes.filter { it != MINUTES_DEFAULT } }
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.data.calendar
|
||||||
|
|
||||||
|
import android.content.ContentResolver
|
||||||
|
import android.provider.CalendarContract
|
||||||
|
|
||||||
|
/** Ids per `IN (…)` list: they go into the SQL literally, which SQLite bounds. */
|
||||||
|
private const val EVENT_ID_BATCH = 50
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reminder minutes of [eventIds], keyed by event, a batched query at a time
|
||||||
|
* rather than one per event. [alertsOnly] keeps just the notification ones.
|
||||||
|
*/
|
||||||
|
internal fun ContentResolver.reminderMinutesByEvent(
|
||||||
|
eventIds: Collection<Long>,
|
||||||
|
alertsOnly: Boolean,
|
||||||
|
): Map<Long, List<Int>> {
|
||||||
|
if (eventIds.isEmpty()) return emptyMap()
|
||||||
|
val out = mutableMapOf<Long, MutableList<Int>>()
|
||||||
|
val method = if (alertsOnly) {
|
||||||
|
"${CalendarContract.Reminders.METHOD} = ${CalendarContract.Reminders.METHOD_ALERT} AND "
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
}
|
||||||
|
eventIds.distinct().chunked(EVENT_ID_BATCH).forEach { batch ->
|
||||||
|
query(
|
||||||
|
CalendarContract.Reminders.CONTENT_URI,
|
||||||
|
arrayOf(CalendarContract.Reminders.EVENT_ID, CalendarContract.Reminders.MINUTES),
|
||||||
|
"$method${CalendarContract.Reminders.EVENT_ID} IN (${batch.joinToString(",")})",
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
)?.use { c ->
|
||||||
|
while (c.moveToNext()) out.getOrPut(c.getLong(0)) { mutableListOf() } += c.getInt(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
package de.jeanlucmakiola.calendula.data.calendar
|
package de.jeanlucmakiola.calendula.data.calendar
|
||||||
|
|
||||||
|
import de.jeanlucmakiola.floret.time.toKotlinInstantFromEpochMillis
|
||||||
import de.jeanlucmakiola.calendula.domain.EventInstance
|
import de.jeanlucmakiola.calendula.domain.EventInstance
|
||||||
import de.jeanlucmakiola.calendula.domain.ics.parseRfc2445DurationMillis
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Map an Events-table row (a search hit) to an [EventInstance]. Unlike the
|
* Map an Events-table row (a search hit) to an [EventInstance]. Unlike the
|
||||||
@@ -10,20 +10,16 @@ import de.jeanlucmakiola.calendula.domain.ics.parseRfc2445DurationMillis
|
|||||||
* of DTEND — reconstruct the end the same way the `.ics` export does.
|
* of DTEND — reconstruct the end the same way the `.ics` export does.
|
||||||
*/
|
*/
|
||||||
internal fun ColumnReader.toSearchResult(): EventInstance? {
|
internal fun ColumnReader.toSearchResult(): EventInstance? {
|
||||||
|
// A pre-1970 series anchor is a legitimately negative epoch-millis DTSTART
|
||||||
|
// (see EventDetailMapper / issue #34); drop only a genuinely absent one, so
|
||||||
|
// long-running birthdays/anniversaries still surface in search.
|
||||||
|
if (isNull(SearchProjection.IDX_DTSTART)) return null
|
||||||
val dtStart = getLong(SearchProjection.IDX_DTSTART)
|
val dtStart = getLong(SearchProjection.IDX_DTSTART)
|
||||||
if (dtStart < 0L) return null
|
val end = endMillis(dtStart, SearchProjection.IDX_DTEND, SearchProjection.IDX_DURATION)
|
||||||
val end = when {
|
.coerceAtLeast(dtStart)
|
||||||
!isNull(SearchProjection.IDX_DTEND) -> getLong(SearchProjection.IDX_DTEND)
|
|
||||||
else -> dtStart + parseRfc2445DurationMillis(getString(SearchProjection.IDX_DURATION))
|
|
||||||
}.coerceAtLeast(dtStart)
|
|
||||||
|
|
||||||
val rawTitle = getString(SearchProjection.IDX_TITLE)
|
val title = getString(SearchProjection.IDX_TITLE).orEmpty()
|
||||||
val title = if (rawTitle.isNullOrEmpty()) Fallbacks.UNTITLED_EVENT else rawTitle
|
val color = getIntOrNull(SearchProjection.IDX_EVENT_COLOR) ?: getInt(SearchProjection.IDX_CALENDAR_COLOR)
|
||||||
val color = if (isNull(SearchProjection.IDX_EVENT_COLOR)) {
|
|
||||||
getInt(SearchProjection.IDX_CALENDAR_COLOR)
|
|
||||||
} else {
|
|
||||||
getInt(SearchProjection.IDX_EVENT_COLOR)
|
|
||||||
}
|
|
||||||
val eventId = getLong(SearchProjection.IDX_ID)
|
val eventId = getLong(SearchProjection.IDX_ID)
|
||||||
|
|
||||||
return EventInstance(
|
return EventInstance(
|
||||||
@@ -36,5 +32,9 @@ internal fun ColumnReader.toSearchResult(): EventInstance? {
|
|||||||
isAllDay = getInt(SearchProjection.IDX_ALL_DAY) != 0,
|
isAllDay = getInt(SearchProjection.IDX_ALL_DAY) != 0,
|
||||||
color = color,
|
color = color,
|
||||||
location = getString(SearchProjection.IDX_LOCATION),
|
location = getString(SearchProjection.IDX_LOCATION),
|
||||||
|
isRecurring = !getString(SearchProjection.IDX_RRULE).isNullOrEmpty() ||
|
||||||
|
!getString(SearchProjection.IDX_RDATE).isNullOrEmpty(),
|
||||||
|
response = mapEventResponse(getInt(SearchProjection.IDX_SELF_ATTENDEE_STATUS)),
|
||||||
|
status = eventStatus(SearchProjection.IDX_STATUS),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,215 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.data.calendar
|
||||||
|
|
||||||
|
import android.accounts.Account
|
||||||
|
import android.accounts.AccountManager
|
||||||
|
import android.content.ContentResolver
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.provider.CalendarContract
|
||||||
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
|
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||||
|
import kotlinx.coroutines.channels.awaitClose
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
import kotlinx.coroutines.flow.callbackFlow
|
||||||
|
import kotlinx.coroutines.flow.channelFlow
|
||||||
|
import kotlinx.coroutines.flow.conflate
|
||||||
|
import kotlinx.coroutines.flow.filterNotNull
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
import kotlinx.coroutines.flow.map
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withTimeoutOrNull
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
/** The account behind a calendar row (`ACCOUNT_NAME` / `ACCOUNT_TYPE`). */
|
||||||
|
data class SyncAccount(val name: String, val type: String) {
|
||||||
|
/** Whether a sync adapter can stand behind it: device-only calendars have none. */
|
||||||
|
val isSyncable: Boolean
|
||||||
|
get() = name.isNotBlank() && type.isNotBlank() && type != CalendarContract.ACCOUNT_TYPE_LOCAL
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Asks the system to run a calendar sync adapter sooner (#303, #240). The sync
|
||||||
|
* itself stays the adapter's job; this only schedules it.
|
||||||
|
*/
|
||||||
|
interface SyncRequester {
|
||||||
|
/** Account types with a calendar sync adapter installed; for any other a request does nothing. */
|
||||||
|
fun adapterAccountTypes(): Set<String>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The accounts of [types] a request may name, or null when any may. From
|
||||||
|
* Android 13 a request for an account the app can't see is dropped without a word.
|
||||||
|
*/
|
||||||
|
fun addressableAccounts(types: Set<String>): Set<SyncAccount>?
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Schedule a sync of [account]; may throw if the system refuses. [userInitiated]
|
||||||
|
* marks it manual, which also overrides master-sync-off — only for a user's tap.
|
||||||
|
*/
|
||||||
|
fun requestSync(account: SyncAccount, userInitiated: Boolean)
|
||||||
|
|
||||||
|
/** Where [account]'s calendar sync stands, or null when the system won't say. */
|
||||||
|
fun syncActivity(account: SyncAccount): SyncActivity?
|
||||||
|
|
||||||
|
/** Fires whenever any sync on the device becomes pending, starts or ends. */
|
||||||
|
fun syncActivityChanges(): Flow<Unit>
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A calendar sync adapter's state for one account, from `READ_SYNC_STATS`. */
|
||||||
|
enum class SyncActivity { Idle, Pending, Active }
|
||||||
|
|
||||||
|
/** How waiting on requested syncs ended: seen through, or not confirmed in time. */
|
||||||
|
enum class SyncWait { Completed, Unconfirmed }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Waits until the syncs of [accounts] have run (#240): each account must have
|
||||||
|
* been seen pending or active and be idle again, or — for one that never showed
|
||||||
|
* up within [graceMillis] — be idle. A sync already running at the first look
|
||||||
|
* isn't the requested one, so it has to finish before the account counts. Unconfirmed after [timeoutMillis], or at
|
||||||
|
* once when the system won't report sync state.
|
||||||
|
*/
|
||||||
|
suspend fun SyncRequester.awaitSyncs(
|
||||||
|
accounts: Set<SyncAccount>,
|
||||||
|
timeoutMillis: Long = SYNC_WAIT_MILLIS,
|
||||||
|
graceMillis: Long = SYNC_GRACE_MILLIS,
|
||||||
|
pollMillis: Long = SYNC_POLL_MILLIS,
|
||||||
|
): SyncWait {
|
||||||
|
if (accounts.isEmpty()) return SyncWait.Completed
|
||||||
|
val seen = HashSet<SyncAccount>()
|
||||||
|
// One already running when asked is someone else's sync: it only counts once idle again.
|
||||||
|
var priorRuns: MutableSet<SyncAccount>? = null
|
||||||
|
val graceOver = AtomicBoolean(false)
|
||||||
|
return withTimeoutOrNull(timeoutMillis) {
|
||||||
|
channelFlow {
|
||||||
|
launch { syncActivityChanges().collect { send(Unit) } }
|
||||||
|
launch {
|
||||||
|
delay(graceMillis)
|
||||||
|
graceOver.set(true)
|
||||||
|
send(Unit)
|
||||||
|
}
|
||||||
|
// The listener alone can miss a change made before it was registered.
|
||||||
|
while (true) {
|
||||||
|
send(Unit)
|
||||||
|
delay(pollMillis)
|
||||||
|
}
|
||||||
|
}.conflate().map {
|
||||||
|
val states = accounts.associateWith { syncActivity(it) ?: return@map SyncWait.Unconfirmed }
|
||||||
|
val prior = priorRuns ?: states.filterValues { it == SyncActivity.Active }.keys.toMutableSet()
|
||||||
|
.also { priorRuns = it }
|
||||||
|
states.forEach { (account, state) ->
|
||||||
|
if (state != SyncActivity.Active) prior -= account
|
||||||
|
if (state != SyncActivity.Idle && account !in prior) seen += account
|
||||||
|
}
|
||||||
|
val done = states.all { (account, state) ->
|
||||||
|
state == SyncActivity.Idle && account !in prior && (account in seen || graceOver.get())
|
||||||
|
}
|
||||||
|
if (done) SyncWait.Completed else null
|
||||||
|
}.filterNotNull().first()
|
||||||
|
} ?: SyncWait.Unconfirmed
|
||||||
|
}
|
||||||
|
|
||||||
|
const val SYNC_WAIT_MILLIS = 60_000L
|
||||||
|
const val SYNC_GRACE_MILLIS = 5_000L
|
||||||
|
const val SYNC_POLL_MILLIS = 2_000L
|
||||||
|
|
||||||
|
@Singleton
|
||||||
|
class AndroidSyncRequester @Inject constructor(
|
||||||
|
@ApplicationContext private val context: Context,
|
||||||
|
) : SyncRequester {
|
||||||
|
// Lists only adapters in packages visible to the app — hence the SyncAdapter <queries> entry.
|
||||||
|
override fun adapterAccountTypes(): Set<String> =
|
||||||
|
ContentResolver.getSyncAdapterTypes()
|
||||||
|
.filter { it.authority == CalendarContract.AUTHORITY }
|
||||||
|
.mapTo(mutableSetOf()) { it.accountType }
|
||||||
|
|
||||||
|
override fun addressableAccounts(types: Set<String>): Set<SyncAccount>? {
|
||||||
|
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return null
|
||||||
|
val manager = AccountManager.get(context)
|
||||||
|
return types.flatMapTo(mutableSetOf()) { type ->
|
||||||
|
manager.getAccountsByType(type).map { SyncAccount(it.name, it.type) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun requestSync(account: SyncAccount, userInitiated: Boolean) {
|
||||||
|
val extras = Bundle().apply {
|
||||||
|
putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true)
|
||||||
|
if (userInitiated) putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true)
|
||||||
|
}
|
||||||
|
ContentResolver.requestSync(
|
||||||
|
Account(account.name, account.type),
|
||||||
|
CalendarContract.AUTHORITY,
|
||||||
|
extras,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun syncActivity(account: SyncAccount): SyncActivity? = try {
|
||||||
|
val android = Account(account.name, account.type)
|
||||||
|
when {
|
||||||
|
ContentResolver.isSyncActive(android, CalendarContract.AUTHORITY) -> SyncActivity.Active
|
||||||
|
ContentResolver.isSyncPending(android, CalendarContract.AUTHORITY) -> SyncActivity.Pending
|
||||||
|
else -> SyncActivity.Idle
|
||||||
|
}
|
||||||
|
} catch (e: SecurityException) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun syncActivityChanges(): Flow<Unit> = callbackFlow {
|
||||||
|
val handle = try {
|
||||||
|
ContentResolver.addStatusChangeListener(
|
||||||
|
ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE or ContentResolver.SYNC_OBSERVER_TYPE_PENDING,
|
||||||
|
) { trySend(Unit) }
|
||||||
|
} catch (e: SecurityException) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
awaitClose { handle?.let(ContentResolver::removeStatusChangeListener) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The distinct non-local accounts behind the visible calendars — what a manual refresh asks. */
|
||||||
|
fun List<CalendarSource>.syncAccounts(): Set<SyncAccount> =
|
||||||
|
filter { it.isVisibleInSystem }
|
||||||
|
.map { SyncAccount(it.accountName, it.accountType) }
|
||||||
|
.filterTo(linkedSetOf()) { it.isSyncable }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Who a sync request can go to: [reachable] by name, [needsAccess] only once the
|
||||||
|
* user lets the app see the account (Android 13+, see [accountAccessIntent]).
|
||||||
|
* [dismissed] are hidden accounts the user said not to ask about.
|
||||||
|
*/
|
||||||
|
data class SyncTargets(
|
||||||
|
val reachable: Set<SyncAccount>,
|
||||||
|
val needsAccess: Set<SyncAccount>,
|
||||||
|
val dismissed: Set<SyncAccount> = emptySet(),
|
||||||
|
) {
|
||||||
|
companion object {
|
||||||
|
val None = SyncTargets(emptySet(), emptySet())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The system account picker, limited to [account]: once picked it becomes
|
||||||
|
* visible to the app, so sync requests can name it.
|
||||||
|
*/
|
||||||
|
fun accountAccessIntent(account: SyncAccount, description: String): Intent =
|
||||||
|
AccountManager.newChooseAccountIntent(
|
||||||
|
null,
|
||||||
|
listOf(Account(account.name, account.type)),
|
||||||
|
arrayOf(account.type),
|
||||||
|
description,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Outcome of a user-triggered sync request (#240). [Completed] is only ever set
|
||||||
|
* once the requested syncs were seen through, see [awaitSyncs].
|
||||||
|
*/
|
||||||
|
enum class SyncRequestResult { Requested, Completed, SomeNeedAccess, PartlyFailed, NeedsAccess, NothingToSync, Failed }
|
||||||
|
|
||||||
|
/** A sync request's [result] and the [accounts] it actually reached. */
|
||||||
|
data class SyncRequest(val result: SyncRequestResult, val accounts: Set<SyncAccount> = emptySet())
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
package de.jeanlucmakiola.calendula.data.calendar
|
|
||||||
|
|
||||||
import kotlin.time.Instant
|
|
||||||
|
|
||||||
fun Long.toKotlinInstantFromEpochMillis(): Instant = Instant.fromEpochMilliseconds(this)
|
|
||||||
|
|
||||||
fun Instant.toEpochMillis(): Long = toEpochMilliseconds()
|
|
||||||
+42
@@ -0,0 +1,42 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.data.contacts
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
|
import de.jeanlucmakiola.calendula.R
|
||||||
|
import de.jeanlucmakiola.calendula.data.calendar.CalendarColorPalette
|
||||||
|
import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType
|
||||||
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolves the localized calendar names/templates and per-type colours the
|
||||||
|
* mirror creates its calendars with. The colours are picked from the shared
|
||||||
|
* palette so managed calendars look native alongside user calendars.
|
||||||
|
*/
|
||||||
|
@Singleton
|
||||||
|
class AndroidSpecialDatesCalendarSpec @Inject constructor(
|
||||||
|
@ApplicationContext private val context: Context,
|
||||||
|
) : SpecialDatesCalendarSpec {
|
||||||
|
|
||||||
|
override fun displayName(type: SpecialDateType): String = context.getString(
|
||||||
|
when (type) {
|
||||||
|
SpecialDateType.Birthday -> R.string.special_dates_calendar_birthday
|
||||||
|
SpecialDateType.Anniversary -> R.string.special_dates_calendar_anniversary
|
||||||
|
SpecialDateType.Custom -> R.string.special_dates_calendar_custom
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
override fun defaultTitleTemplate(type: SpecialDateType): String = context.getString(
|
||||||
|
when (type) {
|
||||||
|
SpecialDateType.Birthday -> R.string.special_dates_default_title_birthday
|
||||||
|
SpecialDateType.Anniversary -> R.string.special_dates_default_title_anniversary
|
||||||
|
SpecialDateType.Custom -> R.string.special_dates_default_title_custom
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
override fun color(type: SpecialDateType): Int = when (type) {
|
||||||
|
SpecialDateType.Birthday -> CalendarColorPalette.Purple
|
||||||
|
SpecialDateType.Anniversary -> CalendarColorPalette.Red
|
||||||
|
SpecialDateType.Custom -> CalendarColorPalette.Blue
|
||||||
|
}
|
||||||
|
}
|
||||||
+103
@@ -0,0 +1,103 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.data.contacts
|
||||||
|
|
||||||
|
import android.Manifest
|
||||||
|
import android.content.Context
|
||||||
|
import android.provider.ContactsContract
|
||||||
|
import android.provider.ContactsContract.CommonDataKinds.Event
|
||||||
|
import android.util.Log
|
||||||
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
|
import de.jeanlucmakiola.calendula.domain.contacts.ContactSpecialDate
|
||||||
|
import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType
|
||||||
|
import de.jeanlucmakiola.calendula.domain.contacts.managedUid
|
||||||
|
import de.jeanlucmakiola.calendula.domain.contacts.parseContactEventDate
|
||||||
|
import de.jeanlucmakiola.floret.android.hasPermission
|
||||||
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads the dated `Event` rows (birthdays, anniversaries, custom dates) of the
|
||||||
|
* device's contacts. Read-only and offline — the one-way source for the
|
||||||
|
* special-dates mirror. Requires `READ_CONTACTS`; returns an empty list when
|
||||||
|
* the permission is absent so the sync can degrade to a stalled state rather
|
||||||
|
* than crash.
|
||||||
|
*/
|
||||||
|
interface ContactSpecialDatesDataSource {
|
||||||
|
fun hasPermission(): Boolean
|
||||||
|
|
||||||
|
/** All usable contact special-dates, deduplicated per contact and type. */
|
||||||
|
fun readSpecialDates(): List<ContactSpecialDate>
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether `READ_CONTACTS` is granted — the gate for every contacts read. */
|
||||||
|
fun Context.hasContactsPermission(): Boolean =
|
||||||
|
hasPermission(Manifest.permission.READ_CONTACTS)
|
||||||
|
|
||||||
|
/** Map a `ContactsContract` event `TYPE` to our calendar bucket. */
|
||||||
|
internal fun specialDateTypeForRawEventType(type: Int): SpecialDateType = when (type) {
|
||||||
|
Event.TYPE_BIRTHDAY -> SpecialDateType.Birthday
|
||||||
|
Event.TYPE_ANNIVERSARY -> SpecialDateType.Anniversary
|
||||||
|
else -> SpecialDateType.Custom
|
||||||
|
}
|
||||||
|
|
||||||
|
@Singleton
|
||||||
|
class AndroidContactSpecialDatesDataSource @Inject constructor(
|
||||||
|
@ApplicationContext private val context: Context,
|
||||||
|
) : ContactSpecialDatesDataSource {
|
||||||
|
|
||||||
|
override fun hasPermission(): Boolean = context.hasContactsPermission()
|
||||||
|
|
||||||
|
override fun readSpecialDates(): List<ContactSpecialDate> {
|
||||||
|
if (!hasPermission()) return emptyList()
|
||||||
|
val resolver = context.contentResolver
|
||||||
|
// A contact can carry the same date more than once (multiple raw contacts
|
||||||
|
// under one aggregate); dedup on the mirror's reconciliation key so exact
|
||||||
|
// duplicates collapse while genuinely distinct dates (two custom events on
|
||||||
|
// one contact) are all kept. Ordered by Data._ID so which of two truly
|
||||||
|
// conflicting rows wins is stable across syncs (no event ping-pong).
|
||||||
|
val seen = HashSet<String>()
|
||||||
|
val result = ArrayList<ContactSpecialDate>()
|
||||||
|
runCatching {
|
||||||
|
resolver.query(
|
||||||
|
ContactsContract.Data.CONTENT_URI,
|
||||||
|
PROJECTION,
|
||||||
|
"${ContactsContract.Data.MIMETYPE} = ?",
|
||||||
|
arrayOf(Event.CONTENT_ITEM_TYPE),
|
||||||
|
"${ContactsContract.Data._ID} ASC",
|
||||||
|
)?.use { c ->
|
||||||
|
val idxDate = c.getColumnIndexOrThrow(Event.START_DATE)
|
||||||
|
val idxType = c.getColumnIndexOrThrow(Event.TYPE)
|
||||||
|
val idxLabel = c.getColumnIndexOrThrow(Event.LABEL)
|
||||||
|
val idxLookup = c.getColumnIndexOrThrow(ContactsContract.Data.LOOKUP_KEY)
|
||||||
|
val idxName = c.getColumnIndexOrThrow(ContactsContract.Data.DISPLAY_NAME_PRIMARY)
|
||||||
|
while (c.moveToNext()) {
|
||||||
|
val lookup = c.getString(idxLookup)?.takeIf { it.isNotEmpty() } ?: continue
|
||||||
|
val parts = parseContactEventDate(c.getString(idxDate)) ?: continue
|
||||||
|
val type = specialDateTypeForRawEventType(c.getInt(idxType))
|
||||||
|
val date = ContactSpecialDate(
|
||||||
|
lookupKey = lookup,
|
||||||
|
displayName = c.getString(idxName)?.trim().orEmpty(),
|
||||||
|
type = type,
|
||||||
|
month = parts.month,
|
||||||
|
day = parts.day,
|
||||||
|
year = parts.year,
|
||||||
|
label = c.getString(idxLabel)?.takeIf { it.isNotBlank() },
|
||||||
|
)
|
||||||
|
if (seen.add(date.managedUid())) result += date
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}.onFailure { Log.w(TAG, "Reading contact special-dates failed", it) }
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val TAG = "ContactSpecialDates"
|
||||||
|
|
||||||
|
val PROJECTION = arrayOf(
|
||||||
|
ContactsContract.Data.LOOKUP_KEY,
|
||||||
|
ContactsContract.Data.DISPLAY_NAME_PRIMARY,
|
||||||
|
Event.START_DATE,
|
||||||
|
Event.TYPE,
|
||||||
|
Event.LABEL,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.data.contacts
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.util.Log
|
||||||
|
import androidx.work.CoroutineWorker
|
||||||
|
import androidx.work.Data
|
||||||
|
import androidx.work.ExistingPeriodicWorkPolicy
|
||||||
|
import androidx.work.ExistingWorkPolicy
|
||||||
|
import androidx.work.OneTimeWorkRequestBuilder
|
||||||
|
import androidx.work.PeriodicWorkRequestBuilder
|
||||||
|
import androidx.work.WorkManager
|
||||||
|
import androidx.work.WorkerParameters
|
||||||
|
import dagger.hilt.EntryPoint
|
||||||
|
import dagger.hilt.InstallIn
|
||||||
|
import dagger.hilt.android.EntryPointAccessors
|
||||||
|
import dagger.hilt.components.SingletonComponent
|
||||||
|
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||||
|
import de.jeanlucmakiola.calendula.data.prefs.SpecialDatesStalledReason
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Schedules the contact special-dates mirror. Birthdays change rarely, so this
|
||||||
|
* is deliberately cheap: a **daily** periodic reconcile, plus an immediate run
|
||||||
|
* on enable / "Sync now" and a debounced one when the app is foregrounded. No
|
||||||
|
* ContentObserver — it would need the process alive and buys almost nothing for
|
||||||
|
* once-a-year events. Everything stays offline (local contacts → local calendar).
|
||||||
|
*/
|
||||||
|
object SpecialDatesScheduler {
|
||||||
|
|
||||||
|
private const val WORK_NAME = "special-dates-sync"
|
||||||
|
private const val WORK_NAME_NOW = "special-dates-sync-now"
|
||||||
|
private const val WORK_NAME_FOREGROUND = "special-dates-sync-foreground"
|
||||||
|
private const val KEY_FOREGROUND = "foreground"
|
||||||
|
|
||||||
|
/** Enqueue (or cancel) the daily periodic reconcile to match [enabled]. */
|
||||||
|
fun apply(context: Context, enabled: Boolean) {
|
||||||
|
val workManager = WorkManager.getInstance(context)
|
||||||
|
if (!enabled) {
|
||||||
|
workManager.cancelUniqueWork(WORK_NAME)
|
||||||
|
workManager.cancelUniqueWork(WORK_NAME_NOW)
|
||||||
|
workManager.cancelUniqueWork(WORK_NAME_FOREGROUND)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val request = PeriodicWorkRequestBuilder<SpecialDatesSyncWorker>(1, TimeUnit.DAYS)
|
||||||
|
// Delay the first periodic run so it never overlaps an immediate run.
|
||||||
|
.setInitialDelay(1, TimeUnit.DAYS)
|
||||||
|
.build()
|
||||||
|
workManager.enqueueUniquePeriodicWork(WORK_NAME, ExistingPeriodicWorkPolicy.UPDATE, request)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run one reconcile immediately. [foreground] runs (the app resuming) are
|
||||||
|
* debounced inside the worker and use their own work name, so a frequent
|
||||||
|
* foreground resync can never REPLACE — and swallow — a pending enable /
|
||||||
|
* "Sync now" run, which always syncs. The engine serializes the two if they
|
||||||
|
* overlap.
|
||||||
|
*/
|
||||||
|
fun runNow(context: Context, foreground: Boolean = false) {
|
||||||
|
val request = OneTimeWorkRequestBuilder<SpecialDatesSyncWorker>()
|
||||||
|
.setInputData(Data.Builder().putBoolean(KEY_FOREGROUND, foreground).build())
|
||||||
|
.build()
|
||||||
|
val name = if (foreground) WORK_NAME_FOREGROUND else WORK_NAME_NOW
|
||||||
|
WorkManager.getInstance(context)
|
||||||
|
.enqueueUniqueWork(name, ExistingWorkPolicy.REPLACE, request)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal const val INPUT_FOREGROUND = KEY_FOREGROUND
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs the [SpecialDatesSyncEngine]. Pulls its collaborators through a Hilt
|
||||||
|
* [EntryPoint] so it works under WorkManager's default worker factory. Records
|
||||||
|
* the run for the settings status line; a missing permission parks the feature
|
||||||
|
* in a stalled state (surfaced in settings) rather than retrying forever.
|
||||||
|
*/
|
||||||
|
class SpecialDatesSyncWorker(
|
||||||
|
appContext: Context,
|
||||||
|
params: WorkerParameters,
|
||||||
|
) : CoroutineWorker(appContext, params) {
|
||||||
|
|
||||||
|
@EntryPoint
|
||||||
|
@InstallIn(SingletonComponent::class)
|
||||||
|
interface Deps {
|
||||||
|
fun settingsPrefs(): SettingsPrefs
|
||||||
|
fun syncEngine(): SpecialDatesSyncEngine
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun doWork(): Result {
|
||||||
|
val deps = EntryPointAccessors.fromApplication(applicationContext, Deps::class.java)
|
||||||
|
val prefs = deps.settingsPrefs()
|
||||||
|
|
||||||
|
val now = System.currentTimeMillis()
|
||||||
|
// A foreground resume can fire often — skip if we synced recently.
|
||||||
|
val foreground = inputData.getBoolean(SpecialDatesScheduler.INPUT_FOREGROUND, false)
|
||||||
|
if (foreground && now - prefs.specialDatesLastForegroundSync.first() < FOREGROUND_DEBOUNCE_MILLIS) {
|
||||||
|
return Result.success()
|
||||||
|
}
|
||||||
|
|
||||||
|
return try {
|
||||||
|
when (val result = deps.syncEngine().sync()) {
|
||||||
|
// The engine re-checks the toggle, so already-queued work never
|
||||||
|
// revives a disabled feature; don't record a run either.
|
||||||
|
SpecialDatesSyncResult.Disabled -> return Result.success()
|
||||||
|
else -> {
|
||||||
|
val stalled = if (result == SpecialDatesSyncResult.PermissionMissing) {
|
||||||
|
SpecialDatesStalledReason.PermissionRevoked
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
prefs.recordSpecialDatesRun(now, stalled)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (foreground) prefs.setSpecialDatesLastForegroundSync(now)
|
||||||
|
Result.success()
|
||||||
|
} catch (e: SecurityException) {
|
||||||
|
// A revoked calendar/contacts permission won't fix itself on retry —
|
||||||
|
// park the feature in a stalled state (surfaced in settings) instead
|
||||||
|
// of retrying with backoff forever.
|
||||||
|
Log.w(TAG, "Special-dates sync lacks a required permission", e)
|
||||||
|
prefs.recordSpecialDatesRun(now, SpecialDatesStalledReason.PermissionRevoked)
|
||||||
|
Result.success()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "Special-dates sync failed", e)
|
||||||
|
Result.retry()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private const val TAG = "SpecialDatesSync"
|
||||||
|
|
||||||
|
/** Skip a foreground-triggered sync if one ran within this window (4h). */
|
||||||
|
private const val FOREGROUND_DEBOUNCE_MILLIS = 4L * 60 * 60 * 1000
|
||||||
|
}
|
||||||
|
}
|
||||||
+305
@@ -0,0 +1,305 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.data.contacts
|
||||||
|
|
||||||
|
import android.provider.CalendarContract
|
||||||
|
import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource
|
||||||
|
import de.jeanlucmakiola.calendula.data.calendar.ManagedEventRow
|
||||||
|
import de.jeanlucmakiola.calendula.data.calendar.toWriteTimes
|
||||||
|
import de.jeanlucmakiola.floret.reminders.ReminderOverride
|
||||||
|
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||||
|
import de.jeanlucmakiola.calendula.domain.Availability
|
||||||
|
import de.jeanlucmakiola.calendula.domain.EventForm
|
||||||
|
import de.jeanlucmakiola.calendula.domain.FormTime
|
||||||
|
import de.jeanlucmakiola.calendula.domain.RecurrenceFreq
|
||||||
|
import de.jeanlucmakiola.calendula.domain.SimpleRecurrence
|
||||||
|
import de.jeanlucmakiola.calendula.domain.contacts.ContactSpecialDate
|
||||||
|
import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType
|
||||||
|
import de.jeanlucmakiola.calendula.domain.contacts.anchorDate
|
||||||
|
import de.jeanlucmakiola.calendula.domain.contacts.managedUid
|
||||||
|
import de.jeanlucmakiola.calendula.domain.contacts.renderSpecialDateTitle
|
||||||
|
import de.jeanlucmakiola.calendula.domain.toRRule
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
import kotlinx.datetime.LocalDateTime
|
||||||
|
import kotlinx.datetime.LocalTime
|
||||||
|
import java.time.ZoneId
|
||||||
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
/** Outcome of one mirror reconcile, reported back so the worker can record status. */
|
||||||
|
enum class SpecialDatesSyncResult { Success, Disabled, PermissionMissing }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Localized, per-type presentation the engine needs but can't derive purely
|
||||||
|
* (calendar display name, colour, and the default title template). Kept behind
|
||||||
|
* an interface so the engine's diff stays unit-testable without Android
|
||||||
|
* resources.
|
||||||
|
*/
|
||||||
|
interface SpecialDatesCalendarSpec {
|
||||||
|
fun displayName(type: SpecialDateType): String
|
||||||
|
fun color(type: SpecialDateType): Int
|
||||||
|
fun defaultTitleTemplate(type: SpecialDateType): String
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The stored title template for [type], falling back to the localized default
|
||||||
|
* when blank/absent — the one resolution rule shared by the sync (what gets
|
||||||
|
* written) and the settings editor (what gets shown).
|
||||||
|
*/
|
||||||
|
fun SpecialDatesCalendarSpec.resolveTitleTemplate(
|
||||||
|
type: SpecialDateType,
|
||||||
|
stored: Map<SpecialDateType, String>,
|
||||||
|
): String = stored[type]?.takeIf { it.isNotBlank() } ?: defaultTitleTemplate(type)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mirrors contact birthdays/anniversaries/custom dates into local calendars,
|
||||||
|
* one per type. Every reconcile is an idempotent diff keyed on the deterministic
|
||||||
|
* `UID_2445` ([managedEventUid]): new contacts are inserted (seeding user-owned
|
||||||
|
* fields once), changed contacts get a *targeted* managed-column update, and
|
||||||
|
* removed contacts are deleted — so a user's own edits (reminders, location,
|
||||||
|
* notes) are never clobbered. See docs/design/contact-special-dates.md.
|
||||||
|
*/
|
||||||
|
@Singleton
|
||||||
|
class SpecialDatesSyncEngine @Inject constructor(
|
||||||
|
private val contacts: ContactSpecialDatesDataSource,
|
||||||
|
private val calendars: CalendarDataSource,
|
||||||
|
private val prefs: SettingsPrefs,
|
||||||
|
private val spec: SpecialDatesCalendarSpec,
|
||||||
|
) {
|
||||||
|
|
||||||
|
// Serializes calendar-lifecycle work: two overlapping syncs (the daily job
|
||||||
|
// racing a "Sync now"/foreground run) would each see no managed calendar and
|
||||||
|
// both create one; a teardown racing an in-flight sync would delete calendars
|
||||||
|
// the sync then recreates. Holding this for the whole of sync()/teardown()
|
||||||
|
// makes those check-then-act sequences atomic, and — because sync() re-reads
|
||||||
|
// the enabled flag inside the lock — a teardown always wins the race.
|
||||||
|
private val lifecycleMutex = Mutex()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reconcile every enabled type against the device's contacts. Returns why it
|
||||||
|
* stopped early (disabled / permission gone) or [SpecialDatesSyncResult.Success].
|
||||||
|
*/
|
||||||
|
suspend fun sync(): SpecialDatesSyncResult = lifecycleMutex.withLock {
|
||||||
|
if (!prefs.specialDatesEnabled.first()) return SpecialDatesSyncResult.Disabled
|
||||||
|
if (!contacts.hasPermission()) return SpecialDatesSyncResult.PermissionMissing
|
||||||
|
|
||||||
|
val enabledTypes = prefs.specialDatesTypes.first()
|
||||||
|
val calendarByType = reconcileCalendars(enabledTypes)
|
||||||
|
|
||||||
|
val desiredByType = contacts.readSpecialDates().groupBy { it.type }
|
||||||
|
val reminderCtx = readReminderContext()
|
||||||
|
val templates = prefs.specialDatesTitleTemplates.first()
|
||||||
|
val showYear = prefs.specialDatesShowYear.first()
|
||||||
|
|
||||||
|
calendarByType.forEach { (type, calendarId) ->
|
||||||
|
val template = spec.resolveTitleTemplate(type, templates)
|
||||||
|
syncType(
|
||||||
|
calendarId = calendarId,
|
||||||
|
type = type,
|
||||||
|
contactsOfType = desiredByType[type].orEmpty(),
|
||||||
|
template = template,
|
||||||
|
showYear = showYear,
|
||||||
|
reminderCtx = reminderCtx,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
SpecialDatesSyncResult.Success
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the reminder default for a type's managed calendar and apply it to
|
||||||
|
* **all** its existing events too (not just future ones) — for managed
|
||||||
|
* calendars the reminder is a calendar-level setting. Persists the per-calendar
|
||||||
|
* all-day override so new events keep matching. No-op if the calendar for
|
||||||
|
* [type] doesn't exist yet.
|
||||||
|
*/
|
||||||
|
suspend fun applyReminders(type: SpecialDateType, override: ReminderOverride) {
|
||||||
|
val calendarId = prefs.specialDatesCalendars.first()[type] ?: return
|
||||||
|
prefs.setCalendarAllDayReminderOverride(calendarId, override)
|
||||||
|
val minutes = when (override) {
|
||||||
|
ReminderOverride.Inherit -> prefs.defaultAllDayReminderMinutes.first()
|
||||||
|
ReminderOverride.None -> emptyList()
|
||||||
|
is ReminderOverride.Minutes -> override.minutes
|
||||||
|
}
|
||||||
|
calendars.applyManagedCalendarReminders(
|
||||||
|
calendarId = calendarId,
|
||||||
|
allDayReminderTimeMinutes = prefs.allDayReminderTimeMinutes.first(),
|
||||||
|
minutes = minutes,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Delete every managed calendar and forget its id — used when the feature is turned off. */
|
||||||
|
suspend fun teardown() = lifecycleMutex.withLock {
|
||||||
|
calendars.findManagedCalendars().forEach { calendars.deleteCalendar(it.id) }
|
||||||
|
SpecialDateType.entries.forEach { prefs.setSpecialDatesCalendarId(it, null) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ensure each enabled type has exactly one managed calendar (adopting an
|
||||||
|
* existing one, or the stored id if it still exists, else creating one) and
|
||||||
|
* that disabled types have none. Returns the calendar id per enabled type.
|
||||||
|
*/
|
||||||
|
private suspend fun reconcileCalendars(enabledTypes: Set<SpecialDateType>): Map<SpecialDateType, Long> {
|
||||||
|
val foundByType = calendars.findManagedCalendars()
|
||||||
|
.groupBy({ it.type }, { it.id })
|
||||||
|
.mapValues { it.value.first() }
|
||||||
|
val stored = prefs.specialDatesCalendars.first()
|
||||||
|
val result = LinkedHashMap<SpecialDateType, Long>()
|
||||||
|
for (type in SpecialDateType.entries) {
|
||||||
|
// A stored id counts only if the calendar still exists (the user may
|
||||||
|
// have deleted it in system settings); otherwise adopt a found one.
|
||||||
|
val existingId = stored[type]?.takeIf { id -> foundByType.containsValue(id) }
|
||||||
|
?: foundByType[type]
|
||||||
|
if (type in enabledTypes) {
|
||||||
|
val id = existingId ?: createCalendar(type)
|
||||||
|
if (stored[type] != id) prefs.setSpecialDatesCalendarId(type, id)
|
||||||
|
result[type] = id
|
||||||
|
} else {
|
||||||
|
if (existingId != null) calendars.deleteCalendar(existingId)
|
||||||
|
if (stored.containsKey(type)) prefs.setSpecialDatesCalendarId(type, null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun createCalendar(type: SpecialDateType): Long {
|
||||||
|
// reconcileCalendars persists the id — the single place ids are recorded.
|
||||||
|
val id = calendars.createManagedCalendar(spec.displayName(type), spec.color(type), type)
|
||||||
|
// Seed a useful all-day reminder default (on the day + a week before), so
|
||||||
|
// birthdays get lead time out of the box. Per-calendar, user-adjustable —
|
||||||
|
// only set when the user hasn't already configured this calendar.
|
||||||
|
if (!prefs.perCalendarAllDayReminderOverride.first().containsKey(id)) {
|
||||||
|
prefs.setCalendarAllDayReminderOverride(
|
||||||
|
id,
|
||||||
|
ReminderOverride.Minutes(DEFAULT_REMINDER_MINUTES),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun syncType(
|
||||||
|
calendarId: Long,
|
||||||
|
type: SpecialDateType,
|
||||||
|
contactsOfType: List<ContactSpecialDate>,
|
||||||
|
template: String,
|
||||||
|
showYear: Boolean,
|
||||||
|
reminderCtx: ReminderContext,
|
||||||
|
) {
|
||||||
|
val built = contactsOfType.map { sd ->
|
||||||
|
buildManagedEvent(calendarId, type, sd, template, showYear, reminderCtx)
|
||||||
|
}
|
||||||
|
val diff = diffManagedEvents(built.map { it.desired }, calendars.queryManagedEvents(calendarId))
|
||||||
|
val formByUid = built.associate { it.desired.uid to it.form }
|
||||||
|
diff.insertUids.forEach { uid ->
|
||||||
|
calendars.insertManagedEvent(formByUid.getValue(uid), uid, reminderCtx.allDayTimeMinutes)
|
||||||
|
}
|
||||||
|
diff.updates.forEach { calendars.updateManagedFields(it.eventId, it.columns) }
|
||||||
|
diff.deleteEventIds.forEach { calendars.deleteEvent(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun buildManagedEvent(
|
||||||
|
calendarId: Long,
|
||||||
|
type: SpecialDateType,
|
||||||
|
sd: ContactSpecialDate,
|
||||||
|
template: String,
|
||||||
|
showYear: Boolean,
|
||||||
|
reminderCtx: ReminderContext,
|
||||||
|
): BuiltManagedEvent {
|
||||||
|
val anchor = sd.anchorDate()
|
||||||
|
val start = LocalDateTime(anchor, LocalTime(0, 0))
|
||||||
|
// The source year is static and correct on every occurrence (unlike age).
|
||||||
|
val year = if (showYear) sd.year else null
|
||||||
|
val title = renderSpecialDateTitle(template, sd.displayName, year)
|
||||||
|
val form = EventForm(
|
||||||
|
calendarId = calendarId,
|
||||||
|
title = title,
|
||||||
|
isAllDay = true,
|
||||||
|
start = FormTime(start),
|
||||||
|
end = FormTime(start),
|
||||||
|
reminders = reminderCtx.resolveAllDay(calendarId),
|
||||||
|
availability = Availability.Free,
|
||||||
|
rrule = YEARLY_RRULE,
|
||||||
|
)
|
||||||
|
val dtStartMillis = form.toWriteTimes(ZoneId.systemDefault()).dtStartMillis
|
||||||
|
return BuiltManagedEvent(
|
||||||
|
desired = ManagedEventDesired(
|
||||||
|
uid = sd.managedUid(),
|
||||||
|
title = title,
|
||||||
|
dtStartMillis = dtStartMillis,
|
||||||
|
rrule = YEARLY_RRULE,
|
||||||
|
),
|
||||||
|
form = form,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Managed events are always all-day, so only the all-day defaults apply.
|
||||||
|
private suspend fun readReminderContext(): ReminderContext = ReminderContext(
|
||||||
|
allDayGlobal = prefs.defaultAllDayReminderMinutes.first(),
|
||||||
|
allDayOverrides = prefs.perCalendarAllDayReminderOverride.first(),
|
||||||
|
allDayTimeMinutes = prefs.allDayReminderTimeMinutes.first(),
|
||||||
|
)
|
||||||
|
|
||||||
|
private data class ReminderContext(
|
||||||
|
val allDayGlobal: List<Int>,
|
||||||
|
val allDayOverrides: Map<Long, List<Int>>,
|
||||||
|
val allDayTimeMinutes: Int,
|
||||||
|
) {
|
||||||
|
/** Same semantics as `resolveDefaultReminder`: present-empty = explicit none. */
|
||||||
|
fun resolveAllDay(calendarId: Long): List<Int> =
|
||||||
|
allDayOverrides[calendarId] ?: allDayGlobal
|
||||||
|
}
|
||||||
|
|
||||||
|
private data class BuiltManagedEvent(val desired: ManagedEventDesired, val form: EventForm)
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
/** "On the day" (0) + one week before (7 days), as all-day lead minutes. */
|
||||||
|
val DEFAULT_REMINDER_MINUTES = listOf(0, 7 * 24 * 60)
|
||||||
|
val YEARLY_RRULE = SimpleRecurrence(freq = RecurrenceFreq.Yearly).toRRule()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The managed columns of a desired event, compared against the existing row. */
|
||||||
|
internal data class ManagedEventDesired(
|
||||||
|
val uid: String,
|
||||||
|
val title: String,
|
||||||
|
val dtStartMillis: Long,
|
||||||
|
val rrule: String?,
|
||||||
|
)
|
||||||
|
|
||||||
|
internal data class ManagedFieldUpdate(val eventId: Long, val columns: Map<String, Any?>)
|
||||||
|
|
||||||
|
internal data class ManagedDiff(
|
||||||
|
val insertUids: List<String>,
|
||||||
|
val updates: List<ManagedFieldUpdate>,
|
||||||
|
val deleteEventIds: List<Long>,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The idempotent diff at the heart of the mirror, keyed on `UID_2445`:
|
||||||
|
* desired-not-existing → insert, existing-not-desired → delete, and for events
|
||||||
|
* in both only the *changed* managed columns (title/dtstart/rrule) are emitted —
|
||||||
|
* so a re-run with no contact changes produces nothing, and a managed update
|
||||||
|
* never touches user-owned columns or reminder rows. Pure, so it's unit-tested.
|
||||||
|
*/
|
||||||
|
internal fun diffManagedEvents(
|
||||||
|
desired: List<ManagedEventDesired>,
|
||||||
|
existing: List<ManagedEventRow>,
|
||||||
|
): ManagedDiff {
|
||||||
|
val desiredByUid = desired.associateBy { it.uid }
|
||||||
|
val existingByUid = existing.associateBy { it.uid }
|
||||||
|
val insertUids = desired.filter { it.uid !in existingByUid }.map { it.uid }
|
||||||
|
val deleteEventIds = existing.filter { it.uid !in desiredByUid }.map { it.eventId }
|
||||||
|
val updates = buildList {
|
||||||
|
for (d in desired) {
|
||||||
|
val row = existingByUid[d.uid] ?: continue
|
||||||
|
val columns = buildMap<String, Any?> {
|
||||||
|
if (row.title != d.title) put(CalendarContract.Events.TITLE, d.title)
|
||||||
|
if (row.dtStartMillis != d.dtStartMillis) {
|
||||||
|
put(CalendarContract.Events.DTSTART, d.dtStartMillis)
|
||||||
|
}
|
||||||
|
if (row.rrule != d.rrule) put(CalendarContract.Events.RRULE, d.rrule)
|
||||||
|
}
|
||||||
|
if (columns.isNotEmpty()) add(ManagedFieldUpdate(row.eventId, columns))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ManagedDiff(insertUids, updates, deleteEventIds)
|
||||||
|
}
|
||||||
@@ -1,188 +0,0 @@
|
|||||||
package de.jeanlucmakiola.calendula.data.crash
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.content.pm.PackageInfo
|
|
||||||
import android.os.Build
|
|
||||||
import androidx.core.content.pm.PackageInfoCompat
|
|
||||||
import java.io.File
|
|
||||||
import java.io.PrintWriter
|
|
||||||
import java.io.StringWriter
|
|
||||||
import java.time.Instant
|
|
||||||
import java.time.ZoneId
|
|
||||||
import java.time.format.DateTimeFormatter
|
|
||||||
import java.util.Locale
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Privacy-respecting crash capture (prod-readiness item 10). On an uncaught
|
|
||||||
* exception it writes a self-contained report to the app's private storage and
|
|
||||||
* then chains to the platform's default handler, so the process still dies
|
|
||||||
* normally (and the OS shows its own "stopped" dialog). Nothing is uploaded —
|
|
||||||
* the app holds no `INTERNET` permission. The user submits the report later,
|
|
||||||
* by hand, as a Gitea issue (see the ui/crash surfaces).
|
|
||||||
*
|
|
||||||
* The report is built from a fixed [CrashContext] allowlist — app/Android/device
|
|
||||||
* version, locale, time, and the stack trace — and **nothing else**: no device
|
|
||||||
* identifiers, no account names, no calendar/event content, no logcat. The user
|
|
||||||
* is always shown the full text before it leaves the device.
|
|
||||||
*/
|
|
||||||
object CrashReporter {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Install the handler. Called first thing in `CalendulaApp.onCreate()` so it
|
|
||||||
* also catches crashes during startup. The handler swallows nothing — it
|
|
||||||
* persists, then delegates to the previously-registered handler.
|
|
||||||
*/
|
|
||||||
fun install(context: Context) {
|
|
||||||
val appContext = context.applicationContext
|
|
||||||
val previous = Thread.getDefaultUncaughtExceptionHandler()
|
|
||||||
Thread.setDefaultUncaughtExceptionHandler { thread, throwable ->
|
|
||||||
// Capturing must never mask the original crash, so guard every step.
|
|
||||||
runCatching {
|
|
||||||
val now = System.currentTimeMillis()
|
|
||||||
writeReport(appContext, buildCrashReport(CrashContext.from(appContext), throwable, now))
|
|
||||||
recordCrashTime(appContext, now)
|
|
||||||
}
|
|
||||||
previous?.uncaughtException(thread, throwable)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The persisted report from the last crash, or null if there is none. */
|
|
||||||
fun pendingReport(context: Context): String? {
|
|
||||||
val file = reportFile(context)
|
|
||||||
return if (file.exists()) runCatching { file.readText() }.getOrNull()?.takeIf { it.isNotBlank() } else null
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Whether to surface the report unprompted (on the next launch): a report
|
|
||||||
* exists and the user hasn't already waved this one away. Settings reaches
|
|
||||||
* the report via [pendingReport] regardless, so "Not now" only stops the
|
|
||||||
* auto-prompt — it doesn't discard the report.
|
|
||||||
*/
|
|
||||||
fun shouldPrompt(context: Context): Boolean =
|
|
||||||
reportFile(context).exists() && !dismissedFile(context).exists()
|
|
||||||
|
|
||||||
/** Stop auto-prompting for the current report without discarding it. */
|
|
||||||
fun dismissPrompt(context: Context) {
|
|
||||||
runCatching { dismissedFile(context).apply { parentFile?.mkdirs() }.writeText("") }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Drop the persisted report once the user has reported it (or from Settings). */
|
|
||||||
fun clearReport(context: Context) {
|
|
||||||
runCatching { reportFile(context).delete() }
|
|
||||||
runCatching { dismissedFile(context).delete() }
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Whether the app appears to be in a startup crash-loop: at least
|
|
||||||
* [LOOP_THRESHOLD] crashes inside [LOOP_WINDOW_MS]. In that case the main UI
|
|
||||||
* can't be trusted to start, so the caller routes straight to the standalone
|
|
||||||
* report screen instead of re-entering the crashing graph.
|
|
||||||
*/
|
|
||||||
fun isCrashLoop(context: Context): Boolean {
|
|
||||||
val times = readCrashTimes(context)
|
|
||||||
if (times.size < LOOP_THRESHOLD) return false
|
|
||||||
val recent = times.sortedDescending()
|
|
||||||
return recent[0] - recent[LOOP_THRESHOLD - 1] <= LOOP_WINDOW_MS
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Mark the app as having started successfully, resetting the loop counter so
|
|
||||||
* an ordinary single crash much later never trips loop detection. The
|
|
||||||
* pending report itself is kept — only the timing trail is cleared.
|
|
||||||
*/
|
|
||||||
fun markHealthy(context: Context) {
|
|
||||||
runCatching { timesFile(context).delete() }
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- persistence -------------------------------------------------------
|
|
||||||
|
|
||||||
private fun writeReport(context: Context, report: String) {
|
|
||||||
val file = reportFile(context).apply { parentFile?.mkdirs() }
|
|
||||||
file.writeText(report.take(MAX_REPORT_CHARS))
|
|
||||||
// A fresh crash should prompt again, even if the previous one was waved away.
|
|
||||||
runCatching { dismissedFile(context).delete() }
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun recordCrashTime(context: Context, nowMillis: Long) {
|
|
||||||
val kept = (readCrashTimes(context) + nowMillis).takeLast(MAX_TIMES)
|
|
||||||
timesFile(context).apply { parentFile?.mkdirs() }
|
|
||||||
.writeText(kept.joinToString("\n"))
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun readCrashTimes(context: Context): List<Long> {
|
|
||||||
val file = timesFile(context)
|
|
||||||
if (!file.exists()) return emptyList()
|
|
||||||
return runCatching { file.readLines().mapNotNull { it.trim().toLongOrNull() } }.getOrDefault(emptyList())
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun crashDir(context: Context) = File(context.filesDir, CRASH_DIR)
|
|
||||||
private fun reportFile(context: Context) = File(crashDir(context), REPORT_FILE)
|
|
||||||
private fun timesFile(context: Context) = File(crashDir(context), TIMES_FILE)
|
|
||||||
private fun dismissedFile(context: Context) = File(crashDir(context), DISMISSED_FILE)
|
|
||||||
|
|
||||||
private const val CRASH_DIR = "crash"
|
|
||||||
private const val REPORT_FILE = "last_crash.txt"
|
|
||||||
private const val TIMES_FILE = "crash_times.txt"
|
|
||||||
private const val DISMISSED_FILE = "dismissed"
|
|
||||||
private const val MAX_TIMES = 5
|
|
||||||
private const val MAX_REPORT_CHARS = 64 * 1024
|
|
||||||
private const val LOOP_THRESHOLD = 2
|
|
||||||
private const val LOOP_WINDOW_MS = 10_000L
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The allowlist of non-personal facts that go into a crash report. Built from
|
|
||||||
* [Build] and the app's own [PackageInfo]; deliberately holds no identifiers.
|
|
||||||
*/
|
|
||||||
data class CrashContext(
|
|
||||||
val appVersionName: String,
|
|
||||||
val appVersionCode: Long,
|
|
||||||
val sdkInt: Int,
|
|
||||||
val androidRelease: String,
|
|
||||||
val manufacturer: String,
|
|
||||||
val model: String,
|
|
||||||
val locale: String,
|
|
||||||
) {
|
|
||||||
companion object {
|
|
||||||
fun from(context: Context): CrashContext {
|
|
||||||
val pkg = runCatching {
|
|
||||||
context.packageManager.getPackageInfo(context.packageName, 0)
|
|
||||||
}.getOrNull()
|
|
||||||
return CrashContext(
|
|
||||||
appVersionName = pkg?.versionName ?: "?",
|
|
||||||
appVersionCode = pkg?.let { PackageInfoCompat.getLongVersionCode(it) } ?: 0L,
|
|
||||||
sdkInt = Build.VERSION.SDK_INT,
|
|
||||||
androidRelease = Build.VERSION.RELEASE ?: "?",
|
|
||||||
manufacturer = Build.MANUFACTURER ?: "?",
|
|
||||||
model = Build.MODEL ?: "?",
|
|
||||||
locale = Locale.getDefault().toLanguageTag(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Render a crash report from the [ctx] allowlist, the [throwable]'s full stack
|
|
||||||
* trace, and the crash [nowMillis]. Pure (no Android, no I/O) so it is unit
|
|
||||||
* tested. The leading marker doubles as the file's sanity check in
|
|
||||||
* [CrashReporter.pendingReport].
|
|
||||||
*/
|
|
||||||
fun buildCrashReport(ctx: CrashContext, throwable: Throwable, nowMillis: Long): String {
|
|
||||||
val trace = StringWriter().also { throwable.printStackTrace(PrintWriter(it)) }.toString().trim()
|
|
||||||
val time = runCatching {
|
|
||||||
Instant.ofEpochMilli(nowMillis).atZone(ZoneId.systemDefault()).format(TIME_FORMAT)
|
|
||||||
}.getOrDefault(nowMillis.toString())
|
|
||||||
return buildString {
|
|
||||||
appendLine("Calendula crash report")
|
|
||||||
appendLine("App version: ${ctx.appVersionName} (${ctx.appVersionCode})")
|
|
||||||
appendLine("Android: ${ctx.androidRelease} (API ${ctx.sdkInt})")
|
|
||||||
appendLine("Device: ${ctx.manufacturer} ${ctx.model}")
|
|
||||||
appendLine("Locale: ${ctx.locale}")
|
|
||||||
appendLine("Time: $time")
|
|
||||||
appendLine()
|
|
||||||
appendLine("Stack trace:")
|
|
||||||
append(trace)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private val TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
|
|
||||||
+2
-1
@@ -2,6 +2,7 @@ package de.jeanlucmakiola.calendula.data.di
|
|||||||
|
|
||||||
import javax.inject.Qualifier
|
import javax.inject.Qualifier
|
||||||
|
|
||||||
|
/** The process-wide `CoroutineScope` that app-lifetime singletons share their flows in. */
|
||||||
@Qualifier
|
@Qualifier
|
||||||
@Retention(AnnotationRetention.BINARY)
|
@Retention(AnnotationRetention.BINARY)
|
||||||
annotation class IoDispatcher
|
annotation class ApplicationScope
|
||||||
@@ -11,13 +11,24 @@ import dagger.hilt.InstallIn
|
|||||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
import dagger.hilt.components.SingletonComponent
|
import dagger.hilt.components.SingletonComponent
|
||||||
import de.jeanlucmakiola.calendula.data.calendar.AndroidCalendarDataSource
|
import de.jeanlucmakiola.calendula.data.calendar.AndroidCalendarDataSource
|
||||||
|
import de.jeanlucmakiola.calendula.data.calendar.AndroidSyncRequester
|
||||||
import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource
|
import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource
|
||||||
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
|
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
|
||||||
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepositoryImpl
|
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepositoryImpl
|
||||||
import de.jeanlucmakiola.calendula.data.reminders.AndroidReminderAlertStore
|
import de.jeanlucmakiola.calendula.data.calendar.SyncRequester
|
||||||
import de.jeanlucmakiola.calendula.data.reminders.ReminderAlertStore
|
import de.jeanlucmakiola.calendula.data.contacts.AndroidContactSpecialDatesDataSource
|
||||||
import kotlinx.coroutines.CoroutineDispatcher
|
import de.jeanlucmakiola.calendula.data.contacts.AndroidSpecialDatesCalendarSpec
|
||||||
|
import de.jeanlucmakiola.calendula.data.contacts.ContactSpecialDatesDataSource
|
||||||
|
import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesCalendarSpec
|
||||||
|
import de.jeanlucmakiola.calendula.data.reminders.ProviderReminderInstanceSource
|
||||||
|
import de.jeanlucmakiola.calendula.data.reminders.ReminderInstanceSource
|
||||||
|
import de.jeanlucmakiola.calendula.data.time.AndroidTodaySource
|
||||||
|
import de.jeanlucmakiola.calendula.data.time.AndroidZoneSource
|
||||||
|
import de.jeanlucmakiola.calendula.data.time.TodaySource
|
||||||
|
import de.jeanlucmakiola.calendula.data.time.ZoneSource
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.SupervisorJob
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
|
||||||
private val Context.calendulaDataStore: DataStore<Preferences> by preferencesDataStore(
|
private val Context.calendulaDataStore: DataStore<Preferences> by preferencesDataStore(
|
||||||
@@ -42,9 +53,39 @@ abstract class DataBindModule {
|
|||||||
|
|
||||||
@Binds
|
@Binds
|
||||||
@Singleton
|
@Singleton
|
||||||
abstract fun bindReminderAlertStore(
|
abstract fun bindSyncRequester(
|
||||||
impl: AndroidReminderAlertStore,
|
impl: AndroidSyncRequester,
|
||||||
): ReminderAlertStore
|
): SyncRequester
|
||||||
|
|
||||||
|
@Binds
|
||||||
|
@Singleton
|
||||||
|
abstract fun bindReminderInstanceSource(
|
||||||
|
impl: ProviderReminderInstanceSource,
|
||||||
|
): ReminderInstanceSource
|
||||||
|
|
||||||
|
@Binds
|
||||||
|
@Singleton
|
||||||
|
abstract fun bindContactSpecialDatesDataSource(
|
||||||
|
impl: AndroidContactSpecialDatesDataSource,
|
||||||
|
): ContactSpecialDatesDataSource
|
||||||
|
|
||||||
|
@Binds
|
||||||
|
@Singleton
|
||||||
|
abstract fun bindSpecialDatesCalendarSpec(
|
||||||
|
impl: AndroidSpecialDatesCalendarSpec,
|
||||||
|
): SpecialDatesCalendarSpec
|
||||||
|
|
||||||
|
@Binds
|
||||||
|
@Singleton
|
||||||
|
abstract fun bindTodaySource(
|
||||||
|
impl: AndroidTodaySource,
|
||||||
|
): TodaySource
|
||||||
|
|
||||||
|
@Binds
|
||||||
|
@Singleton
|
||||||
|
abstract fun bindZoneSource(
|
||||||
|
impl: AndroidZoneSource,
|
||||||
|
): ZoneSource
|
||||||
}
|
}
|
||||||
|
|
||||||
@Module
|
@Module
|
||||||
@@ -57,6 +98,7 @@ object DataProvideModule {
|
|||||||
context.calendulaDataStore
|
context.calendulaDataStore
|
||||||
|
|
||||||
@Provides
|
@Provides
|
||||||
@IoDispatcher
|
@Singleton
|
||||||
fun provideIoDispatcher(): CoroutineDispatcher = Dispatchers.IO
|
@ApplicationScope
|
||||||
|
fun provideApplicationScope(): CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||||
}
|
}
|
||||||
@@ -5,6 +5,10 @@ import android.net.Uri
|
|||||||
import androidx.core.content.FileProvider
|
import androidx.core.content.FileProvider
|
||||||
import androidx.documentfile.provider.DocumentFile
|
import androidx.documentfile.provider.DocumentFile
|
||||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
|
import de.jeanlucmakiola.floret.android.TreeListing
|
||||||
|
import de.jeanlucmakiola.floret.android.deleteTreeFiles
|
||||||
|
import de.jeanlucmakiola.floret.android.listTreeFiles
|
||||||
|
import de.jeanlucmakiola.floret.android.writeTreeFile
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.io.IOException
|
import java.io.IOException
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
@@ -29,34 +33,27 @@ class IcsExporter @Inject constructor(
|
|||||||
} ?: throw IOException("Could not open output stream for export (scheme=${uri.scheme})")
|
} ?: throw IOException("Could not open output stream for export (scheme=${uri.scheme})")
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** The files in the persisted SAF tree [folder], the automatic-backup destination. Throws when unusable. */
|
||||||
* Write [content] to [fileName] inside the persisted SAF tree [folder],
|
fun listFolder(folder: Uri): TreeListing {
|
||||||
* overwriting it if it already exists (the automatic-backup destination).
|
writableFolder(folder)
|
||||||
* Requires a persisted write grant on [folder]. Throws on failure.
|
return context.contentResolver.listTreeFiles(folder)
|
||||||
*/
|
}
|
||||||
fun writeToFolder(folder: Uri, fileName: String, content: String) {
|
|
||||||
|
/** Write the `.ics` [bytes] as [fileName] into [folder]; returns the name the file ended up with. */
|
||||||
|
fun writeToFolder(folder: Uri, listing: TreeListing, fileName: String, bytes: ByteArray): String =
|
||||||
|
context.contentResolver.writeTreeFile(folder, listing, fileName, MIME_CALENDAR, bytes)
|
||||||
|
|
||||||
|
/** Delete [names] from the listed folder; returns the ones that didn't go. */
|
||||||
|
fun deleteFromFolder(listing: TreeListing, names: Collection<String>): Set<String> =
|
||||||
|
context.contentResolver.deleteTreeFiles(listing, names)
|
||||||
|
|
||||||
|
private fun writableFolder(folder: Uri): DocumentFile {
|
||||||
val dir = DocumentFile.fromTreeUri(context, folder)
|
val dir = DocumentFile.fromTreeUri(context, folder)
|
||||||
?: throw IOException("Backup folder is not accessible")
|
?: throw IOException("Backup folder is not accessible")
|
||||||
if (!dir.exists() || !dir.canWrite()) {
|
if (!dir.exists() || !dir.canWrite()) {
|
||||||
throw IOException("Backup folder is missing or not writable")
|
throw IOException("Backup folder is missing or not writable")
|
||||||
}
|
}
|
||||||
// Reuse the canonical file if present and clean up any "name (1).ics"
|
return dir
|
||||||
// duplicates SAF may have created if two runs ever raced — so we always
|
|
||||||
// converge on a single overwritten file.
|
|
||||||
val base = fileName.substringBeforeLast('.')
|
|
||||||
val ext = fileName.substringAfterLast('.', "")
|
|
||||||
var target: DocumentFile? = null
|
|
||||||
for (child in dir.listFiles()) {
|
|
||||||
val name = child.name ?: continue
|
|
||||||
when {
|
|
||||||
name == fileName -> target = child
|
|
||||||
name.startsWith("$base (") && name.endsWith(".$ext") -> child.delete()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
val file = target
|
|
||||||
?: dir.createFile(MIME_CALENDAR, fileName)
|
|
||||||
?: throw IOException("Could not create backup file in the chosen folder")
|
|
||||||
writeDocument(file.uri, content)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -2,83 +2,115 @@ package de.jeanlucmakiola.calendula.data.prefs
|
|||||||
|
|
||||||
import androidx.datastore.core.DataStore
|
import androidx.datastore.core.DataStore
|
||||||
import androidx.datastore.preferences.core.Preferences
|
import androidx.datastore.preferences.core.Preferences
|
||||||
import androidx.datastore.preferences.core.edit
|
import de.jeanlucmakiola.floret.prefs.Pref
|
||||||
import androidx.datastore.preferences.core.longPreferencesKey
|
import de.jeanlucmakiola.floret.prefs.PrefStore
|
||||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
import de.jeanlucmakiola.floret.prefs.nullableBooleanPref
|
||||||
|
import de.jeanlucmakiola.floret.prefs.nullableLongPref
|
||||||
|
import de.jeanlucmakiola.floret.prefs.nullableStringPref
|
||||||
|
import de.jeanlucmakiola.floret.prefs.stringSetPref
|
||||||
|
import de.jeanlucmakiola.calendula.data.calendar.SyncAccount
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
import kotlinx.coroutines.flow.map
|
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* App-side preference for "calendars the user has hidden in this app",
|
* App-side calendar preferences. [hiddenCalendarIds] is the drawer's filter
|
||||||
* separate from the system's per-calendar VISIBLE flag.
|
* sheet — a purely in-app declutter that deliberately does *not* suppress
|
||||||
|
* reminders. Switching a calendar off entirely is the system's
|
||||||
|
* `Calendars.VISIBLE` flag, written straight to the provider (#75);
|
||||||
|
* [pendingDisabledCalendarIds] only holds those switch-offs the app has not been
|
||||||
|
* allowed to write yet.
|
||||||
*
|
*
|
||||||
* Persisted as a comma-separated string of Long ids; non-numeric tokens are
|
* Persisted as a comma-separated string of Long ids; non-numeric tokens are
|
||||||
* silently dropped (defensive — see CalendarPrefsTest).
|
* silently dropped (defensive — see CalendarPrefsTest).
|
||||||
*/
|
*/
|
||||||
@Singleton
|
@Singleton
|
||||||
class CalendarPrefs @Inject constructor(
|
class CalendarPrefs @Inject constructor(
|
||||||
private val store: DataStore<Preferences>,
|
store: DataStore<Preferences>,
|
||||||
) {
|
) {
|
||||||
|
private val prefs = PrefStore(store)
|
||||||
|
|
||||||
val hiddenCalendarIds: Flow<Set<Long>> = store.data.map { prefs ->
|
val hiddenCalendarIds: Flow<Set<Long>> = prefs.flow(CalendarPrefKeys.hiddenCalendarIds)
|
||||||
prefs[HIDDEN_IDS_KEY].orEmpty()
|
|
||||||
.split(',')
|
|
||||||
.mapNotNull { it.trim().toLongOrNull() }
|
|
||||||
.toSet()
|
|
||||||
}
|
|
||||||
|
|
||||||
suspend fun setHiddenCalendarIds(ids: Set<Long>) {
|
suspend fun setHiddenCalendarIds(ids: Set<Long>) = prefs.set(CalendarPrefKeys.hiddenCalendarIds, ids)
|
||||||
store.edit { prefs ->
|
|
||||||
if (ids.isEmpty()) {
|
/** Rewrite the drawer's hidden set atomically from its current value. */
|
||||||
prefs.remove(HIDDEN_IDS_KEY)
|
suspend fun updateHiddenCalendarIds(transform: (Set<Long>) -> Set<Long>) {
|
||||||
} else {
|
prefs.update(CalendarPrefKeys.hiddenCalendarIds, transform)
|
||||||
prefs[HIDDEN_IDS_KEY] = ids.sorted().joinToString(",")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* App-side preference for "calendars the user has disabled in this app" — a
|
* Switch-offs the provider does not know about yet, because writing
|
||||||
* heavier level than [hiddenCalendarIds]. A disabled calendar is removed from
|
* `Calendars.VISIBLE` needs `WRITE_CALENDAR` (#75). Also inherits the
|
||||||
* every surface (drawer filter, event-form picker, import picker) and its
|
* retired app-local model's set, from the same key.
|
||||||
* events never appear; it stays listed only in Settings → Calendars so it can
|
*
|
||||||
* be re-enabled. Stored exactly like the hidden set; never touches the
|
* Honoured as a display and reminder filter while non-empty, but not a
|
||||||
* system's VISIBLE/SYNC_EVENTS flags, so other calendar apps are unaffected.
|
* second visibility model: `CalendarVisibilityReconciler` drains it entry by
|
||||||
|
* entry as soon as the app may write, and nothing adds to it while it may.
|
||||||
*/
|
*/
|
||||||
val disabledCalendarIds: Flow<Set<Long>> = store.data.map { prefs ->
|
val pendingDisabledCalendarIds: Flow<Set<Long>> = prefs.flow(CalendarPrefKeys.pendingDisabledCalendarIds)
|
||||||
prefs[DISABLED_IDS_KEY].orEmpty()
|
|
||||||
.split(',')
|
suspend fun addPendingDisabledCalendarIds(ids: Collection<Long>) {
|
||||||
.mapNotNull { it.trim().toLongOrNull() }
|
prefs.update(CalendarPrefKeys.pendingDisabledCalendarIds) { it + ids }
|
||||||
.toSet()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun setDisabledCalendarIds(ids: Set<Long>) {
|
/**
|
||||||
store.edit { prefs ->
|
* Drop [ids] from the pending set, one at a time as the reconciler flushes
|
||||||
if (ids.isEmpty()) {
|
* them, so a run that fails part-way never re-applies what already landed.
|
||||||
prefs.remove(DISABLED_IDS_KEY)
|
*/
|
||||||
} else {
|
suspend fun removePendingDisabledCalendarIds(ids: Collection<Long>) {
|
||||||
prefs[DISABLED_IDS_KEY] = ids.sorted().joinToString(",")
|
prefs.update(CalendarPrefKeys.pendingDisabledCalendarIds) { it - ids.toSet() }
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether the one-time "visibility follows this device" notice is still
|
||||||
|
* owed. Null until the reconciler has evaluated it (which needs the calendar
|
||||||
|
* permission), false once it has been shown or was never needed.
|
||||||
|
*/
|
||||||
|
val visibilityNoticePending: Flow<Boolean?> = prefs.flow(CalendarPrefKeys.visibilityNoticePending)
|
||||||
|
|
||||||
|
suspend fun setVisibilityNoticePending(pending: Boolean) = prefs.set(CalendarPrefKeys.visibilityNoticePending, pending)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The calendar the user last created an event in; preselected in the
|
* The calendar the user last created an event in; preselected in the
|
||||||
* event form. Null until the first event is created.
|
* event form. Null until the first event is created.
|
||||||
*/
|
*/
|
||||||
val lastUsedCalendarId: Flow<Long?> = store.data.map { prefs ->
|
val lastUsedCalendarId: Flow<Long?> = prefs.flow(CalendarPrefKeys.lastUsedCalendarId)
|
||||||
prefs[LAST_USED_CALENDAR_KEY]
|
|
||||||
}
|
|
||||||
|
|
||||||
suspend fun setLastUsedCalendarId(id: Long) {
|
suspend fun setLastUsedCalendarId(id: Long) = prefs.set(CalendarPrefKeys.lastUsedCalendarId, id)
|
||||||
store.edit { prefs -> prefs[LAST_USED_CALENDAR_KEY] = id }
|
|
||||||
}
|
|
||||||
|
|
||||||
companion object {
|
/**
|
||||||
internal val HIDDEN_IDS_KEY = stringPreferencesKey("hidden_calendar_ids")
|
* Synced accounts the user chose never to be asked to grant sync-request
|
||||||
internal val DISABLED_IDS_KEY = stringPreferencesKey("disabled_calendar_ids")
|
* access for (#240): no grant row, no "other accounts" receipt.
|
||||||
internal val LAST_USED_CALENDAR_KEY = longPreferencesKey("last_used_calendar_id")
|
*/
|
||||||
|
val syncAccessDismissed: Flow<Set<SyncAccount>> = prefs.flow(CalendarPrefKeys.syncAccessDismissed)
|
||||||
|
|
||||||
|
suspend fun setSyncAccessDismissed(account: SyncAccount, dismissed: Boolean) {
|
||||||
|
prefs.update(CalendarPrefKeys.syncAccessDismissed) { if (dismissed) it + account else it - account }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Every key [CalendarPrefs] stores; the names are on-disk data. */
|
||||||
|
internal object CalendarPrefKeys {
|
||||||
|
val hiddenCalendarIds: Pref<Set<Long>> = idSetPref("hidden_calendar_ids")
|
||||||
|
val pendingDisabledCalendarIds: Pref<Set<Long>> = idSetPref("disabled_calendar_ids")
|
||||||
|
val visibilityNoticePending: Pref<Boolean?> = nullableBooleanPref("visibility_notice_pending")
|
||||||
|
val lastUsedCalendarId: Pref<Long?> = nullableLongPref("last_used_calendar_id")
|
||||||
|
val syncAccessDismissed: Pref<Set<SyncAccount>> = stringSetPref("sync_access_dismissed").map(
|
||||||
|
{ stored -> stored.mapNotNullTo(mutableSetOf()) { it.toSyncAccount() } },
|
||||||
|
{ accounts -> accounts.mapTo(mutableSetOf()) { "${it.type}$FIELD_SEPARATOR${it.name}" } },
|
||||||
|
)
|
||||||
|
|
||||||
|
private const val FIELD_SEPARATOR = '\u001F'
|
||||||
|
|
||||||
|
private fun String.toSyncAccount(): SyncAccount? {
|
||||||
|
val split = indexOf(FIELD_SEPARATOR)
|
||||||
|
return if (split <= 0) null else SyncAccount(name = substring(split + 1), type = substring(0, split))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A comma-joined id set; non-numeric tokens are dropped, and an empty set removes the key. */
|
||||||
|
internal fun idSetPref(name: String): Pref<Set<Long>> = nullableStringPref(name).map(
|
||||||
|
{ stored -> stored.orEmpty().split(',').mapNotNull { it.trim().toLongOrNull() }.toSet() },
|
||||||
|
{ ids -> if (ids.isEmpty()) null else ids.sorted().joinToString(",") },
|
||||||
|
)
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.data.prefs
|
||||||
|
|
||||||
|
import androidx.datastore.core.DataStore
|
||||||
|
import androidx.datastore.preferences.core.Preferences
|
||||||
|
import de.jeanlucmakiola.floret.prefs.Pref
|
||||||
|
import de.jeanlucmakiola.floret.prefs.PrefStore
|
||||||
|
import de.jeanlucmakiola.floret.prefs.nullableLongPref
|
||||||
|
import de.jeanlucmakiola.floret.prefs.nullableStringPref
|
||||||
|
import java.time.LocalDate
|
||||||
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How far reminder delivery has got — the one number replacing the provider's
|
||||||
|
* `CalendarAlerts.STATE` (#75). A scan posts the reminders falling after this
|
||||||
|
* watermark and up to now, then moves it to now, so a scan running twice cannot
|
||||||
|
* post twice while a late one still catches up.
|
||||||
|
*
|
||||||
|
* Unset means "never scanned", not zero: the first scan after an install would
|
||||||
|
* otherwise treat every reminder since the epoch as overdue.
|
||||||
|
*/
|
||||||
|
@Singleton
|
||||||
|
class ReminderStatePrefs @Inject constructor(
|
||||||
|
store: DataStore<Preferences>,
|
||||||
|
) {
|
||||||
|
private val prefs = PrefStore(store)
|
||||||
|
|
||||||
|
/** The watermark, or `null` before the first scan has ever run. */
|
||||||
|
suspend fun lastScanMillis(): Long? = prefs.get(ReminderStateKeys.lastScanMillis)
|
||||||
|
|
||||||
|
suspend fun setLastScanMillis(millis: Long) = prefs.set(ReminderStateKeys.lastScanMillis, millis)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The day the last daily summary listed (#459): recorded at once, so neither
|
||||||
|
* a pass failing after posting nor a later time picked the same evening
|
||||||
|
* lists it twice.
|
||||||
|
*/
|
||||||
|
suspend fun lastDigestDay(): LocalDate? =
|
||||||
|
prefs.get(ReminderStateKeys.lastDigestDay)?.let { runCatching { LocalDate.parse(it) }.getOrNull() }
|
||||||
|
|
||||||
|
suspend fun setLastDigestDay(day: LocalDate) = prefs.set(ReminderStateKeys.lastDigestDay, day.toString())
|
||||||
|
|
||||||
|
suspend fun clearLastDigestDay() = prefs.set(ReminderStateKeys.lastDigestDay, null)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The keys [ReminderStatePrefs] stores. */
|
||||||
|
internal object ReminderStateKeys {
|
||||||
|
val lastScanMillis: Pref<Long?> = nullableLongPref("reminder_last_scan_millis")
|
||||||
|
val lastDigestDay: Pref<String?> = nullableStringPref("reminder_last_digest_day")
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,157 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.data.reminders
|
||||||
|
|
||||||
|
import android.app.NotificationChannel
|
||||||
|
import android.app.NotificationManager
|
||||||
|
import android.app.PendingIntent
|
||||||
|
import android.content.Context
|
||||||
|
import android.util.Log
|
||||||
|
import androidx.core.app.NotificationCompat
|
||||||
|
import androidx.core.app.NotificationManagerCompat
|
||||||
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
|
import de.jeanlucmakiola.calendula.MainActivity
|
||||||
|
import de.jeanlucmakiola.calendula.R
|
||||||
|
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||||
|
import de.jeanlucmakiola.calendula.data.prefs.is24Hour
|
||||||
|
import de.jeanlucmakiola.calendula.data.prefs.resolveFirstDay
|
||||||
|
import de.jeanlucmakiola.calendula.domain.reminders.ReminderEventInstance
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
import kotlinx.datetime.isoDayNumber
|
||||||
|
import kotlinx.datetime.toKotlinLocalDate
|
||||||
|
import java.time.DayOfWeek
|
||||||
|
import java.time.LocalDate
|
||||||
|
import java.time.ZoneId
|
||||||
|
import java.time.format.DateTimeFormatter
|
||||||
|
import java.util.Locale
|
||||||
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Posts the daily summary (#459): one notification listing a day's events, on
|
||||||
|
* its own channel, replacing the one before it. Tapping opens that day.
|
||||||
|
*/
|
||||||
|
@Singleton
|
||||||
|
class DailyDigestNotifier @Inject constructor(
|
||||||
|
@ApplicationContext private val context: Context,
|
||||||
|
private val settingsPrefs: SettingsPrefs,
|
||||||
|
) {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Post the summary of [day] listing [listed], or withdraw the last one when
|
||||||
|
* there is nothing to list — yesterday's would otherwise stand in for it.
|
||||||
|
*/
|
||||||
|
suspend fun post(day: LocalDate, listed: List<ReminderEventInstance>) {
|
||||||
|
val manager = NotificationManagerCompat.from(context)
|
||||||
|
if (listed.isEmpty()) {
|
||||||
|
manager.cancel(TAG_DIGEST, NOTIFICATION_ID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ensureChannel()
|
||||||
|
val zone = ZoneId.systemDefault()
|
||||||
|
val locale = Locale.getDefault()
|
||||||
|
val is24Hour = settingsPrefs.timeFormat.first()
|
||||||
|
.is24Hour(android.text.format.DateFormat.is24HourFormat(context))
|
||||||
|
val today = LocalDate.now(zone)
|
||||||
|
val firstDayOfWeek = DayOfWeek.of(settingsPrefs.weekStart.first().resolveFirstDay(locale).isoDayNumber)
|
||||||
|
// The date rides along: the summary stays up into the day it lists,
|
||||||
|
// when "Tomorrow" alone would point at the wrong one.
|
||||||
|
val date = DateTimeFormatter.ofPattern(
|
||||||
|
android.text.format.DateFormat.getBestDateTimePattern(locale, "EEEdMMM"),
|
||||||
|
locale,
|
||||||
|
).format(day)
|
||||||
|
val dayLabel = when (day) {
|
||||||
|
today -> context.getString(R.string.digest_day_relative, context.getString(R.string.reminder_day_today), date)
|
||||||
|
today.plusDays(1) ->
|
||||||
|
context.getString(R.string.digest_day_relative, context.getString(R.string.reminder_day_tomorrow), date)
|
||||||
|
else -> date
|
||||||
|
}
|
||||||
|
val allDay = context.getString(R.string.event_detail_all_day)
|
||||||
|
val lines = listed.map { entry ->
|
||||||
|
// Read against the listed day, so a timed event on it shows its bare
|
||||||
|
// range and one crossing midnight its dates.
|
||||||
|
val time = if (entry.isAllDay) allDay else reminderTimeText(
|
||||||
|
beginMillis = entry.beginMillis,
|
||||||
|
endMillis = entry.endMillis,
|
||||||
|
isAllDay = entry.isAllDay,
|
||||||
|
zone = zone,
|
||||||
|
locale = locale,
|
||||||
|
is24Hour = is24Hour,
|
||||||
|
today = day,
|
||||||
|
firstDayOfWeek = firstDayOfWeek,
|
||||||
|
todayLabel = allDay,
|
||||||
|
tomorrowLabel = context.getString(R.string.reminder_day_tomorrow),
|
||||||
|
yesterdayLabel = context.getString(R.string.reminder_day_yesterday),
|
||||||
|
)
|
||||||
|
context.getString(R.string.digest_line, time, entry.title.ifBlank { context.getString(R.string.event_untitled) })
|
||||||
|
}
|
||||||
|
val title = context.resources.getQuantityString(R.plurals.digest_title, listed.size, dayLabel, listed.size)
|
||||||
|
val style = NotificationCompat.InboxStyle().setBigContentTitle(title)
|
||||||
|
lines.take(MAX_LINES).forEach(style::addLine)
|
||||||
|
if (lines.size > MAX_LINES) {
|
||||||
|
val more = lines.size - MAX_LINES
|
||||||
|
style.setSummaryText(context.resources.getQuantityString(R.plurals.digest_more, more, more))
|
||||||
|
}
|
||||||
|
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
|
||||||
|
.setSmallIcon(R.drawable.ic_notification)
|
||||||
|
.setContentTitle(title)
|
||||||
|
.setContentText(listed.joinToString(", ") { it.title.ifBlank { context.getString(R.string.event_untitled) } })
|
||||||
|
.setStyle(style)
|
||||||
|
.setCategory(NotificationCompat.CATEGORY_REMINDER)
|
||||||
|
.setAutoCancel(true)
|
||||||
|
// Gone once its day is over; "Tomorrow" would read wrong by then anyway.
|
||||||
|
.setTimeoutAfter(
|
||||||
|
(day.plusDays(1).atStartOfDay(zone).toInstant().toEpochMilli() - System.currentTimeMillis())
|
||||||
|
.coerceAtLeast(1L),
|
||||||
|
)
|
||||||
|
.setContentIntent(openDay(day))
|
||||||
|
.build()
|
||||||
|
try {
|
||||||
|
manager.notify(TAG_DIGEST, NOTIFICATION_ID, notification)
|
||||||
|
} catch (e: SecurityException) {
|
||||||
|
Log.w(TAG, "Could not post the daily summary", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether the summary's own channel is switched off in the system settings. */
|
||||||
|
fun isChannelOff(): Boolean =
|
||||||
|
context.getSystemService(NotificationManager::class.java)
|
||||||
|
.getNotificationChannel(CHANNEL_ID)?.importance == NotificationManager.IMPORTANCE_NONE
|
||||||
|
|
||||||
|
/** Withdraw the summary showing, if any. */
|
||||||
|
fun cancel() {
|
||||||
|
NotificationManagerCompat.from(context).cancel(TAG_DIGEST, NOTIFICATION_ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The summary's channel id, created if missing — for the settings deep-link. */
|
||||||
|
fun channelId(): String {
|
||||||
|
ensureChannel()
|
||||||
|
return CHANNEL_ID
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Creates the channel, or renames it after a language change; the user's settings on it stay. */
|
||||||
|
private fun ensureChannel() {
|
||||||
|
val manager = context.getSystemService(NotificationManager::class.java)
|
||||||
|
manager.createNotificationChannel(
|
||||||
|
NotificationChannel(
|
||||||
|
CHANNEL_ID,
|
||||||
|
context.getString(R.string.digest_channel_name),
|
||||||
|
NotificationManager.IMPORTANCE_DEFAULT,
|
||||||
|
).apply { description = context.getString(R.string.digest_channel_description) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun openDay(day: LocalDate): PendingIntent = PendingIntent.getActivity(
|
||||||
|
context,
|
||||||
|
REQUEST_CODE,
|
||||||
|
MainActivity.openDayIntent(context, day.toKotlinLocalDate()),
|
||||||
|
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||||
|
)
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val TAG = "DailyDigestNotifier"
|
||||||
|
const val CHANNEL_ID = "daily_digest"
|
||||||
|
const val TAG_DIGEST = "daily_digest"
|
||||||
|
const val NOTIFICATION_ID = 2
|
||||||
|
const val REQUEST_CODE = 0xD16E
|
||||||
|
const val MAX_LINES = 6
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,92 +0,0 @@
|
|||||||
package de.jeanlucmakiola.calendula.data.reminders
|
|
||||||
|
|
||||||
import android.Manifest
|
|
||||||
import android.content.BroadcastReceiver
|
|
||||||
import android.content.Context
|
|
||||||
import android.content.Intent
|
|
||||||
import android.content.pm.PackageManager
|
|
||||||
import android.provider.CalendarContract
|
|
||||||
import androidx.core.content.ContextCompat
|
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
|
||||||
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
|
|
||||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
|
||||||
import kotlinx.coroutines.CoroutineScope
|
|
||||||
import kotlinx.coroutines.Dispatchers
|
|
||||||
import kotlinx.coroutines.SupervisorJob
|
|
||||||
import kotlinx.coroutines.flow.first
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
import javax.inject.Inject
|
|
||||||
|
|
||||||
/**
|
|
||||||
* True when [this] alert belongs to a calendar the user disabled in-app, so its
|
|
||||||
* reminder must be suppressed (mirroring the event filtering in
|
|
||||||
* CalendarRepositoryImpl). Alerts whose calendar is unknown (id 0L — e.g. a
|
|
||||||
* pre-upgrade snooze PendingIntent minted before EXTRA_CALENDAR_ID existed) are
|
|
||||||
* never treated as disabled. This is the one predicate the disabled-calendar
|
|
||||||
* gate is built from: [postableAlerts] here and the choke point in
|
|
||||||
* [ReminderNotifier.post] both use it.
|
|
||||||
*/
|
|
||||||
internal fun ReminderAlert.isForDisabledCalendar(disabledCalendarIds: Set<Long>): Boolean =
|
|
||||||
calendarId != 0L && calendarId in disabledCalendarIds
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The due alerts that should actually surface as notifications: everything
|
|
||||||
* except alerts whose calendar the user has disabled in-app. The caller still
|
|
||||||
* marks the full due set fired, so suppressed alerts are not re-broadcast by the
|
|
||||||
* provider.
|
|
||||||
*/
|
|
||||||
internal fun postableAlerts(
|
|
||||||
due: List<ReminderAlert>,
|
|
||||||
disabledCalendarIds: Set<Long>,
|
|
||||||
): List<ReminderAlert> = due.filterNot { it.isForDisabledCalendar(disabledCalendarIds) }
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Becomes the app that turns the calendar provider's reminder alarms into
|
|
||||||
* visible notifications (the Etar model — the provider broadcasts
|
|
||||||
* `EVENT_REMINDER` at reminder time but posts nothing itself).
|
|
||||||
*
|
|
||||||
* The broadcast's data URI only carries the alarm time, so it is ignored:
|
|
||||||
* we query every still-scheduled, due `CalendarAlerts` row ourselves, post
|
|
||||||
* them, and mark them fired. Posting happens before marking — a crash in
|
|
||||||
* between re-posts silently (same tag) rather than losing the reminder.
|
|
||||||
*/
|
|
||||||
@AndroidEntryPoint
|
|
||||||
class EventReminderReceiver : BroadcastReceiver() {
|
|
||||||
|
|
||||||
@Inject lateinit var alertStore: ReminderAlertStore
|
|
||||||
@Inject lateinit var notifier: ReminderNotifier
|
|
||||||
@Inject lateinit var settingsPrefs: SettingsPrefs
|
|
||||||
@Inject lateinit var calendarPrefs: CalendarPrefs
|
|
||||||
@Inject lateinit var suppressedStore: SuppressedReminderStore
|
|
||||||
|
|
||||||
override fun onReceive(context: Context, intent: Intent) {
|
|
||||||
if (intent.action != CalendarContract.ACTION_EVENT_REMINDER) return
|
|
||||||
val readGranted = ContextCompat.checkSelfPermission(
|
|
||||||
context, Manifest.permission.READ_CALENDAR,
|
|
||||||
) == PackageManager.PERMISSION_GRANTED
|
|
||||||
if (!readGranted || !notifier.canPost()) return
|
|
||||||
|
|
||||||
val pendingResult = goAsync()
|
|
||||||
CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
|
|
||||||
try {
|
|
||||||
if (settingsPrefs.remindersEnabled.first()) {
|
|
||||||
val now = System.currentTimeMillis()
|
|
||||||
val due = alertStore.dueAlerts(now)
|
|
||||||
val disabled = calendarPrefs.disabledCalendarIds.first()
|
|
||||||
val postable = postableAlerts(due, disabled)
|
|
||||||
// Suppress reminders for disabled calendars, but still mark
|
|
||||||
// every due alert fired so the provider stops re-broadcasting
|
|
||||||
// the suppressed ones. Stash those suppressed alerts so
|
|
||||||
// re-enabling their calendar can recover them (they would
|
|
||||||
// otherwise stay STATE_FIRED forever with no re-scan).
|
|
||||||
postable.forEach { notifier.post(it) }
|
|
||||||
alertStore.markFired(due.map { it.alertId }, now)
|
|
||||||
suppressedStore.stash(due - postable.toSet(), now)
|
|
||||||
suppressedStore.purgeExpired(now)
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
pendingResult.finish()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.data.reminders
|
||||||
|
|
||||||
|
import kotlinx.coroutines.channels.BufferOverflow
|
||||||
|
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||||
|
import kotlinx.coroutines.flow.SharedFlow
|
||||||
|
import kotlinx.coroutines.flow.asSharedFlow
|
||||||
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What the full-screen alerts (#171) share within the process: the reminder
|
||||||
|
* [ReminderRingService] is ringing for, and the reminders just dismissed or
|
||||||
|
* snoozed, so an alert screen showing one closes whichever way it was handled.
|
||||||
|
*/
|
||||||
|
@Singleton
|
||||||
|
class FullScreenAlerts @Inject constructor() {
|
||||||
|
|
||||||
|
/** Written only by [ReminderRingService], on the main thread, for as long as it rings. */
|
||||||
|
@Volatile
|
||||||
|
var ringing: ReminderAlert? = null
|
||||||
|
internal set
|
||||||
|
|
||||||
|
/** Rings handed to [ReminderRingService] that have not reached it yet, with how many starts each. */
|
||||||
|
private val pending = ConcurrentHashMap<Long, Pair<ReminderAlert, Int>>()
|
||||||
|
|
||||||
|
/** Set when the service is stopped from outside but its ring should go back to the shade. */
|
||||||
|
@Volatile
|
||||||
|
internal var handBackOnDestroy = false
|
||||||
|
|
||||||
|
internal fun addPending(alert: ReminderAlert) {
|
||||||
|
pending.compute(alert.key) { _, entry -> alert to ((entry?.second ?: 0) + 1) }
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun removePending(alert: ReminderAlert) {
|
||||||
|
pending.computeIfPresent(alert.key) { _, entry -> if (entry.second <= 1) null else entry.first to entry.second - 1 }
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun isPending(alert: ReminderAlert): Boolean = pending.containsKey(alert.key)
|
||||||
|
|
||||||
|
internal val anyPending: Boolean get() = pending.isNotEmpty()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether a ring going or on its way [match]es, so a stop is worth sending.
|
||||||
|
* Pending first: the service sets [ringing] before it lets a start go.
|
||||||
|
*/
|
||||||
|
fun mayRing(match: RingMatch): Boolean =
|
||||||
|
pending.values.any { match.matches(it.first) } || ringing?.let(match::matches) == true
|
||||||
|
|
||||||
|
private val handledKeys = MutableSharedFlow<Long>(
|
||||||
|
extraBufferCapacity = 8,
|
||||||
|
onBufferOverflow = BufferOverflow.DROP_OLDEST,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** The [ReminderAlert.key]s of reminders as they are dismissed, snoozed or handed back. */
|
||||||
|
val handled: SharedFlow<Long> = handledKeys.asSharedFlow()
|
||||||
|
|
||||||
|
fun markHandled(alert: ReminderAlert) {
|
||||||
|
handledKeys.tryEmit(alert.key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What becomes of a ring once its settings are re-read. */
|
||||||
|
enum class RingVerdict { Ring, HandBack, Drop }
|
||||||
|
|
||||||
|
/** Which ring a stop is for. */
|
||||||
|
sealed interface RingMatch {
|
||||||
|
fun matches(alert: ReminderAlert): Boolean
|
||||||
|
|
||||||
|
data class Key(val key: Long) : RingMatch {
|
||||||
|
override fun matches(alert: ReminderAlert) = alert.key == key
|
||||||
|
}
|
||||||
|
|
||||||
|
data class Occurrence(val occurrenceKey: Long) : RingMatch {
|
||||||
|
override fun matches(alert: ReminderAlert) = alert.occurrenceKey == occurrenceKey
|
||||||
|
}
|
||||||
|
|
||||||
|
data class Calendar(val calendarId: Long) : RingMatch {
|
||||||
|
override fun matches(alert: ReminderAlert) = alert.calendarId == calendarId
|
||||||
|
}
|
||||||
|
|
||||||
|
data object Any : RingMatch {
|
||||||
|
override fun matches(alert: ReminderAlert) = true
|
||||||
|
}
|
||||||
|
}
|
||||||
+52
-30
@@ -3,27 +3,27 @@ package de.jeanlucmakiola.calendula.data.reminders
|
|||||||
import android.content.BroadcastReceiver
|
import android.content.BroadcastReceiver
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
|
import androidx.core.net.toUri
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import de.jeanlucmakiola.floret.android.goAsync
|
||||||
import kotlinx.coroutines.Dispatchers
|
|
||||||
import kotlinx.coroutines.SupervisorJob
|
|
||||||
import kotlinx.coroutines.flow.first
|
import kotlinx.coroutines.flow.first
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handles the "Snooze" and "Dismiss" actions on a reminder notification, plus
|
* Handles the "Snooze" and "Dismiss" actions on a reminder notification, plus
|
||||||
* the internal re-show when a snooze elapses. All three are app-internal
|
* the internal re-show when a snooze elapses. All three are app-internal
|
||||||
* intents (notification action buttons and our own [ReminderSnoozeScheduler]
|
* intents (notification action buttons, the full-screen alert's buttons and
|
||||||
* alarm), so the receiver is not exported.
|
* our own [ReminderSnoozeScheduler] alarm), so the receiver is not exported.
|
||||||
*
|
*
|
||||||
* - **Dismiss** just cancels the notification — the `CalendarAlerts` row is
|
* - **Dismiss** just cancels the notification — the scan's watermark has moved
|
||||||
* already fired, so nothing re-posts it.
|
* past this reminder, so nothing re-posts it.
|
||||||
* - **Snooze** cancels the notification and schedules an exact alarm to re-show
|
* - **Snooze** cancels the notification and schedules an exact alarm to re-show
|
||||||
* it after the user's snooze delay.
|
* it after the user's snooze delay.
|
||||||
* - **Show** (the alarm) re-posts the same notification, so the user can snooze
|
* - **Show** (the alarm) re-posts the same notification, so the user can snooze
|
||||||
* or dismiss it again.
|
* or dismiss it again — unless the calendar was switched off during the
|
||||||
|
* snooze, which [ReminderNotifier.post] catches — this alarm is its own
|
||||||
|
* trigger, outside the ordinary scan.
|
||||||
*/
|
*/
|
||||||
@AndroidEntryPoint
|
@AndroidEntryPoint
|
||||||
class ReminderActionReceiver : BroadcastReceiver() {
|
class ReminderActionReceiver : BroadcastReceiver() {
|
||||||
@@ -38,31 +38,25 @@ class ReminderActionReceiver : BroadcastReceiver() {
|
|||||||
ACTION_DISMISS -> notifier.cancel(alert)
|
ACTION_DISMISS -> notifier.cancel(alert)
|
||||||
|
|
||||||
ACTION_SNOOZE -> {
|
ACTION_SNOOZE -> {
|
||||||
|
// Tapped on a stale view: the reminder that replaced it stays put.
|
||||||
|
if (notifier.isSuperseded(alert)) return
|
||||||
// Cancel now so the notification doesn't linger until the alarm;
|
// Cancel now so the notification doesn't linger until the alarm;
|
||||||
// the snooze delay read is the only async work.
|
// the snooze delay read is the only async work.
|
||||||
notifier.cancel(alert)
|
notifier.cancel(alert)
|
||||||
val pendingResult = goAsync()
|
goAsync {
|
||||||
CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
|
|
||||||
try {
|
|
||||||
val minutes = settingsPrefs.snoozeMinutes.first()
|
val minutes = settingsPrefs.snoozeMinutes.first()
|
||||||
val triggerAt = System.currentTimeMillis() + minutes * 60_000L
|
val triggerAt = System.currentTimeMillis() + minutes * 60_000L
|
||||||
scheduler.schedule(alert, triggerAt)
|
scheduler.schedule(alert, triggerAt)
|
||||||
} finally {
|
|
||||||
pendingResult.finish()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ACTION_SHOW -> {
|
ACTION_SHOW -> {
|
||||||
val pendingResult = goAsync()
|
goAsync {
|
||||||
CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
|
// A later reminder posted while this one was snoozed has taken its place.
|
||||||
try {
|
if (notifier.isSuperseded(alert)) return@goAsync
|
||||||
if (settingsPrefs.remindersEnabled.first() && notifier.canPost()) {
|
if (settingsPrefs.remindersEnabled.first() && notifier.canPost()) {
|
||||||
notifier.post(alert)
|
notifier.post(alert)
|
||||||
}
|
}
|
||||||
} finally {
|
|
||||||
pendingResult.finish()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -73,7 +67,17 @@ class ReminderActionReceiver : BroadcastReceiver() {
|
|||||||
const val ACTION_DISMISS = "de.jeanlucmakiola.calendula.reminders.DISMISS"
|
const val ACTION_DISMISS = "de.jeanlucmakiola.calendula.reminders.DISMISS"
|
||||||
const val ACTION_SHOW = "de.jeanlucmakiola.calendula.reminders.SHOW"
|
const val ACTION_SHOW = "de.jeanlucmakiola.calendula.reminders.SHOW"
|
||||||
|
|
||||||
private const val EXTRA_ALERT_ID = "alert_id"
|
/**
|
||||||
|
* Not handled here — the notification body opens the detail screen
|
||||||
|
* directly. It only claims a slot in [requestCode] so that intent stays
|
||||||
|
* distinct from the three this receiver does handle.
|
||||||
|
*/
|
||||||
|
const val ACTION_OPEN = "de.jeanlucmakiola.calendula.reminders.OPEN"
|
||||||
|
|
||||||
|
/** Not handled here either: the slot of the full-screen alert's own intent (#171). */
|
||||||
|
const val ACTION_ALERT_SCREEN = "de.jeanlucmakiola.calendula.reminders.ALERT_SCREEN"
|
||||||
|
|
||||||
|
private const val EXTRA_ALERT_KEY = "alert_key"
|
||||||
private const val EXTRA_EVENT_ID = "event_id"
|
private const val EXTRA_EVENT_ID = "event_id"
|
||||||
private const val EXTRA_CALENDAR_ID = "calendar_id"
|
private const val EXTRA_CALENDAR_ID = "calendar_id"
|
||||||
private const val EXTRA_BEGIN = "begin"
|
private const val EXTRA_BEGIN = "begin"
|
||||||
@@ -82,11 +86,23 @@ class ReminderActionReceiver : BroadcastReceiver() {
|
|||||||
private const val EXTRA_LOCATION = "location"
|
private const val EXTRA_LOCATION = "location"
|
||||||
private const val EXTRA_ALL_DAY = "all_day"
|
private const val EXTRA_ALL_DAY = "all_day"
|
||||||
|
|
||||||
/** An explicit intent to this receiver carrying [alert] as extras. */
|
/**
|
||||||
|
* An explicit intent to this receiver carrying [alert] as extras. The
|
||||||
|
* data URI duplicates no information but is what keeps two reminders'
|
||||||
|
* `PendingIntent`s apart — `filterEquals` never compares extras. The
|
||||||
|
* snooze alarm is the exception: one per occurrence, so a later snooze
|
||||||
|
* replaces an earlier one and a newer reminder can cancel it.
|
||||||
|
*/
|
||||||
fun intent(context: Context, action: String, alert: ReminderAlert): Intent =
|
fun intent(context: Context, action: String, alert: ReminderAlert): Intent =
|
||||||
Intent(context, ReminderActionReceiver::class.java).apply {
|
Intent(context, ReminderActionReceiver::class.java).apply {
|
||||||
this.action = action
|
this.action = action
|
||||||
putExtra(EXTRA_ALERT_ID, alert.alertId)
|
data = "calendula://reminder/${identity(alert, action)}".toUri()
|
||||||
|
putAlert(alert)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Carries [alert] as extras, for [alertFrom] to read back. */
|
||||||
|
fun Intent.putAlert(alert: ReminderAlert): Intent = apply {
|
||||||
|
putExtra(EXTRA_ALERT_KEY, alert.key)
|
||||||
putExtra(EXTRA_EVENT_ID, alert.eventId)
|
putExtra(EXTRA_EVENT_ID, alert.eventId)
|
||||||
putExtra(EXTRA_CALENDAR_ID, alert.calendarId)
|
putExtra(EXTRA_CALENDAR_ID, alert.calendarId)
|
||||||
putExtra(EXTRA_BEGIN, alert.beginMillis)
|
putExtra(EXTRA_BEGIN, alert.beginMillis)
|
||||||
@@ -97,23 +113,29 @@ class ReminderActionReceiver : BroadcastReceiver() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A stable request code per (alert, action) so the three PendingIntents
|
* A stable request code per (alert, action), so one notification's
|
||||||
* of one notification stay distinct and don't clobber each other.
|
* PendingIntents stay distinct. The shift keeps the action slot intact;
|
||||||
|
* the top bits it drops are separated by [intent]'s URI.
|
||||||
*/
|
*/
|
||||||
fun requestCode(alert: ReminderAlert, action: String): Int {
|
fun requestCode(alert: ReminderAlert, action: String): Int {
|
||||||
val actionOffset = when (action) {
|
val actionOffset = when (action) {
|
||||||
ACTION_SNOOZE -> 1
|
ACTION_SNOOZE -> 1
|
||||||
ACTION_DISMISS -> 2
|
ACTION_DISMISS -> 2
|
||||||
ACTION_SHOW -> 3
|
ACTION_SHOW -> 3
|
||||||
|
ACTION_OPEN -> 4
|
||||||
|
ACTION_ALERT_SCREEN -> 5
|
||||||
else -> 0
|
else -> 0
|
||||||
}
|
}
|
||||||
return alert.alertId.toInt() * 8 + actionOffset
|
return (identity(alert, action).toInt() shl 3) + actionOffset
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun alertFrom(intent: Intent): ReminderAlert? {
|
private fun identity(alert: ReminderAlert, action: String): Long =
|
||||||
if (!intent.hasExtra(EXTRA_ALERT_ID)) return null
|
if (action == ACTION_SHOW) alert.occurrenceKey else alert.key
|
||||||
|
|
||||||
|
fun alertFrom(intent: Intent): ReminderAlert? {
|
||||||
|
if (!intent.hasExtra(EXTRA_ALERT_KEY)) return null
|
||||||
return ReminderAlert(
|
return ReminderAlert(
|
||||||
alertId = intent.getLongExtra(EXTRA_ALERT_ID, 0L),
|
key = intent.getLongExtra(EXTRA_ALERT_KEY, 0L),
|
||||||
eventId = intent.getLongExtra(EXTRA_EVENT_ID, 0L),
|
eventId = intent.getLongExtra(EXTRA_EVENT_ID, 0L),
|
||||||
calendarId = intent.getLongExtra(EXTRA_CALENDAR_ID, 0L),
|
calendarId = intent.getLongExtra(EXTRA_CALENDAR_ID, 0L),
|
||||||
beginMillis = intent.getLongExtra(EXTRA_BEGIN, 0L),
|
beginMillis = intent.getLongExtra(EXTRA_BEGIN, 0L),
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.data.reminders
|
||||||
|
|
||||||
|
import android.app.AlarmManager
|
||||||
|
import android.app.PendingIntent
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import androidx.core.content.getSystemService
|
||||||
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
|
import de.jeanlucmakiola.floret.android.setWakeup
|
||||||
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Holds the app's own wake-up for the next reminder (#75). Exactly one alarm
|
||||||
|
* exists at a time, for the earliest reminder ahead; every firing re-scans and
|
||||||
|
* re-arms. Exact, with an inexact allow-while-idle fallback where the OS
|
||||||
|
* withholds the capability (API 31–32 with the permission revoked).
|
||||||
|
*/
|
||||||
|
@Singleton
|
||||||
|
class ReminderAlarmScheduler @Inject constructor(
|
||||||
|
@ApplicationContext private val context: Context,
|
||||||
|
) {
|
||||||
|
|
||||||
|
fun scheduleScan(triggerAtMillis: Long) {
|
||||||
|
val alarmManager = context.getSystemService<AlarmManager>() ?: return
|
||||||
|
alarmManager.setWakeup(triggerAtMillis, scanPendingIntent(PendingIntent.FLAG_UPDATE_CURRENT))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Drop the pending wake-up — reminders are off, or there is nothing to wait for. */
|
||||||
|
fun cancelScan() {
|
||||||
|
val alarmManager = context.getSystemService<AlarmManager>() ?: return
|
||||||
|
alarmManager.cancel(scanPendingIntent(PendingIntent.FLAG_UPDATE_CURRENT))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun scanPendingIntent(flags: Int): PendingIntent = PendingIntent.getBroadcast(
|
||||||
|
context,
|
||||||
|
SCAN_REQUEST_CODE,
|
||||||
|
Intent(context, ReminderScheduleReceiver::class.java)
|
||||||
|
.setAction(ReminderScheduleReceiver.ACTION_SCAN),
|
||||||
|
flags or PendingIntent.FLAG_IMMUTABLE,
|
||||||
|
)
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
// Fixed: there is only ever one scan alarm, and re-arming must replace it.
|
||||||
|
const val SCAN_REQUEST_CODE = 0x5CA1
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.data.reminders
|
||||||
|
|
||||||
|
import de.jeanlucmakiola.calendula.domain.reminders.PlannedReminder
|
||||||
|
import de.jeanlucmakiola.calendula.domain.reminders.occurrenceKey
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One reminder as the notification layer needs it: what to show, and the stable
|
||||||
|
* [key] identifying it across a reboot, a re-scan and a reinstall. Derived from
|
||||||
|
* the reminder itself (see [PlannedReminder.key]) — in-house delivery has no
|
||||||
|
* `CalendarAlerts` row to take an id from (#75).
|
||||||
|
*/
|
||||||
|
data class ReminderAlert(
|
||||||
|
val key: Long,
|
||||||
|
val eventId: Long,
|
||||||
|
val calendarId: Long,
|
||||||
|
val beginMillis: Long,
|
||||||
|
val endMillis: Long,
|
||||||
|
/** Raw event title; may be blank — the notifier substitutes "(no title)". */
|
||||||
|
val title: String,
|
||||||
|
val location: String?,
|
||||||
|
val isAllDay: Boolean,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The occurrence [ReminderAlert] belongs to. Keys the notification and the
|
||||||
|
* snooze alarm, so a later reminder for the same occurrence replaces the earlier
|
||||||
|
* one instead of stacking beside it (#463).
|
||||||
|
*/
|
||||||
|
val ReminderAlert.occurrenceKey: Long get() = occurrenceKey(eventId, beginMillis)
|
||||||
|
|
||||||
|
fun PlannedReminder.toAlert(): ReminderAlert = ReminderAlert(
|
||||||
|
key = key,
|
||||||
|
eventId = instance.eventId,
|
||||||
|
calendarId = instance.calendarId,
|
||||||
|
beginMillis = instance.beginMillis,
|
||||||
|
endMillis = instance.endMillis,
|
||||||
|
title = instance.title,
|
||||||
|
location = instance.location,
|
||||||
|
isAllDay = instance.isAllDay,
|
||||||
|
)
|
||||||
@@ -1,115 +0,0 @@
|
|||||||
package de.jeanlucmakiola.calendula.data.reminders
|
|
||||||
|
|
||||||
import android.content.ContentValues
|
|
||||||
import android.content.Context
|
|
||||||
import android.provider.CalendarContract
|
|
||||||
import android.util.Log
|
|
||||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
|
||||||
import javax.inject.Inject
|
|
||||||
import javax.inject.Singleton
|
|
||||||
|
|
||||||
/**
|
|
||||||
* One due row of the provider's `CalendarAlerts` table (a join with Events).
|
|
||||||
* Stays in the data layer: alerts feed the notification path only and never
|
|
||||||
* reach a screen, so there is no domain model for them.
|
|
||||||
*/
|
|
||||||
data class ReminderAlert(
|
|
||||||
val alertId: Long,
|
|
||||||
val eventId: Long,
|
|
||||||
val calendarId: Long,
|
|
||||||
val beginMillis: Long,
|
|
||||||
val endMillis: Long,
|
|
||||||
/** Raw event title; may be blank — the notifier substitutes "(no title)". */
|
|
||||||
val title: String,
|
|
||||||
val location: String?,
|
|
||||||
val isAllDay: Boolean,
|
|
||||||
)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Seam over the `CalendarAlerts` table so the receiver logic can be exercised
|
|
||||||
* without a ContentResolver. The provider creates these rows itself — only
|
|
||||||
* for `METHOD_ALERT` reminders (verified in AOSP `CalendarAlarmManager`), so
|
|
||||||
* email reminders never show up here.
|
|
||||||
*/
|
|
||||||
interface ReminderAlertStore {
|
|
||||||
|
|
||||||
/** Alerts that are due (`ALARM_TIME` has passed) and still unhandled. */
|
|
||||||
fun dueAlerts(nowMillis: Long): List<ReminderAlert>
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Mark the given alerts handled (`STATE_FIRED`) so a later broadcast does
|
|
||||||
* not surface them again. Best effort: this write needs `WRITE_CALENDAR`,
|
|
||||||
* which the user may have declined — then re-broadcasts silently replace
|
|
||||||
* the already-posted notifications instead (same tag, alert-once).
|
|
||||||
*/
|
|
||||||
fun markFired(alertIds: List<Long>, nowMillis: Long)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Singleton
|
|
||||||
class AndroidReminderAlertStore @Inject constructor(
|
|
||||||
@ApplicationContext private val context: Context,
|
|
||||||
) : ReminderAlertStore {
|
|
||||||
|
|
||||||
override fun dueAlerts(nowMillis: Long): List<ReminderAlert> = context.contentResolver.query(
|
|
||||||
CalendarContract.CalendarAlerts.CONTENT_URI,
|
|
||||||
PROJECTION,
|
|
||||||
CalendarContract.CalendarAlerts.STATE + " = ? AND " +
|
|
||||||
CalendarContract.CalendarAlerts.ALARM_TIME + " <= ?",
|
|
||||||
arrayOf(
|
|
||||||
CalendarContract.CalendarAlerts.STATE_SCHEDULED.toString(),
|
|
||||||
nowMillis.toString(),
|
|
||||||
),
|
|
||||||
CalendarContract.CalendarAlerts.BEGIN + " ASC",
|
|
||||||
)?.use { c ->
|
|
||||||
buildList {
|
|
||||||
while (c.moveToNext()) {
|
|
||||||
add(
|
|
||||||
ReminderAlert(
|
|
||||||
alertId = c.getLong(0),
|
|
||||||
eventId = c.getLong(1),
|
|
||||||
calendarId = c.getLong(2),
|
|
||||||
beginMillis = c.getLong(3),
|
|
||||||
endMillis = c.getLong(4),
|
|
||||||
title = c.getString(5).orEmpty(),
|
|
||||||
location = c.getString(6)?.takeIf { it.isNotBlank() },
|
|
||||||
isAllDay = c.getInt(7) == 1,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} ?: emptyList()
|
|
||||||
|
|
||||||
override fun markFired(alertIds: List<Long>, nowMillis: Long) {
|
|
||||||
if (alertIds.isEmpty()) return
|
|
||||||
val values = ContentValues().apply {
|
|
||||||
put(CalendarContract.CalendarAlerts.STATE, CalendarContract.CalendarAlerts.STATE_FIRED)
|
|
||||||
put(CalendarContract.CalendarAlerts.RECEIVED_TIME, nowMillis)
|
|
||||||
put(CalendarContract.CalendarAlerts.NOTIFY_TIME, nowMillis)
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
context.contentResolver.update(
|
|
||||||
CalendarContract.CalendarAlerts.CONTENT_URI,
|
|
||||||
values,
|
|
||||||
CalendarContract.CalendarAlerts._ID +
|
|
||||||
" IN (" + alertIds.joinToString(",") + ")",
|
|
||||||
null,
|
|
||||||
)
|
|
||||||
} catch (e: SecurityException) {
|
|
||||||
Log.w(TAG, "Cannot mark alerts fired without WRITE_CALENDAR", e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private companion object {
|
|
||||||
const val TAG = "ReminderAlertStore"
|
|
||||||
val PROJECTION = arrayOf(
|
|
||||||
CalendarContract.CalendarAlerts._ID,
|
|
||||||
CalendarContract.CalendarAlerts.EVENT_ID,
|
|
||||||
CalendarContract.CalendarAlerts.CALENDAR_ID,
|
|
||||||
CalendarContract.CalendarAlerts.BEGIN,
|
|
||||||
CalendarContract.CalendarAlerts.END,
|
|
||||||
CalendarContract.CalendarAlerts.TITLE,
|
|
||||||
CalendarContract.CalendarAlerts.EVENT_LOCATION,
|
|
||||||
CalendarContract.CalendarAlerts.ALL_DAY,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.data.reminders
|
||||||
|
|
||||||
|
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||||
|
import de.jeanlucmakiola.calendula.ui.common.groupByAccount
|
||||||
|
|
||||||
|
/** The single channel every reminder posted on before they moved per calendar (#145). */
|
||||||
|
const val LEGACY_REMINDER_CHANNEL_ID = "reminders"
|
||||||
|
|
||||||
|
/** The silent channel ringing full-screen alerts post on (#171); outside the per-calendar namespace. */
|
||||||
|
const val RING_CHANNEL_ID = "reminders_ring"
|
||||||
|
|
||||||
|
private const val CHANNEL_PREFIX = "reminders.calendar."
|
||||||
|
private const val GROUP_PREFIX = "reminders.account."
|
||||||
|
private const val LOCAL_GROUP_ID = GROUP_PREFIX + "local"
|
||||||
|
|
||||||
|
private const val VERSION_SEPARATOR = ".v"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The notification channel [calendarId]'s reminders post on. A sound picked in
|
||||||
|
* the app moves it to a new [version] (#518), since a channel's sound is fixed
|
||||||
|
* once created; version 0 is the unversioned id #145 introduced.
|
||||||
|
*/
|
||||||
|
fun reminderChannelId(calendarId: Long, version: Int = 0): String =
|
||||||
|
if (version == 0) "$CHANNEL_PREFIX$calendarId" else "$CHANNEL_PREFIX$calendarId$VERSION_SEPARATOR$version"
|
||||||
|
|
||||||
|
/** The calendar and version a reminder channel id names, or null for any other id. */
|
||||||
|
fun parseReminderChannelId(channelId: String): Pair<Long, Int>? {
|
||||||
|
if (!isReminderChannelId(channelId)) return null
|
||||||
|
val rest = channelId.removePrefix(CHANNEL_PREFIX)
|
||||||
|
val calendar = rest.substringBefore(VERSION_SEPARATOR).toLongOrNull() ?: return null
|
||||||
|
if (VERSION_SEPARATOR !in rest) return calendar to 0
|
||||||
|
val version = rest.substringAfter(VERSION_SEPARATOR).toIntOrNull()?.takeIf { it > 0 } ?: return null
|
||||||
|
return calendar to version
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Each calendar's current channel version: the highest one that exists, so a
|
||||||
|
* new version only takes over once it is written. A calendar with none falls
|
||||||
|
* back to its [highWater] mark — re-creating that id restores its own settings.
|
||||||
|
*/
|
||||||
|
fun currentReminderChannelVersions(existingChannelIds: Collection<String>, highWater: Map<Long, Int>): Map<Long, Int> {
|
||||||
|
val existing = existingChannelIds.mapNotNull(::parseReminderChannelId)
|
||||||
|
.groupBy({ it.first }, { it.second })
|
||||||
|
.mapValues { (_, versions) -> versions.max() }
|
||||||
|
return highWater + existing
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether [channelId] is one of the per-calendar reminder channels. */
|
||||||
|
fun isReminderChannelId(channelId: String): Boolean = channelId.startsWith(CHANNEL_PREFIX)
|
||||||
|
|
||||||
|
/** Whether [groupId] is one of the per-account reminder channel groups. */
|
||||||
|
fun isReminderGroupId(groupId: String): Boolean = groupId.startsWith(GROUP_PREFIX)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One account's channel group, labelled as the calendar manager labels it. The
|
||||||
|
* app's own device calendars share a single group ([isLocal]); [ambiguous]
|
||||||
|
* marks a [label] another group shows too, so it should name the source app.
|
||||||
|
*/
|
||||||
|
data class ReminderChannelGroupSpec(
|
||||||
|
val id: String,
|
||||||
|
val label: String,
|
||||||
|
val accountType: String,
|
||||||
|
val isLocal: Boolean,
|
||||||
|
val ambiguous: Boolean,
|
||||||
|
)
|
||||||
|
|
||||||
|
data class ReminderChannelSpec(
|
||||||
|
val id: String,
|
||||||
|
val calendarId: Long,
|
||||||
|
val name: String,
|
||||||
|
/** Null only for a channel created before its calendar could be looked up. */
|
||||||
|
val groupId: String?,
|
||||||
|
/**
|
||||||
|
* Whether a sync creates it up front. A calendar that syncs no events never
|
||||||
|
* fires, so its channel only appears once something posts on it.
|
||||||
|
*/
|
||||||
|
val upFront: Boolean = true,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** What a channel already looks like in the system, as far as the plan compares it. */
|
||||||
|
data class ExistingReminderChannel(val id: String, val name: String, val description: String?, val groupId: String?)
|
||||||
|
|
||||||
|
data class ReminderChannelPlan(
|
||||||
|
val groups: List<ReminderChannelGroupSpec>,
|
||||||
|
val channels: List<ReminderChannelSpec>,
|
||||||
|
/**
|
||||||
|
* The [channels] a sync writes: missing up-front ones, and existing ones
|
||||||
|
* whose name or (localized) description changed, or that still lack a group.
|
||||||
|
*/
|
||||||
|
val channelsToWrite: List<ReminderChannelSpec>,
|
||||||
|
/** The [groups] holding a channel that exists or is about to be written. */
|
||||||
|
val groupsInUse: List<ReminderChannelGroupSpec>,
|
||||||
|
val staleChannelIds: List<String>,
|
||||||
|
val staleGroupIds: List<String>,
|
||||||
|
/** Stale channels kept for now, because a notification on them is still showing. */
|
||||||
|
val keptChannelIds: List<String> = emptyList(),
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What the reminder channels should look like for [calendars]: one channel per
|
||||||
|
* calendar inside a group per account, which of them need writing, and the
|
||||||
|
* reminder channels and groups in [existing] / [existingGroupIds] no calendar
|
||||||
|
* claims any more. Ids outside the reminder namespace (the backup channel, the
|
||||||
|
* legacy channel) are never touched.
|
||||||
|
*/
|
||||||
|
fun planReminderChannels(
|
||||||
|
calendars: List<CalendarSource>,
|
||||||
|
existing: Collection<ExistingReminderChannel>,
|
||||||
|
existingGroupIds: Collection<String>,
|
||||||
|
unnamed: String,
|
||||||
|
description: String,
|
||||||
|
versions: Map<Long, Int> = emptyMap(),
|
||||||
|
showingChannelIds: Set<String> = emptySet(),
|
||||||
|
): ReminderChannelPlan {
|
||||||
|
val (local, synced) = calendars.partition { it.isLocal }
|
||||||
|
val groups = buildList {
|
||||||
|
if (local.isNotEmpty()) {
|
||||||
|
add(ReminderChannelGroupSpec(LOCAL_GROUP_ID, "", local.first().accountType, isLocal = true, ambiguous = false))
|
||||||
|
}
|
||||||
|
synced.groupByAccount().forEach { group ->
|
||||||
|
add(
|
||||||
|
ReminderChannelGroupSpec(
|
||||||
|
id = accountGroupId(group.key.type, group.key.name),
|
||||||
|
label = group.label,
|
||||||
|
accountType = group.accountType,
|
||||||
|
isLocal = false,
|
||||||
|
ambiguous = group.ambiguous,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val existingById = existing.associateBy { it.id }
|
||||||
|
val channels = calendars.map { calendar ->
|
||||||
|
ReminderChannelSpec(
|
||||||
|
id = reminderChannelId(calendar.id, versions[calendar.id] ?: 0),
|
||||||
|
calendarId = calendar.id,
|
||||||
|
name = calendar.displayName.ifBlank { unnamed },
|
||||||
|
groupId = if (calendar.isLocal) LOCAL_GROUP_ID else accountGroupId(calendar.accountType, calendar.accountName),
|
||||||
|
upFront = calendar.isLocal || calendar.syncsEvents,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
val wantedChannels = channels.mapTo(HashSet()) { it.id }
|
||||||
|
val wantedGroups = groups.mapTo(HashSet()) { it.id }
|
||||||
|
val toWrite = channels.filter { spec ->
|
||||||
|
val current = existingById[spec.id]
|
||||||
|
if (current == null) {
|
||||||
|
spec.upFront
|
||||||
|
} else {
|
||||||
|
current.name != spec.name || current.description != description ||
|
||||||
|
(current.groupId == null && spec.groupId != null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val usedGroupIds = channels
|
||||||
|
.filter { it.id in existingById || it in toWrite }
|
||||||
|
.mapNotNullTo(HashSet()) { it.groupId }
|
||||||
|
val (kept, stale) = existingById.keys
|
||||||
|
.filter { isReminderChannelId(it) && it !in wantedChannels }
|
||||||
|
.partition { it in showingChannelIds }
|
||||||
|
val keptGroups = kept.mapNotNullTo(HashSet()) { existingById.getValue(it).groupId }
|
||||||
|
return ReminderChannelPlan(
|
||||||
|
groups = groups,
|
||||||
|
channels = channels,
|
||||||
|
channelsToWrite = toWrite,
|
||||||
|
groupsInUse = groups.filter { it.id in usedGroupIds },
|
||||||
|
staleChannelIds = stale,
|
||||||
|
staleGroupIds = existingGroupIds.filter { isReminderGroupId(it) && it !in wantedGroups && it !in keptGroups },
|
||||||
|
keptChannelIds = kept,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun accountGroupId(type: String, name: String): String = "$GROUP_PREFIX$type/$name"
|
||||||
|
|
||||||
|
/** A channel as far as its blocked state goes: switched off itself, and the group it sits in. */
|
||||||
|
data class ReminderChannelState(val blocked: Boolean, val groupId: String?)
|
||||||
|
|
||||||
|
/** Reminder notifications the system blocks, while Calendula would post them. */
|
||||||
|
data class ReminderChannelStatus(
|
||||||
|
val appBlocked: Boolean = false,
|
||||||
|
val blockedCalendarIds: Set<Long> = emptySet(),
|
||||||
|
/** The blocked ones whose whole account group is off, which only the app's own screen can undo. */
|
||||||
|
val groupBlockedCalendarIds: Set<Long> = emptySet(),
|
||||||
|
/** The shared ring channel (#171) is switched off, so ringing calendars only sound once. */
|
||||||
|
val ringBlocked: Boolean = false,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What the system blocks of [calendarIds]' reminders: all of them while the
|
||||||
|
* app's notifications are off, otherwise those whose channel, or the group it
|
||||||
|
* sits in, is switched off. A calendar without a channel yet isn't blocked.
|
||||||
|
*/
|
||||||
|
fun reminderChannelStatus(
|
||||||
|
calendarIds: Collection<Long>,
|
||||||
|
appEnabled: Boolean,
|
||||||
|
channels: Map<String, ReminderChannelState>,
|
||||||
|
blockedGroupIds: Set<String>,
|
||||||
|
versions: Map<Long, Int> = emptyMap(),
|
||||||
|
): ReminderChannelStatus {
|
||||||
|
fun channel(calendarId: Long) = channels[reminderChannelId(calendarId, versions[calendarId] ?: 0)]
|
||||||
|
val groupBlocked = calendarIds.filterTo(HashSet()) { channel(it)?.groupId in blockedGroupIds }
|
||||||
|
val blocked = if (!appEnabled) {
|
||||||
|
calendarIds.toSet()
|
||||||
|
} else {
|
||||||
|
calendarIds.filterTo(HashSet()) { channel(it)?.blocked == true } + groupBlocked
|
||||||
|
}
|
||||||
|
return ReminderChannelStatus(
|
||||||
|
appBlocked = !appEnabled,
|
||||||
|
blockedCalendarIds = blocked,
|
||||||
|
groupBlockedCalendarIds = groupBlocked,
|
||||||
|
ringBlocked = appEnabled && channels[RING_CHANNEL_ID]?.blocked == true,
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,416 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.data.reminders
|
||||||
|
|
||||||
|
import android.app.Notification
|
||||||
|
import android.app.NotificationChannel
|
||||||
|
import android.app.NotificationChannelGroup
|
||||||
|
import android.app.NotificationManager
|
||||||
|
import android.app.NotificationManager.IMPORTANCE_DEFAULT
|
||||||
|
import android.app.NotificationManager.IMPORTANCE_LOW
|
||||||
|
import android.app.NotificationManager.IMPORTANCE_MIN
|
||||||
|
import android.content.Context
|
||||||
|
import android.media.AudioAttributes
|
||||||
|
import android.net.Uri
|
||||||
|
import android.util.Log
|
||||||
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
|
import de.jeanlucmakiola.calendula.R
|
||||||
|
import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource
|
||||||
|
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||||
|
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||||
|
import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle
|
||||||
|
import de.jeanlucmakiola.calendula.ui.common.sourceAppLabel
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import java.util.Locale
|
||||||
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The reminder notification channels: one per calendar, grouped by account
|
||||||
|
* (#145), created up front so each calendar can be muted or given its own sound
|
||||||
|
* in the system settings before it ever fires.
|
||||||
|
*
|
||||||
|
* A channel the user has touched keeps their settings; [sync] only creates the
|
||||||
|
* missing ones, renames changed ones, and deletes those whose calendar is gone.
|
||||||
|
* A sound picked in the app ([setSound], #518) recreates the channel under the
|
||||||
|
* calendar's next version; the old one goes once nothing shows on it.
|
||||||
|
*/
|
||||||
|
@Singleton
|
||||||
|
class ReminderChannels @Inject constructor(
|
||||||
|
@ApplicationContext private val context: Context,
|
||||||
|
private val calendarDataSource: CalendarDataSource,
|
||||||
|
private val settingsPrefs: SettingsPrefs,
|
||||||
|
) {
|
||||||
|
private val manager: NotificationManager
|
||||||
|
get() = context.getSystemService(NotificationManager::class.java)
|
||||||
|
|
||||||
|
/** What the last [sync] saw, so an unchanged provider costs no channel writes. */
|
||||||
|
@Volatile
|
||||||
|
private var lastSync: Any? = null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bring the channels in line with the provider's calendars. An empty
|
||||||
|
* snapshot changes nothing: that is a provider hiccup far more often than
|
||||||
|
* every calendar gone at once.
|
||||||
|
*/
|
||||||
|
@Synchronized
|
||||||
|
fun sync() {
|
||||||
|
val calendars = calendarDataSource.calendars()
|
||||||
|
if (calendars.isEmpty()) return
|
||||||
|
val manager = manager
|
||||||
|
val existing = manager.notificationChannels
|
||||||
|
val existingIds = existing.mapTo(HashSet()) { it.id }
|
||||||
|
val versions = currentVersions(existingIds).also { knownVersions = it }
|
||||||
|
if (syncKey(calendars, existingIds, versions) == lastSync && LEGACY_REMINDER_CHANNEL_ID !in existingIds) return
|
||||||
|
val groups = manager.notificationChannelGroups
|
||||||
|
val groupIds = groups.map { it.id }
|
||||||
|
// Active notifications are only read when there is something stale to protect.
|
||||||
|
val plan = plan(calendars, existing, groupIds, versions).let { draft ->
|
||||||
|
if (draft.staleChannelIds.isEmpty()) draft else plan(calendars, existing, groupIds, versions, showingChannelIds(draft.staleChannelIds))
|
||||||
|
}
|
||||||
|
plan.staleChannelIds.forEach(manager::deleteNotificationChannel)
|
||||||
|
plan.staleGroupIds.forEach(manager::deleteNotificationChannelGroup)
|
||||||
|
val groupNames = groups.associate { it.id to it.name?.toString() }
|
||||||
|
write(
|
||||||
|
groups = plan.groupsInUse.filter { groupNames[it.id] != groupLabel(it) },
|
||||||
|
channels = plan.channelsToWrite,
|
||||||
|
existing = existing,
|
||||||
|
)
|
||||||
|
if (RING_CHANNEL_ID in existingIds) ensureRingChannel()
|
||||||
|
val ids = existingIds - plan.staleChannelIds.toSet() + plan.channelsToWrite.map { it.id }
|
||||||
|
val legacyGone = retireLegacyChannel()
|
||||||
|
// A kept channel still has to go once its notification does, so don't cache.
|
||||||
|
lastSync = if (plan.keptChannelIds.isEmpty()) {
|
||||||
|
syncKey(calendars, if (legacyGone) ids - LEGACY_REMINDER_CHANNEL_ID else ids, versions)
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun syncKey(calendars: List<CalendarSource>, channelIds: Set<String>, versions: Map<Long, Int>): Any = listOf(
|
||||||
|
calendars.map { listOf(it.id, it.displayName, it.accountName, it.accountType, it.isLocal, it.syncsEvents) },
|
||||||
|
Locale.getDefault(),
|
||||||
|
channelIds,
|
||||||
|
versions,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The current versions last resolved under the lock ([sync], [channelFor]).
|
||||||
|
* Only [recreate], under the same lock, moves a calendar higher and updates
|
||||||
|
* it, so a hit whose channel still exists is current.
|
||||||
|
*/
|
||||||
|
@Volatile
|
||||||
|
private var knownVersions: Map<Long, Int> = emptyMap()
|
||||||
|
|
||||||
|
private fun currentVersions(existingChannelIds: Collection<String>): Map<Long, Int> =
|
||||||
|
currentReminderChannelVersions(existingChannelIds, runBlocking { settingsPrefs.reminderChannelVersions.first() })
|
||||||
|
|
||||||
|
/** Channels with a notification on screen; on failure all of [candidates] count, so none is deleted. */
|
||||||
|
private fun showingChannelIds(candidates: Collection<String>): Set<String> = runCatching {
|
||||||
|
manager.activeNotifications.mapNotNullTo(HashSet()) { it.notification.channelId }
|
||||||
|
}.getOrElse { e ->
|
||||||
|
Log.w(TAG, "Could not read active notifications", e)
|
||||||
|
candidates.toSet()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The channel to post [calendarId]'s reminder on, created first if a sync
|
||||||
|
* has not got to it yet. Null when the calendar no longer exists. Should the
|
||||||
|
* calendar lookup fail or come back empty, the channel is still created,
|
||||||
|
* plainly named and ungrouped, for the next sync to name and file — a
|
||||||
|
* reminder is never lost to its channel. A ringing [style] posts on the
|
||||||
|
* shared ring channel instead, once the calendar is known to exist.
|
||||||
|
*/
|
||||||
|
@Synchronized
|
||||||
|
fun channelFor(calendarId: Long, style: ReminderAlertStyle = ReminderAlertStyle.Notification): String? {
|
||||||
|
val calendarChannel = calendarChannelFor(calendarId) ?: return null
|
||||||
|
return if (style == ReminderAlertStyle.FullScreenRing) ringChannel() else calendarChannel
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The channel a ringing full-screen alert (#171) posts on, shared by every
|
||||||
|
* calendar. Silent: the ring service owns the sound and vibration, so the
|
||||||
|
* channel adds neither. High importance keeps the heads-up a denied
|
||||||
|
* full-screen intent degrades to.
|
||||||
|
*/
|
||||||
|
private fun ringChannel(): String {
|
||||||
|
ensureRingChannel()
|
||||||
|
return RING_CHANNEL_ID
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates the ring channel, or renames it after a language change. Called
|
||||||
|
* as soon as a calendar is set to ring, so the channel can be checked in
|
||||||
|
* system settings (and switched on, where a skin starts it off) before the
|
||||||
|
* first ring.
|
||||||
|
*/
|
||||||
|
@Synchronized
|
||||||
|
fun ensureRingChannel() {
|
||||||
|
val manager = manager
|
||||||
|
val name = context.getString(R.string.reminder_ring_channel_name)
|
||||||
|
val description = context.getString(R.string.reminder_ring_channel_description)
|
||||||
|
val current = manager.getNotificationChannel(RING_CHANNEL_ID)
|
||||||
|
if (current != null && current.name?.toString() == name && current.description == description) return
|
||||||
|
manager.createNotificationChannel(
|
||||||
|
NotificationChannel(
|
||||||
|
RING_CHANNEL_ID,
|
||||||
|
name,
|
||||||
|
NotificationManager.IMPORTANCE_HIGH,
|
||||||
|
).apply {
|
||||||
|
this.description = description
|
||||||
|
setSound(null, null)
|
||||||
|
enableVibration(false)
|
||||||
|
lockscreenVisibility = Notification.VISIBILITY_PUBLIC
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether a ring may sound for [calendarId]: neither its own channel, its
|
||||||
|
* account's group nor the ring channel is blocked, since the service plays
|
||||||
|
* the sound itself.
|
||||||
|
*/
|
||||||
|
fun canRing(calendarId: Long): Boolean {
|
||||||
|
val status = status(listOf(calendarId))
|
||||||
|
return !status.appBlocked && calendarId !in status.blockedCalendarIds && !status.ringBlocked
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun calendarChannelFor(calendarId: Long): String? {
|
||||||
|
val manager = manager
|
||||||
|
knownVersions[calendarId]?.let { version ->
|
||||||
|
val known = reminderChannelId(calendarId, version)
|
||||||
|
if (manager.getNotificationChannel(known) != null) return known
|
||||||
|
}
|
||||||
|
val existing = manager.notificationChannels
|
||||||
|
val versions = currentVersions(existing.map { it.id }).also { knownVersions = it }
|
||||||
|
val id = reminderChannelId(calendarId, versions[calendarId] ?: 0)
|
||||||
|
if (existing.any { it.id == id }) return id
|
||||||
|
val calendars = try {
|
||||||
|
calendarDataSource.calendars()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "Could not look up calendar $calendarId for its channel", e)
|
||||||
|
emptyList()
|
||||||
|
}
|
||||||
|
val fallback = ReminderChannelSpec(id, calendarId, context.getString(R.string.reminder_channel_name), null)
|
||||||
|
if (calendars.isEmpty()) {
|
||||||
|
write(emptyList(), listOf(fallback), existing)
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
val plan = plan(calendars, existing, emptyList(), versions)
|
||||||
|
val spec = plan.channels.firstOrNull { it.calendarId == calendarId } ?: return null
|
||||||
|
try {
|
||||||
|
val knownGroups = manager.notificationChannelGroups.mapTo(HashSet()) { it.id }
|
||||||
|
write(
|
||||||
|
groups = plan.groups.filter { it.id == spec.groupId && it.id !in knownGroups },
|
||||||
|
channels = listOf(spec),
|
||||||
|
existing = existing,
|
||||||
|
)
|
||||||
|
} catch (e: RuntimeException) {
|
||||||
|
Log.w(TAG, "Could not file the channel of calendar $calendarId", e)
|
||||||
|
write(emptyList(), listOf(fallback), existing)
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run [block] with [calendarId]'s channel held: no sound pick or sync can
|
||||||
|
* move or retire it until [block] returns. Null, without running [block],
|
||||||
|
* when the calendar is gone or its channel can't be made; [block]'s own
|
||||||
|
* failures propagate.
|
||||||
|
*/
|
||||||
|
@Synchronized
|
||||||
|
fun <T> withChannel(calendarId: Long, block: (String) -> T): T? {
|
||||||
|
val channelId = try {
|
||||||
|
channelFor(calendarId)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "No channel for calendar $calendarId", e)
|
||||||
|
null
|
||||||
|
}
|
||||||
|
return channelId?.let(block)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What the system currently lets through for [calendarIds]' reminders (#145). */
|
||||||
|
fun status(calendarIds: Collection<Long>): ReminderChannelStatus {
|
||||||
|
val manager = manager
|
||||||
|
val appEnabled = manager.areNotificationsEnabled()
|
||||||
|
val existing = manager.notificationChannels
|
||||||
|
val channels = existing.associate {
|
||||||
|
it.id to ReminderChannelState(it.importance == NotificationManager.IMPORTANCE_NONE, it.group)
|
||||||
|
}
|
||||||
|
val blockedGroups = manager.notificationChannelGroups.filter { it.isBlocked }.mapTo(HashSet()) { it.id }
|
||||||
|
return reminderChannelStatus(calendarIds, appEnabled, channels, blockedGroups, currentVersions(channels.keys))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A "Silent" (low) channel keeps its sound but never plays it. */
|
||||||
|
private fun NotificationChannel.audibleSound(): Uri? =
|
||||||
|
sound.takeUnless { importance in IMPORTANCE_MIN..IMPORTANCE_LOW }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The sound each of [calendarIds]' channels plays; null is silent. A
|
||||||
|
* calendar whose channel doesn't exist yet is left out.
|
||||||
|
*/
|
||||||
|
fun sounds(calendarIds: Collection<Long>): Map<Long, Uri?> {
|
||||||
|
val byId = manager.notificationChannels.associateBy { it.id }
|
||||||
|
val versions = currentVersions(byId.keys)
|
||||||
|
return calendarIds.mapNotNull { id ->
|
||||||
|
byId[reminderChannelId(id, versions[id] ?: 0)]?.let { id to it.audibleSound() }
|
||||||
|
}.toMap()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Give [calendarIds]' reminders [sound] (null = silent). A channel's sound is
|
||||||
|
* fixed once created, so each moves to a new channel version carrying over
|
||||||
|
* everything else, and the old one retires in the sync that follows (#518). Calendars without a
|
||||||
|
* channel are skipped unless [createMissing]. Returns whether every move
|
||||||
|
* went through.
|
||||||
|
*/
|
||||||
|
suspend fun setSound(calendarIds: Collection<Long>, sound: Uri?, createMissing: Boolean): Boolean {
|
||||||
|
if (createMissing) calendarIds.forEach(::channelFor)
|
||||||
|
val existingIds = manager.notificationChannels.mapTo(HashSet()) { it.id }
|
||||||
|
val current = currentVersions(existingIds)
|
||||||
|
val floors = calendarIds
|
||||||
|
.filter { reminderChannelId(it, current[it] ?: 0) in existingIds }
|
||||||
|
.associateWith { (current[it] ?: 0) + 1 }
|
||||||
|
if (floors.isEmpty()) return false
|
||||||
|
val applied = recreate(settingsPrefs.reserveReminderChannelVersions(floors), sound)
|
||||||
|
// Retire the old versions now, or each calendar shows twice in system settings until the next scan.
|
||||||
|
try {
|
||||||
|
sync()
|
||||||
|
} catch (e: RuntimeException) {
|
||||||
|
Log.w(TAG, "Old channel versions left to the next sync", e)
|
||||||
|
}
|
||||||
|
return applied
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create each calendar's [versions] from its current channel. The old one is
|
||||||
|
* left to the next [sync], which retires it once nothing shows on it.
|
||||||
|
*/
|
||||||
|
@Synchronized
|
||||||
|
private fun recreate(versions: Map<Long, Int>, sound: Uri?): Boolean {
|
||||||
|
val manager = manager
|
||||||
|
val byId = manager.notificationChannels.associateBy { it.id }
|
||||||
|
val current = currentReminderChannelVersions(byId.keys, emptyMap())
|
||||||
|
var allApplied = true
|
||||||
|
versions.forEach { (calendarId, version) ->
|
||||||
|
val from = current[calendarId]?.takeIf { it < version }
|
||||||
|
val old = from?.let { byId[reminderChannelId(calendarId, it)] }
|
||||||
|
if (old == null) {
|
||||||
|
allApplied = false
|
||||||
|
return@forEach
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
// Picking a sound asks for one, which a "Silent" (low) channel would never play.
|
||||||
|
val importance = if (sound != null && old.importance in IMPORTANCE_MIN..IMPORTANCE_LOW) {
|
||||||
|
IMPORTANCE_DEFAULT
|
||||||
|
} else {
|
||||||
|
old.importance
|
||||||
|
}
|
||||||
|
manager.createNotificationChannel(
|
||||||
|
NotificationChannel(reminderChannelId(calendarId, version), old.name, importance).apply {
|
||||||
|
description = old.description
|
||||||
|
old.group?.let { group = it }
|
||||||
|
inheritFrom(old)
|
||||||
|
setSound(sound, old.audioAttributes ?: DEFAULT_AUDIO_ATTRIBUTES)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
knownVersions = knownVersions + (calendarId to version)
|
||||||
|
} catch (e: RuntimeException) {
|
||||||
|
Log.w(TAG, "Could not move calendar $calendarId to a new sound", e)
|
||||||
|
allApplied = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lastSync = null
|
||||||
|
return allApplied
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun plan(
|
||||||
|
calendars: List<CalendarSource>,
|
||||||
|
existing: List<NotificationChannel>,
|
||||||
|
existingGroupIds: List<String>,
|
||||||
|
versions: Map<Long, Int>,
|
||||||
|
showingChannelIds: Set<String> = emptySet(),
|
||||||
|
): ReminderChannelPlan = planReminderChannels(
|
||||||
|
calendars = calendars,
|
||||||
|
existing = existing.map { ExistingReminderChannel(it.id, it.name.toString(), it.description, it.group) },
|
||||||
|
existingGroupIds = existingGroupIds,
|
||||||
|
unnamed = context.getString(R.string.calendar_unnamed),
|
||||||
|
description = context.getString(R.string.reminder_channel_description),
|
||||||
|
versions = versions,
|
||||||
|
showingChannelIds = showingChannelIds,
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun write(
|
||||||
|
groups: List<ReminderChannelGroupSpec>,
|
||||||
|
channels: List<ReminderChannelSpec>,
|
||||||
|
existing: List<NotificationChannel>,
|
||||||
|
) {
|
||||||
|
val manager = manager
|
||||||
|
if (groups.isNotEmpty()) {
|
||||||
|
manager.createNotificationChannelGroups(groups.map { NotificationChannelGroup(it.id, groupLabel(it)) })
|
||||||
|
}
|
||||||
|
if (channels.isEmpty()) return
|
||||||
|
val byId = existing.associateBy { it.id }
|
||||||
|
val description = context.getString(R.string.reminder_channel_description)
|
||||||
|
val template = byId[LEGACY_REMINDER_CHANNEL_ID]
|
||||||
|
// Importance only applies on creation; an existing channel keeps its own.
|
||||||
|
manager.createNotificationChannels(
|
||||||
|
channels.map { spec ->
|
||||||
|
val current = byId[spec.id]
|
||||||
|
NotificationChannel(
|
||||||
|
spec.id,
|
||||||
|
spec.name,
|
||||||
|
current?.importance ?: template?.importance ?: NotificationManager.IMPORTANCE_HIGH,
|
||||||
|
).apply {
|
||||||
|
this.description = description
|
||||||
|
spec.groupId?.let { group = it }
|
||||||
|
if (current == null && template != null) inheritFrom(template)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Carry a channel's sound, vibration, lights and badge over to a new one: the
|
||||||
|
* legacy channel to a per-calendar one on upgrade, or a calendar's channel to
|
||||||
|
* its next version (#518). Lock-screen visibility and a DND override can't
|
||||||
|
* follow: the system resets both on channels an app creates.
|
||||||
|
*/
|
||||||
|
private fun NotificationChannel.inheritFrom(template: NotificationChannel) {
|
||||||
|
setSound(template.sound, template.audioAttributes)
|
||||||
|
// The pattern setter also flips vibration on or off, so it goes first.
|
||||||
|
vibrationPattern = template.vibrationPattern
|
||||||
|
enableVibration(template.shouldVibrate())
|
||||||
|
enableLights(template.shouldShowLights())
|
||||||
|
lightColor = template.lightColor
|
||||||
|
setShowBadge(template.canShowBadge())
|
||||||
|
// Only honoured with Do Not Disturb access, so usually left to the user.
|
||||||
|
setBypassDnd(template.canBypassDnd())
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete the pre-#145 channel once the per-calendar ones carry its settings,
|
||||||
|
* but not while a reminder posted on it is still on screen — deleting the
|
||||||
|
* channel would take that notification with it. Returns whether it is gone.
|
||||||
|
*/
|
||||||
|
private fun retireLegacyChannel(): Boolean {
|
||||||
|
val manager = manager
|
||||||
|
if (manager.getNotificationChannel(LEGACY_REMINDER_CHANNEL_ID) == null) return true
|
||||||
|
val showing = LEGACY_REMINDER_CHANNEL_ID in showingChannelIds(listOf(LEGACY_REMINDER_CHANNEL_ID))
|
||||||
|
if (!showing) manager.deleteNotificationChannel(LEGACY_REMINDER_CHANNEL_ID)
|
||||||
|
return !showing
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun groupLabel(group: ReminderChannelGroupSpec): String {
|
||||||
|
if (group.isLocal) return context.getString(R.string.calendars_local_header)
|
||||||
|
val name = group.label.ifBlank { context.getString(R.string.calendar_unnamed) }
|
||||||
|
if (!group.ambiguous) return name
|
||||||
|
return context.getString(R.string.calendars_account_from_source, name, sourceAppLabel(context, group.accountType))
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val TAG = "ReminderChannels"
|
||||||
|
|
||||||
|
val DEFAULT_AUDIO_ATTRIBUTES: AudioAttributes = Notification.AUDIO_ATTRIBUTES_DEFAULT
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
+99
@@ -0,0 +1,99 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.data.reminders
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.provider.CalendarContract
|
||||||
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
|
import de.jeanlucmakiola.calendula.data.calendar.instancesUri
|
||||||
|
import de.jeanlucmakiola.calendula.data.calendar.reminderMinutesByEvent
|
||||||
|
import de.jeanlucmakiola.calendula.domain.reminders.ReminderEventInstance
|
||||||
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The read side of in-house reminder delivery: occurrences and their reminder
|
||||||
|
* offsets, read from `Instances` and `Reminders` rather than `CalendarAlerts`,
|
||||||
|
* which cannot be assumed to be written (#75).
|
||||||
|
*
|
||||||
|
* An interface so [ReminderScanner] can be exercised on the JVM.
|
||||||
|
*/
|
||||||
|
interface ReminderInstanceSource {
|
||||||
|
|
||||||
|
/** Occurrences overlapping `[fromMillis, toMillis]`, of switched-on calendars. */
|
||||||
|
fun occurrences(fromMillis: Long, toMillis: Long): List<ReminderEventInstance>
|
||||||
|
|
||||||
|
/** `METHOD_ALERT` reminder offsets per event id, for the given events. */
|
||||||
|
fun reminderMinutes(eventIds: Collection<Long>): Map<Long, List<Int>>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The largest `METHOD_ALERT` offset anywhere in the table, so the query
|
||||||
|
* window can be stretched to cover it and a long-lead reminder is planned
|
||||||
|
* before it comes due rather than firing late.
|
||||||
|
*/
|
||||||
|
fun longestReminderMinutes(): Int
|
||||||
|
}
|
||||||
|
|
||||||
|
@Singleton
|
||||||
|
class ProviderReminderInstanceSource @Inject constructor(
|
||||||
|
@ApplicationContext private val context: Context,
|
||||||
|
) : ReminderInstanceSource {
|
||||||
|
|
||||||
|
override fun occurrences(fromMillis: Long, toMillis: Long): List<ReminderEventInstance> {
|
||||||
|
val uri = instancesUri(fromMillis, toMillis)
|
||||||
|
// `visible` is the flag the app's one visibility model writes (#75).
|
||||||
|
// The status clause mirrors CalendarDataSource.instances: NULL means
|
||||||
|
// "normal", so a bare `!= CANCELED` would drop every ordinary event.
|
||||||
|
// An invitation the user declined is answered — it stays on the calendar
|
||||||
|
// struck through, but it plans nothing (#180). NULL again means "no
|
||||||
|
// answer recorded", which is not a "no".
|
||||||
|
val selection = "${CalendarContract.Calendars.VISIBLE} = 1 AND " +
|
||||||
|
"(${CalendarContract.Instances.STATUS} IS NULL OR " +
|
||||||
|
"${CalendarContract.Instances.STATUS} != " +
|
||||||
|
"${CalendarContract.Events.STATUS_CANCELED}) AND " +
|
||||||
|
"(${CalendarContract.Instances.SELF_ATTENDEE_STATUS} IS NULL OR " +
|
||||||
|
"${CalendarContract.Instances.SELF_ATTENDEE_STATUS} != " +
|
||||||
|
"${CalendarContract.Attendees.ATTENDEE_STATUS_DECLINED})"
|
||||||
|
return context.contentResolver.query(
|
||||||
|
uri, OCCURRENCE_PROJECTION, selection, null, null,
|
||||||
|
)?.use { c ->
|
||||||
|
buildList {
|
||||||
|
while (c.moveToNext()) {
|
||||||
|
add(
|
||||||
|
ReminderEventInstance(
|
||||||
|
eventId = c.getLong(0),
|
||||||
|
calendarId = c.getLong(1),
|
||||||
|
beginMillis = c.getLong(2),
|
||||||
|
endMillis = if (c.isNull(3)) 0L else c.getLong(3),
|
||||||
|
title = c.getString(4).orEmpty(),
|
||||||
|
location = c.getString(5)?.takeIf { it.isNotBlank() },
|
||||||
|
isAllDay = c.getInt(6) == 1,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} ?: emptyList()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun reminderMinutes(eventIds: Collection<Long>): Map<Long, List<Int>> =
|
||||||
|
context.contentResolver.reminderMinutesByEvent(eventIds, alertsOnly = true)
|
||||||
|
|
||||||
|
override fun longestReminderMinutes(): Int = context.contentResolver.query(
|
||||||
|
CalendarContract.Reminders.CONTENT_URI,
|
||||||
|
arrayOf(CalendarContract.Reminders.MINUTES),
|
||||||
|
"${CalendarContract.Reminders.METHOD} = ${CalendarContract.Reminders.METHOD_ALERT}",
|
||||||
|
null,
|
||||||
|
// One row is enough: the provider passes the sort order to SQLite.
|
||||||
|
"${CalendarContract.Reminders.MINUTES} DESC",
|
||||||
|
)?.use { c -> if (c.moveToFirst()) c.getInt(0) else 0 } ?: 0
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
val OCCURRENCE_PROJECTION = arrayOf(
|
||||||
|
CalendarContract.Instances.EVENT_ID,
|
||||||
|
CalendarContract.Instances.CALENDAR_ID,
|
||||||
|
CalendarContract.Instances.BEGIN,
|
||||||
|
CalendarContract.Instances.END,
|
||||||
|
CalendarContract.Instances.TITLE,
|
||||||
|
CalendarContract.Instances.EVENT_LOCATION,
|
||||||
|
CalendarContract.Instances.ALL_DAY,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
+62
@@ -0,0 +1,62 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.data.reminders
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.util.Log
|
||||||
|
import androidx.work.CoroutineWorker
|
||||||
|
import androidx.work.ExistingPeriodicWorkPolicy
|
||||||
|
import androidx.work.PeriodicWorkRequestBuilder
|
||||||
|
import androidx.work.WorkManager
|
||||||
|
import androidx.work.WorkerParameters
|
||||||
|
import dagger.hilt.EntryPoint
|
||||||
|
import dagger.hilt.InstallIn
|
||||||
|
import dagger.hilt.android.EntryPointAccessors
|
||||||
|
import dagger.hilt.components.SingletonComponent
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The backstop under the alarm: a daily scan that runs whether or not the alarm
|
||||||
|
* survived. Finds nothing to do in the steady state; it exists for the device
|
||||||
|
* that quietly drops the alarm without a reboot to announce it (#75).
|
||||||
|
*/
|
||||||
|
object ReminderMaintenanceScheduler {
|
||||||
|
|
||||||
|
private const val WORK_NAME = "reminder-scan-maintenance"
|
||||||
|
|
||||||
|
/** Enqueue the daily backstop; idempotent, so every launch may call it. */
|
||||||
|
fun apply(context: Context) {
|
||||||
|
val request = PeriodicWorkRequestBuilder<ReminderMaintenanceWorker>(1, TimeUnit.DAYS)
|
||||||
|
// The launch scan covers now; let the first periodic run wait.
|
||||||
|
.setInitialDelay(1, TimeUnit.DAYS)
|
||||||
|
.build()
|
||||||
|
WorkManager.getInstance(context)
|
||||||
|
.enqueueUniquePeriodicWork(WORK_NAME, ExistingPeriodicWorkPolicy.UPDATE, request)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class ReminderMaintenanceWorker(
|
||||||
|
appContext: Context,
|
||||||
|
params: WorkerParameters,
|
||||||
|
) : CoroutineWorker(appContext, params) {
|
||||||
|
|
||||||
|
@EntryPoint
|
||||||
|
@InstallIn(SingletonComponent::class)
|
||||||
|
interface Deps {
|
||||||
|
fun reminderScanner(): ReminderScanner
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun doWork(): Result = try {
|
||||||
|
EntryPointAccessors.fromApplication(applicationContext, Deps::class.java)
|
||||||
|
.reminderScanner()
|
||||||
|
.scan()
|
||||||
|
Result.success()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
// The scan swallows its own failures, so anything reaching here is the
|
||||||
|
// entry point itself — a retry will not mend it.
|
||||||
|
Log.w(TAG, "Reminder maintenance scan failed", e)
|
||||||
|
Result.success()
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val TAG = "ReminderMaintenance"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,80 +1,208 @@
|
|||||||
package de.jeanlucmakiola.calendula.data.reminders
|
package de.jeanlucmakiola.calendula.data.reminders
|
||||||
|
|
||||||
import android.Manifest
|
import android.Manifest
|
||||||
import android.app.NotificationChannel
|
import android.app.Notification
|
||||||
import android.app.NotificationManager
|
|
||||||
import android.app.PendingIntent
|
import android.app.PendingIntent
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.pm.PackageManager
|
import android.content.Intent
|
||||||
|
import androidx.core.net.toUri
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
|
import android.os.Bundle
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import androidx.core.app.NotificationCompat
|
import androidx.core.app.NotificationCompat
|
||||||
import androidx.core.app.NotificationManagerCompat
|
import androidx.core.app.NotificationManagerCompat
|
||||||
import androidx.core.content.ContextCompat
|
|
||||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
import de.jeanlucmakiola.calendula.MainActivity
|
import de.jeanlucmakiola.calendula.MainActivity
|
||||||
import de.jeanlucmakiola.calendula.R
|
import de.jeanlucmakiola.calendula.R
|
||||||
|
import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource
|
||||||
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
|
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
|
||||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||||
import de.jeanlucmakiola.calendula.data.prefs.is24Hour
|
import de.jeanlucmakiola.calendula.data.prefs.is24Hour
|
||||||
|
import de.jeanlucmakiola.calendula.data.prefs.resolveFirstDay
|
||||||
|
import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle
|
||||||
|
import de.jeanlucmakiola.calendula.domain.reminders.alertStyleFor
|
||||||
|
import de.jeanlucmakiola.calendula.ui.reminders.ReminderAlertActivity
|
||||||
|
import de.jeanlucmakiola.floret.android.hasPermission
|
||||||
|
import de.jeanlucmakiola.floret.ring.canUseFullScreenIntent
|
||||||
|
import de.jeanlucmakiola.calendula.domain.reminders.reminderLink
|
||||||
|
import de.jeanlucmakiola.calendula.domain.reminders.reminderMapQuery
|
||||||
|
import de.jeanlucmakiola.floret.android.resolvableMapsSearchIntent
|
||||||
import kotlinx.coroutines.flow.first
|
import kotlinx.coroutines.flow.first
|
||||||
|
import kotlinx.datetime.isoDayNumber
|
||||||
|
import java.time.DayOfWeek
|
||||||
|
import java.time.Instant
|
||||||
import java.time.ZoneId
|
import java.time.ZoneId
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Posts one notification per due reminder alert on a dedicated channel.
|
* Posts one notification per occurrence on its calendar's channel
|
||||||
* Tapping opens the event's detail screen; the tag is the alert id, so a
|
* ([ReminderChannels], #145), or as a full-screen alert where the calendar
|
||||||
* re-broadcast of an alert we couldn't mark fired replaces its notification
|
* asks for one (#171). Tapping opens the event's detail screen.
|
||||||
* silently ([NotificationCompat.Builder.setOnlyAlertOnce]) instead of
|
*
|
||||||
* duplicating it.
|
* The tag is the [occurrenceKey], so each reminder for an occurrence replaces
|
||||||
|
* the one before it in place (#463). A different reminder alerts afresh; the
|
||||||
|
* same one posted again — a catch-up pass overlapping the alarm that already
|
||||||
|
* fired — replaces its notification silently.
|
||||||
*/
|
*/
|
||||||
@Singleton
|
@Singleton
|
||||||
class ReminderNotifier @Inject constructor(
|
class ReminderNotifier @Inject constructor(
|
||||||
@ApplicationContext private val context: Context,
|
@ApplicationContext private val context: Context,
|
||||||
private val settingsPrefs: SettingsPrefs,
|
private val settingsPrefs: SettingsPrefs,
|
||||||
private val calendarPrefs: CalendarPrefs,
|
private val calendarPrefs: CalendarPrefs,
|
||||||
|
private val calendarDataSource: CalendarDataSource,
|
||||||
|
private val channels: ReminderChannels,
|
||||||
|
private val alerts: FullScreenAlerts,
|
||||||
) {
|
) {
|
||||||
|
|
||||||
/** False when the user declined `POST_NOTIFICATIONS` or muted the app. */
|
/** False when the user declined `POST_NOTIFICATIONS` or muted the app. */
|
||||||
fun canPost(): Boolean {
|
fun canPost(): Boolean {
|
||||||
val granted = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
|
val granted = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
|
||||||
ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) ==
|
context.hasPermission(Manifest.permission.POST_NOTIFICATIONS)
|
||||||
PackageManager.PERMISSION_GRANTED
|
|
||||||
return granted && NotificationManagerCompat.from(context).areNotificationsEnabled()
|
return granted && NotificationManagerCompat.from(context).areNotificationsEnabled()
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun post(alert: ReminderAlert) {
|
/**
|
||||||
// The single choke point for the disabled-calendar gate: it covers both
|
* The single choke point for "this calendar posts no reminders": switched
|
||||||
// the provider broadcast (EventReminderReceiver) and a snoozed re-show
|
* off (also covering a snooze armed before the switch-off, and a read-only
|
||||||
// (ReminderActionReceiver), so a calendar disabled after a snooze no
|
* install whose switch lives in [CalendarPrefs]), or its notifications
|
||||||
// longer notifies — without either receiver duplicating the check.
|
* turned off in Calendula's own settings (#272).
|
||||||
if (alert.isForDisabledCalendar(calendarPrefs.disabledCalendarIds.first())) return
|
*/
|
||||||
ensureChannel()
|
private suspend fun isSilenced(calendarId: Long): Boolean =
|
||||||
val title = alert.title.ifBlank { context.getString(R.string.event_untitled) }
|
calendarId in settingsPrefs.mutedReminderCalendarIds.first() ||
|
||||||
|
calendarId in calendarPrefs.pendingDisabledCalendarIds.first() ||
|
||||||
|
calendarDataSource.isCalendarVisible(calendarId) == false
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Post [alert] in its calendar's alert style (#171), unless the calendar is
|
||||||
|
* silenced or gone. [ring] false posts a ringing style as a full-screen
|
||||||
|
* alert that sounds once instead; [quiet] posts a plain notification that
|
||||||
|
* makes no sound. Both are how a ring hands a reminder back to the shade.
|
||||||
|
*/
|
||||||
|
suspend fun post(alert: ReminderAlert, quiet: Boolean = false, ring: Boolean = true) {
|
||||||
|
if (isSilenced(alert.calendarId)) return
|
||||||
|
var style = when {
|
||||||
|
quiet -> ReminderAlertStyle.Notification
|
||||||
|
else -> effectiveStyle(alert).let {
|
||||||
|
if (it == ReminderAlertStyle.FullScreenRing && !ring) ReminderAlertStyle.FullScreen else it
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Rung already and handed back to the shade: a catch-up post leaves it there.
|
||||||
|
if (style == ReminderAlertStyle.FullScreenRing && (isShowing(alert) || alerts.isPending(alert))) return
|
||||||
|
val title = displayTitle(alert)
|
||||||
|
val text = contentText(alert)
|
||||||
|
if (style == ReminderAlertStyle.FullScreenRing) {
|
||||||
|
val ringChannel = channelFor(alert, style)
|
||||||
|
if (ringChannel != null &&
|
||||||
|
ReminderRingService.start(context, alerts, alert, build(alert, ringChannel, title, text, style, quiet = false))
|
||||||
|
) {
|
||||||
|
// An earlier reminder for this occurrence gives way to the ring.
|
||||||
|
NotificationManagerCompat.from(context).cancel(alert.occurrenceKey.toString(), NOTIFICATION_ID)
|
||||||
|
cancelLegacy(alert)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// No ring channel, or Android refused the ring: still full-screen, sounding once on the calendar's channel.
|
||||||
|
if (ringChannel != null) stopRing(RingMatch.Occurrence(alert.occurrenceKey))
|
||||||
|
style = ReminderAlertStyle.FullScreen
|
||||||
|
} else if (ring) {
|
||||||
|
// A fresh reminder replaces a ring for its occurrence from before the style changed.
|
||||||
|
stopRing(RingMatch.Occurrence(alert.occurrenceKey))
|
||||||
|
}
|
||||||
|
// Under the channel lock, so a sound picked meanwhile (#518) can't move it mid-post.
|
||||||
|
val posted = channels.withChannel(alert.calendarId) { channelId ->
|
||||||
|
notify(alert, build(alert, channelId, title, text, style, quiet))
|
||||||
|
}
|
||||||
|
if (posted == null) {
|
||||||
|
Log.i(TAG, "Dropped the reminder of event ${alert.eventId}: no channel for calendar ${alert.calendarId}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether a ring for [alert] should go on, now that settings may have changed since it started. */
|
||||||
|
suspend fun ringVerdict(alert: ReminderAlert): RingVerdict = when {
|
||||||
|
!settingsPrefs.remindersEnabled.first() || !canPost() || isSilenced(alert.calendarId) ||
|
||||||
|
calendarDataSource.isCalendarVisible(alert.calendarId) == null -> RingVerdict.Drop
|
||||||
|
effectiveStyle(alert) != ReminderAlertStyle.FullScreenRing -> RingVerdict.HandBack
|
||||||
|
else -> RingVerdict.Ring
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether a live ring for [alert] may go on: its notification can still be seen, and its calendar still notifies. */
|
||||||
|
suspend fun canStillRing(alert: ReminderAlert): Boolean =
|
||||||
|
canPost() && channels.canRing(alert.calendarId) && !isSilenced(alert.calendarId)
|
||||||
|
|
||||||
|
/** The calendar's style, short of ringing where the user blocked its calendar, group or the ring channel. */
|
||||||
|
private suspend fun effectiveStyle(alert: ReminderAlert): ReminderAlertStyle {
|
||||||
|
val chosen = settingsPrefs.reminderAlertStyles.first().alertStyleFor(alert.calendarId)
|
||||||
|
return if (chosen == ReminderAlertStyle.FullScreenRing && !channels.canRing(alert.calendarId)) {
|
||||||
|
ReminderAlertStyle.FullScreen
|
||||||
|
} else {
|
||||||
|
chosen
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun channelFor(alert: ReminderAlert, style: ReminderAlertStyle): String? = try {
|
||||||
|
channels.channelFor(alert.calendarId, style).also {
|
||||||
|
if (it == null) Log.i(TAG, "Dropped the reminder of event ${alert.eventId}: calendar ${alert.calendarId} is gone")
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "No channel for the reminder of event ${alert.eventId}", e)
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun contentText(alert: ReminderAlert): String =
|
||||||
|
listOfNotNull(timeText(alert), alert.location).joinToString(" · ")
|
||||||
|
|
||||||
|
/** When [alert]'s occurrence happens, as its notification words it. */
|
||||||
|
suspend fun timeText(alert: ReminderAlert): String {
|
||||||
val is24Hour = settingsPrefs.timeFormat.first()
|
val is24Hour = settingsPrefs.timeFormat.first()
|
||||||
.is24Hour(android.text.format.DateFormat.is24HourFormat(context))
|
.is24Hour(android.text.format.DateFormat.is24HourFormat(context))
|
||||||
val time = reminderTimeText(
|
val zone = ZoneId.systemDefault()
|
||||||
|
val locale = Locale.getDefault()
|
||||||
|
// resolveFirstDay yields a kotlinx.datetime day; bridge it to java.time by
|
||||||
|
// its shared ISO number (1..7) for the date math in reminderTimeText.
|
||||||
|
val firstDayOfWeek = DayOfWeek.of(settingsPrefs.weekStart.first().resolveFirstDay(locale).isoDayNumber)
|
||||||
|
return reminderTimeText(
|
||||||
beginMillis = alert.beginMillis,
|
beginMillis = alert.beginMillis,
|
||||||
endMillis = alert.endMillis,
|
endMillis = alert.endMillis,
|
||||||
isAllDay = alert.isAllDay,
|
isAllDay = alert.isAllDay,
|
||||||
zone = ZoneId.systemDefault(),
|
zone = zone,
|
||||||
locale = Locale.getDefault(),
|
locale = locale,
|
||||||
is24Hour = is24Hour,
|
is24Hour = is24Hour,
|
||||||
|
today = Instant.now().atZone(zone).toLocalDate(),
|
||||||
|
firstDayOfWeek = firstDayOfWeek,
|
||||||
|
todayLabel = context.getString(R.string.reminder_day_today),
|
||||||
|
tomorrowLabel = context.getString(R.string.reminder_day_tomorrow),
|
||||||
|
yesterdayLabel = context.getString(R.string.reminder_day_yesterday),
|
||||||
)
|
)
|
||||||
val text = listOfNotNull(time, alert.location).joinToString(" · ")
|
}
|
||||||
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
|
|
||||||
|
/**
|
||||||
|
* The reminder's notification in [style]. A ringing one belongs to
|
||||||
|
* [ReminderRingService]: ongoing and opening the alert screen. A full-screen
|
||||||
|
* one adds the alert screen as a full-screen intent where Android allows
|
||||||
|
* it, degrading to a heads-up where it does not, and is dismissed by a
|
||||||
|
* swipe, so its screen closes too.
|
||||||
|
*/
|
||||||
|
private fun build(
|
||||||
|
alert: ReminderAlert,
|
||||||
|
channelId: String,
|
||||||
|
title: String,
|
||||||
|
text: String,
|
||||||
|
style: ReminderAlertStyle,
|
||||||
|
quiet: Boolean,
|
||||||
|
): Notification {
|
||||||
|
val ringing = style == ReminderAlertStyle.FullScreenRing
|
||||||
|
val fullScreen = style.isFullScreen
|
||||||
|
val builder = NotificationCompat.Builder(context, channelId)
|
||||||
.setSmallIcon(R.drawable.ic_notification)
|
.setSmallIcon(R.drawable.ic_notification)
|
||||||
.setContentTitle(title)
|
.setContentTitle(title)
|
||||||
.setContentText(text)
|
.setContentText(text)
|
||||||
.setWhen(alert.beginMillis)
|
.setWhen(alert.beginMillis)
|
||||||
.setShowWhen(false)
|
.setShowWhen(false)
|
||||||
.setCategory(NotificationCompat.CATEGORY_EVENT)
|
.setCategory(if (ringing) NotificationCompat.CATEGORY_ALARM else NotificationCompat.CATEGORY_EVENT)
|
||||||
.setPriority(NotificationCompat.PRIORITY_HIGH)
|
.setPriority(if (ringing) NotificationCompat.PRIORITY_MAX else NotificationCompat.PRIORITY_HIGH)
|
||||||
.setAutoCancel(true)
|
.addExtras(Bundle().apply { putLong(EXTRA_REMINDER_KEY, alert.key) })
|
||||||
.setOnlyAlertOnce(true)
|
.setContentIntent(if (ringing) alertScreenIntent(alert) else detailIntent(alert))
|
||||||
.setContentIntent(detailIntent(alert))
|
|
||||||
.addAction(
|
.addAction(
|
||||||
R.drawable.ic_notification_snooze,
|
R.drawable.ic_notification_snooze,
|
||||||
context.getString(R.string.reminder_action_snooze),
|
context.getString(R.string.reminder_action_snooze),
|
||||||
@@ -85,21 +213,94 @@ class ReminderNotifier @Inject constructor(
|
|||||||
context.getString(R.string.reminder_action_dismiss),
|
context.getString(R.string.reminder_action_dismiss),
|
||||||
actionIntent(alert, ReminderActionReceiver.ACTION_DISMISS),
|
actionIntent(alert, ReminderActionReceiver.ACTION_DISMISS),
|
||||||
)
|
)
|
||||||
.build()
|
// Room for one more button: a meeting link beats the place, being the likelier next step.
|
||||||
|
// A ring leaves it to the alert screen, so opening something can't leave it sounding.
|
||||||
|
if (!ringing) {
|
||||||
|
linkIntent(alert)?.let {
|
||||||
|
builder.addAction(R.drawable.ic_notification_link, context.getString(R.string.reminder_action_open_link), it)
|
||||||
|
} ?: mapIntent(alert)?.let {
|
||||||
|
builder.addAction(R.drawable.ic_notification_map, context.getString(R.string.event_detail_open_in_maps), it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (fullScreen) builder.setDeleteIntent(actionIntent(alert, ReminderActionReceiver.ACTION_DISMISS))
|
||||||
|
if (ringing) {
|
||||||
|
builder.setOngoing(true).setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
|
||||||
|
} else {
|
||||||
|
builder.setAutoCancel(true).setOnlyAlertOnce(shownKey(alert) == alert.key)
|
||||||
|
}
|
||||||
|
if (quiet) builder.setSilent(true)
|
||||||
|
if (fullScreen && context.canUseFullScreenIntent()) builder.setFullScreenIntent(alertScreenIntent(alert), true)
|
||||||
|
return builder.build()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun notify(alert: ReminderAlert, notification: Notification) {
|
||||||
|
val manager = NotificationManagerCompat.from(context)
|
||||||
|
cancelLegacy(alert)
|
||||||
try {
|
try {
|
||||||
NotificationManagerCompat.from(context)
|
manager.notify(alert.occurrenceKey.toString(), NOTIFICATION_ID, notification)
|
||||||
.notify(alert.alertId.toString(), NOTIFICATION_ID, notification)
|
|
||||||
} catch (e: SecurityException) {
|
} catch (e: SecurityException) {
|
||||||
// POST_NOTIFICATIONS was revoked between canPost() and here.
|
// POST_NOTIFICATIONS was revoked between canPost() and here.
|
||||||
Log.w(TAG, "Could not post reminder for event ${alert.eventId}", e)
|
Log.w(TAG, "Could not post reminder for event ${alert.eventId}", e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Remove a posted reminder (snooze re-shows it later; dismiss is final). */
|
/**
|
||||||
|
* Remove [alert]'s notification (snooze re-shows it later; dismiss is final),
|
||||||
|
* unless a later reminder has replaced it — an action tapped on a stale view
|
||||||
|
* mustn't take the newer one with it.
|
||||||
|
*/
|
||||||
fun cancel(alert: ReminderAlert) {
|
fun cancel(alert: ReminderAlert) {
|
||||||
NotificationManagerCompat.from(context).cancel(alert.alertId.toString(), NOTIFICATION_ID)
|
val manager = NotificationManagerCompat.from(context)
|
||||||
|
if (shownKey(alert) == alert.key) manager.cancel(alert.occurrenceKey.toString(), NOTIFICATION_ID)
|
||||||
|
// Posted before reminders shared a notification, under the reminder's own key.
|
||||||
|
manager.cancel(alert.key.toString(), NOTIFICATION_ID)
|
||||||
|
stopRing(RingMatch.Key(alert.key))
|
||||||
|
alerts.markHandled(alert)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Stop the ring if it is for a reminder [match]es; [handBack] keeps it in the shade, quietly. */
|
||||||
|
fun stopRing(match: RingMatch, handBack: Boolean = false) {
|
||||||
|
if (alerts.mayRing(match)) ReminderRingService.stop(context, alerts, match, handBack)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether a different reminder for [alert]'s occurrence is on screen now. */
|
||||||
|
fun isSuperseded(alert: ReminderAlert): Boolean {
|
||||||
|
val ringing = alerts.ringing?.takeIf { it.occurrenceKey == alert.occurrenceKey }
|
||||||
|
if (ringing != null) return ringing.key != alert.key
|
||||||
|
return shownKey(alert).let { it != null && it != alert.key }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether [alert] itself is still on screen, as a notification or ringing. */
|
||||||
|
fun isShowing(alert: ReminderAlert): Boolean =
|
||||||
|
alerts.ringing?.key == alert.key || shownKey(alert) == alert.key
|
||||||
|
|
||||||
|
/** The key of the reminder showing for [alert]'s occurrence, if any. */
|
||||||
|
private fun shownKey(alert: ReminderAlert): Long? {
|
||||||
|
val tag = alert.occurrenceKey.toString()
|
||||||
|
return NotificationManagerCompat.from(context).activeNotifications
|
||||||
|
.firstOrNull { it.tag == tag && it.id == NOTIFICATION_ID }
|
||||||
|
?.notification?.extras
|
||||||
|
?.takeIf { it.containsKey(EXTRA_REMINDER_KEY) }
|
||||||
|
?.getLong(EXTRA_REMINDER_KEY)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove a reminder for the same occurrence posted before reminders shared a
|
||||||
|
* notification. It carries no reminder key; its time and title identify it.
|
||||||
|
*/
|
||||||
|
private fun cancelLegacy(alert: ReminderAlert) {
|
||||||
|
val manager = NotificationManagerCompat.from(context)
|
||||||
|
manager.activeNotifications
|
||||||
|
.filter { it.id == NOTIFICATION_ID && it.notification.channelId == LEGACY_REMINDER_CHANNEL_ID }
|
||||||
|
.filter { !it.notification.extras.containsKey(EXTRA_REMINDER_KEY) }
|
||||||
|
.filter { it.notification.`when` == alert.beginMillis }
|
||||||
|
.filter { it.notification.extras.getCharSequence(NotificationCompat.EXTRA_TITLE)?.toString() == displayTitle(alert) }
|
||||||
|
.forEach { manager.cancel(it.tag, it.id) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun displayTitle(alert: ReminderAlert): String =
|
||||||
|
alert.title.ifBlank { context.getString(R.string.event_untitled) }
|
||||||
|
|
||||||
private fun actionIntent(alert: ReminderAlert, action: String): PendingIntent =
|
private fun actionIntent(alert: ReminderAlert, action: String): PendingIntent =
|
||||||
PendingIntent.getBroadcast(
|
PendingIntent.getBroadcast(
|
||||||
context,
|
context,
|
||||||
@@ -108,31 +309,66 @@ class ReminderNotifier @Inject constructor(
|
|||||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
private fun alertScreenIntent(alert: ReminderAlert): PendingIntent = PendingIntent.getActivity(
|
||||||
|
context,
|
||||||
|
ReminderActionReceiver.requestCode(alert, ReminderActionReceiver.ACTION_ALERT_SCREEN),
|
||||||
|
ReminderAlertActivity.intent(context, alert),
|
||||||
|
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||||
|
)
|
||||||
|
|
||||||
private fun detailIntent(alert: ReminderAlert): PendingIntent = PendingIntent.getActivity(
|
private fun detailIntent(alert: ReminderAlert): PendingIntent = PendingIntent.getActivity(
|
||||||
context,
|
context,
|
||||||
/* requestCode = */ alert.alertId.toInt(),
|
// Shares the per-(alert, action) request-code scheme with the buttons.
|
||||||
|
/* requestCode = */ ReminderActionReceiver.requestCode(
|
||||||
|
alert, ReminderActionReceiver.ACTION_OPEN,
|
||||||
|
),
|
||||||
MainActivity.eventDetailIntent(context, alert.eventId, alert.beginMillis, alert.endMillis),
|
MainActivity.eventDetailIntent(context, alert.eventId, alert.beginMillis, alert.endMillis),
|
||||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||||
)
|
)
|
||||||
|
|
||||||
/** Channel creation is idempotent; re-running refreshes the localized name. */
|
/**
|
||||||
private fun ensureChannel() {
|
* Opens the first web link in [alert]'s location, e.g. a meeting, started
|
||||||
val channel = NotificationChannel(
|
* directly like [mapIntent]. Null without a link or an app to open it.
|
||||||
CHANNEL_ID,
|
*/
|
||||||
context.getString(R.string.reminder_channel_name),
|
private fun linkIntent(alert: ReminderAlert): PendingIntent? {
|
||||||
NotificationManager.IMPORTANCE_HIGH,
|
val link = reminderLink(alert.location) ?: return null
|
||||||
).apply {
|
val intent = Intent(Intent.ACTION_VIEW, link.toUri())
|
||||||
description = context.getString(R.string.reminder_channel_description)
|
.addCategory(Intent.CATEGORY_BROWSABLE)
|
||||||
|
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||||
|
if (intent.resolveActivity(context.packageManager) == null) return null
|
||||||
|
return PendingIntent.getActivity(
|
||||||
|
context,
|
||||||
|
/* requestCode = */ 0,
|
||||||
|
intent,
|
||||||
|
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
NotificationManagerCompat.from(context).createNotificationChannel(channel)
|
|
||||||
|
/**
|
||||||
|
* Opens [alert]'s location in maps like the detail screen does, started
|
||||||
|
* directly (no receiver trampoline). Leaves the notification up for a later
|
||||||
|
* snooze or dismiss. Null without a place to look up (a bare meeting link
|
||||||
|
* isn't one) or an app to open it.
|
||||||
|
*/
|
||||||
|
private fun mapIntent(alert: ReminderAlert): PendingIntent? {
|
||||||
|
val query = reminderMapQuery(alert.location) ?: return null
|
||||||
|
val intent = context.resolvableMapsSearchIntent(query) ?: return null
|
||||||
|
return PendingIntent.getActivity(
|
||||||
|
context,
|
||||||
|
// An implicit activity intent: filterEquals already keeps it apart from the others.
|
||||||
|
/* requestCode = */ 0,
|
||||||
|
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||||
|
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private companion object {
|
private companion object {
|
||||||
const val TAG = "ReminderNotifier"
|
const val TAG = "ReminderNotifier"
|
||||||
const val CHANNEL_ID = "reminders"
|
|
||||||
|
|
||||||
// One id, distinct tags: the tag (alert id) already keys the
|
// One id, distinct tags: the tag (occurrence) already keys the
|
||||||
// notification, so a fixed id keeps cancellation/replacement simple.
|
// notification, so a fixed id keeps cancellation/replacement simple.
|
||||||
const val NOTIFICATION_ID = 1
|
const val NOTIFICATION_ID = 1
|
||||||
|
|
||||||
|
const val EXTRA_REMINDER_KEY = "de.jeanlucmakiola.calendula.reminder_key"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,354 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.data.reminders
|
||||||
|
|
||||||
|
import android.app.Notification
|
||||||
|
import android.app.Service
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.media.RingtoneManager
|
||||||
|
import android.os.IBinder
|
||||||
|
import android.util.Log
|
||||||
|
import androidx.core.app.NotificationManagerCompat
|
||||||
|
import androidx.core.content.IntentCompat
|
||||||
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
|
import de.jeanlucmakiola.calendula.data.di.ApplicationScope
|
||||||
|
import de.jeanlucmakiola.calendula.data.reminders.ReminderActionReceiver.Companion.putAlert
|
||||||
|
import de.jeanlucmakiola.floret.ring.RingVibrator
|
||||||
|
import de.jeanlucmakiola.floret.ring.RingWakeLock
|
||||||
|
import de.jeanlucmakiola.floret.ring.TonePlayer
|
||||||
|
import de.jeanlucmakiola.floret.ring.isInCall
|
||||||
|
import de.jeanlucmakiola.floret.ring.startRingForeground
|
||||||
|
import kotlinx.coroutines.CancellationException
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
|
import kotlinx.coroutines.SupervisorJob
|
||||||
|
import kotlinx.coroutines.cancel
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import javax.inject.Inject
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rings a reminder whose calendar asks for "Ring until dismissed" (#171): the
|
||||||
|
* alarm sound looped with vibration, for as long as the reminder is neither
|
||||||
|
* dismissed nor snoozed, up to [RING_TIMEOUT_MILLIS]. Then it goes quiet and
|
||||||
|
* hands the reminder back to the shade as an ordinary notification.
|
||||||
|
*
|
||||||
|
* One reminder rings at a time. A new one takes over, and the one it replaces
|
||||||
|
* goes back to the shade, silently, unless it was for the same occurrence.
|
||||||
|
* Starts and stops both arrive as commands, so they are handled on the main
|
||||||
|
* thread in the order they were sent.
|
||||||
|
*/
|
||||||
|
@AndroidEntryPoint
|
||||||
|
class ReminderRingService : Service() {
|
||||||
|
|
||||||
|
@Inject lateinit var alerts: FullScreenAlerts
|
||||||
|
@Inject lateinit var notifier: ReminderNotifier
|
||||||
|
|
||||||
|
@Inject @ApplicationScope
|
||||||
|
lateinit var appScope: CoroutineScope
|
||||||
|
|
||||||
|
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||||
|
|
||||||
|
private val tones by lazy { TonePlayer(this) }
|
||||||
|
private val vibrator by lazy { RingVibrator(this) }
|
||||||
|
private val wakeLock by lazy { RingWakeLock(this, WAKE_LOCK_TAG, RING_TIMEOUT_MILLIS) }
|
||||||
|
|
||||||
|
private var ringing: Job? = null
|
||||||
|
private var timeout: Job? = null
|
||||||
|
private var notificationId = RING_NOTIFICATION_ID
|
||||||
|
private var lastStartId: Int? = null
|
||||||
|
|
||||||
|
/** The start the system would redeliver, so a takeover can mark it done. */
|
||||||
|
private var ringStartId: Int? = null
|
||||||
|
|
||||||
|
/** Whether the ring's players were ever built, so a stop-only service builds none. */
|
||||||
|
private var rang = false
|
||||||
|
|
||||||
|
override fun onBind(intent: Intent?): IBinder? = null
|
||||||
|
|
||||||
|
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||||
|
lastStartId = startId
|
||||||
|
if (intent?.action == ACTION_STOP) {
|
||||||
|
stop(intent)
|
||||||
|
return START_NOT_STICKY
|
||||||
|
}
|
||||||
|
val alert = intent?.let(ReminderActionReceiver::alertFrom)
|
||||||
|
if (intent == null || alert == null) {
|
||||||
|
stopIfIdle()
|
||||||
|
return START_NOT_STICKY
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return startRing(intent, alert, startId)
|
||||||
|
} finally {
|
||||||
|
// Only now, once alerts.ringing says whether it rings, so a stop sent meanwhile is never skipped.
|
||||||
|
if (flags and START_FLAG_REDELIVERY == 0) alerts.removePending(alert)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startRing(intent: Intent, alert: ReminderAlert, startId: Int): Int {
|
||||||
|
val notification = IntentCompat.getParcelableExtra(intent, EXTRA_NOTIFICATION, Notification::class.java)
|
||||||
|
if (notification == null) {
|
||||||
|
stopIfIdle()
|
||||||
|
return START_NOT_STICKY
|
||||||
|
}
|
||||||
|
val previous = alerts.ringing
|
||||||
|
// A different reminder posts under the other id, so it is a new
|
||||||
|
// notification whose full-screen intent opens; an update would not.
|
||||||
|
val replacing = previous != null && previous.key != alert.key
|
||||||
|
val shown = notificationId
|
||||||
|
if (replacing) notificationId = if (shown == RING_NOTIFICATION_ID) OTHER_RING_NOTIFICATION_ID else RING_NOTIFICATION_ID
|
||||||
|
val foreground = runCatching { startRingForeground(notificationId, notification) }
|
||||||
|
if (foreground.isFailure) {
|
||||||
|
// A restart after a process death may be refused a foreground start:
|
||||||
|
// the reminder still shows full-screen, sounding once.
|
||||||
|
Log.w(TAG, "Could not ring for event ${alert.eventId}", foreground.exceptionOrNull())
|
||||||
|
notificationId = shown
|
||||||
|
handBack(alert, quiet = false)
|
||||||
|
stopIfIdle()
|
||||||
|
return START_NOT_STICKY
|
||||||
|
}
|
||||||
|
if (replacing) NotificationManagerCompat.from(this).cancel(shown)
|
||||||
|
// A duplicate start for this very ring leaves the original in charge of redelivery.
|
||||||
|
if (previous?.key == alert.key) return START_NOT_STICKY
|
||||||
|
// Only the newest start is redelivered after a process death; the older
|
||||||
|
// ones are done, so a handled reminder never rings again.
|
||||||
|
ringStartId?.let { stopSelfResult(it) }
|
||||||
|
ringStartId = startId
|
||||||
|
alerts.ringing = alert
|
||||||
|
if (previous != null) {
|
||||||
|
// Its screen closes either way; another occurrence goes back to the shade.
|
||||||
|
if (previous.occurrenceKey != alert.occurrenceKey) handBack(previous) else alerts.markHandled(previous)
|
||||||
|
}
|
||||||
|
val since = intent.getLongExtra(EXTRA_SINCE, System.currentTimeMillis())
|
||||||
|
ring(alert, remaining = since + RING_TIMEOUT_MILLIS - System.currentTimeMillis())
|
||||||
|
return START_REDELIVER_INTENT
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
if (rang) releaseRing()
|
||||||
|
// Stopped from outside: its screen must not stay up for a ring that is gone.
|
||||||
|
alerts.ringing?.let { if (alerts.handBackOnDestroy) handBack(it) else alerts.markHandled(it) }
|
||||||
|
alerts.handBackOnDestroy = false
|
||||||
|
alerts.ringing = null
|
||||||
|
scope.cancel()
|
||||||
|
super.onDestroy()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Rings for what is left of the ring's time, so a ring restarted after a process death does not begin again. */
|
||||||
|
private fun ring(alert: ReminderAlert, remaining: Long) {
|
||||||
|
releaseRing()
|
||||||
|
rang = true
|
||||||
|
wakeLock.acquire()
|
||||||
|
timeout = scope.launch {
|
||||||
|
delay(remaining.coerceAtLeast(0L))
|
||||||
|
giveUp()
|
||||||
|
}
|
||||||
|
ringing = scope.launch {
|
||||||
|
// Settings changed while this ring was on its way apply before it makes a sound.
|
||||||
|
val verdict = try {
|
||||||
|
withContext(Dispatchers.IO) { notifier.ringVerdict(alert) }
|
||||||
|
} catch (e: CancellationException) {
|
||||||
|
throw e
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "Could not re-check the ring for event ${alert.eventId}", e)
|
||||||
|
RingVerdict.Ring
|
||||||
|
}
|
||||||
|
if (verdict != RingVerdict.Ring) {
|
||||||
|
// Never heard yet, so it alerts once in its new style.
|
||||||
|
if (verdict == RingVerdict.HandBack) handBack(alert, quiet = false)
|
||||||
|
end()
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
sound(alert)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tone and vibration, paused for a phone call and back after it, until the
|
||||||
|
* user hides the ring's notification, which would leave no way to stop it.
|
||||||
|
*/
|
||||||
|
private suspend fun sound(alert: ReminderAlert) {
|
||||||
|
var sounding = false
|
||||||
|
var tick = 0
|
||||||
|
while (true) {
|
||||||
|
if (tick++ % VISIBILITY_CHECK_TICKS == 0 && !stillRings(alert)) {
|
||||||
|
handBack(alert)
|
||||||
|
end()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val inCall = isInCall()
|
||||||
|
if (inCall && sounding) {
|
||||||
|
tones.stop()
|
||||||
|
vibrator.stop()
|
||||||
|
sounding = false
|
||||||
|
} else if (!inCall && !sounding) {
|
||||||
|
vibrator.start()
|
||||||
|
tones.play(scope, ringSources())
|
||||||
|
sounding = true
|
||||||
|
}
|
||||||
|
delay(CALL_CHECK_MILLIS)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun stillRings(alert: ReminderAlert): Boolean = try {
|
||||||
|
withContext(Dispatchers.IO) { notifier.canStillRing(alert) }
|
||||||
|
} catch (e: CancellationException) {
|
||||||
|
throw e
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "Could not re-check the ring for event ${alert.eventId}", e)
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun stop(intent: Intent) {
|
||||||
|
val current = alerts.ringing
|
||||||
|
if (current != null && matchFrom(intent).matches(current)) {
|
||||||
|
if (intent.getBooleanExtra(EXTRA_HAND_BACK, false)) handBack(current)
|
||||||
|
end()
|
||||||
|
} else {
|
||||||
|
stopIfIdle()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Rung long enough: back to the shade quietly. */
|
||||||
|
private fun giveUp() {
|
||||||
|
timeout = null
|
||||||
|
alerts.ringing?.let(::handBack)
|
||||||
|
end()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ends the ring, closes its screen, and stops the service unless a newer command is on its way. */
|
||||||
|
private fun end() {
|
||||||
|
alerts.ringing?.let(alerts::markHandled)
|
||||||
|
releaseRing()
|
||||||
|
alerts.ringing = null
|
||||||
|
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||||
|
stopIfIdle()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Declines while a newer command is still on its way. */
|
||||||
|
private fun stopIfIdle() {
|
||||||
|
if (alerts.ringing == null) lastStartId?.let { stopSelfResult(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [alert] back in the shade, in the app's scope so a service stopped
|
||||||
|
* meanwhile cannot cancel it, and its alert screen closed. A newer reminder
|
||||||
|
* for the occurrence that took its place meanwhile is left alone.
|
||||||
|
*/
|
||||||
|
private fun handBack(alert: ReminderAlert, quiet: Boolean = true) {
|
||||||
|
alerts.markHandled(alert)
|
||||||
|
appScope.launch {
|
||||||
|
try {
|
||||||
|
if (!notifier.isSuperseded(alert)) notifier.post(alert, quiet = quiet, ring = false)
|
||||||
|
} catch (e: CancellationException) {
|
||||||
|
throw e
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "Could not hand the reminder of event ${alert.eventId} back", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun releaseRing() {
|
||||||
|
ringing?.cancel()
|
||||||
|
ringing = null
|
||||||
|
timeout?.cancel()
|
||||||
|
timeout = null
|
||||||
|
tones.stop()
|
||||||
|
vibrator.stop()
|
||||||
|
wakeLock.release()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The device's alarm sound; "None", or none opening, leaves the vibration. */
|
||||||
|
private fun ringSources() = listOfNotNull(
|
||||||
|
RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM),
|
||||||
|
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM),
|
||||||
|
)
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private const val TAG = "ReminderRingService"
|
||||||
|
private const val ACTION_RING = "de.jeanlucmakiola.calendula.reminders.RING"
|
||||||
|
private const val ACTION_STOP = "de.jeanlucmakiola.calendula.reminders.RING_STOP"
|
||||||
|
private const val EXTRA_NOTIFICATION = "notification"
|
||||||
|
private const val EXTRA_SINCE = "since"
|
||||||
|
private const val CALL_CHECK_MILLIS = 1_000L
|
||||||
|
|
||||||
|
/** How many call checks between re-reading whether the ring's notification can still be seen. */
|
||||||
|
private const val VISIBILITY_CHECK_TICKS = 5
|
||||||
|
private const val EXTRA_MATCH_KIND = "match_kind"
|
||||||
|
private const val EXTRA_MATCH_VALUE = "match_value"
|
||||||
|
private const val EXTRA_HAND_BACK = "hand_back"
|
||||||
|
private const val WAKE_LOCK_TAG = "calendula:reminder-ring"
|
||||||
|
|
||||||
|
/** Clear of the reminders' tagged id 1 and the backup notice's 2. */
|
||||||
|
private const val RING_NOTIFICATION_ID = 171
|
||||||
|
private const val OTHER_RING_NOTIFICATION_ID = 172
|
||||||
|
|
||||||
|
/** How long a reminder rings unanswered before it goes quiet. */
|
||||||
|
const val RING_TIMEOUT_MILLIS = 10L * 60 * 1000
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rings [alert] under [notification]. False when Android refused to
|
||||||
|
* start the service from where the reminder fired.
|
||||||
|
*/
|
||||||
|
fun start(context: Context, alerts: FullScreenAlerts, alert: ReminderAlert, notification: Notification): Boolean {
|
||||||
|
val intent = Intent(context, ReminderRingService::class.java)
|
||||||
|
.setAction(ACTION_RING)
|
||||||
|
.putAlert(alert)
|
||||||
|
.putExtra(EXTRA_NOTIFICATION, notification)
|
||||||
|
.putExtra(EXTRA_SINCE, System.currentTimeMillis())
|
||||||
|
alerts.addPending(alert)
|
||||||
|
return try {
|
||||||
|
RingWakeLock.handOff(context, WAKE_LOCK_TAG)
|
||||||
|
context.startForegroundService(intent)
|
||||||
|
true
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "Could not start the ring for event ${alert.eventId}", e)
|
||||||
|
alerts.removePending(alert)
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stops the ring if it is for a reminder [match]es, in order with the
|
||||||
|
* starts sent before it. [handBack] puts it back in the shade quietly.
|
||||||
|
* A command rather than `stopService`, which would also drop a start
|
||||||
|
* still on its way; sent while the ring's foreground service keeps the
|
||||||
|
* app allowed to.
|
||||||
|
*/
|
||||||
|
fun stop(context: Context, alerts: FullScreenAlerts, match: RingMatch, handBack: Boolean = false) {
|
||||||
|
val (kind, value) = when (match) {
|
||||||
|
is RingMatch.Key -> 0 to match.key
|
||||||
|
is RingMatch.Occurrence -> 1 to match.occurrenceKey
|
||||||
|
is RingMatch.Calendar -> 2 to match.calendarId
|
||||||
|
RingMatch.Any -> 3 to 0L
|
||||||
|
}
|
||||||
|
val intent = Intent(context, ReminderRingService::class.java)
|
||||||
|
.setAction(ACTION_STOP)
|
||||||
|
.putExtra(EXTRA_MATCH_KIND, kind)
|
||||||
|
.putExtra(EXTRA_MATCH_VALUE, value)
|
||||||
|
.putExtra(EXTRA_HAND_BACK, handBack)
|
||||||
|
try {
|
||||||
|
context.startService(intent)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "Could not stop the ring", e)
|
||||||
|
// Refused from the background: nothing must ring on regardless,
|
||||||
|
// unless a start is still on its way, which this would crash.
|
||||||
|
if (!alerts.anyPending) {
|
||||||
|
alerts.handBackOnDestroy = handBack
|
||||||
|
context.stopService(Intent(context, ReminderRingService::class.java))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun matchFrom(intent: Intent): RingMatch {
|
||||||
|
val value = intent.getLongExtra(EXTRA_MATCH_VALUE, 0L)
|
||||||
|
return when (intent.getIntExtra(EXTRA_MATCH_KIND, 3)) {
|
||||||
|
0 -> RingMatch.Key(value)
|
||||||
|
1 -> RingMatch.Occurrence(value)
|
||||||
|
2 -> RingMatch.Calendar(value)
|
||||||
|
else -> RingMatch.Any
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,242 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.data.reminders
|
||||||
|
|
||||||
|
import android.Manifest
|
||||||
|
import android.content.Context
|
||||||
|
import android.util.Log
|
||||||
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
|
import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource
|
||||||
|
import de.jeanlucmakiola.calendula.data.calendar.withoutProviderDefaults
|
||||||
|
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
|
||||||
|
import de.jeanlucmakiola.calendula.data.prefs.ReminderStatePrefs
|
||||||
|
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||||
|
import de.jeanlucmakiola.calendula.domain.reminders.DailyDigestSettings
|
||||||
|
import de.jeanlucmakiola.calendula.domain.reminders.digestEntries
|
||||||
|
import de.jeanlucmakiola.calendula.domain.reminders.planReminders
|
||||||
|
import de.jeanlucmakiola.calendula.domain.reminders.scheduleDigest
|
||||||
|
import de.jeanlucmakiola.calendula.domain.reminders.reminderQueryHorizon
|
||||||
|
import de.jeanlucmakiola.calendula.domain.reminders.reminderWatermark
|
||||||
|
import de.jeanlucmakiola.calendula.domain.reminders.scheduleReminders
|
||||||
|
import de.jeanlucmakiola.floret.android.hasPermission
|
||||||
|
import de.jeanlucmakiola.floret.di.IoDispatcher
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.CoroutineStart
|
||||||
|
import kotlinx.coroutines.SupervisorJob
|
||||||
|
import kotlinx.coroutines.channels.BufferOverflow
|
||||||
|
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||||
|
import kotlinx.coroutines.flow.debounce
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
import kotlinx.coroutines.flow.launchIn
|
||||||
|
import kotlinx.coroutines.flow.onEach
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import java.time.ZoneId
|
||||||
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One pass of in-house reminder delivery: read what is planned, post what has
|
||||||
|
* come due, and arm the next wake-up. Every trigger runs the same [scan], and
|
||||||
|
* re-running is always safe — the watermark in [ReminderStatePrefs] decides what
|
||||||
|
* is owed, not the trigger.
|
||||||
|
*/
|
||||||
|
@Singleton
|
||||||
|
class ReminderScanner @Inject constructor(
|
||||||
|
@ApplicationContext private val context: Context,
|
||||||
|
private val source: ReminderInstanceSource,
|
||||||
|
private val calendarDataSource: CalendarDataSource,
|
||||||
|
private val notifier: ReminderNotifier,
|
||||||
|
private val digestNotifier: DailyDigestNotifier,
|
||||||
|
private val channels: ReminderChannels,
|
||||||
|
private val snoozes: ReminderSnoozeScheduler,
|
||||||
|
private val alarms: ReminderAlarmScheduler,
|
||||||
|
private val state: ReminderStatePrefs,
|
||||||
|
private val calendarPrefs: CalendarPrefs,
|
||||||
|
private val settingsPrefs: SettingsPrefs,
|
||||||
|
@IoDispatcher private val io: kotlinx.coroutines.CoroutineDispatcher,
|
||||||
|
) {
|
||||||
|
|
||||||
|
// Triggers overlap freely (an alarm during a burst of edits); serialize so
|
||||||
|
// two passes can't both read the same watermark and post the same reminder.
|
||||||
|
private val scanLock = Mutex()
|
||||||
|
|
||||||
|
private val scope = CoroutineScope(SupervisorJob() + io)
|
||||||
|
private val providerChanges = MutableSharedFlow<Unit>(
|
||||||
|
replay = 0, extraBufferCapacity = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST,
|
||||||
|
)
|
||||||
|
private var watching = false
|
||||||
|
|
||||||
|
suspend fun scan() = withContext(io) {
|
||||||
|
scanLock.withLock {
|
||||||
|
try {
|
||||||
|
runScan()
|
||||||
|
} catch (e: SecurityException) {
|
||||||
|
// Permission revoked mid-flight; the next grant re-scans.
|
||||||
|
Log.w(TAG, "Reminder scan lacks the calendar permission", e)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "Reminder scan failed", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun runScan() {
|
||||||
|
val now = System.currentTimeMillis()
|
||||||
|
if (!hasReadCalendar()) return
|
||||||
|
|
||||||
|
val lastFired = reminderWatermark(state.lastScanMillis(), now)
|
||||||
|
val horizon = now + MAX_ALARM_INTERVAL_MILLIS
|
||||||
|
val digestSettings = settingsPrefs.dailyDigest.first()
|
||||||
|
val nextDigest = if (digestSettings.enabled) postDigest(digestSettings, lastFired, now) else null
|
||||||
|
val nextReminder = try {
|
||||||
|
if (settingsPrefs.remindersEnabled.first()) reminders(lastFired, now, horizon) else null
|
||||||
|
} catch (e: Exception) {
|
||||||
|
// The watermark stays, so the next pass owes these reminders again;
|
||||||
|
// keep that pass, and the summary's next moment, armed.
|
||||||
|
alarms.scheduleScan(minOf(nextDigest ?: horizon, now + RETRY_AFTER_FAILURE_MILLIS))
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
|
||||||
|
// Advance even when nothing could be posted, so muting notifications
|
||||||
|
// doesn't build a backlog — and while both are off, so switching one
|
||||||
|
// back on doesn't replay it.
|
||||||
|
state.setLastScanMillis(now)
|
||||||
|
val next = listOfNotNull(nextReminder, nextDigest).minOrNull()
|
||||||
|
if (next == null) alarms.cancelScan() else alarms.scheduleScan(minOf(next, horizon))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Post the event reminders that are due; returns the next wake-up they need. */
|
||||||
|
private suspend fun reminders(lastFired: Long, now: Long, horizon: Long): Long {
|
||||||
|
syncChannels()
|
||||||
|
val lookahead = reminderQueryHorizon(LOOKAHEAD_MILLIS, source.longestReminderMinutes())
|
||||||
|
// Reach into the past too: an all-day "at time of event" encodes to a
|
||||||
|
// negative offset, and a catch-up pass needs the occurrences it missed.
|
||||||
|
// Calendars muted in-app (#272) plan nothing, so they arm no wake-ups.
|
||||||
|
val muted = settingsPrefs.mutedReminderCalendarIds.first()
|
||||||
|
val occurrences = source.occurrences(now - PAST_WINDOW_MILLIS, now + lookahead)
|
||||||
|
.filter { it.calendarId !in muted }
|
||||||
|
val planned = planReminders(
|
||||||
|
instances = occurrences,
|
||||||
|
minutesByEvent = source.reminderMinutes(occurrences.map { it.eventId })
|
||||||
|
.withoutProviderDefaults(),
|
||||||
|
zone = ZoneId.systemDefault(),
|
||||||
|
allDayTimeMinutes = settingsPrefs.allDayReminderTimeMinutes.first(),
|
||||||
|
)
|
||||||
|
|
||||||
|
val schedule = scheduleReminders(
|
||||||
|
planned = planned,
|
||||||
|
lastFiredMillis = lastFired,
|
||||||
|
nowMillis = now,
|
||||||
|
horizonMillis = horizon,
|
||||||
|
)
|
||||||
|
|
||||||
|
if (notifier.canPost()) {
|
||||||
|
schedule.due.forEach {
|
||||||
|
val alert = it.toAlert()
|
||||||
|
snoozes.cancel(alert)
|
||||||
|
notifier.post(alert)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return schedule.nextAlarmMillis
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Post the daily summary if it is owed (#459); returns its next moment. It
|
||||||
|
* leaves out calendars excluded from it, not those muted for reminders —
|
||||||
|
* a calendar too noisy to ping per event can still belong in the overview.
|
||||||
|
*/
|
||||||
|
private suspend fun postDigest(settings: DailyDigestSettings, lastFired: Long, now: Long): Long {
|
||||||
|
val zone = ZoneId.systemDefault()
|
||||||
|
val listed = try {
|
||||||
|
state.lastDigestDay()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "Could not read the last daily summary", e)
|
||||||
|
null
|
||||||
|
}
|
||||||
|
val schedule = scheduleDigest(
|
||||||
|
timeMinutes = settings.timeMinutes,
|
||||||
|
day = settings.day,
|
||||||
|
zone = zone,
|
||||||
|
// A moment that passed before the summary was last changed is not owed.
|
||||||
|
lastFiredMillis = maxOf(lastFired, settings.armedAtMillis),
|
||||||
|
nowMillis = now,
|
||||||
|
lastListedDay = listed,
|
||||||
|
)
|
||||||
|
val day = schedule.dueDay
|
||||||
|
// A blocked channel would swallow it; the day stays owed until allowed.
|
||||||
|
if (day != null && notifier.canPost() && !digestNotifier.isChannelOff()) {
|
||||||
|
// A failed summary must not cost the event reminders this pass owes.
|
||||||
|
try {
|
||||||
|
// A day either side: all-day occurrences sit at UTC midnight, which
|
||||||
|
// can fall outside the local day they stand for.
|
||||||
|
val from = day.minusDays(1).atStartOfDay(zone).toInstant().toEpochMilli()
|
||||||
|
val to = day.plusDays(2).atStartOfDay(zone).toInstant().toEpochMilli()
|
||||||
|
val left = settings.excludedCalendarIds + calendarPrefs.pendingDisabledCalendarIds.first()
|
||||||
|
digestNotifier.post(day, digestEntries(source.occurrences(from, to), day, zone, left))
|
||||||
|
state.setLastDigestDay(day)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "Daily summary failed", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return schedule.nextAlarmMillis
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A provider change re-scans, so a calendar added, renamed or removed keeps
|
||||||
|
* its channel in step here. Skipped while reminders are off, when the
|
||||||
|
* channels have nothing to do. A failure never costs the reminders.
|
||||||
|
*/
|
||||||
|
private fun syncChannels() {
|
||||||
|
try {
|
||||||
|
channels.sync()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "Reminder channel sync failed", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun hasReadCalendar(): Boolean = context.hasPermission(Manifest.permission.READ_CALENDAR)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Re-scan when the provider changes, so a saved or deleted event re-arms the
|
||||||
|
* alarm at once. Debounced, since a single save lands as several
|
||||||
|
* notifications. Process-lifetime only; other triggers cover the rest.
|
||||||
|
*/
|
||||||
|
fun startWatchingProvider() {
|
||||||
|
if (watching) return
|
||||||
|
watching = true
|
||||||
|
providerChanges
|
||||||
|
.debounce(PROVIDER_CHANGE_DEBOUNCE_MILLIS)
|
||||||
|
.onEach { scan() }
|
||||||
|
.launchIn(scope)
|
||||||
|
calendarDataSource.registerChangeListener { providerChanges.tryEmit(Unit) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fire-and-forget scan for callers that are not in a coroutine already. */
|
||||||
|
fun scanInBackground() {
|
||||||
|
scope.launch(start = CoroutineStart.DEFAULT) { scan() }
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val TAG = "ReminderScanner"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How far ahead occurrences are read. Stretched further by the longest
|
||||||
|
* reminder offset in the table, so this is only the floor.
|
||||||
|
*/
|
||||||
|
const val LOOKAHEAD_MILLIS = 7L * 24 * 60 * 60 * 1000
|
||||||
|
|
||||||
|
/** How far back to look for occurrences that may still owe a reminder. */
|
||||||
|
const val PAST_WINDOW_MILLIS = 24L * 60 * 60 * 1000
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Never wait longer than a day for the next pass: it rolls the lookahead
|
||||||
|
* window forward and re-arms an alarm the system may have dropped.
|
||||||
|
*/
|
||||||
|
const val MAX_ALARM_INTERVAL_MILLIS = 24L * 60 * 60 * 1000
|
||||||
|
|
||||||
|
const val PROVIDER_CHANGE_DEBOUNCE_MILLIS = 2_000L
|
||||||
|
|
||||||
|
/** How soon a pass whose reminders failed is tried again. */
|
||||||
|
const val RETRY_AFTER_FAILURE_MILLIS = 15L * 60 * 1000
|
||||||
|
}
|
||||||
|
}
|
||||||
+43
@@ -0,0 +1,43 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.data.reminders
|
||||||
|
|
||||||
|
import android.content.BroadcastReceiver
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
|
import de.jeanlucmakiola.floret.android.goAsync
|
||||||
|
import javax.inject.Inject
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Every out-of-process reason to re-run a reminder scan: our own [ACTION_SCAN]
|
||||||
|
* alarm, boot and package-replaced (both wipe pending alarms), and time or
|
||||||
|
* timezone changes (both move reminders relative to the armed alarm). All do the
|
||||||
|
* same thing, since [ReminderScanner.scan] is idempotent.
|
||||||
|
*
|
||||||
|
* Exported for the system broadcasts; an early scan triggered by another app is
|
||||||
|
* harmless.
|
||||||
|
*/
|
||||||
|
@AndroidEntryPoint
|
||||||
|
class ReminderScheduleReceiver : BroadcastReceiver() {
|
||||||
|
|
||||||
|
@Inject lateinit var scanner: ReminderScanner
|
||||||
|
|
||||||
|
override fun onReceive(context: Context, intent: Intent) {
|
||||||
|
// Checked despite every action doing the same thing: the receiver is
|
||||||
|
// exported and the broadcasts it takes are protected, so any other
|
||||||
|
// action did not come from where it claims to.
|
||||||
|
if (intent.action !in HANDLED_ACTIONS) return
|
||||||
|
goAsync { scanner.scan() }
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val ACTION_SCAN = "de.jeanlucmakiola.calendula.reminders.SCAN"
|
||||||
|
|
||||||
|
private val HANDLED_ACTIONS = setOf(
|
||||||
|
ACTION_SCAN,
|
||||||
|
Intent.ACTION_BOOT_COMPLETED,
|
||||||
|
Intent.ACTION_MY_PACKAGE_REPLACED,
|
||||||
|
Intent.ACTION_TIME_CHANGED,
|
||||||
|
Intent.ACTION_TIMEZONE_CHANGED,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
+19
-26
@@ -3,21 +3,20 @@ package de.jeanlucmakiola.calendula.data.reminders
|
|||||||
import android.app.AlarmManager
|
import android.app.AlarmManager
|
||||||
import android.app.PendingIntent
|
import android.app.PendingIntent
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.os.Build
|
|
||||||
import androidx.core.content.getSystemService
|
import androidx.core.content.getSystemService
|
||||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
|
import de.jeanlucmakiola.floret.android.setWakeup
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Schedules a one-off exact alarm that re-shows a snoozed reminder.
|
* Schedules a one-off exact alarm that re-shows a snoozed reminder. Separate
|
||||||
|
* from [ReminderAlarmScheduler]'s single moving scan alarm: a snooze is pinned
|
||||||
|
* to one reminder and has to outlive the watermark moving past it, so it carries
|
||||||
|
* the reminder in its own intent.
|
||||||
*
|
*
|
||||||
* The app otherwise relies entirely on the calendar provider's `EVENT_REMINDER`
|
* Falls back to an inexact allow-while-idle alarm where the OS withholds the
|
||||||
* broadcast (the Etar model), but a snoozed reminder has no provider backing —
|
* exact-alarm capability (API 31–32 with the permission revoked).
|
||||||
* its `CalendarAlerts` row is already fired — so we must re-fire it ourselves.
|
|
||||||
* A snooze that lands late is a broken snooze, hence an *exact* alarm; we fall
|
|
||||||
* back to an inexact allow-while-idle alarm only if the OS withholds the
|
|
||||||
* exact-alarm capability (API 31–32 where the user revoked it).
|
|
||||||
*/
|
*/
|
||||||
@Singleton
|
@Singleton
|
||||||
class ReminderSnoozeScheduler @Inject constructor(
|
class ReminderSnoozeScheduler @Inject constructor(
|
||||||
@@ -32,24 +31,18 @@ class ReminderSnoozeScheduler @Inject constructor(
|
|||||||
ReminderActionReceiver.intent(context, ReminderActionReceiver.ACTION_SHOW, alert),
|
ReminderActionReceiver.intent(context, ReminderActionReceiver.ACTION_SHOW, alert),
|
||||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||||
)
|
)
|
||||||
if (canScheduleExact(alarmManager)) {
|
alarmManager.setWakeup(triggerAtMillis, pendingIntent)
|
||||||
alarmManager.setExactAndAllowWhileIdle(
|
|
||||||
AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent,
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
// Exact alarms revoked (API 31–32): an inexact wake is the honest
|
|
||||||
// best we can do without nagging for SCHEDULE_EXACT_ALARM.
|
|
||||||
alarmManager.setAndAllowWhileIdle(
|
|
||||||
AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Drop a snooze still pending for [alert]'s occurrence, so it can't re-show over a newer reminder. */
|
||||||
* True on API < 31 (no restriction), and on 31+ when the exact-alarm
|
fun cancel(alert: ReminderAlert) {
|
||||||
* capability is held — auto-granted via `USE_EXACT_ALARM` on API 33+
|
val pendingIntent = PendingIntent.getBroadcast(
|
||||||
* (Calendula is a calendar app), user-revocable on 31–32.
|
context,
|
||||||
*/
|
ReminderActionReceiver.requestCode(alert, ReminderActionReceiver.ACTION_SHOW),
|
||||||
private fun canScheduleExact(alarmManager: AlarmManager): Boolean =
|
ReminderActionReceiver.intent(context, ReminderActionReceiver.ACTION_SHOW, alert),
|
||||||
Build.VERSION.SDK_INT < Build.VERSION_CODES.S || alarmManager.canScheduleExactAlarms()
|
PendingIntent.FLAG_NO_CREATE or PendingIntent.FLAG_IMMUTABLE,
|
||||||
|
) ?: return
|
||||||
|
context.getSystemService<AlarmManager>()?.cancel(pendingIntent)
|
||||||
|
pendingIntent.cancel()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,24 +1,42 @@
|
|||||||
package de.jeanlucmakiola.calendula.data.reminders
|
package de.jeanlucmakiola.calendula.data.reminders
|
||||||
|
|
||||||
|
import de.jeanlucmakiola.calendula.domain.runsMidnightToMidnight
|
||||||
import de.jeanlucmakiola.calendula.ui.common.timeOfDayFormatter
|
import de.jeanlucmakiola.calendula.ui.common.timeOfDayFormatter
|
||||||
|
import java.time.DayOfWeek
|
||||||
import java.time.Instant
|
import java.time.Instant
|
||||||
|
import java.time.LocalDate
|
||||||
import java.time.ZoneId
|
import java.time.ZoneId
|
||||||
import java.time.ZoneOffset
|
import java.time.ZoneOffset
|
||||||
import java.time.format.DateTimeFormatter
|
import java.time.format.DateTimeFormatter
|
||||||
import java.time.format.FormatStyle
|
import java.time.format.FormatStyle
|
||||||
|
import java.time.format.TextStyle
|
||||||
|
import java.time.temporal.ChronoUnit
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
|
import kotlinx.datetime.toKotlinTimeZone
|
||||||
|
import kotlin.time.Instant as KInstant
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The one line of time context in a reminder notification. Pure so it can be
|
* The one line of time context in a reminder notification. Pure so it can be
|
||||||
* JVM-tested:
|
* JVM-tested.
|
||||||
*
|
*
|
||||||
* - timed, same day: "09:30 – 10:00"
|
* Timed events that fall on a day other than [today] are prefixed with that
|
||||||
* - timed, crossing days: "11 Jun, 23:30 – 12 Jun, 00:30" (medium date + short time)
|
* day, so a reminder fired ahead of time no longer reads as if the event were
|
||||||
* - all-day, one day: "11 Jun 2026"
|
* today (issue #46). The prefix prefers natural language and stays short:
|
||||||
* - all-day, multi-day: "11 Jun 2026 – 12 Jun 2026"
|
|
||||||
*
|
*
|
||||||
* All-day instances store UTC midnights with an exclusive end, so they are
|
* - today: "09:30 – 10:00" (no prefix)
|
||||||
* read in UTC and the end day is the last *covered* day.
|
* - tomorrow / yesterday: "Tomorrow, 09:30 – 10:00" ([tomorrowLabel] / [yesterdayLabel])
|
||||||
|
* - elsewhere this week: "Thu, 09:30 – 10:00" (localized short weekday)
|
||||||
|
* - further out: "16 Jul, 09:30 – 10:00" (medium date — a weekday
|
||||||
|
* alone would be ambiguous)
|
||||||
|
* - timed, crossing days: "11 Jun, 23:30 – 12 Jun, 00:30" (medium date + short time,
|
||||||
|
* already unambiguous)
|
||||||
|
* - all-day, one day: "Tomorrow" / "Thu" / "11 Jun 2026" (same relative rules,
|
||||||
|
* plus [todayLabel] — no time range to lean on)
|
||||||
|
* - all-day, multi-day: "Tomorrow – 12 Jun 2026" (relative start, explicit end)
|
||||||
|
*
|
||||||
|
* All-day instances store UTC midnights with an exclusive end, so they are read
|
||||||
|
* in UTC and the end day is the last *covered* day (issue #308). A timed event
|
||||||
|
* from local midnight to local midnight reads like one too, in [zone] (#296).
|
||||||
*/
|
*/
|
||||||
fun reminderTimeText(
|
fun reminderTimeText(
|
||||||
beginMillis: Long,
|
beginMillis: Long,
|
||||||
@@ -27,34 +45,102 @@ fun reminderTimeText(
|
|||||||
zone: ZoneId,
|
zone: ZoneId,
|
||||||
locale: Locale,
|
locale: Locale,
|
||||||
is24Hour: Boolean,
|
is24Hour: Boolean,
|
||||||
|
today: LocalDate,
|
||||||
|
firstDayOfWeek: DayOfWeek,
|
||||||
|
todayLabel: String,
|
||||||
|
tomorrowLabel: String,
|
||||||
|
yesterdayLabel: String,
|
||||||
): String {
|
): String {
|
||||||
if (isAllDay) {
|
val wholeDays = !isAllDay && runsMidnightToMidnight(
|
||||||
|
KInstant.fromEpochMilliseconds(beginMillis),
|
||||||
|
KInstant.fromEpochMilliseconds(endMillis),
|
||||||
|
zone.toKotlinTimeZone(),
|
||||||
|
)
|
||||||
|
if (isAllDay || wholeDays) {
|
||||||
|
val dayZone = if (isAllDay) ZoneOffset.UTC else zone
|
||||||
val dateFormat = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(locale)
|
val dateFormat = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(locale)
|
||||||
// (atZone().toLocalDate() instead of LocalDate.ofInstant — API 34+)
|
// (atZone().toLocalDate() instead of LocalDate.ofInstant — API 34+)
|
||||||
val firstDay = Instant.ofEpochMilli(beginMillis).atZone(ZoneOffset.UTC).toLocalDate()
|
val firstDay = Instant.ofEpochMilli(beginMillis).atZone(dayZone).toLocalDate()
|
||||||
val lastDay = Instant.ofEpochMilli(endMillis).atZone(ZoneOffset.UTC).toLocalDate()
|
val lastDay = Instant.ofEpochMilli(endMillis).atZone(dayZone).toLocalDate()
|
||||||
.minusDays(1)
|
.minusDays(1)
|
||||||
.coerceAtLeast(firstDay)
|
.coerceAtLeast(firstDay)
|
||||||
return if (lastDay == firstDay) {
|
val start = relativeDayPrefix(
|
||||||
dateFormat.format(firstDay)
|
day = firstDay,
|
||||||
} else {
|
today = today,
|
||||||
dateFormat.format(firstDay) + RANGE + dateFormat.format(lastDay)
|
firstDayOfWeek = firstDayOfWeek,
|
||||||
}
|
locale = locale,
|
||||||
|
dateFormat = dateFormat,
|
||||||
|
tomorrowLabel = tomorrowLabel,
|
||||||
|
yesterdayLabel = yesterdayLabel,
|
||||||
|
) ?: todayLabel
|
||||||
|
return if (lastDay == firstDay) start else start + RANGE + dateFormat.format(lastDay)
|
||||||
}
|
}
|
||||||
|
|
||||||
val timeFormat = timeOfDayFormatter(is24Hour, locale)
|
val timeFormat = timeOfDayFormatter(is24Hour, locale)
|
||||||
|
val dateFormat = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(locale)
|
||||||
val begin = Instant.ofEpochMilli(beginMillis).atZone(zone)
|
val begin = Instant.ofEpochMilli(beginMillis).atZone(zone)
|
||||||
val end = Instant.ofEpochMilli(endMillis).atZone(zone)
|
val end = Instant.ofEpochMilli(endMillis).atZone(zone)
|
||||||
return if (begin.toLocalDate() == end.toLocalDate()) {
|
return if (begin.toLocalDate() == end.toLocalDate()) {
|
||||||
timeFormat.format(begin) + RANGE + timeFormat.format(end)
|
val range = timeFormat.format(begin) + RANGE + timeFormat.format(end)
|
||||||
|
val prefix = relativeDayPrefix(
|
||||||
|
day = begin.toLocalDate(),
|
||||||
|
today = today,
|
||||||
|
firstDayOfWeek = firstDayOfWeek,
|
||||||
|
locale = locale,
|
||||||
|
dateFormat = dateFormat,
|
||||||
|
tomorrowLabel = tomorrowLabel,
|
||||||
|
yesterdayLabel = yesterdayLabel,
|
||||||
|
)
|
||||||
|
if (prefix == null) range else "$prefix, $range"
|
||||||
} else {
|
} else {
|
||||||
// Cross-day: medium date + the chosen short time, joined per side. Built
|
// Cross-day: medium date + the chosen short time, joined per side. Built
|
||||||
// from the two formatters (not ofLocalizedDateTime) so the 12/24h choice
|
// from the two formatters (not ofLocalizedDateTime) so the 12/24h choice
|
||||||
// applies to the time portion too.
|
// applies to the time portion too. The explicit dates already say which
|
||||||
val dateFormat = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(locale)
|
// day, so no relative prefix is layered on top.
|
||||||
val dateTime = { z: java.time.ZonedDateTime -> "${dateFormat.format(z)}, ${timeFormat.format(z)}" }
|
val dateTime = { z: java.time.ZonedDateTime -> "${dateFormat.format(z)}, ${timeFormat.format(z)}" }
|
||||||
dateTime(begin) + RANGE + dateTime(end)
|
dateTime(begin) + RANGE + dateTime(end)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A short label for [day] relative to [today], or `null` when it *is* today (the
|
||||||
|
* common case, which needs no prefix). Weekday names are used only within the
|
||||||
|
* current week — a "next Wednesday" would be indistinguishable from this one, so
|
||||||
|
* anything past this week falls back to the exact date.
|
||||||
|
*/
|
||||||
|
private fun relativeDayPrefix(
|
||||||
|
day: LocalDate,
|
||||||
|
today: LocalDate,
|
||||||
|
firstDayOfWeek: DayOfWeek,
|
||||||
|
locale: Locale,
|
||||||
|
dateFormat: DateTimeFormatter,
|
||||||
|
tomorrowLabel: String,
|
||||||
|
yesterdayLabel: String,
|
||||||
|
): String? = when (ChronoUnit.DAYS.between(today, day)) {
|
||||||
|
0L -> null
|
||||||
|
1L -> tomorrowLabel
|
||||||
|
-1L -> yesterdayLabel
|
||||||
|
else -> if (isSameWeek(day, today, firstDayOfWeek)) {
|
||||||
|
day.dayOfWeek.getDisplayName(TextStyle.SHORT, locale)
|
||||||
|
} else {
|
||||||
|
dateFormat.format(day)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True when [day] and [today] share the same week. The week boundary honours the
|
||||||
|
* user's *week starts on* setting (already resolved to a concrete [firstDayOfWeek],
|
||||||
|
* with [firstDayOfWeek] falling back to the locale default upstream).
|
||||||
|
*/
|
||||||
|
private fun isSameWeek(day: LocalDate, today: LocalDate, firstDayOfWeek: DayOfWeek): Boolean {
|
||||||
|
val startOfWeek = today.previousOrSame(firstDayOfWeek)
|
||||||
|
return !day.isBefore(startOfWeek) && day.isBefore(startOfWeek.plusWeeks(1))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The most recent [target] on or before this date (this date itself when it matches). */
|
||||||
|
private fun LocalDate.previousOrSame(target: DayOfWeek): LocalDate {
|
||||||
|
val backtrack = (dayOfWeek.value - target.value + 7) % 7
|
||||||
|
return minusDays(backtrack.toLong())
|
||||||
|
}
|
||||||
|
|
||||||
private const val RANGE = " – "
|
private const val RANGE = " – "
|
||||||
-130
@@ -1,130 +0,0 @@
|
|||||||
package de.jeanlucmakiola.calendula.data.reminders
|
|
||||||
|
|
||||||
import androidx.datastore.core.DataStore
|
|
||||||
import androidx.datastore.preferences.core.MutablePreferences
|
|
||||||
import androidx.datastore.preferences.core.Preferences
|
|
||||||
import androidx.datastore.preferences.core.edit
|
|
||||||
import androidx.datastore.preferences.core.stringSetPreferencesKey
|
|
||||||
import java.util.Base64
|
|
||||||
import javax.inject.Inject
|
|
||||||
import javax.inject.Singleton
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Still relevant while the event has not ended: a reminder for an event that is
|
|
||||||
* already over is pointless to re-surface. Falls back to the begin time when the
|
|
||||||
* end is unknown (0L). Used both to decide what to re-post and to purge the stash.
|
|
||||||
*/
|
|
||||||
internal fun ReminderAlert.isRelevantAt(nowMillis: Long): Boolean =
|
|
||||||
(endMillis.takeIf { it > 0L } ?: beginMillis) >= nowMillis
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Local stash of reminder alerts that fired while their calendar was disabled
|
|
||||||
* in-app. [EventReminderReceiver] marks every due alert `STATE_FIRED` regardless
|
|
||||||
* (so the provider stops re-broadcasting the suppressed ones), which would
|
|
||||||
* otherwise lose those reminders forever — there is no re-scan. Stashing lets
|
|
||||||
* [de.jeanlucmakiola.calendula.ui.calendars.CalendarsViewModel] re-post them if
|
|
||||||
* the user re-enables the calendar before the event is over.
|
|
||||||
*
|
|
||||||
* Persisted in the shared preferences DataStore as a set of self-describing
|
|
||||||
* strings (one per alert); the stash never reaches a screen, so there is no
|
|
||||||
* domain model. Entries whose event has already ended are dropped on the next
|
|
||||||
* stash/recover/purge, so the stash only ever holds a handful of pending alerts.
|
|
||||||
*/
|
|
||||||
@Singleton
|
|
||||||
class SuppressedReminderStore @Inject constructor(
|
|
||||||
private val store: DataStore<Preferences>,
|
|
||||||
) {
|
|
||||||
|
|
||||||
/** Add [alerts] to the stash, replacing any existing entry with the same id. */
|
|
||||||
suspend fun stash(alerts: List<ReminderAlert>, nowMillis: Long) {
|
|
||||||
if (alerts.isEmpty()) return
|
|
||||||
store.edit { prefs ->
|
|
||||||
val byId = decodeAll(prefs).associateByTo(mutableMapOf()) { it.alertId }
|
|
||||||
alerts.forEach { byId[it.alertId] = it }
|
|
||||||
prefs.putStash(byId.values.filter { it.isRelevantAt(nowMillis) })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Remove and return the still-relevant stashed alerts belonging to any of
|
|
||||||
* [calendarIds]; drops expired entries for every calendar in passing.
|
|
||||||
*/
|
|
||||||
suspend fun recoverFor(calendarIds: Set<Long>, nowMillis: Long): List<ReminderAlert> {
|
|
||||||
val recovered = mutableListOf<ReminderAlert>()
|
|
||||||
store.edit { prefs ->
|
|
||||||
val kept = decodeAll(prefs).filter { alert ->
|
|
||||||
when {
|
|
||||||
!alert.isRelevantAt(nowMillis) -> false // expired: drop
|
|
||||||
alert.calendarId in calendarIds -> { recovered += alert; false }
|
|
||||||
else -> true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
prefs.putStash(kept)
|
|
||||||
}
|
|
||||||
return recovered
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Drop entries whose event has already ended — cheap opportunistic cleanup. */
|
|
||||||
suspend fun purgeExpired(nowMillis: Long) {
|
|
||||||
store.edit { prefs ->
|
|
||||||
prefs.putStash(decodeAll(prefs).filter { it.isRelevantAt(nowMillis) })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun decodeAll(prefs: Preferences): List<ReminderAlert> =
|
|
||||||
prefs[KEY].orEmpty().mapNotNull { decodeStashEntry(it) }
|
|
||||||
|
|
||||||
private fun MutablePreferences.putStash(alerts: List<ReminderAlert>) {
|
|
||||||
val encoded = alerts.map { encodeStashEntry(it) }.toSet()
|
|
||||||
if (encoded.isEmpty()) remove(KEY) else set(KEY, encoded)
|
|
||||||
}
|
|
||||||
|
|
||||||
private companion object {
|
|
||||||
val KEY = stringSetPreferencesKey("suppressed_reminders")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// One stash entry as a delimited string. The '|' separator is safe because every
|
|
||||||
// free-text field is Base64-encoded first (that alphabet never contains '|'), and
|
|
||||||
// a null location is stored as a distinct sentinel that Base64 also never yields.
|
|
||||||
private const val FIELD_SEP = "|"
|
|
||||||
private const val NULL_LOCATION = "-"
|
|
||||||
|
|
||||||
internal fun encodeStashEntry(alert: ReminderAlert): String = listOf(
|
|
||||||
alert.alertId.toString(),
|
|
||||||
alert.eventId.toString(),
|
|
||||||
alert.calendarId.toString(),
|
|
||||||
alert.beginMillis.toString(),
|
|
||||||
alert.endMillis.toString(),
|
|
||||||
if (alert.isAllDay) "1" else "0",
|
|
||||||
alert.title.toBase64(),
|
|
||||||
alert.location?.toBase64() ?: NULL_LOCATION,
|
|
||||||
).joinToString(FIELD_SEP)
|
|
||||||
|
|
||||||
/** Reverse of [encodeStashEntry]; returns null for a malformed entry (dropped). */
|
|
||||||
internal fun decodeStashEntry(raw: String): ReminderAlert? {
|
|
||||||
val parts = raw.split(FIELD_SEP)
|
|
||||||
if (parts.size != 8) return null
|
|
||||||
return try {
|
|
||||||
ReminderAlert(
|
|
||||||
alertId = parts[0].toLong(),
|
|
||||||
eventId = parts[1].toLong(),
|
|
||||||
calendarId = parts[2].toLong(),
|
|
||||||
beginMillis = parts[3].toLong(),
|
|
||||||
endMillis = parts[4].toLong(),
|
|
||||||
title = parts[6].fromBase64(),
|
|
||||||
location = parts[7].takeIf { it != NULL_LOCATION }?.fromBase64(),
|
|
||||||
isAllDay = parts[5] == "1",
|
|
||||||
)
|
|
||||||
} catch (e: NumberFormatException) {
|
|
||||||
null
|
|
||||||
} catch (e: IllegalArgumentException) { // bad Base64
|
|
||||||
null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun String.toBase64(): String =
|
|
||||||
Base64.getEncoder().encodeToString(toByteArray(Charsets.UTF_8))
|
|
||||||
|
|
||||||
private fun String.fromBase64(): String =
|
|
||||||
String(Base64.getDecoder().decode(this), Charsets.UTF_8)
|
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.data.time
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
|
import de.jeanlucmakiola.calendula.data.di.ApplicationScope
|
||||||
|
import de.jeanlucmakiola.floret.android.broadcastTicks
|
||||||
|
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
import kotlinx.coroutines.flow.SharingStarted
|
||||||
|
import kotlinx.coroutines.flow.shareIn
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||||
|
import kotlinx.coroutines.flow.onEach
|
||||||
|
import kotlinx.coroutines.flow.transformLatest
|
||||||
|
import kotlinx.datetime.LocalDate
|
||||||
|
import kotlinx.datetime.TimeZone
|
||||||
|
import kotlinx.datetime.toLocalDateTime
|
||||||
|
import javax.inject.Inject
|
||||||
|
import kotlin.time.Clock
|
||||||
|
|
||||||
|
/** The current local date, re-emitted whenever it changes (#373). */
|
||||||
|
interface TodaySource {
|
||||||
|
val today: Flow<LocalDate>
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Re-reads the date on every minute boundary while collected, and at once on the
|
||||||
|
* system's date, time and zone broadcasts, which can arrive late or not at all.
|
||||||
|
* One receiver and tick loop is shared by every collector.
|
||||||
|
*/
|
||||||
|
@OptIn(ExperimentalCoroutinesApi::class)
|
||||||
|
class AndroidTodaySource @Inject constructor(
|
||||||
|
@ApplicationContext private val context: Context,
|
||||||
|
@ApplicationScope scope: CoroutineScope,
|
||||||
|
) : TodaySource {
|
||||||
|
|
||||||
|
override val today: Flow<LocalDate> = context
|
||||||
|
.broadcastTicks(Intent.ACTION_DATE_CHANGED, Intent.ACTION_TIME_CHANGED, Intent.ACTION_TIMEZONE_CHANGED)
|
||||||
|
.transformLatest {
|
||||||
|
while (true) {
|
||||||
|
emit(currentDate())
|
||||||
|
delay(MINUTE_MILLIS - Clock.System.now().toEpochMilliseconds() % MINUTE_MILLIS)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.distinctUntilChanged()
|
||||||
|
.shareIn(scope, SharingStarted.WhileSubscribed(replayExpirationMillis = 0), replay = 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
private const val MINUTE_MILLIS = 60_000L
|
||||||
|
|
||||||
|
fun currentDate(): LocalDate = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()).date
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Today as a hot flow seeded with [initial]. [onRollover] runs with the previous
|
||||||
|
* and the new date each time the day changes while collected, so a screen left
|
||||||
|
* open over midnight can move off yesterday (#373).
|
||||||
|
*/
|
||||||
|
fun Flow<LocalDate>.stateFollowingDays(
|
||||||
|
scope: CoroutineScope,
|
||||||
|
initial: LocalDate,
|
||||||
|
onRollover: (old: LocalDate, new: LocalDate) -> Unit,
|
||||||
|
): StateFlow<LocalDate> {
|
||||||
|
var last = initial
|
||||||
|
return onEach { date ->
|
||||||
|
val old = last
|
||||||
|
last = date
|
||||||
|
if (old != date) onRollover(old, date)
|
||||||
|
}.stateWhileSubscribed(scope, initial)
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.data.time
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
|
import de.jeanlucmakiola.calendula.data.di.ApplicationScope
|
||||||
|
import de.jeanlucmakiola.floret.android.broadcastTicks
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
import kotlinx.coroutines.flow.SharingStarted
|
||||||
|
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||||
|
import kotlinx.coroutines.flow.map
|
||||||
|
import kotlinx.coroutines.flow.shareIn
|
||||||
|
import kotlinx.datetime.TimeZone
|
||||||
|
import javax.inject.Inject
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The zone the device is in. Every screen that turns wall clock into instants
|
||||||
|
* reads it from here, so the timeline, the event form and a saved move use the
|
||||||
|
* same zone (#387).
|
||||||
|
*/
|
||||||
|
interface ZoneSource {
|
||||||
|
/** The device's zone, re-emitted whenever it changes. */
|
||||||
|
val zone: Flow<TimeZone>
|
||||||
|
|
||||||
|
/** The device's zone right now. */
|
||||||
|
fun current(): TimeZone
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Follows the system's zone broadcast, one receiver shared by every collector. */
|
||||||
|
class AndroidZoneSource @Inject constructor(
|
||||||
|
@ApplicationContext private val context: Context,
|
||||||
|
@ApplicationScope scope: CoroutineScope,
|
||||||
|
) : ZoneSource {
|
||||||
|
|
||||||
|
override val zone: Flow<TimeZone> = context.broadcastTicks(Intent.ACTION_TIMEZONE_CHANGED)
|
||||||
|
.map { current() }
|
||||||
|
.distinctUntilChanged()
|
||||||
|
.shareIn(scope, SharingStarted.WhileSubscribed(replayExpirationMillis = 0), replay = 1)
|
||||||
|
|
||||||
|
override fun current(): TimeZone = TimeZone.currentSystemDefault()
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.domain
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The ways a calendar can behave unlike a plain, writable one — each a reason it
|
||||||
|
* is missing from the event and import pickers (#76).
|
||||||
|
*/
|
||||||
|
enum class CalendarStateLabel {
|
||||||
|
/**
|
||||||
|
* A special-dates mirror the app fills from contacts. Writable and visible,
|
||||||
|
* yet no event target: anything authored here is deleted by the next sync.
|
||||||
|
*/
|
||||||
|
MANAGED,
|
||||||
|
|
||||||
|
/** Contents can't be modified: a WebCal subscription, a read-only share. */
|
||||||
|
READ_ONLY,
|
||||||
|
|
||||||
|
/** The account holds the events, but this device isn't syncing them down. */
|
||||||
|
NOT_SYNCED,
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether the account keeps this calendar's events off the device
|
||||||
|
* (`Calendars.SYNC_EVENTS = 0`) — empty by construction. Device-local calendars
|
||||||
|
* are excluded: nothing syncs them by definition, and one from another app can
|
||||||
|
* hold real events at `sync_events = 0`.
|
||||||
|
*/
|
||||||
|
val CalendarSource.isNotSynced: Boolean
|
||||||
|
get() = !syncsEvents && !isLocal
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether a visibility switch on this calendar can change anything the user
|
||||||
|
* would see — it can't for a non-syncing one, with no events on the device.
|
||||||
|
*/
|
||||||
|
val CalendarSource.hasVisibilitySwitch: Boolean
|
||||||
|
get() = !isNotSynced
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether this calendar can be offered as a target for a new or imported event.
|
||||||
|
* The one predicate behind both pickers, so the states [CalendarStateLabel]
|
||||||
|
* names on a manager row are exactly the states that keep a calendar out of them
|
||||||
|
* (#76). An event already living in an excluded calendar keeps it; the editor
|
||||||
|
* adds that calendar back to its picker.
|
||||||
|
*/
|
||||||
|
val CalendarSource.isEventTarget: Boolean
|
||||||
|
get() = canModifyContents && isVisibleInSystem && !isManaged && !isNotSynced
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether this calendar's events may have their times rewritten by a drag (#68).
|
||||||
|
* Deliberately not [isEventTarget]: a managed event stays editable (reminders,
|
||||||
|
* notes) yet must never move, since the next contacts sync would put it back.
|
||||||
|
*/
|
||||||
|
val CalendarSource.allowsEventMove: Boolean
|
||||||
|
get() = canModifyContents && !isManaged
|
||||||
|
|
||||||
|
/** Every state worth naming on this calendar's row, in reading order. */
|
||||||
|
fun CalendarSource.stateLabels(): List<CalendarStateLabel> = buildList {
|
||||||
|
if (isManaged) add(CalendarStateLabel.MANAGED)
|
||||||
|
if (!canModifyContents) add(CalendarStateLabel.READ_ONLY)
|
||||||
|
if (isNotSynced) add(CalendarStateLabel.NOT_SYNCED)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calendar-manager order within one group: the ones you can actually act on
|
||||||
|
* first, the non-syncing ones after them. Stable otherwise, so the provider's
|
||||||
|
* display-name ordering survives.
|
||||||
|
*/
|
||||||
|
fun List<CalendarSource>.orderedForManager(): List<CalendarSource> =
|
||||||
|
sortedBy { it.isNotSynced }
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.domain
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The `Calendars.VISIBLE` writes that flush the app's pending "switched off"
|
||||||
|
* set into the provider, plus the ids that need no write at all.
|
||||||
|
*/
|
||||||
|
data class CalendarVisibilityPlan(
|
||||||
|
val hide: Set<Long> = emptySet(),
|
||||||
|
val settled: Set<Long> = emptySet(),
|
||||||
|
) {
|
||||||
|
val isEmpty: Boolean get() = hide.isEmpty() && settled.isEmpty()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reconcile [pendingDisabledIds] — switch-offs the app could not write, plus
|
||||||
|
* what the retired app-local visibility model left behind (#75) — against the
|
||||||
|
* calendars actually on the device.
|
||||||
|
*
|
||||||
|
* Only ever *hides*: switching a system-hidden calendar back on would un-hide it
|
||||||
|
* in every other calendar app too. Calendula follows the flag and explains
|
||||||
|
* itself once (see [hasSystemHiddenCalendars]).
|
||||||
|
*
|
||||||
|
* [CalendarVisibilityPlan.settled] carries the ids needing no write — already
|
||||||
|
* hidden, or gone from the device.
|
||||||
|
*/
|
||||||
|
fun calendarVisibilityPlan(
|
||||||
|
calendars: List<CalendarSource>,
|
||||||
|
pendingDisabledIds: Set<Long>,
|
||||||
|
): CalendarVisibilityPlan {
|
||||||
|
val byId = calendars.associateBy { it.id }
|
||||||
|
val hide = mutableSetOf<Long>()
|
||||||
|
val settled = mutableSetOf<Long>()
|
||||||
|
for (id in pendingDisabledIds) {
|
||||||
|
val calendar = byId[id]
|
||||||
|
// Gone from the device, or already invisible — nothing to write.
|
||||||
|
if (calendar != null && calendar.isVisibleInSystem) hide += id else settled += id
|
||||||
|
}
|
||||||
|
return CalendarVisibilityPlan(hide = hide, settled = settled)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether any calendar is switched off at system level without Calendula having
|
||||||
|
* asked for it — the condition the one-time notice explains.
|
||||||
|
*/
|
||||||
|
fun hasSystemHiddenCalendars(
|
||||||
|
calendars: List<CalendarSource>,
|
||||||
|
pendingDisabledIds: Set<Long>,
|
||||||
|
): Boolean = calendars.any { !it.isVisibleInSystem && it.id !in pendingDisabledIds }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The failure a calendar list implies, or null when there is something to show.
|
||||||
|
* Distinguishes "the device has no calendars" from "every one of them is
|
||||||
|
* switched off" (#239) — both leave the grid empty, but only the second is
|
||||||
|
* fixed from Settings → Calendars.
|
||||||
|
*
|
||||||
|
* The filter sheet's own hidden set is deliberately not folded in: emptying it
|
||||||
|
* is a deliberate act taken moments earlier, in a sheet that is still one tap
|
||||||
|
* away.
|
||||||
|
*/
|
||||||
|
fun calendarListFailure(calendars: List<CalendarSource>): FailureReason? = when {
|
||||||
|
calendars.isEmpty() -> FailureReason.NoCalendarsConfigured
|
||||||
|
calendars.none { it.isVisibleInSystem } -> FailureReason.AllCalendarsHidden
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.domain
|
||||||
|
|
||||||
|
import de.jeanlucmakiola.calendula.domain.color.Oklch
|
||||||
|
import de.jeanlucmakiola.calendula.domain.color.eventTone
|
||||||
|
import de.jeanlucmakiola.calendula.domain.color.oklchOf
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Curates an account's published event palette for the colour picker.
|
||||||
|
*
|
||||||
|
* Sync adapters differ wildly in what they publish: Google exposes a
|
||||||
|
* hand-picked two-dozen set, while CalDAV adapters (DAVx5) dump all ~147 CSS3
|
||||||
|
* named colours — including exact-value aliases (aqua/cyan, the gray/grey
|
||||||
|
* spelling pairs) and dozens of visually indistinguishable whites and grays
|
||||||
|
* (#22).
|
||||||
|
*
|
||||||
|
* Crucially, curation runs against the colour the picker actually *paints*, not
|
||||||
|
* the raw provider value — and it gets that colour from the same [eventTone]
|
||||||
|
* the picker calls, rather than from a copy of its shaping kept in step by hand.
|
||||||
|
* Because a harmonised container pins lightness, the raw palette's lightness
|
||||||
|
* axis is invisible on screen: two raw colours that look different — a navy and
|
||||||
|
* a mid blue — paint as one swatch, and every neutral (black, the grays, white)
|
||||||
|
* paints as the same grey. Judging distinctness in raw space, as before, left
|
||||||
|
* near-identical painted swatches and stranded the neutrals as a run of
|
||||||
|
* look-alike tints at the end of the grid.
|
||||||
|
*
|
||||||
|
* Three steps, all in painted space:
|
||||||
|
* 1. Collapse swatches that paint identically to one (alphabetically-first key
|
||||||
|
* wins, deterministically) — this folds aliases, dark/light shades of a
|
||||||
|
* hue, and all the neutrals together.
|
||||||
|
* 2. Oversized palettes (> [CURATION_TRIGGER_SIZE]) drop the neutral-origin
|
||||||
|
* swatches — with lightness pinned, a grey source paints as plain grey, so
|
||||||
|
* "has no hue left" is simply zero chroma — and are then thinned to visually
|
||||||
|
* distinct colours: most vivid first, a colour is kept only when at least
|
||||||
|
* [MIN_DISTANCE] away in Oklab from every colour already kept. Small
|
||||||
|
* palettes are already curated by their adapter and pass through whole.
|
||||||
|
* 3. The survivors are ordered like a rainbow — continuously by painted hue —
|
||||||
|
* with the wheel cut at its single widest empty gap so the one unavoidable
|
||||||
|
* seam lands in dead space and no hue family is torn across both ends.
|
||||||
|
*
|
||||||
|
* Every surviving option keeps its provider [EventColorOption.key], so a pick
|
||||||
|
* still round-trips through sync.
|
||||||
|
*/
|
||||||
|
fun List<EventColorOption>.curatedForPicker(): List<EventColorOption> {
|
||||||
|
val painted = sortedBy { it.key }
|
||||||
|
.distinctBy { paintedArgb(it.argb) }
|
||||||
|
.map { it to oklchOf(paintedArgb(it.argb)) }
|
||||||
|
val kept = if (painted.size <= CURATION_TRIGGER_SIZE) {
|
||||||
|
painted
|
||||||
|
} else {
|
||||||
|
thin(painted.filter { (_, painted) -> painted.chroma > 0f })
|
||||||
|
}
|
||||||
|
return orderAroundWheel(kept).map { (option, _) -> option }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Orders swatches continuously around the (painted) hue wheel, then cuts the
|
||||||
|
* circle at its widest angular gap so the single seam lands in empty space
|
||||||
|
* instead of mid-family. Saturation breaks ties, vivid first.
|
||||||
|
*/
|
||||||
|
private fun orderAroundWheel(
|
||||||
|
swatches: List<Pair<EventColorOption, Oklch>>,
|
||||||
|
): List<Pair<EventColorOption, Oklch>> {
|
||||||
|
if (swatches.size < 2) return swatches
|
||||||
|
val byHue = swatches.sortedWith(
|
||||||
|
compareBy({ (_, painted) -> painted.hue }, { (_, painted) -> -painted.chroma }),
|
||||||
|
)
|
||||||
|
// Split the wheel after the largest empty arc between neighbouring hues;
|
||||||
|
// the default is the wrap gap (last hue back round to the first), i.e. the
|
||||||
|
// familiar 0→360 order, and we only rotate away from it for a wider void.
|
||||||
|
var cutAfter = byHue.lastIndex
|
||||||
|
var widestGap = 360f - byHue.last().second.hue + byHue.first().second.hue
|
||||||
|
for (i in 0 until byHue.lastIndex) {
|
||||||
|
val gap = byHue[i + 1].second.hue - byHue[i].second.hue
|
||||||
|
if (gap > widestGap) {
|
||||||
|
widestGap = gap
|
||||||
|
cutAfter = i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return byHue.subList(cutAfter + 1, byHue.size) + byHue.subList(0, cutAfter + 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Greedy max-distance filter: vivid colours stake out clusters first. */
|
||||||
|
private fun thin(
|
||||||
|
swatches: List<Pair<EventColorOption, Oklch>>,
|
||||||
|
): List<Pair<EventColorOption, Oklch>> {
|
||||||
|
val byVividness = swatches
|
||||||
|
.sortedWith(
|
||||||
|
compareByDescending<Pair<EventColorOption, Oklch>> { it.second.chroma }
|
||||||
|
.thenBy { it.first.key },
|
||||||
|
)
|
||||||
|
val kept = mutableListOf<Pair<EventColorOption, Oklch>>()
|
||||||
|
for (candidate in byVividness) {
|
||||||
|
if (kept.none { it.second.distanceTo(candidate.second) < MIN_DISTANCE }) kept += candidate
|
||||||
|
}
|
||||||
|
return kept
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The colour the picker paints for [argb]; the light theme stands in as the
|
||||||
|
* reference, since a harmonised container differs only in lightness by theme
|
||||||
|
* and curation compares hue and chroma. */
|
||||||
|
private fun paintedArgb(argb: Int): Int =
|
||||||
|
eventTone(argb, dark = false, harmonise = true).container
|
||||||
|
|
||||||
|
/** Palettes at most this big skip the thinning (Google's ~26 pass through). */
|
||||||
|
private const val CURATION_TRIGGER_SIZE = 36
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Minimum Oklab distance between surviving painted swatches. Painted colours all
|
||||||
|
* share one lightness, so this is really a hue/chroma separation — far enough
|
||||||
|
* apart that two swatches never read as the same colour in the grid.
|
||||||
|
*/
|
||||||
|
private const val MIN_DISTANCE = 0.025f
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The palette entry closest to [argb], or null when the account publishes no
|
||||||
|
* palette (its calendars then take a raw `EVENT_COLOR` instead).
|
||||||
|
*
|
||||||
|
* Used to land a colour that came from outside the account — an imported `.ics`
|
||||||
|
* carries an arbitrary ARGB, while a palette calendar only accepts one of its
|
||||||
|
* own keys. Distance is measured in Oklab, so the match is the one that looks
|
||||||
|
* closest rather than the one that is closest in RGB coordinates.
|
||||||
|
*/
|
||||||
|
fun List<EventColorOption>.nearestTo(argb: Int): EventColorOption? {
|
||||||
|
val target = oklchOf(argb)
|
||||||
|
return minByOrNull { oklchOf(it.argb).distanceTo(target) }
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.domain
|
||||||
|
|
||||||
|
import kotlinx.datetime.TimeZone
|
||||||
|
import kotlinx.datetime.atStartOfDayIn
|
||||||
|
import kotlin.time.Instant
|
||||||
|
|
||||||
|
/** Lower values appear first in lists and get the upper visible lanes in grids. */
|
||||||
|
fun EventInstance.displayPriority(zone: TimeZone): Int = when {
|
||||||
|
isCrossedOut -> 3
|
||||||
|
spansMultipleDays(zone) -> 0
|
||||||
|
coversWholeDays(zone) -> 1
|
||||||
|
else -> 2
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shared order for agenda and split day lists. Grid bars add their lane geometry.
|
||||||
|
* Each event's priority is worked out once, not on every comparison.
|
||||||
|
*/
|
||||||
|
fun List<EventInstance>.sortedForDisplay(zone: TimeZone): List<EventInstance> =
|
||||||
|
map { Triple(it, it.displayPriority(zone), it.displayStart(zone)) }
|
||||||
|
.sortedWith(
|
||||||
|
compareBy<Triple<EventInstance, Int, Instant>> { it.second }
|
||||||
|
.thenBy { it.third }
|
||||||
|
.thenBy { it.first.title }
|
||||||
|
.thenBy { it.first.instanceId },
|
||||||
|
)
|
||||||
|
.map { it.first }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Where an event starts for ordering: a whole-day event at local midnight of its
|
||||||
|
* first day, since an all-day one is stored at UTC midnight and would otherwise
|
||||||
|
* sort around timed events by the device's offset (#296).
|
||||||
|
*/
|
||||||
|
internal fun EventInstance.displayStart(zone: TimeZone): Instant =
|
||||||
|
if (coversWholeDays(zone)) spanFirstDay(zone).atStartOfDayIn(zone) else start
|
||||||
@@ -1,29 +1,57 @@
|
|||||||
package de.jeanlucmakiola.calendula.domain
|
package de.jeanlucmakiola.calendula.domain
|
||||||
|
|
||||||
|
import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder
|
||||||
|
import de.jeanlucmakiola.calendula.domain.reminders.splitTimedReminders
|
||||||
import kotlinx.datetime.LocalDate
|
import kotlinx.datetime.LocalDate
|
||||||
import kotlinx.datetime.LocalDateTime
|
import kotlinx.datetime.LocalDateTime
|
||||||
import kotlinx.datetime.LocalTime
|
import kotlinx.datetime.LocalTime
|
||||||
import kotlinx.datetime.TimeZone
|
import kotlinx.datetime.TimeZone
|
||||||
|
import kotlinx.datetime.UtcOffset
|
||||||
import kotlinx.datetime.toLocalDateTime
|
import kotlinx.datetime.toLocalDateTime
|
||||||
import kotlin.time.Instant
|
import kotlin.time.Instant
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* User input for creating an event (and, from v1.3, editing one). Times are
|
* User input for creating an event (and, from v1.3, editing one). Times are
|
||||||
* wall-clock values in the device zone; the data layer translates them to
|
* wall-clock values in [timezone]; the data layer translates them to provider
|
||||||
* provider millis (all-day events normalise to UTC midnights there).
|
* millis (all-day events normalise to UTC midnights there).
|
||||||
*/
|
*/
|
||||||
data class EventForm(
|
data class EventForm(
|
||||||
val calendarId: Long?,
|
val calendarId: Long?,
|
||||||
val title: String = "",
|
val title: String = "",
|
||||||
val isAllDay: Boolean = false,
|
val isAllDay: Boolean = false,
|
||||||
val start: LocalDateTime,
|
val start: FormTime,
|
||||||
val end: LocalDateTime,
|
val end: FormTime,
|
||||||
|
/**
|
||||||
|
* The zone [start]/[end] are wall-clock values in, or null to follow the
|
||||||
|
* device — null is not "no zone", it is "whichever zone the device is in
|
||||||
|
* when this is saved", which is what an event authored and lived in one
|
||||||
|
* place wants. The data layer resolves it at write time and always stamps a
|
||||||
|
* concrete `EVENT_TIMEZONE`.
|
||||||
|
*
|
||||||
|
* A non-null value pins the event to a zone regardless of where the device
|
||||||
|
* is, so it keeps tracking that zone's offset across DST. [toEditForm] only
|
||||||
|
* sets it when the stored zone differs from the device's, so merely opening
|
||||||
|
* a local event never reveals the field — and re-opening a pinned one in
|
||||||
|
* another zone round-trips it rather than silently re-anchoring it.
|
||||||
|
*
|
||||||
|
* Always null for all-day events: those are date-anchored, not zone-anchored
|
||||||
|
* (see [EventFormField.Timezone] and the data layer's UTC-midnight rule).
|
||||||
|
*/
|
||||||
|
val timezone: String? = null,
|
||||||
val location: String = "",
|
val location: String = "",
|
||||||
val description: String = "",
|
val description: String = "",
|
||||||
/** Reminder lead times in minutes before the start, deduplicated. */
|
/** Reminder lead times in minutes before the start, deduplicated. */
|
||||||
val reminders: List<Int> = emptyList(),
|
val reminders: List<Int> = emptyList(),
|
||||||
|
/**
|
||||||
|
* "N days before at HH:MM" reminders of a timed event (#459), written as lead
|
||||||
|
* times measured from [start] at save time. Ignored while [isAllDay], so a
|
||||||
|
* round trip through all-day keeps them.
|
||||||
|
*/
|
||||||
|
val fixedReminders: List<FixedTimeReminder> = emptyList(),
|
||||||
val availability: Availability = Availability.Busy,
|
val availability: Availability = Availability.Busy,
|
||||||
val accessLevel: AccessLevel = AccessLevel.Default,
|
val accessLevel: AccessLevel = AccessLevel.Default,
|
||||||
|
/** Confirmed / Tentative / Cancelled (#388). */
|
||||||
|
val status: EventStatus = EventStatus.Confirmed,
|
||||||
/**
|
/**
|
||||||
* Bare RRULE value (`Events.RRULE` convention, no "RRULE:" prefix); null
|
* Bare RRULE value (`Events.RRULE` convention, no "RRULE:" prefix); null
|
||||||
* means a one-off event. May hold rules the simple picker can't express —
|
* means a one-off event. May hold rules the simple picker can't express —
|
||||||
@@ -52,6 +80,19 @@ data class EventForm(
|
|||||||
val attendees: List<EventAttendee> = emptyList(),
|
val attendees: List<EventAttendee> = emptyList(),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One end of a form's span: a wall-clock [dateTime] in the form's zone, and the
|
||||||
|
* [offset] it was read at when the fall-back hour repeats that wall clock — both
|
||||||
|
* of the hour's instants share one [LocalDateTime] (#387). Null everywhere else,
|
||||||
|
* so a time changed and changed back compares equal again. A time picked by hand
|
||||||
|
* gets its pass from [repicked]; one without an offset reads as the earlier
|
||||||
|
* pass. One value, so a time never changes without its pass. See [toFormTime].
|
||||||
|
*/
|
||||||
|
data class FormTime(val dateTime: LocalDateTime, val offset: UtcOffset? = null) {
|
||||||
|
val date: LocalDate get() = dateTime.date
|
||||||
|
val time: LocalTime get() = dateTime.time
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* One editable guest: the user controls the [email] (the identity we dedup and
|
* One editable guest: the user controls the [email] (the identity we dedup and
|
||||||
* write on), an optional display [name], and whether they're [optional] rather
|
* write on), an optional display [name], and whether they're [optional] rather
|
||||||
@@ -66,14 +107,23 @@ data class EventAttendee(
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* The form's optional sections. Which ones show by default is a user setting;
|
* The form's optional sections. Which ones show by default is a user setting;
|
||||||
* the rest unfold behind a "more fields" button.
|
* the rest unfold behind a "more fields" button. Declaration order is the order
|
||||||
|
* they're offered in, so a new constant goes where it belongs on the form, not
|
||||||
|
* at the end.
|
||||||
*/
|
*/
|
||||||
enum class EventFormField {
|
enum class EventFormField {
|
||||||
Location,
|
Location,
|
||||||
Description,
|
Description,
|
||||||
|
/**
|
||||||
|
* Pins the event's wall-clock times to a zone. Offered right after the time
|
||||||
|
* fields it qualifies, and suppressed entirely for all-day events, whose
|
||||||
|
* dates are deliberately zone-free.
|
||||||
|
*/
|
||||||
|
Timezone,
|
||||||
Reminders,
|
Reminders,
|
||||||
Recurrence,
|
Recurrence,
|
||||||
Availability,
|
Availability,
|
||||||
|
Status,
|
||||||
Visibility,
|
Visibility,
|
||||||
Color,
|
Color,
|
||||||
Attendees,
|
Attendees,
|
||||||
@@ -100,18 +150,32 @@ enum class EventFormProblem {
|
|||||||
* All-day provider times are UTC midnights with an exclusive end; the form
|
* All-day provider times are UTC midnights with an exclusive end; the form
|
||||||
* shows the last covered day and keeps placeholder wall-clock times in case
|
* shows the last covered day and keeps placeholder wall-clock times in case
|
||||||
* the user switches the event to timed.
|
* the user switches the event to timed.
|
||||||
|
*
|
||||||
|
* A timed event stored in a zone other than [zone] is prefilled *in its own
|
||||||
|
* zone* and keeps it pinned, so the wall-clock the form shows is the one the
|
||||||
|
* event means ("the New York 09:00 call") and a later save re-anchors it to the
|
||||||
|
* same zone rather than the device's.
|
||||||
*/
|
*/
|
||||||
fun EventDetail.toEditForm(beginMillis: Long, endMillis: Long, zone: TimeZone): EventForm {
|
fun EventDetail.toEditForm(beginMillis: Long, endMillis: Long, zone: TimeZone): EventForm {
|
||||||
val (start, end) = if (instance.isAllDay) {
|
// All-day events are date-anchored and carry a nominal "UTC" that is an
|
||||||
val startDate = Instant.fromEpochMilliseconds(beginMillis)
|
// anchor, not a location, so they never pin a zone.
|
||||||
.toLocalDateTime(TimeZone.UTC).date
|
val pinned = if (instance.isAllDay) {
|
||||||
val endExclusive = Instant.fromEpochMilliseconds(endMillis)
|
null
|
||||||
.toLocalDateTime(TimeZone.UTC).date
|
|
||||||
val endDate = maxOf(startDate, LocalDate.fromEpochDays(endExclusive.toEpochDays() - 1))
|
|
||||||
LocalDateTime(startDate, LocalTime(9, 0)) to LocalDateTime(endDate, LocalTime(10, 0))
|
|
||||||
} else {
|
} else {
|
||||||
Instant.fromEpochMilliseconds(beginMillis).toLocalDateTime(zone) to
|
eventTimezone
|
||||||
Instant.fromEpochMilliseconds(endMillis).toLocalDateTime(zone)
|
?.takeIf { it != zone.id }
|
||||||
|
// An unparseable id (a malformed sync row) can't be honoured or
|
||||||
|
// shown; fall back to the device zone rather than failing the open.
|
||||||
|
?.let { id -> zoneOrNull(id)?.let { id to it } }
|
||||||
|
}
|
||||||
|
val pinnedZone = pinned?.first
|
||||||
|
val formZone = pinned?.second ?: zone
|
||||||
|
val begin = Instant.fromEpochMilliseconds(beginMillis)
|
||||||
|
val finish = Instant.fromEpochMilliseconds(endMillis)
|
||||||
|
val (start, end) = if (instance.isAllDay) {
|
||||||
|
allDayFormTimes(begin.toLocalDateTime(TimeZone.UTC).date, finish.toLocalDateTime(TimeZone.UTC).date)
|
||||||
|
} else {
|
||||||
|
begin.toFormTime(formZone) to finish.toFormTime(formZone)
|
||||||
}
|
}
|
||||||
return EventForm(
|
return EventForm(
|
||||||
calendarId = instance.calendarId,
|
calendarId = instance.calendarId,
|
||||||
@@ -119,12 +183,14 @@ fun EventDetail.toEditForm(beginMillis: Long, endMillis: Long, zone: TimeZone):
|
|||||||
isAllDay = instance.isAllDay,
|
isAllDay = instance.isAllDay,
|
||||||
start = start,
|
start = start,
|
||||||
end = end,
|
end = end,
|
||||||
|
timezone = pinnedZone,
|
||||||
location = instance.location.orEmpty(),
|
location = instance.location.orEmpty(),
|
||||||
description = description.orEmpty(),
|
description = description.orEmpty(),
|
||||||
reminders = reminders.map { it.minutes }.distinct().sorted(),
|
reminders = reminders.map { it.minutes }.distinct().sorted(),
|
||||||
availability = availability,
|
availability = availability,
|
||||||
accessLevel = accessLevel,
|
accessLevel = accessLevel,
|
||||||
rrule = rrule?.removePrefix("RRULE:")?.takeIf { it.isNotBlank() },
|
status = status,
|
||||||
|
rrule = rrule.normalizedRrule(),
|
||||||
// The provider fills EVENT_COLOR from the key, so [color] is the
|
// The provider fills EVENT_COLOR from the key, so [color] is the
|
||||||
// swatch either way; a null colour means the event inherits its
|
// swatch either way; a null colour means the event inherits its
|
||||||
// calendar's colour.
|
// calendar's colour.
|
||||||
@@ -159,7 +225,7 @@ fun EventDetail.toEditForm(beginMillis: Long, endMillis: Long, zone: TimeZone):
|
|||||||
* re-deriving with the same occurrence would mask an externally moved
|
* re-deriving with the same occurrence would mask an externally moved
|
||||||
* event. Guests are covered (the form writes editable attendees), so an
|
* event. Guests are covered (the form writes editable attendees), so an
|
||||||
* external attendee change now also trips the conflict check. Still not
|
* external attendee change now also trips the conflict check. Still not
|
||||||
* covered: status, the user's own response, reminder methods, the
|
* covered: the user's own response, reminder methods, the
|
||||||
* organizer/resource rows, and a recurring event's duration.
|
* organizer/resource rows, and a recurring event's duration.
|
||||||
*/
|
*/
|
||||||
data class EditSnapshot(
|
data class EditSnapshot(
|
||||||
@@ -176,6 +242,49 @@ fun EventDetail.toEditSnapshot(beginMillis: Long, endMillis: Long, zone: TimeZon
|
|||||||
rowEnd = instance.end,
|
rowEnd = instance.end,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Form times for an all-day span stored as UTC midnights with an exclusive
|
||||||
|
* end: the last covered day (never before [start]), with placeholder
|
||||||
|
* wall-clock times kept in case the user switches the event to timed.
|
||||||
|
*/
|
||||||
|
internal fun allDayFormTimes(start: LocalDate, endExclusive: LocalDate?): Pair<FormTime, FormTime> {
|
||||||
|
val end = endExclusive?.let { maxOf(start, LocalDate.fromEpochDays(it.toEpochDays() - 1)) } ?: start
|
||||||
|
return FormTime(LocalDateTime(start, LocalTime(9, 0))) to FormTime(LocalDateTime(end, LocalTime(10, 0)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The bare RRULE value the form edits; blank means none. */
|
||||||
|
internal fun String?.normalizedRrule(): String? = this?.removePrefix("RRULE:")?.takeIf { it.isNotBlank() }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether this form may be saved apart from its series, as one modified
|
||||||
|
* occurrence or as a split-off "this & following" tail. A cancelled exception
|
||||||
|
* row is how Android records a deleted occurrence, and Google reads an inserted
|
||||||
|
* cancelled event as deleted, so either would vanish rather than show struck
|
||||||
|
* through (#388).
|
||||||
|
*/
|
||||||
|
fun EventForm.canSaveApartFromSeries(): Boolean = status != EventStatus.Cancelled
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The status a newly inserted row may carry. Google reads an inserted cancelled
|
||||||
|
* event as deleted, so every new row (a copy, an import, a calendar move or an
|
||||||
|
* exception) starts confirmed instead (#388).
|
||||||
|
*/
|
||||||
|
fun EventStatus.forNewEvent(): EventStatus = if (this == EventStatus.Cancelled) EventStatus.Confirmed else this
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether this form's times mean something else in [target] — a timed event
|
||||||
|
* pinned to another zone. False when there's nothing to disambiguate: an
|
||||||
|
* unpinned event (already in [target]), one pinned to [target] itself, an
|
||||||
|
* all-day event (no zone), or an unparseable pinned zone.
|
||||||
|
*
|
||||||
|
* The form edits a pinned event in its own zone, so this is what tells the UI
|
||||||
|
* to show the other side of the pair rather than making the user do the arithmetic.
|
||||||
|
*/
|
||||||
|
fun EventForm.isPinnedAwayFrom(target: TimeZone): Boolean {
|
||||||
|
if (isAllDay) return false
|
||||||
|
return resolvedZone(target).id != target.id
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The optional sections that hold a value in [form] — when editing, these
|
* The optional sections that hold a value in [form] — when editing, these
|
||||||
* must be visible regardless of the user's default-fields setting, or the
|
* must be visible regardless of the user's default-fields setting, or the
|
||||||
@@ -184,17 +293,29 @@ fun EventDetail.toEditSnapshot(beginMillis: Long, endMillis: Long, zone: TimeZon
|
|||||||
fun EventForm.populatedFields(): Set<EventFormField> = buildSet {
|
fun EventForm.populatedFields(): Set<EventFormField> = buildSet {
|
||||||
if (location.isNotBlank()) add(EventFormField.Location)
|
if (location.isNotBlank()) add(EventFormField.Location)
|
||||||
if (description.isNotBlank()) add(EventFormField.Description)
|
if (description.isNotBlank()) add(EventFormField.Description)
|
||||||
if (reminders.isNotEmpty()) add(EventFormField.Reminders)
|
if (timezone != null) add(EventFormField.Timezone)
|
||||||
|
if (reminders.isNotEmpty() || (!isAllDay && fixedReminders.isNotEmpty())) add(EventFormField.Reminders)
|
||||||
if (rrule != null) add(EventFormField.Recurrence)
|
if (rrule != null) add(EventFormField.Recurrence)
|
||||||
if (availability != Availability.Busy) add(EventFormField.Availability)
|
if (availability != Availability.Busy) add(EventFormField.Availability)
|
||||||
|
if (status != EventStatus.Confirmed) add(EventFormField.Status)
|
||||||
if (accessLevel != AccessLevel.Default) add(EventFormField.Visibility)
|
if (accessLevel != AccessLevel.Default) add(EventFormField.Visibility)
|
||||||
if (colorKey != null || color != null) add(EventFormField.Color)
|
if (colorKey != null || color != null) add(EventFormField.Color)
|
||||||
if (attendees.isNotEmpty()) add(EventFormField.Attendees)
|
if (attendees.isNotEmpty()) add(EventFormField.Attendees)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun EventForm.problems(): Set<EventFormProblem> = buildSet {
|
/**
|
||||||
|
* What stops this form from saving. A timed span is checked as instants in the
|
||||||
|
* form's zone (else [deviceZone]): one ending in the fall-back hour's repeat can
|
||||||
|
* end on an earlier wall clock than it starts (#387).
|
||||||
|
*/
|
||||||
|
fun EventForm.problems(deviceZone: TimeZone): Set<EventFormProblem> = buildSet {
|
||||||
if (calendarId == null) add(EventFormProblem.NoCalendar)
|
if (calendarId == null) add(EventFormProblem.NoCalendar)
|
||||||
val endsTooEarly = if (isAllDay) end.date < start.date else end < start
|
val endsTooEarly = if (isAllDay) {
|
||||||
|
end.date < start.date
|
||||||
|
} else {
|
||||||
|
val zone = resolvedZone(deviceZone)
|
||||||
|
endInstant(zone) < startInstant(zone)
|
||||||
|
}
|
||||||
if (endsTooEarly) add(EventFormProblem.EndBeforeStart)
|
if (endsTooEarly) add(EventFormProblem.EndBeforeStart)
|
||||||
// An UNTIL before the first day would make the provider generate zero
|
// An UNTIL before the first day would make the provider generate zero
|
||||||
// occurrences — the event would silently vanish from every view.
|
// occurrences — the event would silently vanish from every view.
|
||||||
@@ -203,3 +324,44 @@ fun EventForm.problems(): Set<EventFormProblem> = buildSet {
|
|||||||
add(EventFormProblem.RecurrenceEndsBeforeStart)
|
add(EventFormProblem.RecurrenceEndsBeforeStart)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A create form seeded from this occurrence, to save a copy as a new,
|
||||||
|
* independent event (#52). The recurrence is dropped — a duplicate is a single
|
||||||
|
* event. The source calendar is only requested: the editor keeps it while it can
|
||||||
|
* take new events and otherwise resolves the calendar like a new event, which
|
||||||
|
* lets a read-only event be copied into an editable one. [instance]'s own times
|
||||||
|
* carry over.
|
||||||
|
*/
|
||||||
|
fun EventDetail.toDuplicateForm(
|
||||||
|
zone: TimeZone,
|
||||||
|
knownFixed: Set<FixedTimeReminder> = emptySet(),
|
||||||
|
): EventForm =
|
||||||
|
toEditForm(
|
||||||
|
beginMillis = instance.start.toEpochMilliseconds(),
|
||||||
|
endMillis = instance.end.toEpochMilliseconds(),
|
||||||
|
zone = zone,
|
||||||
|
).withFixedTimeRemindersRead(knownFixed, zone).copy(
|
||||||
|
rrule = null,
|
||||||
|
status = status.forNewEvent(),
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This form with its timed reminders read back into lead times and
|
||||||
|
* [EventForm.fixedReminders] ([splitTimedReminders]), the wall clock taken in
|
||||||
|
* [deviceZone]. All-day forms come back untouched.
|
||||||
|
*/
|
||||||
|
fun EventForm.withFixedTimeRemindersRead(known: Set<FixedTimeReminder>, deviceZone: TimeZone): EventForm {
|
||||||
|
if (isAllDay || reminders.isEmpty()) return this
|
||||||
|
val split = splitTimedReminders(
|
||||||
|
reminders, startInstant(resolvedZone(deviceZone)), deviceZone, known, wallClock = rrule != null,
|
||||||
|
)
|
||||||
|
return copy(reminders = split.leadMinutes, fixedReminders = (fixedReminders + split.fixed).distinct())
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The offsets [EventForm.fixedReminders] store for this form's start; empty for an all-day form. */
|
||||||
|
fun EventForm.fixedReminderOffsets(deviceZone: TimeZone): List<Int> {
|
||||||
|
if (isAllDay || fixedReminders.isEmpty()) return emptyList()
|
||||||
|
val start = startInstant(resolvedZone(deviceZone))
|
||||||
|
return fixedReminders.map { it.offsetMinutes(start, deviceZone, wallClock = rrule != null) }
|
||||||
|
}
|
||||||
@@ -0,0 +1,239 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.domain
|
||||||
|
|
||||||
|
import kotlinx.datetime.DateTimeUnit
|
||||||
|
import kotlinx.datetime.TimeZone
|
||||||
|
import kotlinx.datetime.YearMonth
|
||||||
|
import kotlinx.datetime.atStartOfDayIn
|
||||||
|
import kotlinx.datetime.number
|
||||||
|
import kotlinx.datetime.plus
|
||||||
|
import kotlinx.datetime.toLocalDateTime
|
||||||
|
import kotlin.time.Instant
|
||||||
|
|
||||||
|
/** An event with the free text the search may have matched it on. */
|
||||||
|
data class SearchCandidate(
|
||||||
|
val event: EventInstance,
|
||||||
|
val description: String? = null,
|
||||||
|
/** Null when the event has none: [EventInstance.title] is then a display
|
||||||
|
* placeholder, which the query must not catch on. */
|
||||||
|
val title: String? = event.title,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** A matched run inside one of a hit's texts, for highlighting. */
|
||||||
|
data class MatchSpan(val start: Int, val end: Int)
|
||||||
|
|
||||||
|
/** The part of a description a token matched, elided to what fits a row. */
|
||||||
|
data class DescriptionSnippet(
|
||||||
|
val text: String,
|
||||||
|
val spans: List<MatchSpan>,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** One result: the event, plus where the query matched it. */
|
||||||
|
data class SearchHit(
|
||||||
|
val event: EventInstance,
|
||||||
|
val titleSpans: List<MatchSpan> = emptyList(),
|
||||||
|
val locationSpans: List<MatchSpan> = emptyList(),
|
||||||
|
val descriptionSnippet: DescriptionSnippet? = null,
|
||||||
|
/** Already over, so the row can say so. Finished-today counts. */
|
||||||
|
val isPast: Boolean = false,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** One month's worth of hits, as the results list draws them under a header. */
|
||||||
|
data class SearchMonth(
|
||||||
|
val year: Int,
|
||||||
|
/** 1–12, so the UI can build the month's first day for a localized label. */
|
||||||
|
val monthNumber: Int,
|
||||||
|
val hits: List<SearchHit>,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** A finished search: a calendar of hits, plus the description-only ones. */
|
||||||
|
data class SearchResults(
|
||||||
|
val months: List<SearchMonth>,
|
||||||
|
val inDescriptions: List<SearchHit>,
|
||||||
|
) {
|
||||||
|
val isEmpty: Boolean get() = months.isEmpty() && inDescriptions.isEmpty()
|
||||||
|
|
||||||
|
/** Every hit, whichever section it sits in — for select-all and delete. */
|
||||||
|
val allHits: List<SearchHit> get() = months.flatMap { it.hits } + inDescriptions
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Turning a typed query into the results list.
|
||||||
|
*
|
||||||
|
* An event has to carry *every* whitespace-separated token, each in any of
|
||||||
|
* title / location / description; case is folded in Kotlin rather than by SQL's
|
||||||
|
* ASCII-only `LIKE`, so "ärzte" finds "Ärzte".
|
||||||
|
*
|
||||||
|
* Results are a calendar, not a ranking: months from the current one, then
|
||||||
|
* forwards, then backwards, and inside a month what is still to come before
|
||||||
|
* what has passed. The day is the boundary, not the moment. A hit the query
|
||||||
|
* only reached through its description is held back in
|
||||||
|
* [SearchResults.inDescriptions] rather than dated among the real ones.
|
||||||
|
*/
|
||||||
|
object EventSearch {
|
||||||
|
|
||||||
|
/** Characters of description kept around the match in a row's snippet. */
|
||||||
|
private const val SNIPPET_LENGTH = 96
|
||||||
|
|
||||||
|
/** Characters of lead-in shown before the match, when there is room. */
|
||||||
|
private const val SNIPPET_LEAD = 24
|
||||||
|
|
||||||
|
private val WHITESPACE = Regex("\\s+")
|
||||||
|
|
||||||
|
/** Shared with the data layer so its SQL pre-filter tokenises identically. */
|
||||||
|
fun tokenize(query: String): List<String> =
|
||||||
|
query.trim().split(WHITESPACE).filter { it.isNotEmpty() }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Search [candidates] for [query], dropping any that don't carry every token.
|
||||||
|
* [now] marks a hit as over, [todayStart] is where it stops being current.
|
||||||
|
* [zone] places each event on the calendar through the span rule, so an
|
||||||
|
* all-day event keeps its own day whichever side of UTC we are on (#82).
|
||||||
|
*/
|
||||||
|
fun search(
|
||||||
|
candidates: List<SearchCandidate>,
|
||||||
|
query: String,
|
||||||
|
now: Instant,
|
||||||
|
todayStart: Instant,
|
||||||
|
zone: TimeZone,
|
||||||
|
): SearchResults {
|
||||||
|
val tokens = tokenize(query)
|
||||||
|
if (tokens.isEmpty()) return SearchResults(emptyList(), emptyList())
|
||||||
|
|
||||||
|
val today = todayStart.toLocalDateTime(zone).date
|
||||||
|
val matched = candidates.mapNotNull { candidate -> match(candidate, tokens, now, zone) }
|
||||||
|
val (upcoming, past) = matched.partition { it.event.spanLastDay(zone) >= today }
|
||||||
|
// What is left reads forwards; what is behind us reads backwards from
|
||||||
|
// today, nearest first.
|
||||||
|
val ordered = upcoming.sortedBy { it.event.dayStart(zone) } +
|
||||||
|
past.sortedByDescending { it.event.dayStart(zone) }
|
||||||
|
|
||||||
|
val (inDescriptions, dated) = ordered.partition { it.descriptionOnly }
|
||||||
|
return SearchResults(
|
||||||
|
months = groupByMonth(dated, zone, todayStart),
|
||||||
|
inDescriptions = inDescriptions.map { it.hit },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Months from the current one, then forwards, then backwards. */
|
||||||
|
private fun groupByMonth(
|
||||||
|
dated: List<Matched>,
|
||||||
|
zone: TimeZone,
|
||||||
|
todayStart: Instant,
|
||||||
|
): List<SearchMonth> {
|
||||||
|
val current = todayStart.toLocalDateTime(zone).date.let { YearMonth(it.year, it.month) }
|
||||||
|
val groups = dated.groupBy { m -> m.event.spanFirstDay(zone).let { YearMonth(it.year, it.month) } }
|
||||||
|
val (behind, ahead) = groups.keys.partition { it < current }
|
||||||
|
return (ahead.sorted() + behind.sortedDescending()).map { month ->
|
||||||
|
SearchMonth(
|
||||||
|
year = month.year,
|
||||||
|
monthNumber = month.month.number,
|
||||||
|
hits = groups.getValue(month).map { it.hit },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun match(
|
||||||
|
candidate: SearchCandidate,
|
||||||
|
tokens: List<String>,
|
||||||
|
now: Instant,
|
||||||
|
zone: TimeZone,
|
||||||
|
): Matched? {
|
||||||
|
val title = candidate.title?.takeIf { it.isNotBlank() }
|
||||||
|
val location = candidate.event.location?.takeIf { it.isNotBlank() }
|
||||||
|
// Collapsed so a multi-line description matches the way it is drawn.
|
||||||
|
val rich = candidate.description?.let(::descriptionRichText)
|
||||||
|
val description = rich?.text
|
||||||
|
?.replace(WHITESPACE, " ")
|
||||||
|
?.trim()
|
||||||
|
?.takeIf { it.isNotEmpty() }
|
||||||
|
// A link's address isn't in the drawn text, but "zoom.us" should still find the invite.
|
||||||
|
val linkUrls = rich?.links.orEmpty().map { it.url }
|
||||||
|
|
||||||
|
// Mid-word counts: "termin" has to keep finding "Zahnarzttermin".
|
||||||
|
val present = { token: String ->
|
||||||
|
title?.contains(token, ignoreCase = true) == true ||
|
||||||
|
location?.contains(token, ignoreCase = true) == true ||
|
||||||
|
description?.contains(token, ignoreCase = true) == true ||
|
||||||
|
linkUrls.any { it.contains(token, ignoreCase = true) }
|
||||||
|
}
|
||||||
|
if (!tokens.all(present)) return null
|
||||||
|
|
||||||
|
val descriptionSpans = description?.let { spansIn(it, tokens) }.orEmpty()
|
||||||
|
val titleSpans = title?.let { spansIn(it, tokens) }.orEmpty()
|
||||||
|
val locationSpans = location?.let { spansIn(it, tokens) }.orEmpty()
|
||||||
|
return Matched(
|
||||||
|
hit = SearchHit(
|
||||||
|
event = candidate.event,
|
||||||
|
titleSpans = titleSpans,
|
||||||
|
locationSpans = locationSpans,
|
||||||
|
descriptionSnippet = description
|
||||||
|
?.takeIf { descriptionSpans.isNotEmpty() }
|
||||||
|
?.let { snippet(it, descriptionSpans) },
|
||||||
|
isPast = candidate.event.dayEnd(zone) < now,
|
||||||
|
),
|
||||||
|
// Nothing in the name or the place caught the query: it is only here
|
||||||
|
// for something in its notes.
|
||||||
|
descriptionOnly = titleSpans.isEmpty() && locationSpans.isEmpty(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every occurrence of every token in [text], merged where they overlap. */
|
||||||
|
private fun spansIn(text: String, tokens: List<String>): List<MatchSpan> {
|
||||||
|
val raw = mutableListOf<MatchSpan>()
|
||||||
|
for (token in tokens) {
|
||||||
|
var index = text.indexOf(token, startIndex = 0, ignoreCase = true)
|
||||||
|
while (index >= 0) {
|
||||||
|
raw += MatchSpan(index, index + token.length)
|
||||||
|
index = text.indexOf(token, startIndex = index + 1, ignoreCase = true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (raw.isEmpty()) return emptyList()
|
||||||
|
val sorted = raw.sortedBy { it.start }
|
||||||
|
val merged = mutableListOf(sorted.first())
|
||||||
|
for (span in sorted.drop(1)) {
|
||||||
|
val last = merged.last()
|
||||||
|
if (span.start <= last.end) {
|
||||||
|
merged[merged.lastIndex] = MatchSpan(last.start, maxOf(last.end, span.end))
|
||||||
|
} else {
|
||||||
|
merged += span
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return merged
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A window of [description] around its first match, elided at both ends,
|
||||||
|
* with the spans rebased onto it and any falling outside dropped.
|
||||||
|
*/
|
||||||
|
private fun snippet(description: String, spans: List<MatchSpan>): DescriptionSnippet {
|
||||||
|
if (description.length <= SNIPPET_LENGTH) {
|
||||||
|
return DescriptionSnippet(description, spans)
|
||||||
|
}
|
||||||
|
val first = spans.first().start
|
||||||
|
val start = (first - SNIPPET_LEAD).coerceIn(0, (description.length - SNIPPET_LENGTH))
|
||||||
|
val end = (start + SNIPPET_LENGTH).coerceAtMost(description.length)
|
||||||
|
val prefix = if (start > 0) "…" else ""
|
||||||
|
val suffix = if (end < description.length) "…" else ""
|
||||||
|
val text = prefix + description.substring(start, end) + suffix
|
||||||
|
val shift = prefix.length - start
|
||||||
|
val rebased = spans
|
||||||
|
.filter { it.start >= start && it.end <= end }
|
||||||
|
.map { MatchSpan(it.start + shift, it.end + shift) }
|
||||||
|
return DescriptionSnippet(text, rebased)
|
||||||
|
}
|
||||||
|
|
||||||
|
private data class Matched(val hit: SearchHit, val descriptionOnly: Boolean) {
|
||||||
|
val event: EventInstance get() = hit.event
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The event's first day as an instant in [zone]. An all-day event sits at
|
||||||
|
* UTC midnight, so its raw start would rank it on a day it isn't drawn on.
|
||||||
|
*/
|
||||||
|
private fun EventInstance.dayStart(zone: TimeZone): Instant =
|
||||||
|
if (isAllDay) spanFirstDay(zone).atStartOfDayIn(zone) else start
|
||||||
|
|
||||||
|
/** The moment the event's last day is over in [zone], exclusive. */
|
||||||
|
private fun EventInstance.dayEnd(zone: TimeZone): Instant =
|
||||||
|
if (isAllDay) spanLastDay(zone).plus(1, DateTimeUnit.DAY).atStartOfDayIn(zone) else end
|
||||||
|
}
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.domain
|
||||||
|
|
||||||
|
import kotlinx.datetime.DateTimeUnit
|
||||||
|
import kotlinx.datetime.LocalDateTime
|
||||||
|
import kotlinx.datetime.TimeZone
|
||||||
|
import kotlinx.datetime.UtcOffset
|
||||||
|
import kotlinx.datetime.offsetAt
|
||||||
|
import kotlinx.datetime.plus
|
||||||
|
import kotlinx.datetime.toInstant
|
||||||
|
import kotlinx.datetime.toJavaLocalDateTime
|
||||||
|
import kotlinx.datetime.toJavaZoneId
|
||||||
|
import kotlinx.datetime.toJavaZoneOffset
|
||||||
|
import kotlinx.datetime.toKotlinUtcOffset
|
||||||
|
import kotlinx.datetime.toLocalDateTime
|
||||||
|
import java.time.ZonedDateTime
|
||||||
|
import kotlin.time.Instant
|
||||||
|
import kotlin.time.toJavaInstant
|
||||||
|
import kotlin.time.toKotlinInstant
|
||||||
|
|
||||||
|
/** [id] as a zone, or null when the tz database doesn't know it. */
|
||||||
|
internal fun zoneOrNull(id: String): TimeZone? = runCatching { TimeZone.of(id) }.getOrNull()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The zone this form's wall-clock times mean, matching what the data layer
|
||||||
|
* resolves them in at write time: the form's own pinned zone, else [deviceZone].
|
||||||
|
*/
|
||||||
|
fun EventForm.resolvedZone(deviceZone: TimeZone): TimeZone =
|
||||||
|
timezone?.let(::zoneOrNull) ?: deviceZone
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This wall-clock time in [zone], at [preferred] when the fall-back hour repeats
|
||||||
|
* it and that is one of its two offsets — otherwise the earlier one (#387).
|
||||||
|
*/
|
||||||
|
fun LocalDateTime.resolveIn(zone: TimeZone, preferred: UtcOffset?): Instant =
|
||||||
|
ZonedDateTime.ofLocal(toJavaLocalDateTime(), zone.toJavaZoneId(), preferred?.toJavaZoneOffset())
|
||||||
|
.toInstant().toKotlinInstant()
|
||||||
|
|
||||||
|
/** Whether this instant's wall clock in [zone] is one the fall-back hour repeats. */
|
||||||
|
fun Instant.inRepeatedHour(zone: TimeZone): Boolean {
|
||||||
|
val zid = zone.toJavaZoneId()
|
||||||
|
return zid.rules.getTransition(java.time.LocalDateTime.ofInstant(toJavaInstant(), zid))?.isOverlap == true
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [at]'s offset in this zone when its wall clock is one the fall-back hour
|
||||||
|
* repeats, else null: elsewhere the wall clock alone already names the instant.
|
||||||
|
* What a [FormTime.offset] holds (#387).
|
||||||
|
*/
|
||||||
|
fun TimeZone.repeatedHourOffsetAt(at: Instant): UtcOffset? = if (at.inRepeatedHour(this)) offsetAt(at) else null
|
||||||
|
|
||||||
|
/** This instant as a [FormTime] in [zone], keeping its pass of a repeated hour. */
|
||||||
|
fun Instant.toFormTime(zone: TimeZone): FormTime = FormTime(toLocalDateTime(zone), zone.repeatedHourOffsetAt(this))
|
||||||
|
|
||||||
|
/** This time as an instant in [zone], on its kept pass of a repeated hour. */
|
||||||
|
fun FormTime.instantIn(zone: TimeZone): Instant = dateTime.resolveIn(zone, offset)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This edge of an event moved to [picked] by hand — a picker or a resize handle —
|
||||||
|
* as a [FormTime] in [zone]. A time in the spring-forward gap moves on to the
|
||||||
|
* real one, as the provider would read it. A wall clock the fall-back hour
|
||||||
|
* repeats has two instants; which one it means (#387):
|
||||||
|
* - [original]'s, when [picked] is the wall clock the event was opened with, so
|
||||||
|
* a time changed and changed back is the time it was;
|
||||||
|
* - else the one that moves the edge in the direction the user moved it:
|
||||||
|
* earlier than this edge's instant when [picked] is before [shownAt] (where
|
||||||
|
* the edge was on screen), later when after;
|
||||||
|
* - kept within [notBefore]..[notAfter] (the other edge), and to the ones
|
||||||
|
* [drawable] accepts — where the screen can show it — when any fit.
|
||||||
|
*/
|
||||||
|
fun FormTime.repicked(
|
||||||
|
picked: LocalDateTime,
|
||||||
|
zone: TimeZone,
|
||||||
|
shownAt: LocalDateTime = dateTime,
|
||||||
|
original: FormTime? = null,
|
||||||
|
notBefore: Instant? = null,
|
||||||
|
notAfter: Instant? = null,
|
||||||
|
drawable: (Instant) -> Boolean = { true },
|
||||||
|
): FormTime {
|
||||||
|
if (picked == dateTime && picked == shownAt) return this
|
||||||
|
val offsets = zone.toJavaZoneId().rules.getValidOffsets(picked.toJavaLocalDateTime())
|
||||||
|
if (offsets.isEmpty()) return FormTime(picked).instantIn(zone).toFormTime(zone)
|
||||||
|
if (offsets.size == 1) return FormTime(picked)
|
||||||
|
val passes = offsets.map { picked.toInstant(it.toKotlinUtcOffset()) }.sorted()
|
||||||
|
val bounded = passes.filter { (notBefore == null || it >= notBefore) && (notAfter == null || it <= notAfter) }
|
||||||
|
.ifEmpty { passes }
|
||||||
|
val fitting = bounded.filter(drawable).ifEmpty { bounded }
|
||||||
|
if (original?.dateTime == picked && original.offset != null && original.instantIn(zone) in fitting) return original
|
||||||
|
val from = instantIn(zone)
|
||||||
|
val chosen = when {
|
||||||
|
picked < shownAt -> fitting.lastOrNull { it < from }
|
||||||
|
picked > shownAt -> fitting.firstOrNull { it > from }
|
||||||
|
else -> null
|
||||||
|
} ?: fitting.minBy { (it - from).absoluteValue }
|
||||||
|
return chosen.toFormTime(zone)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The form's start as an instant in [zone]. */
|
||||||
|
fun EventForm.startInstant(zone: TimeZone): Instant = start.instantIn(zone)
|
||||||
|
|
||||||
|
/** The form's end as an instant in [zone]. */
|
||||||
|
fun EventForm.endInstant(zone: TimeZone): Instant = end.instantIn(zone)
|
||||||
|
|
||||||
|
/** The form's timed span set to these instants, read in [zone]. */
|
||||||
|
fun EventForm.withTimes(start: Instant, end: Instant, zone: TimeZone): EventForm =
|
||||||
|
copy(start = start.toFormTime(zone), end = end.toFormTime(zone))
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The form pinned to [zoneId] (null: the device). A kept pass of a repeated hour
|
||||||
|
* was one of the old zone's, so it goes when the zone the times mean changes.
|
||||||
|
*/
|
||||||
|
fun EventForm.withTimezone(zoneId: String?, deviceZone: TimeZone): EventForm {
|
||||||
|
val pinned = copy(timezone = zoneId)
|
||||||
|
if (pinned.resolvedZone(deviceZone) == resolvedZone(deviceZone)) return pinned
|
||||||
|
return pinned.withoutKeptPasses()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The form with its start picked by hand, keeping its length. A repeated hour's
|
||||||
|
* pass is [repicked]: [original] is the start the event was opened with.
|
||||||
|
*/
|
||||||
|
fun EventForm.withStart(start: LocalDateTime, zone: TimeZone, original: FormTime? = null): EventForm {
|
||||||
|
val span = endInstant(zone) - startInstant(zone)
|
||||||
|
val startAt = this.start.repicked(start, zone, original = original).instantIn(zone)
|
||||||
|
return withTimes(startAt, startAt + span, zone)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The form with its end picked by hand. A repeated hour's pass is [repicked],
|
||||||
|
* kept after the start where it can be: [original] is the end the event was
|
||||||
|
* opened with.
|
||||||
|
*/
|
||||||
|
fun EventForm.withEnd(end: LocalDateTime, zone: TimeZone, original: FormTime? = null): EventForm =
|
||||||
|
copy(end = this.end.repicked(end, zone, original = original, notBefore = startInstant(zone)))
|
||||||
|
|
||||||
|
/** The form with no kept passes: its times as the wall clock alone says them. */
|
||||||
|
fun EventForm.withoutKeptPasses(): EventForm = copy(start = FormTime(start.dateTime), end = FormTime(end.dateTime))
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The form moved so it starts at [newStart], keeping its **instant** duration —
|
||||||
|
* a recurring event's length travels to the provider as `DURATION`, so keeping
|
||||||
|
* wall clock instead would rewrite the series' length across a DST boundary.
|
||||||
|
*
|
||||||
|
* All-day events are date-anchored — use [shiftedByDays]; this returns them
|
||||||
|
* untouched.
|
||||||
|
*/
|
||||||
|
fun EventForm.shiftedTo(newStart: Instant, deviceZone: TimeZone): EventForm {
|
||||||
|
if (isAllDay) return this
|
||||||
|
val zone = resolvedZone(deviceZone)
|
||||||
|
val span = endInstant(zone) - startInstant(zone)
|
||||||
|
return withTimes(newStart, newStart + span, zone)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The form moved [days] calendar days, keeping its time of day and its span.
|
||||||
|
* All-day events are pure date arithmetic; a timed one preserves its **instant**
|
||||||
|
* duration, for the same reason [shiftedTo] does.
|
||||||
|
*/
|
||||||
|
fun EventForm.shiftedByDays(days: Int, deviceZone: TimeZone): EventForm {
|
||||||
|
if (days == 0) return this
|
||||||
|
val newStart = LocalDateTime(start.date.plus(days, DateTimeUnit.DAY), start.time)
|
||||||
|
if (isAllDay) {
|
||||||
|
return copy(
|
||||||
|
start = FormTime(newStart),
|
||||||
|
end = FormTime(LocalDateTime(end.date.plus(days, DateTimeUnit.DAY), end.time)),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
val zone = resolvedZone(deviceZone)
|
||||||
|
val span = endInstant(zone) - startInstant(zone)
|
||||||
|
val startAt = FormTime(newStart, start.offset).instantIn(zone)
|
||||||
|
// The start keeps the wall clock it was moved to, even one the spring-forward
|
||||||
|
// gap skips, so a recurring series still sees a whole-day move.
|
||||||
|
val movedStart = startAt.toFormTime(zone).takeIf { it.dateTime == newStart } ?: FormTime(newStart)
|
||||||
|
return copy(start = movedStart, end = (startAt + span).toFormTime(zone))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The form with new start and end, each in the form's own zone — a resize. An
|
||||||
|
* all-day event becomes timed: one dragged out of the all-day strip.
|
||||||
|
*/
|
||||||
|
fun EventForm.resizedTo(newStart: Instant, newEnd: Instant, deviceZone: TimeZone): EventForm {
|
||||||
|
val timed = copy(isAllDay = false)
|
||||||
|
return timed.withTimes(newStart, newEnd, timed.resolvedZone(deviceZone))
|
||||||
|
}
|
||||||
@@ -0,0 +1,396 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.domain
|
||||||
|
|
||||||
|
/** Inline formatting an HTML description keeps; fonts, sizes and colours are dropped. */
|
||||||
|
enum class InlineStyle { Bold, Italic, Underline, Strikethrough, Superscript, Subscript, Monospace }
|
||||||
|
|
||||||
|
data class StyleRange(val start: Int, val end: Int, val style: InlineStyle)
|
||||||
|
|
||||||
|
/** A link from an `<a href>`, spanning [start] until [end] (exclusive). */
|
||||||
|
data class LinkRange(val start: Int, val end: Int, val url: String)
|
||||||
|
|
||||||
|
/** Text as drawn, with the formatting and links that sit on it. Plain text has neither. */
|
||||||
|
data class RichText(
|
||||||
|
val text: String,
|
||||||
|
val styles: List<StyleRange> = emptyList(),
|
||||||
|
val links: List<LinkRange> = emptyList(),
|
||||||
|
) {
|
||||||
|
/**
|
||||||
|
* [text] with each link's address after it, where the text doesn't already
|
||||||
|
* show it, so a copied "Join the meeting" still carries its URL.
|
||||||
|
*/
|
||||||
|
fun copyText(): String {
|
||||||
|
if (links.isEmpty()) return text
|
||||||
|
val out = StringBuilder(text)
|
||||||
|
for (link in links.sortedByDescending { it.end }) {
|
||||||
|
val address = link.url.removePrefix("mailto:").removePrefix("tel:")
|
||||||
|
if (address !in text.substring(link.start, link.end)) out.insert(link.end, " ($address)")
|
||||||
|
}
|
||||||
|
return out.toString()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun looksLikeHtml(text: String): Boolean = htmlTagRegex.containsMatchIn(text)
|
||||||
|
|
||||||
|
/** [description] as it reads: HTML rendered down to [RichText], plain text as it is. */
|
||||||
|
fun descriptionRichText(description: String): RichText =
|
||||||
|
if (looksLikeHtml(description)) parseHtml(description) else RichText(description)
|
||||||
|
|
||||||
|
private val BLOCK_TAGS = setOf(
|
||||||
|
"p", "div", "ul", "ol", "li", "table", "tr", "blockquote", "pre", "hr", "section", "article",
|
||||||
|
"header", "footer", "dl", "dt", "dd", "address", "center", "h1", "h2", "h3", "h4", "h5", "h6",
|
||||||
|
)
|
||||||
|
|
||||||
|
// Their content is never text to show.
|
||||||
|
private val SKIPPED_TAGS = setOf("head", "style", "script", "title", "xml", "template")
|
||||||
|
|
||||||
|
private val STYLE_TAGS = mapOf(
|
||||||
|
"b" to InlineStyle.Bold, "strong" to InlineStyle.Bold, "th" to InlineStyle.Bold,
|
||||||
|
"h1" to InlineStyle.Bold, "h2" to InlineStyle.Bold, "h3" to InlineStyle.Bold,
|
||||||
|
"h4" to InlineStyle.Bold, "h5" to InlineStyle.Bold, "h6" to InlineStyle.Bold,
|
||||||
|
"i" to InlineStyle.Italic, "em" to InlineStyle.Italic, "cite" to InlineStyle.Italic,
|
||||||
|
"u" to InlineStyle.Underline, "ins" to InlineStyle.Underline,
|
||||||
|
"s" to InlineStyle.Strikethrough, "strike" to InlineStyle.Strikethrough, "del" to InlineStyle.Strikethrough,
|
||||||
|
"sup" to InlineStyle.Superscript, "sub" to InlineStyle.Subscript,
|
||||||
|
"code" to InlineStyle.Monospace, "tt" to InlineStyle.Monospace, "pre" to InlineStyle.Monospace,
|
||||||
|
)
|
||||||
|
|
||||||
|
// A real tag the renderer knows, not prose like "<3" or "a < b". Google
|
||||||
|
// Calendar and Exchange both store their descriptions as HTML.
|
||||||
|
private val htmlTagRegex = Regex(
|
||||||
|
(BLOCK_TAGS + SKIPPED_TAGS + STYLE_TAGS.keys + setOf("html", "body", "br", "span", "a", "font", "img", "meta", "td"))
|
||||||
|
.joinToString("|", prefix = """</?(?:""", postfix = """)(?:\s[^<>]*)?/?>"""),
|
||||||
|
RegexOption.IGNORE_CASE,
|
||||||
|
)
|
||||||
|
|
||||||
|
private val LINK_SCHEMES = listOf("http://", "https://", "mailto:", "tel:")
|
||||||
|
|
||||||
|
private const val NBSP = '\u00A0'
|
||||||
|
private const val CELL_SEPARATOR = " · "
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Render [html] down to text with its inline formatting and links. Blocks and
|
||||||
|
* `<br>` become line breaks, list items get a bullet or number, table rows a
|
||||||
|
* line each with their cells side by side. Lenient about broken markup:
|
||||||
|
* whatever doesn't parse as a tag stays text.
|
||||||
|
*/
|
||||||
|
fun parseHtml(html: String): RichText = HtmlRenderer(html).render()
|
||||||
|
|
||||||
|
// Markup that sets its own lines. Without any, the text's newlines are the
|
||||||
|
// lines: "Agenda:\n1. Intro" with one <a href> in it stays on two lines.
|
||||||
|
private val lineTagRegex = Regex("""<(?:br|p|div|li|tr|h[1-6]|pre|blockquote|table)\b""", RegexOption.IGNORE_CASE)
|
||||||
|
|
||||||
|
private class HtmlRenderer(private val html: String) {
|
||||||
|
private val out = StringBuilder()
|
||||||
|
private val styles = mutableListOf<StyleRange>()
|
||||||
|
private val links = mutableListOf<LinkRange>()
|
||||||
|
private val openStyles = mutableListOf<Pair<String, Int>>()
|
||||||
|
private var openLink: Pair<String, Int>? = null
|
||||||
|
private val lists = mutableListOf<ListState>()
|
||||||
|
private val keepNewlines = !lineTagRegex.containsMatchIn(html)
|
||||||
|
private var preDepth = 0
|
||||||
|
private var rowStart = 0
|
||||||
|
private var cellNeedsSeparator = false
|
||||||
|
// Where the current list item's bullet ends, so a <p> inside the item
|
||||||
|
// doesn't push its text off the bullet's line.
|
||||||
|
private var markerEnd = -1
|
||||||
|
|
||||||
|
private class ListState(val ordered: Boolean, var count: Int = 0)
|
||||||
|
|
||||||
|
fun render(): RichText {
|
||||||
|
var i = 0
|
||||||
|
while (i < html.length) {
|
||||||
|
val lt = html.indexOf('<', i)
|
||||||
|
if (lt < 0) {
|
||||||
|
text(html.substring(i))
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if (lt > i) text(html.substring(i, lt))
|
||||||
|
i = tag(lt)
|
||||||
|
}
|
||||||
|
return normalize()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Handle the markup at [lt]; returns where reading continues. */
|
||||||
|
private fun tag(lt: Int): Int {
|
||||||
|
if (html.startsWith("<!--", lt)) {
|
||||||
|
val end = html.indexOf("-->", lt + 4)
|
||||||
|
return if (end < 0) html.length else end + 3
|
||||||
|
}
|
||||||
|
if (html.startsWith("<!", lt) || html.startsWith("<?", lt)) {
|
||||||
|
val end = html.indexOf('>', lt)
|
||||||
|
return if (end < 0) html.length else end + 1
|
||||||
|
}
|
||||||
|
val closing = html.getOrNull(lt + 1) == '/'
|
||||||
|
val nameStart = if (closing) lt + 2 else lt + 1
|
||||||
|
if (html.getOrNull(nameStart)?.isLetter() != true) {
|
||||||
|
text("<")
|
||||||
|
return lt + 1
|
||||||
|
}
|
||||||
|
val end = tagEnd(lt)
|
||||||
|
if (end < 0) {
|
||||||
|
text("<")
|
||||||
|
return lt + 1
|
||||||
|
}
|
||||||
|
if (!closing && isAutolink(html.substring(nameStart, end))) {
|
||||||
|
text(html.substring(lt, end + 1))
|
||||||
|
return end + 1
|
||||||
|
}
|
||||||
|
var nameEnd = nameStart
|
||||||
|
while (nameEnd < end && (html[nameEnd].isLetterOrDigit() || html[nameEnd] == ':')) nameEnd++
|
||||||
|
val name = html.substring(nameStart, nameEnd).lowercase()
|
||||||
|
val attrs = html.substring(nameEnd, end)
|
||||||
|
if (closing) {
|
||||||
|
close(name)
|
||||||
|
} else if (name in SKIPPED_TAGS && !attrs.trimEnd().endsWith("/")) {
|
||||||
|
// Never closed (an omitted </head> is valid): just ignore the tag.
|
||||||
|
val closeAt = html.indexOf("</$name", end, ignoreCase = true)
|
||||||
|
if (closeAt < 0) return end + 1
|
||||||
|
val closeEnd = html.indexOf('>', closeAt)
|
||||||
|
return if (closeEnd < 0) html.length else closeEnd + 1
|
||||||
|
} else {
|
||||||
|
open(name, attrs)
|
||||||
|
}
|
||||||
|
return end + 1
|
||||||
|
}
|
||||||
|
|
||||||
|
/** An angle-bracketed URL or address (`<https://…>`, `<a@b.c>`), kept as text. */
|
||||||
|
private fun isAutolink(inner: String): Boolean =
|
||||||
|
LINK_SCHEMES.any { inner.startsWith(it, ignoreCase = true) } ||
|
||||||
|
('@' in inner && inner.none { it.isWhitespace() || it == '=' })
|
||||||
|
|
||||||
|
/** The `>` closing the tag at [lt], skipping any inside quoted attributes. */
|
||||||
|
private fun tagEnd(lt: Int): Int {
|
||||||
|
var quote: Char? = null
|
||||||
|
for (j in lt + 1 until html.length) {
|
||||||
|
val c = html[j]
|
||||||
|
when {
|
||||||
|
quote != null -> if (c == quote) quote = null
|
||||||
|
c == '"' || c == '\'' -> quote = c
|
||||||
|
c == '>' -> return j
|
||||||
|
c == '<' -> return -1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun open(name: String, attrs: String) {
|
||||||
|
when (name) {
|
||||||
|
"br" -> newline()
|
||||||
|
"li" -> {
|
||||||
|
markerEnd = -1
|
||||||
|
cellNeedsSeparator = false
|
||||||
|
lineBreak()
|
||||||
|
val list = lists.lastOrNull()
|
||||||
|
out.append("$NBSP$NBSP".repeat((lists.size - 1).coerceAtLeast(0)))
|
||||||
|
if (list?.ordered == true) {
|
||||||
|
list.count++
|
||||||
|
out.append("${list.count}. ")
|
||||||
|
} else {
|
||||||
|
out.append("• ")
|
||||||
|
}
|
||||||
|
markerEnd = out.length
|
||||||
|
}
|
||||||
|
"ul", "ol" -> {
|
||||||
|
cellNeedsSeparator = false
|
||||||
|
lineBreak()
|
||||||
|
val start = startRegex.find(attrs)?.groupValues?.get(1)?.toIntOrNull() ?: 1
|
||||||
|
lists += ListState(ordered = name == "ol", count = start - 1)
|
||||||
|
}
|
||||||
|
"tr" -> {
|
||||||
|
lineBreak()
|
||||||
|
rowStart = out.length
|
||||||
|
cellNeedsSeparator = false
|
||||||
|
}
|
||||||
|
"td", "th" -> {
|
||||||
|
// An empty spacer cell leaves nothing behind, not even its .
|
||||||
|
if (rowStart <= out.length && (rowStart until out.length).none { out[it].isContent() }) {
|
||||||
|
cut(rowStart)
|
||||||
|
} else {
|
||||||
|
cellNeedsSeparator = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"a" -> {
|
||||||
|
closeLink()
|
||||||
|
hrefRegex.find(attrs)
|
||||||
|
?.groupValues?.drop(1)?.firstOrNull { it.isNotEmpty() }
|
||||||
|
?.let(::decodeEntities)
|
||||||
|
?.trim()
|
||||||
|
?.let { href ->
|
||||||
|
val scheme = LINK_SCHEMES.firstOrNull { href.startsWith(it, ignoreCase = true) }
|
||||||
|
?: return@let
|
||||||
|
// Intent filters match the scheme case-sensitively.
|
||||||
|
openLink = scheme + href.substring(scheme.length) to out.length
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else -> if (name in BLOCK_TAGS) lineBreak()
|
||||||
|
}
|
||||||
|
if (name == "pre") preDepth++
|
||||||
|
STYLE_TAGS[name]?.let { openStyles += name to out.length }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun close(name: String) {
|
||||||
|
// A row's last cell, if empty, leaves a separator pending; it ends with the row.
|
||||||
|
if (name == "tr" || name == "table") cellNeedsSeparator = false
|
||||||
|
val index = openStyles.indexOfLast { it.first == name }
|
||||||
|
if (index >= 0) {
|
||||||
|
val (_, start) = openStyles.removeAt(index)
|
||||||
|
if (out.length > start) styles += StyleRange(start, out.length, STYLE_TAGS.getValue(name))
|
||||||
|
}
|
||||||
|
if (name == "pre") preDepth = (preDepth - 1).coerceAtLeast(0)
|
||||||
|
if (name == "li" || name == "ul" || name == "ol") {
|
||||||
|
if (out.length == markerEnd) cut(out.lastIndexOf("\n") + 1)
|
||||||
|
markerEnd = -1
|
||||||
|
}
|
||||||
|
when (name) {
|
||||||
|
"ul", "ol" -> {
|
||||||
|
lists.removeLastOrNull()
|
||||||
|
lineBreak()
|
||||||
|
}
|
||||||
|
"a" -> closeLink()
|
||||||
|
else -> if (name in BLOCK_TAGS) lineBreak()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun closeLink() {
|
||||||
|
val (url, start) = openLink ?: return
|
||||||
|
if (out.length > start) links += LinkRange(start, out.length, url)
|
||||||
|
openLink = null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun text(raw: String) {
|
||||||
|
val decoded = decodeEntities(raw)
|
||||||
|
if (preDepth > 0) {
|
||||||
|
out.append(decoded.replace("\r\n", "\n"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for (c in decoded) {
|
||||||
|
if (c == '\n' && keepNewlines) {
|
||||||
|
newline()
|
||||||
|
} else if (c == ' ' || c == '\n' || c == '\t' || c == '\r' || c == '\u000C') {
|
||||||
|
if (out.isNotEmpty() && out.last() != ' ' && out.last() != '\n') out.append(' ')
|
||||||
|
} else {
|
||||||
|
if (cellNeedsSeparator && c.isContent()) separateCell()
|
||||||
|
out.append(c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Put this cell's text beside the row's last, even after a block in that cell ended its line. */
|
||||||
|
private fun separateCell() {
|
||||||
|
cellNeedsSeparator = false
|
||||||
|
var end = out.length
|
||||||
|
while (end > rowStart && !out[end - 1].isContent()) end--
|
||||||
|
cut(end)
|
||||||
|
out.append(CELL_SEPARATOR)
|
||||||
|
openStyles.replaceAll { (name, start) -> name to if (start >= end) out.length else start }
|
||||||
|
openLink = openLink?.let { (url, start) -> url to if (start >= end) out.length else start }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun Char.isContent() = !isWhitespace() && this != NBSP
|
||||||
|
|
||||||
|
private fun newline() {
|
||||||
|
trimTrailingSpaces()
|
||||||
|
out.append('\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
/** End the current line, unless it's already ended or holds just a bullet. */
|
||||||
|
private fun lineBreak() {
|
||||||
|
if (out.length == markerEnd) return
|
||||||
|
trimTrailingSpaces()
|
||||||
|
if (out.isNotEmpty() && out.last() != '\n') out.append('\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun trimTrailingSpaces() {
|
||||||
|
while (out.isNotEmpty() && out.last() == ' ') out.setLength(out.length - 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Drop the output from [length] on, with whatever formatting lay only there. */
|
||||||
|
private fun cut(length: Int) {
|
||||||
|
if (length >= out.length) return
|
||||||
|
out.setLength(length)
|
||||||
|
styles.replaceAll { it.copy(end = minOf(it.end, length)) }
|
||||||
|
styles.removeAll { it.end <= it.start }
|
||||||
|
links.replaceAll { it.copy(end = minOf(it.end, length)) }
|
||||||
|
links.removeAll { it.end <= it.start }
|
||||||
|
openStyles.replaceAll { (name, start) -> name to minOf(start, length) }
|
||||||
|
openLink = openLink?.let { (url, start) -> url to minOf(start, length) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tidy the rendered text: no-break spaces become plain, lines lose trailing
|
||||||
|
* blanks, runs of empty lines shrink to one and the ends are trimmed. Spans
|
||||||
|
* move with the text they cover.
|
||||||
|
*/
|
||||||
|
private fun normalize(): RichText {
|
||||||
|
closeLink()
|
||||||
|
for ((name, start) in openStyles) {
|
||||||
|
if (out.length > start) styles += StyleRange(start, out.length, STYLE_TAGS.getValue(name))
|
||||||
|
}
|
||||||
|
val src = out.toString().replace(NBSP, ' ')
|
||||||
|
val map = IntArray(src.length + 1)
|
||||||
|
val result = StringBuilder()
|
||||||
|
var i = 0
|
||||||
|
while (i < src.length) {
|
||||||
|
var lineEnd = src.indexOf('\n', i)
|
||||||
|
if (lineEnd < 0) lineEnd = src.length
|
||||||
|
var contentEnd = lineEnd
|
||||||
|
while (contentEnd > i && src[contentEnd - 1].isWhitespace()) contentEnd--
|
||||||
|
for (j in i until lineEnd) {
|
||||||
|
map[j] = result.length
|
||||||
|
if (j < contentEnd) result.append(src[j])
|
||||||
|
}
|
||||||
|
if (lineEnd < src.length) {
|
||||||
|
map[lineEnd] = result.length
|
||||||
|
if (!result.endsWith("\n\n")) result.append('\n')
|
||||||
|
}
|
||||||
|
i = lineEnd + 1
|
||||||
|
}
|
||||||
|
map[src.length] = result.length
|
||||||
|
val leading = result.length - result.trimStart().length
|
||||||
|
val text = result.trim().toString()
|
||||||
|
fun at(index: Int) = (map[index] - leading).coerceIn(0, text.length)
|
||||||
|
return RichText(
|
||||||
|
text = text,
|
||||||
|
styles = styles.mapNotNull { r -> StyleRange(at(r.start), at(r.end), r.style).takeIf { it.end > it.start } },
|
||||||
|
links = links.mapNotNull { r -> LinkRange(at(r.start), at(r.end), r.url).takeIf { it.end > it.start } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private val startRegex = Regex("""(?:^|\s)start\s*=\s*["']?(-?\d{1,6})""", RegexOption.IGNORE_CASE)
|
||||||
|
private val hrefRegex = Regex("""(?:^|\s)href\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))""", RegexOption.IGNORE_CASE)
|
||||||
|
|
||||||
|
// Latin-1 ( … ÿ) in code point order, then the common extras.
|
||||||
|
private val LATIN1_ENTITIES = ("nbsp iexcl cent pound curren yen brvbar sect uml copy ordf laquo not shy reg macr " +
|
||||||
|
"deg plusmn sup2 sup3 acute micro para middot cedil sup1 ordm raquo frac14 frac12 frac34 iquest " +
|
||||||
|
"Agrave Aacute Acirc Atilde Auml Aring AElig Ccedil Egrave Eacute Ecirc Euml Igrave Iacute Icirc Iuml " +
|
||||||
|
"ETH Ntilde Ograve Oacute Ocirc Otilde Ouml times Oslash Ugrave Uacute Ucirc Uuml Yacute THORN szlig " +
|
||||||
|
"agrave aacute acirc atilde auml aring aelig ccedil egrave eacute ecirc euml igrave iacute icirc iuml " +
|
||||||
|
"eth ntilde ograve oacute ocirc otilde ouml divide oslash ugrave uacute ucirc uuml yacute thorn yuml").split(' ')
|
||||||
|
|
||||||
|
private val ENTITIES: Map<String, String> = LATIN1_ENTITIES.withIndex()
|
||||||
|
.associate { (i, name) -> name to (0xA0 + i).toChar().toString() } + mapOf(
|
||||||
|
"amp" to "&", "lt" to "<", "gt" to ">", "quot" to "\"", "apos" to "'",
|
||||||
|
"ndash" to "–", "mdash" to "—", "hellip" to "…", "bull" to "•",
|
||||||
|
"lsquo" to "‘", "rsquo" to "’", "ldquo" to "“", "rdquo" to "”", "sbquo" to "‚", "bdquo" to "„",
|
||||||
|
"euro" to "€", "trade" to "™", "OElig" to "Œ", "oelig" to "œ", "Scaron" to "Š", "scaron" to "š",
|
||||||
|
"zwnj" to "\u200C", "zwj" to "\u200D", "ensp" to "\u2002", "emsp" to "\u2003", "thinsp" to "\u2009",
|
||||||
|
)
|
||||||
|
|
||||||
|
// A named reference needs its ";": "?id=5®=eu" in a link is a query, not "®".
|
||||||
|
private val entityRegex = Regex("""&(?:(#[0-9]{1,7}|#[xX][0-9a-fA-F]{1,6});?|([a-zA-Z][a-zA-Z0-9]{1,31});)""")
|
||||||
|
|
||||||
|
/** Decode character references; an unknown name is left as written. */
|
||||||
|
internal fun decodeEntities(text: String): String {
|
||||||
|
if ('&' !in text) return text
|
||||||
|
return entityRegex.replace(text) { match ->
|
||||||
|
val name = match.groupValues[2]
|
||||||
|
if (name.isNotEmpty()) return@replace ENTITIES[name] ?: match.value
|
||||||
|
val body = match.groupValues[1]
|
||||||
|
val code = when {
|
||||||
|
body.startsWith("#x", ignoreCase = true) -> body.substring(2).toIntOrNull(16)
|
||||||
|
else -> body.substring(1).toIntOrNull()
|
||||||
|
}
|
||||||
|
if (code == null || code == 0 || !Character.isValidCodePoint(code)) "�" else String(Character.toChars(code))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.domain
|
||||||
|
|
||||||
|
import kotlinx.datetime.TimeZone
|
||||||
|
import kotlinx.datetime.toLocalDateTime
|
||||||
|
import kotlin.time.Duration.Companion.hours
|
||||||
|
import kotlin.time.Instant
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build a prefilled [EventForm] from an `ACTION_INSERT` intent's extras (issue
|
||||||
|
* #30). External apps and widgets (e.g. the Todo Agenda widget) launch the
|
||||||
|
* calendar this way to create a new event, passing the fields as
|
||||||
|
* [android.provider.CalendarContract] extras. Any field the intent omits falls
|
||||||
|
* back to the same defaults the in-app "new event" uses — a timed start at the
|
||||||
|
* next full hour, and a placeholder hour for a missing end that the form then
|
||||||
|
* stretches to the default-duration setting (the intent is opened as
|
||||||
|
* `ImportSource.InsertOpenEnded`, #54). [calendarId] is the calendar the
|
||||||
|
* intent names, if any; the editor preselects it while it is a target and otherwise
|
||||||
|
* resolves the calendar like a plain new event (#429).
|
||||||
|
*
|
||||||
|
* Pure (no Android types) so it is unit-testable; the intent parsing that reads
|
||||||
|
* the extras lives in `MainActivity.insertFormOrNull`.
|
||||||
|
*/
|
||||||
|
fun buildInsertEventForm(
|
||||||
|
beginMillis: Long? = null,
|
||||||
|
endMillis: Long? = null,
|
||||||
|
isAllDay: Boolean = false,
|
||||||
|
title: String?,
|
||||||
|
description: String?,
|
||||||
|
location: String? = null,
|
||||||
|
rrule: String? = null,
|
||||||
|
calendarId: Long? = null,
|
||||||
|
zone: TimeZone,
|
||||||
|
now: Instant,
|
||||||
|
): EventForm {
|
||||||
|
val (start, end) = if (isAllDay) {
|
||||||
|
val startDate = beginMillis
|
||||||
|
?.let { Instant.fromEpochMilliseconds(it).toLocalDateTime(TimeZone.UTC).date }
|
||||||
|
?: now.toLocalDateTime(zone).date
|
||||||
|
val endExclusive = endMillis?.let { Instant.fromEpochMilliseconds(it).toLocalDateTime(TimeZone.UTC).date }
|
||||||
|
allDayFormTimes(startDate, endExclusive)
|
||||||
|
} else {
|
||||||
|
val startAt = beginMillis?.let(Instant::fromEpochMilliseconds) ?: nextFullHour(now)
|
||||||
|
val endAt = endMillis?.let(Instant::fromEpochMilliseconds)?.takeIf { it >= startAt }
|
||||||
|
?: (startAt + 1.hours)
|
||||||
|
startAt.toFormTime(zone) to endAt.toFormTime(zone)
|
||||||
|
}
|
||||||
|
return EventForm(
|
||||||
|
calendarId = calendarId,
|
||||||
|
title = title.orEmpty(),
|
||||||
|
isAllDay = isAllDay,
|
||||||
|
start = start,
|
||||||
|
end = end,
|
||||||
|
location = location.orEmpty(),
|
||||||
|
description = description.orEmpty(),
|
||||||
|
// Bare RRULE value (Events.RRULE convention); tolerate a leading "RRULE:"
|
||||||
|
// some callers include.
|
||||||
|
rrule = rrule.normalizedRrule(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The first full hour after [now]: may roll into the next day before midnight. */
|
||||||
|
internal fun nextFullHour(now: Instant): Instant {
|
||||||
|
val hourMillis = 3_600_000L
|
||||||
|
return Instant.fromEpochMilliseconds((now.toEpochMilliseconds() / hourMillis + 1) * hourMillis)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Title and description for text shared or selected into the app (#306). */
|
||||||
|
data class SharedText(val title: String, val description: String)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Split shared text into an event title and description: the share's subject
|
||||||
|
* becomes the title and the text the description. Without a subject the text's
|
||||||
|
* first non-blank line is the title and the rest the description. A title longer
|
||||||
|
* than [maxTitle] is cut, and the full text then stays in the description.
|
||||||
|
* Null when there is nothing to use.
|
||||||
|
*/
|
||||||
|
fun sharedTextOrNull(subject: String?, text: String?, maxTitle: Int = 255): SharedText? {
|
||||||
|
val body = text?.trim().orEmpty()
|
||||||
|
val given = subject?.trim()?.takeIf { it.isNotEmpty() }
|
||||||
|
val (title, rest) = if (given != null) {
|
||||||
|
given to body
|
||||||
|
} else {
|
||||||
|
val lines = body.lines()
|
||||||
|
val first = lines.firstOrNull()?.trim()?.takeIf { it.isNotEmpty() } ?: return null
|
||||||
|
first to lines.drop(1).joinToString("\n").trim()
|
||||||
|
}
|
||||||
|
if (title.length <= maxTitle) return SharedText(title, rest)
|
||||||
|
val cut = title.take(maxTitle).let { if (it.last().isHighSurrogate()) it.dropLast(1) else it }
|
||||||
|
val full = if (given != null) listOf(given, body).filter { it.isNotEmpty() }.joinToString("\n\n") else body
|
||||||
|
return SharedText(cut.trimEnd(), full)
|
||||||
|
}
|
||||||
Loaded 100 of 951 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user