Compare commits

...

233 Commits

Author SHA1 Message Date
J-Jamet
e7bbb47422 Merge branch 'release/2.5.0.0beta13' 2018-07-14 11:11:36 +02:00
J-Jamet
846bc7edb1 Update Changelogs 2018-07-14 11:01:34 +02:00
J-Jamet
99a9842a1f Fix null pointer on nodeButtonView 2018-07-14 10:47:52 +02:00
J-Jamet
33009138c3 Update version and fix memory crash 2018-07-14 10:23:04 +02:00
J-Jamet
c74b82ebd8 Fix changelogs 2018-07-13 17:06:20 +02:00
J-Jamet
49ea92a4a5 WebDav - Merge branch 'translations' into develop 2018-07-13 14:50:25 +02:00
David Ramiro
6cc4eeaa30 Translated using Weblate (German)
Currently translated at 100,0% (296 of 296 strings)

Translation: KeePass DX/Strings
Translate-URL: https://hosted.weblate.org/projects/keepass-dx/strings/de/
2018-07-13 13:53:21 +02:00
David Ramiro
1b89f79888 Translated using Weblate (German)
Currently translated at 100,0% (296 of 296 strings)

Translation: KeePass DX/Strings
Translate-URL: https://hosted.weblate.org/projects/keepass-dx/strings/de/
2018-07-13 13:53:21 +02:00
Ale-Ma
07d99de3ea Translated using Weblate (Italian)
Currently translated at 51.6% (153 of 296 strings)

Translation: KeePass DX/Strings
Translate-URL: https://hosted.weblate.org/projects/keepass-dx/strings/it/
2018-07-13 13:53:21 +02:00
piegope
ae757affa1 Translated using Weblate (Spanish)
Currently translated at 100.0% (296 of 296 strings)

Translation: KeePass DX/Strings
Translate-URL: https://hosted.weblate.org/projects/keepass-dx/strings/es/
2018-07-13 13:53:21 +02:00
Max
482b6296fc Translated using Weblate (Russian)
Currently translated at 57.0% (169 of 296 strings)

Translation: KeePass DX/Strings
Translate-URL: https://hosted.weblate.org/projects/keepass-dx/strings/ru/
2018-07-13 13:53:21 +02:00
piegope
d37ce729f0 Translated using Weblate (Español (España))
Currently translated at 100,0% (296 of 296 strings)

Translation: KeePass DX/Strings
Translate-URL: https://hosted.weblate.org/projects/keepass-dx/strings/es/
2018-07-13 13:53:21 +02:00
ButterflyOfFire
e92ce232bc Translated using Weblate (Arabic)
Currently translated at 35.1% (104 of 296 strings)

Translation: KeePass DX/Strings
Translate-URL: https://hosted.weblate.org/projects/keepass-dx/strings/ar/
2018-07-13 13:53:21 +02:00
piegope
78ae44b160 Translated using Weblate (Spanish)
Currently translated at 87.5% (259 of 296 strings)

Translation: KeePass DX/Strings
Translate-URL: https://hosted.weblate.org/projects/keepass-dx/strings/es/
2018-07-13 13:53:21 +02:00
Ale-Ma
49ce87a8e0 Translated using Weblate (Italian)
Currently translated at 51.3% (152 of 296 strings)

Translation: KeePass DX/Strings
Translate-URL: https://hosted.weblate.org/projects/keepass-dx/strings/it/
2018-07-13 13:53:21 +02:00
ButterflyOfFire
d2fe5ce884 Translated using Weblate (Arabic)
Currently translated at 34.7% (103 of 296 strings)

Translation: KeePass DX/Strings
Translate-URL: https://hosted.weblate.org/projects/keepass-dx/strings/ar/
2018-07-13 13:53:21 +02:00
ButterflyOfFire
5e695756de Added translation using Weblate (Arabe) 2018-07-13 13:53:21 +02:00
Max
0506a75417 Translated using Weblate (Russian)
Currently translated at 57.0% (169 of 296 strings)

Translation: KeePass DX/Strings
Translate-URL: https://hosted.weblate.org/projects/keepass-dx/strings/ru/
2018-07-13 13:53:21 +02:00
dienteperro
34e1316144 Translated using Weblate (Spanish)
Currently translated at 57.0% (169 of 296 strings)

Translation: KeePass DX/Strings
Translate-URL: https://hosted.weblate.org/projects/keepass-dx/strings/es/
2018-07-13 13:53:21 +02:00
Kunzisoft
18dffa6c75 Translated using Weblate (English)
Currently translated at 100.0% (296 of 296 strings)

Translation: KeePass DX/Strings
Translate-URL: https://hosted.weblate.org/projects/keepass-dx/strings/en/
2018-07-13 13:53:21 +02:00
Kunzisoft
03621c378e Translated using Weblate (French)
Currently translated at 100.0% (296 of 296 strings)

Translation: KeePass DX/Strings
Translate-URL: https://hosted.weblate.org/projects/keepass-dx/strings/fr/
2018-07-13 13:53:21 +02:00
Kunzisoft
aff9312419 Translated using Weblate (French)
Currently translated at 100.0% (296 of 296 strings)

Translation: KeePass DX/Strings
Translate-URL: https://hosted.weblate.org/projects/keepass-dx/strings/fr/
2018-07-13 13:53:21 +02:00
J-Jamet
4651b1be96 Icons depends now of setting of list items #97 2018-07-13 11:25:02 +02:00
J-Jamet
32497a22d2 Add dialog with a warning to copy, add the setting to copy the protected custom fields #139 2018-07-12 21:53:05 +02:00
J-Jamet
3b5ef56c16 Fix clean clipboard in notification 2018-07-11 18:26:49 +02:00
J-Jamet
d4cc3a58d8 Remove copy menu for group 2018-07-11 12:24:37 +02:00
J-Jamet
afedbb38b2 Merge remote-tracking branch 'origin/develop' into develop 2018-07-11 12:15:26 +02:00
J-Jamet
fe70bf3877 Fix database creation workflow 2018-07-11 12:15:04 +02:00
J-Jamet
f14ee6cf1c Update changelogs 2018-07-10 14:45:56 +02:00
J-Jamet
1791b15f85 Update gradle and remove compatibility mode for FingerPrintManager 2018-07-10 11:24:00 +02:00
J-Jamet
6c5b3b3a0d Fix german translation 2018-07-10 11:24:00 +02:00
J-Jamet
6ea2287679 Update German translation - Merge branch 'davidramiro-develop' into develop 2018-07-09 14:49:32 +02:00
David Ramiro
cad4ec22b4 Update German translation 2018-07-08 22:10:28 +02:00
J-Jamet
f277983caf Merge branch 'develop' of https://github.com/Kunzisoft/KeePassDX into develop 2018-07-06 08:54:14 +02:00
J-Jamet
5e561e5321 Update descriptions 2018-07-06 08:53:54 +02:00
J-Jamet
ef83dbcae2 Fix errors highlight by @gaul fb715950a7 2018-07-04 13:19:06 +02:00
J-Jamet
ab6c69adcb Standardize the slide animation 2018-07-04 12:59:32 +02:00
J-Jamet
1c90747476 Add setting to disable education screens 2018-07-02 11:25:59 +02:00
J-Jamet
c3b3d8482c Update changelog 2018-07-01 21:53:40 +02:00
J-Jamet
86b4d92599 Change DbHeaderV4 number 2018-07-01 21:53:25 +02:00
J-Jamet
1f6786b1f8 Fix null pointer for enableButtonOncheckedChangeListener 2018-07-01 12:50:59 +02:00
J-Jamet
4cd2b153f4 Fix broadcast unregister receiver 2018-07-01 11:54:46 +02:00
J-Jamet
27b0810688 Merge branch 'feature/Magikeyboard' into develop 2018-06-30 16:10:08 +02:00
J-Jamet
94c72a4cf6 Remove Jelly Bean condition 2018-06-30 16:04:03 +02:00
J-Jamet
e634116e71 Fix bugs for Kitkat device 2018-06-30 15:22:16 +02:00
J-Jamet
9021cb5bc8 Add TODO, dev dialog and fix icon bug 2018-06-29 19:02:31 +02:00
J-Jamet
3674900a54 Add receiver to lock the entry in the keyboard 2018-06-29 17:59:58 +02:00
J-Jamet
9855ae79c3 Add keyboard notification 2018-06-29 16:56:13 +02:00
J-Jamet
fe1a4985f1 Add settings bones 2018-06-26 00:25:09 +02:00
J-Jamet
015a368a1d Add keyboard explanation 2018-06-25 17:00:57 +02:00
J-Jamet
07f59e071d Upgrade changelogs 2018-06-25 11:37:06 +02:00
J-Jamet
670e2bfe33 Refining activity animations 2018-06-25 11:25:28 +02:00
J-Jamet
992b6382a3 Fix disabled button 2018-06-25 11:00:50 +02:00
J-Jamet
c3ac550c93 Add setting to disable the open button #126 2018-06-25 10:42:19 +02:00
J-Jamet
acba7fc5de New adaptive icon 2018-06-24 21:22:36 +02:00
J-Jamet
ccb500fdf4 Fix search with Autofill service #130 2018-06-23 11:40:33 +02:00
J-Jamet
44111507e7 Change style of keyboard 2018-06-22 18:27:07 +02:00
J-Jamet
5f14596ed2 Assign entry elements to keys 2018-06-10 21:51:09 +02:00
J-Jamet
4ad65c8f4a Retrieve entry selected in keyboard 2018-06-10 14:03:34 +02:00
J-Jamet
b4b215fe30 Lock since keyboard and refactor 2018-06-08 17:59:18 +02:00
J-Jamet
d8a8005d70 Merge branch 'develop' into feature/Magikeyboard 2018-06-06 19:23:48 +02:00
J-Jamet
37ca15b77c Refactor lock 2018-06-06 19:11:20 +02:00
J-Jamet
6c18fe5591 Fix the spelling error 2018-06-05 19:24:26 +02:00
J-Jamet
fdcb05467c First commit to add Magikeyboard 2018-06-03 16:33:59 +02:00
J-Jamet
ef8db46ae7 Update changelogs 2018-05-31 18:26:03 +02:00
J-Jamet
14f56c77e8 Merge branch 'feature/IconsVector' into develop 2018-05-31 17:37:45 +02:00
J-Jamet
44e21084e4 Change material icons as XML 2018-05-31 17:37:08 +02:00
J-Jamet
b7f1275789 Fix globe icon #125 2018-05-31 15:24:09 +02:00
J-Jamet
b1be05db4d Set folder icon by default for a new group #122 2018-05-31 13:21:38 +02:00
J-Jamet
09c776fd7e Remove "Rounds fix" setting no more used 2018-05-31 11:53:45 +02:00
J-Jamet
e8a24790a5 Upgrade version and changelogs 2018-05-30 11:51:28 +02:00
J-Jamet
8b3be79266 Merge branch 'feature/ListNodesFragment' into develop 2018-05-30 11:16:13 +02:00
J-Jamet
e5f0572c1c Change node menu as XML 2018-05-30 10:03:38 +02:00
J-Jamet
68df3bc6c3 Set messages in threads 2018-05-29 23:04:43 +02:00
J-Jamet
a3da960c26 Fix toolbar paste action and colors 2018-05-29 22:27:38 +02:00
J-Jamet
d9490f9840 Refactor runnable action 2018-05-29 19:58:27 +02:00
J-Jamet
3b24f9d821 Merge branch 'feature/NodeMenu' into feature/ListNodesFragment 2018-05-29 12:18:09 +02:00
J-Jamet
bf35897e92 Add toolbar paste and animations for activities 2018-05-29 12:09:08 +02:00
J-Jamet
977705b42d Fix group title 2018-05-28 20:12:09 +02:00
J-Jamet
459bc40515 Add Move for Entries and Groups 2018-05-28 19:53:45 +02:00
J-Jamet
eb8ca9355c Merge branch 'feature/ListNodesFragment' into feature/NodeMenu 2018-05-28 18:10:06 +02:00
J-Jamet
31f7b0d5be Fix timeout for fragment 2018-05-28 17:54:38 +02:00
J-Jamet
7c54946c4b Fix fragment - Merge branch 'feature/ListNodesFragment' into feature/NodeMenu 2018-05-25 22:09:35 +02:00
J-Jamet
5aaf2c222a Fix fragment during orientation change 2018-05-25 21:52:09 +02:00
J-Jamet
9424feefce Add contextual bar to paste and add move entry 2018-05-24 19:51:28 +02:00
Jérémy JAMET
a3917ccab6 Add translation link in Readme.md 2018-05-24 14:48:28 +02:00
J-Jamet
5286a60142 Group activity with fragment for navigation 2018-05-24 00:11:46 +02:00
J-Jamet
d4459de49b Rename string clipboard cleared 2018-05-23 12:25:08 +02:00
J-Jamet
05dba6668c Change about description string key 2018-05-23 10:25:50 +02:00
J-Jamet
c15a1c6eaa Refactor KDF Engine for v3 2018-05-22 15:22:04 +02:00
J-Jamet
fe8c962f73 Better KDF Exception management 2018-05-22 12:52:12 +02:00
J-Jamet
4192cf2403 Add FAQ store time 2018-05-18 11:02:02 +02:00
J-Jamet
1817f1aa9e Fix extended ASCII in default setting 2018-05-18 09:09:07 +02:00
J-Jamet
afacf352ed Merge branch 'develop' of https://github.com/Kunzisoft/KeePassDX into develop 2018-05-15 15:43:30 +02:00
J-Jamet
d3ebbba2a1 Remove compat methods 2018-05-15 15:43:03 +02:00
J-Jamet
460edf1745 Merge branch 'develop' of https://github.com/Kunzisoft/KeePassDX into develop 2018-05-13 22:22:21 +02:00
J-Jamet
dacb19d412 Add Gimp source for store screens 2018-05-13 22:21:28 +02:00
Jérémy JAMET
fe8158db85 Update FAQ.md 2018-05-13 20:13:24 +02:00
Jérémy JAMET
a36e4fbcd0 Update FAQ link 2018-05-13 20:11:32 +02:00
J-Jamet
9442c7ef07 Merge tag '2.5.0.0beta11' into develop 2018-05-13 18:23:52 +02:00
J-Jamet
d4a0b59eb1 Merge branch 'release/2.5.0.0beta11' 2018-05-13 18:23:37 +02:00
J-Jamet
07600949ab Upgrade version and fix potential null pointer for kdf 2018-05-13 18:14:25 +02:00
J-Jamet
7efaad1818 Fix database creation issue 2018-05-13 17:54:35 +02:00
J-Jamet
e32b0d1c25 Merge tag '2.5.0.0beta10' into develop 2018-05-13 17:05:32 +02:00
J-Jamet
0fdcc29aa2 Merge branch 'release/2.5.0.0beta10' 2018-05-13 17:05:10 +02:00
J-Jamet
37bedbffc9 Fix italian translation for compilation 2018-05-13 16:59:35 +02:00
J-Jamet
46505150c4 New Red Volcano theme and change visual feature message for version libre 2018-05-13 16:47:59 +02:00
J-Jamet
e18c5c90cc Upgrade changelogs 2018-05-13 14:52:59 +02:00
J-Jamet
1f5649d9d2 Merge branch 'feature/ChangeAlgorithms' into develop #9 #29 2018-05-13 14:25:31 +02:00
J-Jamet
7bbd55a9fd Add binary to memory explanation 2018-05-13 14:17:19 +02:00
J-Jamet
92eeccf84e Fix algorithm and kdf function for database V3 and add small trad 2018-05-13 13:55:37 +02:00
J-Jamet
7bcc289518 Upgrade explanations 2018-05-13 13:02:09 +02:00
J-Jamet
507f758c0d Add memory usage and parallelism for Argon2 settings 2018-05-12 23:53:41 +02:00
J-Jamet
6afffb7245 Register UUID of database version in KDF parameter 2018-05-11 19:19:16 +02:00
J-Jamet
c62f4ae0b3 Text if choose only one extension #105 2018-05-11 13:25:33 +02:00
J-Jamet
ee80c614e0 Fix layer error for icon free #113 2018-05-11 12:44:33 +02:00
J-Jamet
fea7af6910 Dynamic creation of KdfEngine, reorganise code 2018-05-09 15:17:55 +02:00
J-Jamet
c72aa0e97d Merge branch 'develop' into feature/ChangeAlgorithms to Fix NDK 2018-05-09 12:01:16 +02:00
J-Jamet
3dd60b5392 Fix ndk filters 2018-05-09 10:59:48 +02:00
J-Jamet
a357267552 #107 Set master password in landscape 2018-05-07 10:47:00 +02:00
J-Jamet
1badeb2eef Change FAQ as markdown and add descriptions 2018-05-07 10:34:27 +02:00
Yhaulez
0bb8d2a417 Create FAQ 2018-05-06 16:26:19 +02:00
J-Jamet
4a215db83c Change toolbar style and password layout 2018-05-05 23:16:39 +02:00
J-Jamet
512e55a170 Fix fingerprint animation and for first init 2018-05-05 20:39:01 +02:00
J-Jamet
1ebe8dc022 Update fingerprint state with checkbox 2018-05-04 21:24:57 +02:00
J-Jamet
cafeabdbc3 Fix search styles 2018-05-02 21:31:04 +02:00
J-Jamet
b342b26409 Update readme 2018-05-02 20:59:05 +02:00
J-Jamet
938c3a07af Fix wait dialog callback 2018-05-02 20:52:16 +02:00
J-Jamet
16288f98f7 Merge branch 'develop' into feature/ChangeAlgorithms 2018-05-02 15:57:47 +02:00
J-Jamet
a932156e85 Remove unused progressbar 2018-05-02 15:26:24 +02:00
J-Jamet
64e9b9fb6d Fix lock orientation change 2018-05-02 14:02:10 +02:00
J-Jamet
7af28550da Merge branch 'feature/RefactorProgress' into develop #98 2018-05-02 13:49:56 +02:00
J-Jamet
60e2d786dd Change progress dialog title, and remove code 2018-05-02 13:49:03 +02:00
J-Jamet
ec08f3430d Add progress bar for all, create database in a single progress dialog 2018-05-02 09:54:55 +02:00
J-Jamet
a50aa0fb95 Fix null pointer for KeyDerivationName 2018-05-02 07:16:55 +02:00
J-Jamet
cf026e8eaa Update progress bar and message progress 2018-05-01 20:03:43 +02:00
J-Jamet
77614d0c4a Upgrade changelogs and version 2018-04-30 19:54:50 +02:00
J-Jamet
e8d71039d7 refactor 2018-04-30 18:18:13 +02:00
J-Jamet
4164b5bd37 Fix crash by locking activity position 2018-04-30 17:47:31 +02:00
J-Jamet
3c66ec82b5 Upgrade French 2018-04-30 17:00:42 +02:00
J-Jamet
b796c16877 Upgrade Italian 2018-04-30 16:57:10 +02:00
J-Jamet
42d34d8f0c Add material icon pack in free version and change texts 2018-04-30 16:10:18 +02:00
J-Jamet
5fbb37df82 Fix german fingerprint error 2018-04-29 14:07:56 +02:00
J-Jamet
52e12d7cbd Upgrade russian translation 2018-04-28 22:34:25 +02:00
J-Jamet
5cf5719e8e Fix education text color 2018-04-28 20:08:33 +02:00
J-Jamet
af3a80143e Fix crash by return blank when Resources$NotFoundException 2018-04-28 19:49:59 +02:00
J-Jamet
90db27c3fe Refactor Master key functions 2018-04-28 18:15:30 +02:00
J-Jamet
3d584b76f7 Choose kdf and encapsulate code 2018-04-28 15:58:04 +02:00
J-Jamet
fbf3dec421 Assign algorithm dynamically 2018-04-28 12:20:18 +02:00
J-Jamet
1d36683128 Remove screens in Readme 2018-04-28 11:11:50 +02:00
J-Jamet
cefc546c0a Upgrade german translation 2018-04-28 11:08:23 +02:00
J-Jamet
7aeb51813c Show algorithm dialog 2018-04-26 23:00:15 +02:00
J-Jamet
d6fc29ec79 Creation of classes and prepare assignment for algorithms 2018-04-26 22:00:11 +02:00
J-Jamet
9af182e0c3 Change dark style 2018-04-26 16:14:22 +02:00
J-Jamet
c7120b997f Fix contribution issue for KeePass DX Pro 2018-04-26 14:39:45 +02:00
J-Jamet
e61571fcec Upgrade fastlane 2018-04-26 12:18:14 +02:00
J-Jamet
9a900b32b2 Merge tag '2.5.0.0beta9' into develop
2.5.0.0beta9
2018-04-25 13:16:14 +02:00
J-Jamet
1033dd78b0 Merge branch 'release/2.5.0.0beta9' 2018-04-25 13:15:44 +02:00
J-Jamet
4aaae3f59e Upgrade readme and screen 2018-04-25 13:15:13 +02:00
J-Jamet
1424633a58 Update screenshots 2018-04-25 01:36:30 +02:00
J-Jamet
c9b98094e5 Change purple colors 2018-04-24 00:46:31 +02:00
J-Jamet
5707026985 Change fingerprint visual 2018-04-24 00:36:37 +02:00
J-Jamet
bfcfb842fb Fix visual bugs 2018-04-23 20:59:59 +02:00
J-Jamet
8fe2230891 Fix visual bugs 2018-04-23 20:40:17 +02:00
J-Jamet
41cc0b1a5a Fix compilation 2018-04-23 19:20:15 +02:00
J-Jamet
cc8c525dab Upgrade fastlane 2018-04-23 18:55:32 +02:00
J-Jamet
92bc3c2838 Add pro app name 2018-04-23 15:51:13 +02:00
J-Jamet
1d065e7bc5 Fix crash when orientation change after a modification 2018-04-21 15:44:17 +02:00
J-Jamet
fb1b90a281 Add modification 2018-04-21 14:20:43 +02:00
J-Jamet
268f716104 Upgrade fastlane 2018-04-21 07:14:34 +02:00
J-Jamet
b7328875f1 Fix filepicker style 2018-04-20 20:27:34 +02:00
J-Jamet
02ee58efa7 Add dev to crypt settings and comment transition 2018-04-20 19:59:31 +02:00
J-Jamet
6754881847 Add activity animation 2018-04-20 17:57:39 +02:00
J-Jamet
6e4c5d8c26 Add transition for settings 2018-04-20 17:43:08 +02:00
J-Jamet
544648c2eb Remove TODO 2018-04-20 16:03:10 +02:00
J-Jamet
e62f8bf56b Solve empty password issue #2 2018-04-20 15:48:53 +02:00
J-Jamet
7f5138b08b Upgrade Changelogs and versions 2018-04-20 10:44:22 +02:00
J-Jamet
a367aeaf12 Change font by Droid Sans Mono Slashed and activate by default, add it in password generator #86 2018-04-19 11:09:55 +02:00
J-Jamet
fc6453beba Keyboard setting with dev dialog 2018-04-18 22:28:49 +02:00
J-Jamet
8a981b7a79 Move appearance settings 2018-04-18 21:26:42 +02:00
J-Jamet
d7f9a02699 New selection screen 2018-04-18 19:32:51 +02:00
J-Jamet
7c9153ea04 Open button expanded and add small text 2018-04-17 14:09:44 +02:00
J-Jamet
2c16fe3335 Add fab menu 2018-04-16 21:32:56 +02:00
J-Jamet
eb14d27ca5 #88 Fix crash when header can't be write 2018-04-16 19:47:27 +02:00
J-Jamet
7024178069 #88 Open file with kitkat 2018-04-16 19:37:03 +02:00
J-Jamet
c85ce3e0e8 Replace standart by standard 2018-04-16 16:14:27 +02:00
J-Jamet
067c5ff1cf Fix bugs for Icons and Styles, add contribution and pro dialog 2018-04-16 15:27:45 +02:00
J-Jamet
429bd99f1c Upgrade app icons 2018-04-15 23:44:35 +02:00
J-Jamet
7b5bb0fd97 Add ocean theme and fix styles 2018-04-15 21:07:44 +02:00
J-Jamet
ae50f424d3 App icon for each flavor 2018-04-15 19:28:59 +02:00
J-Jamet
53cc1ad673 Disable custom font and clipboard notification by default #86 2018-04-15 12:08:44 +02:00
J-Jamet
ceb80c6cac Remove the first activity, fix colors in Classic theme and fix custom icon tint 2018-04-14 21:54:29 +02:00
J-Jamet
71bd3ab780 Add splashscreen 2018-04-14 20:39:15 +02:00
J-Jamet
8a40a4b3ae Fix visual bugs, add classic theme and pro theme #27 2018-04-14 19:58:26 +02:00
J-Jamet
7772db17ae Change productFlavors names 2018-04-14 15:36:41 +02:00
J-Jamet
11738d807c Merge branch 'feature/IconPackModules' into develop 2018-04-13 20:55:15 +02:00
J-Jamet
80b9a8fa50 List of IconPack as gradle entity 2018-04-13 20:54:05 +02:00
J-Jamet
d619f6581e Fix landscape icon #84 2018-04-13 20:04:11 +02:00
J-Jamet
697e9aa923 Fix visual bugs and save icon pack setting 2018-04-13 19:47:56 +02:00
J-Jamet
15c843fbb9 Add setting to choose an IconPack 2018-04-13 17:08:13 +02:00
J-Jamet
b6b7e61cfb Add tint for icon pack 2018-04-12 19:21:53 +02:00
J-Jamet
d5b0ee9371 Add feather icon and licences for icon packs 2018-04-12 17:32:06 +02:00
J-Jamet
e86807c3d3 Clean code and solve recovered icon 2018-04-11 20:57:04 +02:00
J-Jamet
08fcb119a9 Finish merge material_icon_pack 2018-04-11 19:10:48 +02:00
J-Jamet
edff33afd1 Merge branch 'justintime4tea-53_new-icon-pack' into feature/IconPackModules (Move in module material_icon_pack)
# Conflicts:
#	app/build.gradle
#	icon-pack-classic/src/main/res/drawable-hdpi/classic_64_32dp.png
#	icon-pack-classic/src/main/res/drawable-ldpi/classic_64_32dp.png
#	icon-pack-classic/src/main/res/drawable/classic_64_32dp.png
2018-04-11 19:09:53 +02:00
J-Jamet
bdfa963bed Merge branch '53_new-icon-pack' of git://github.com/justintime4tea/KeePass-Libre into justintime4tea-53_new-icon-pack 2018-04-11 18:23:17 +02:00
J-Jamet
4eff247865 Add icon pack identifier 2018-04-11 18:13:58 +02:00
J-Jamet
3e3d5bd7d8 Merge branch 'feature/Education' into develop 2018-04-11 15:31:18 +02:00
J-Jamet
5a74d1be8f Add links for field reference and autofill setting, add doc, fix glitches, add changelogs 2018-04-10 21:15:05 +02:00
J-Jamet
812eccfe0e Sort_selection as ScrollView #83 2018-04-10 19:01:22 +02:00
J-Jamet
d00c337382 Fix visual issues in education screens 2018-04-10 17:58:17 +02:00
J-Jamet
54dbcc95ab Change education for entries screens 2018-04-10 17:31:22 +02:00
J-Jamet
2e5ddd80ff Change education for group screen 2018-04-10 15:18:27 +02:00
J-Jamet
2c44a4d760 Change education for password screen 2018-04-10 12:44:49 +02:00
J-Jamet
f8561222d5 Change education for database selection 2018-04-10 12:23:41 +02:00
J-Jamet
2c8e3e9c8e Merge branch 'develop' into feature/Education
# Conflicts:
#	app/src/main/java/com/kunzisoft/keepass/activities/EntryActivity.java
#	app/src/main/java/com/kunzisoft/keepass/activities/EntryEditActivity.java
#	app/src/main/java/com/kunzisoft/keepass/activities/GroupActivity.java
#	app/src/main/java/com/kunzisoft/keepass/fileselect/FileSelectActivity.java
#	app/src/main/java/com/kunzisoft/keepass/password/PasswordActivity.java
#	app/src/main/java/com/kunzisoft/keepass/utils/MenuUtil.java
#	app/src/main/res/values/donottranslate.xml
2018-04-10 10:33:52 +02:00
J-Jamet
ccbc6c07ed Update supportVersion libraries 2018-04-10 09:59:33 +02:00
J-Jamet
47e820e3d8 (Implementation) Merge branch 'justintime4tea-kunzi-develop' into develop 2018-04-10 09:49:24 +02:00
J-Jamet
13dea4b567 New icon pack importer 2018-04-09 21:37:28 +02:00
Justin Gross
70d1ce715e Change compile to implementation 2018-04-08 16:20:07 -04:00
J-Jamet
cc41545c0a create Classic Icon Pack 2018-04-08 12:45:25 +02:00
J-Jamet
aded8fab0a Rebuild classic icons (Add apple icon and remove numbers) 2018-04-07 15:41:52 +02:00
J-Jamet
9cb4d28ad8 Upgrade Readme 2018-04-07 10:31:59 +02:00
J-Jamet
a1b2235fb3 Merge tag '2.5.0.0beta8' into develop
2.5.0.0beta8
2018-04-06 20:29:47 +02:00
Justin Gross
ed7f6e4b68 Update icons to font awesome 2018-04-04 16:49:40 -04:00
Justin Gross
1ebba9d8be Merge pull request #1 from Kunzisoft/develop
Merge upstream changes
2018-04-04 11:00:37 -04:00
J-Jamet
347522b9a6 Add lock, field copy, sort and donation 2018-04-03 20:40:52 +02:00
J-Jamet
918f563faa Change Education for Password layout and fix translations 2018-04-03 17:11:46 +02:00
J-Jamet
041f3eb568 Solve visual bugs and translation 2018-04-02 12:59:02 +02:00
J-Jamet
4a1d97a622 Add entry edit screens preference 2018-04-01 16:34:54 +02:00
J-Jamet
cd0d712f56 Add reset education screens preference 2018-04-01 00:37:30 +02:00
J-Jamet
761d9a1883 Add education to "add button" 2018-03-31 21:59:05 +02:00
J-Jamet
2c9a6d7c26 Add education to database selection 2018-03-31 21:24:39 +02:00
729 changed files with 28197 additions and 4799 deletions

1
.gitignore vendored
View File

@@ -71,6 +71,7 @@ app/app.iml
# Art # Art
art/screen*.png art/screen*.png
art/logo_512.png art/logo_512.png
art/store_screens/
# Dir linux # Dir linux
.directory .directory

View File

@@ -1,3 +1,39 @@
KeepassDX (2.5.0.0beta11)
* Fix memory issue with parcelable (crash in beta12 version)
KeepassDX (2.5.0.0beta12)
* Added the Magikeyboard to fill the forms (settings still in development)
* Added move and copy for groups and entries
* New navigation in a single screen / new animations between activities
* New icons for the material pack / vectorization
* New adaptive launcher icon
* Icons depends now of setting of list items
* Added a setting to disable the open button when no password is identified
* Added a setting to disable the education screens
* Added a setting to disable the copy of protected custom fields
* Fix the fingerprint recognition (WARNING : The keystore is reinit, you must delete the old keys)
* Fix small bugs
KeepassDX (2.5.0.0beta11)
* Fix crash in beta10 version
KeepassDX (2.5.0.0beta10)
* Dynamically change Algorithm and Key Derivation Function in settings
* Upgrade translations
* New red volcano theme, fix classic dark theme
* Add Material Icon Pack to the Free version
* Update fingerprint state with checkbox
* Fix bugs
KeepassDX (2.5.0.0beta9)
* Education Screens to learn how to use the app
* New designs
* New custom font for character visibility
* New themes
* New icon pack
* Change setting organisation
* Pro version
KeepassDX (2.5.0.0beta8) KeepassDX (2.5.0.0beta8)
* Hide custom entries protected * Hide custom entries protected
* Best management of field references (https://keepass.info/help/base/fieldrefs.html) * Best management of field references (https://keepass.info/help/base/fieldrefs.html)

55
FAQ.md Normal file
View File

@@ -0,0 +1,55 @@
# F.A.Q.
## Why KeePass DX?
KeePass DX is an **Android password manager** implemented from Keepass password manager.
KeePass DX was created to meet the security and usability needs of a KeePass application on Android :
- To be easy to use with **secure password management and form filling tools**.
- To use only tools under **open source license** to guarantee the security of the application (With [open source store](https://f-droid.org/en/) and no closed API).
- To be in a **native langage** (java) for weight, security and a better integration of the application.
- To respect **Android design, architecture and ergonomic**.
## What makes KeePass DX stand out from other password managers?
- We **do not recover your sensitive data** on a private server or a closed cloud, you have control of your passwords.
- We respect **KeePass file standards** to maintain compatibility and data porting on different devices (computers and portable devices with different operating system).
- The code is **open source**, which implies increased **security**, you can check how the encryption algorithms are implemented.
- We remain attentive to **your needs** and we can even integrate the features that you have defined.
- We **do not put advertising** even in the free version.
## How am I sure my passwords are safely stored on the application?
- We allow users to save and use passwords, keys and digital identities in a secure way by **integrating the last encryption algorithms** and **Android architecture standards**.
- You can increase the security of your database by increasing the rounds of encryption keys. *(In Settings -> Database Settings when your database is open)* **Warning**: *Increase the number of rounds sparingly to have a reasonable opening time.*
## Can I store my data on a cloud storage?
**Yes** this is possible. Otherwise, we **recommend using cloud with personal server and open source license**, like [NextCloud](https://f-droid.org/en/packages/com.nextcloud.client/) to be sure how your databases are stored.
## Can I recover my passwords on another device if I loose my main device?
**Yes** you can, but you **must first save the .kdb or .kdbx file from your database to an external storage** *(like a hardrive or a cloud)*.
We recommend you save your data after each modification so incase you loose your android device you could retrieve the data and import it into the new KeePass DX installed on the new android device.
## Why are updates not available at the same time on all stores?
- **PlayStore** only needs an APK generated and manually signed to be available on the store, it usually takes **20 minutes** to be available because it is deployed with fastlane. But the management of the APK and its data by the google servers is obscure.
- **F-Droid**, to **ensure that the code is open source**, checks the sources directly on git repository (by checking the presence of new tags) and builds itself the APK that the server signs during the compilation of code and dependencies. Updating the project will take **1-10 days** for F-Droid to analyze all available repositories, build sources and deploy the generated APK. So F-Droid is slower for deployment but it is run by **volunteers** and guaranteed a **clean APK**. :)
## Why not an online version?
The offline and online client concepts only exists with Keepass2Android because the file access network tools are directly integrated into the code of the main application. Which is a very dubious choice knowing that **it is not normally the purpose of a password management application to take care of external file synchronization on clouds** (which can be under closed licensed and recover your data base), it is rather the purpose of the [file management application](https://developer.android.com/guide/topics/providers/document-provider).
## Can I open my database easily other than with a password?
**Yes**, we have integrated a secure openning option of fingerprint for android devices that support this feature, so no one can access the application without scanning his/her fingerprint or fill a master key.
## Can I open my database without my master key (master password and/or key file)?
**No**, you can not open a database file without the master password (and / or) the associated key file. Be sure to remember your master password and save the key file in a safe place.
## Can I suggest features and report bugs for the application?
**Yes**, we welcome this you could go ahead and do that on our github:
https://github.com/Kunzisoft/KeePassDX

View File

@@ -0,0 +1,396 @@
Attribution 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are
intended for use by those authorized to give the public
permission to use material in ways otherwise restricted by
copyright and certain other rights. Our licenses are
irrevocable. Licensors should read and understand the terms
and conditions of the license they choose before applying it.
Licensors should also secure all rights necessary before
applying our licenses so that the public can reuse the
material as expected. Licensors should clearly mark any
material not subject to the license. This includes other CC-
licensed material, or material used under an exception or
limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public
licenses, a licensor grants the public permission to use the
licensed material under specified terms and conditions. If
the licensor's permission is not necessary for any reason--for
example, because of any applicable exception or limitation to
copyright--then that use is not regulated by the license. Our
licenses grant only permissions under copyright and certain
other rights that a licensor has authority to grant. Use of
the licensed material may still be restricted for other
reasons, including because others have copyright or other
rights in the material. A licensor may make special requests,
such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to
respect those requests where reasonable. More considerations
for the public:
wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution 4.0 International Public License
By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution 4.0 International Public License ("Public License"). To the
extent this Public License may be interpreted as a contract, You are
granted the Licensed Rights in consideration of Your acceptance of
these terms and conditions, and the Licensor grants You such rights in
consideration of benefits the Licensor receives from making the
Licensed Material available under these terms and conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar
Rights that is derived from or based upon the Licensed Material
and in which the Licensed Material is translated, altered,
arranged, transformed, or otherwise modified in a manner requiring
permission under the Copyright and Similar Rights held by the
Licensor. For purposes of this Public License, where the Licensed
Material is a musical work, performance, or sound recording,
Adapted Material is always produced where the Licensed Material is
synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright
and Similar Rights in Your contributions to Adapted Material in
accordance with the terms and conditions of this Public License.
c. Copyright and Similar Rights means copyright and/or similar rights
closely related to copyright including, without limitation,
performance, broadcast, sound recording, and Sui Generis Database
Rights, without regard to how the rights are labeled or
categorized. For purposes of this Public License, the rights
specified in Section 2(b)(1)-(2) are not Copyright and Similar
Rights.
d. Effective Technological Measures means those measures that, in the
absence of proper authority, may not be circumvented under laws
fulfilling obligations under Article 11 of the WIPO Copyright
Treaty adopted on December 20, 1996, and/or similar international
agreements.
e. Exceptions and Limitations means fair use, fair dealing, and/or
any other exception or limitation to Copyright and Similar Rights
that applies to Your use of the Licensed Material.
f. Licensed Material means the artistic or literary work, database,
or other material to which the Licensor applied this Public
License.
g. Licensed Rights means the rights granted to You subject to the
terms and conditions of this Public License, which are limited to
all Copyright and Similar Rights that apply to Your use of the
Licensed Material and that the Licensor has authority to license.
h. Licensor means the individual(s) or entity(ies) granting rights
under this Public License.
i. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material
available to the public including in ways that members of the
public may access the material from a place and at a time
individually chosen by them.
j. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and of
the Council of 11 March 1996 on the legal protection of databases,
as amended and/or succeeded, as well as other essentially
equivalent rights anywhere in the world.
k. You means the individual or entity exercising the Licensed Rights
under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License,
the Licensor hereby grants You a worldwide, royalty-free,
non-sublicensable, non-exclusive, irrevocable license to
exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or
in part; and
b. produce, reproduce, and Share Adapted Material.
2. Exceptions and Limitations. For the avoidance of doubt, where
Exceptions and Limitations apply to Your use, this Public
License does not apply, and You do not need to comply with
its terms and conditions.
3. Term. The term of this Public License is specified in Section
6(a).
4. Media and formats; technical modifications allowed. The
Licensor authorizes You to exercise the Licensed Rights in
all media and formats whether now known or hereafter created,
and to make technical modifications necessary to do so. The
Licensor waives and/or agrees not to assert any right or
authority to forbid You from making technical modifications
necessary to exercise the Licensed Rights, including
technical modifications necessary to circumvent Effective
Technological Measures. For purposes of this Public License,
simply making modifications authorized by this Section 2(a)
(4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every
recipient of the Licensed Material automatically
receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this
Public License.
b. No downstream restrictions. You may not offer or impose
any additional or different terms or conditions on, or
apply any Effective Technological Measures to, the
Licensed Material if doing so restricts exercise of the
Licensed Rights by any recipient of the Licensed
Material.
6. No endorsement. Nothing in this Public License constitutes or
may be construed as permission to assert or imply that You
are, or that Your use of the Licensed Material is, connected
with, or sponsored, endorsed, or granted official status by,
the Licensor or others designated to receive attribution as
provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not
licensed under this Public License, nor are publicity,
privacy, and/or other similar personality rights; however, to
the extent possible, the Licensor waives and/or agrees not to
assert any such rights held by the Licensor to the limited
extent necessary to allow You to exercise the Licensed
Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this
Public License.
3. To the extent possible, the Licensor waives any right to
collect royalties from You for the exercise of the Licensed
Rights, whether directly or through a collecting society
under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly
reserves any right to collect such royalties.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the
following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified
form), You must:
a. retain the following if it is supplied by the Licensor
with the Licensed Material:
i. identification of the creator(s) of the Licensed
Material and any others designated to receive
attribution, in any reasonable manner requested by
the Licensor (including by pseudonym if
designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of
warranties;
v. a URI or hyperlink to the Licensed Material to the
extent reasonably practicable;
b. indicate if You modified the Licensed Material and
retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this
Public License, and include the text of, or the URI or
hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any
reasonable manner based on the medium, means, and context in
which You Share the Licensed Material. For example, it may be
reasonable to satisfy the conditions by providing a URI or
hyperlink to a resource that includes the required
information.
3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
4. If You Share Adapted Material You produce, the Adapter's
License You apply must not prevent recipients of the Adapted
Material from complying with this Public License.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
to extract, reuse, reproduce, and Share all or a substantial
portion of the contents of the database;
b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material; and
c. You must comply with the conditions in Section 3(a) if You Share
all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided
above shall be interpreted in a manner that, to the extent
possible, most closely approximates an absolute disclaimer and
waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and
Similar Rights licensed here. However, if You fail to comply with
this Public License, then Your rights under this Public License
terminate automatically.
b. Where Your right to use the Licensed Material has terminated under
Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided
it is cured within 30 days of Your discovery of the
violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any
right the Licensor may have to seek remedies for Your violations
of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the
Licensed Material under separate terms or conditions or stop
distributing the Licensed Material at any time; however, doing so
will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different
terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the
Licensed Material not stated herein are separate from and
independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and
shall not be interpreted to, reduce, limit, restrict, or impose
conditions on any use of the Licensed Material that could lawfully
be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is
deemed unenforceable, it shall be automatically reformed to the
minimum extent necessary to make it enforceable. If the provision
cannot be reformed, it shall be severed from this Public License
without affecting the enforceability of the remaining terms and
conditions.
c. No term or condition of this Public License will be waived and no
failure to comply consented to unless expressly agreed to by the
Licensor.
d. Nothing in this Public License constitutes or may be interpreted
as a limitation upon, or waiver of, any privileges and immunities
that apply to the Licensor or You, including from the legal
processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the “Licensor.” The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.
Creative Commons may be contacted at creativecommons.org.

View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -1,43 +1,48 @@
# Android Keepass DX # Android Keepass DX
<img src="https://raw.githubusercontent.com/Kunzisoft/KeePassDX/master/fastlane/metadata/android/en-US/images/icon.png"> Keepass DX is a material design Keepass Client for manage keys and passwords in crypt database for your android device. <img src="https://raw.githubusercontent.com/Kunzisoft/KeePassDX/master/art/icon.png"> Keepass DX is a **multi-format KeePass manager for Android devices**. The application allows to create keys and passwords in a secure way by integrating with the Android design standards.
<img src="https://raw.githubusercontent.com/Kunzisoft/KeePassDX/master/art/screen.jpg" width="220">
### Features ### Features
* Create database files / entries and groups * Create database files / entries and groups
* Support for .kdb and .kdbx files (version 1 to 4) * Support for **.kdb** and **.kdbx** files (version 1 to 4) with AES - Twofish - ChaCha20 - Argon2 algorithm
* Open database, copy username / password, open URI / URL * **Compatible** with the majority of alternative programs (KeePass, KeePassX, KeePass XC...)
* Fingerprint for fast unlocking * Allows **fast copy** of fields and opening of URI / URL
* Material design with themes * **Fingerprint** for fast unlocking
* AutoFill and Integration (Development in progress) * Material design with **themes**
* Precise management of settings * **AutoFill** and Integration
* Field filling **keyboard**
* Precise management of **settings**
<img src="https://raw.githubusercontent.com/Kunzisoft/KeePassDX/master/fastlane/metadata/android/en-US/images/phoneScreenshots/screen1.jpg" width="220"> Keepass DX is **open source** and **ad-free**.
<img src="https://raw.githubusercontent.com/Kunzisoft/KeePassDX/master/fastlane/metadata/android/en-US/images/phoneScreenshots/screen2.jpg" width="220">
## What is KeePass? ## What is KeePass DX?
Today you need to remember many passwords. You need a password for the Windows network logon, your e-mail account, your website's FTP password, online passwords (like website member account), etc. etc. etc. The list is endless. Also, you should use different passwords for each account. Because if you use only one password everywhere and someone gets this password you have a problem... A serious problem. The thief would have access to your e-mail account, website, etc. Unimaginable. Today you need to remember many passwords. You need a password for your e-mail account, your website's FTP password, online passwords (like website member account), etc. etc. etc. The list is endless. Also, you **should use different passwords for each account**. Because if you use only one password everywhere and someone gets this password you have a problem... A serious problem. The thief would have access to your e-mail account, website, etc. Unimaginable.
KeePass is a free open source password manager, which helps you to manage your passwords in a secure way. You can put all your passwords in one database, which is locked with one master key or a key file. So you only have to remember one single master password or select the key file to unlock the whole database. The databases are encrypted using the best and most secure encryption algorithms currently known (AES and Twofish). For more information, see the features page. KeePass DX is a **free open source password manager for Android**, which helps you to **manage your passwords in a secure way**. You can put all your passwords in one database, which is locked with one **master key** or a **key file**. So you **only have to remember one single master password or select the key file** to unlock the whole database. The databases are encrypted using the best and **most secure encryption algorithms** currently known.
## Is it really free? ## Is it really free?
Yes, KeePass is really free, and more than that: it is open source (OSI certified). You can have a look at its full source and check whether the encryption algorithms are implemented correctly. Yes, KeePass DX is under **free license (OSI certified)** and **without advertising**. You can have a look at its full source and check whether the encryption algorithms are implemented correctly.
## Donation *Note : If you access the application from a store, visual features may not be available to incentivize the contribution to the work of open source projects. These optional visuals are accessible after a donation (and a small congratulation message :) or the purchase of an extended version, but do not worry, the main features remain completely free.*
Even if the application is free, to maintain the application, you can make donations. ## Contributions
[![Donation Paypal](https://4.bp.blogspot.com/-ncaIbUGaHOk/WfhaThYUPGI/AAAAAAAAAVQ/_HidNgdB1q4DaC24ujaKNzH64KUUJiQewCLcBGAs/s1600/pay-with-paypal.png)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=KM6QMDAXZM3UU "Kunzisoft Paypal Donation") You can contribute in different ways to help us on our work.
[![Donation Liberapay](https://liberapay.com/assets/widgets/donate.svg)](https://liberapay.com/Kunzisoft/donate "Kunzisoft Liberapay Donation") * Add features by a **[pull request](https://help.github.com/articles/about-pull-requests/)**.
* Help to **[translate](https://hosted.weblate.org/projects/keepass-dx/strings/)** into your language (By using [Weblate](https://hosted.weblate.org/projects/keepass-dx/) or with a manual [pull request](https://help.github.com/articles/about-pull-requests/))
<img src="https://raw.githubusercontent.com/Kunzisoft/KeePassDX/master/fastlane/metadata/android/en-US/images/phoneScreenshots/screen4.jpg" width="220"> * **[Donate](https://www.kunzisoft.com/donation)** 人◕ ‿‿ ◕人Y for a better service and a quick development of your features.
<img src="https://raw.githubusercontent.com/Kunzisoft/KeePassDX/master/fastlane/metadata/android/en-US/images/phoneScreenshots/screen5.jpg" width="220"> * Buy the **[Pro version](https://play.google.com/store/apps/details?id=com.kunzisoft.keepass.pro)** of KeePass DX
## Download ## Download
*We recommend the installation from [F-Droid](https://f-droid.org/en/packages/com.kunzisoft.keepass.libre/) which verifies that all libraries and application code are open source.*
[<img src="https://f-droid.org/badge/get-it-on.png" [<img src="https://f-droid.org/badge/get-it-on.png"
alt="Get it on F-Droid" alt="Get it on F-Droid"
height="80">](https://f-droid.org/en/packages/com.kunzisoft.keepass.libre/) height="80">](https://f-droid.org/en/packages/com.kunzisoft.keepass.libre/)
@@ -45,10 +50,20 @@ Even if the application is free, to maintain the application, you can make donat
[<img src="https://play.google.com/intl/en_us/badges/images/generic/en_badge_web_generic.png" [<img src="https://play.google.com/intl/en_us/badges/images/generic/en_badge_web_generic.png"
alt="Get it on Google Play" alt="Get it on Google Play"
height="80">](https://play.google.com/store/apps/details?id=com.kunzisoft.keepass.free) height="80">](https://play.google.com/store/apps/details?id=com.kunzisoft.keepass.free)
## F.A.Q.
Other questions? You can read the [F.A.Q.](https://github.com/Kunzisoft/KeePassDX/blob/master/FAQ.md)
## Other devices
- [KeePass XC](https://keepassxc.org/) (https://keepassxc.org/) works with **GNU/Linux**, **Mac** and **Windows**, is updated regularly and under the terms of the GNU General Public License. This is the recommended version for computers.
- [KeePass](https://keepass.info/) (https://keepass.info/) is the historical project, with good technical documentation for standardized database files but only running on **Windows**.
## License ## License
Copyright (c) 2017 Jeremy Jamet / Kunzisoft. Copyright (c) 2017 Jeremy Jamet / [Kunzisoft](https://www.kunzisoft.com).
This file is part of KeePass DX. This file is part of KeePass DX.
@@ -65,4 +80,4 @@ Even if the application is free, to maintain the application, you can make donat
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with KeePass DX. If not, see <http://www.gnu.org/licenses/>. along with KeePass DX. If not, see <http://www.gnu.org/licenses/>.
This project is a fork of [KeepassDroid](https://github.com/bpellin/keepassdroid) by bpellin. *This project is a fork of [KeepassDroid](https://github.com/bpellin/keepassdroid) by bpellin.*

View File

@@ -1,24 +1,21 @@
apply plugin: 'com.android.application' apply plugin: 'com.android.application'
android { android {
compileSdkVersion = 27 compileSdkVersion 27
buildToolsVersion = '27.0.3' buildToolsVersion '27.0.3'
defaultConfig { defaultConfig {
applicationId "com.kunzisoft.keepass" applicationId "com.kunzisoft.keepass"
minSdkVersion 14 minSdkVersion 15
targetSdkVersion 27 targetSdkVersion 27
versionCode = 8 versionCode = 13
versionName = "2.5.0.0beta8" versionName = "2.5.0.0beta13"
multiDexEnabled true multiDexEnabled true
testApplicationId = "com.kunzisoft.keepass.tests" testApplicationId = "com.kunzisoft.keepass.tests"
testInstrumentationRunner = "android.test.InstrumentationTestRunner" testInstrumentationRunner = "android.test.InstrumentationTestRunner"
ndk { buildConfigField "String[]", "ICON_PACKS", "{\"classic\",\"material\"}"
abiFilters 'x86', 'x86_64', 'armeabi', 'armeabi-v7a',
'arm64-v8a', 'mips', 'mips64'
}
} }
externalNativeBuild { externalNativeBuild {
@@ -44,28 +41,42 @@ android {
applicationIdSuffix = ".libre" applicationIdSuffix = ".libre"
versionNameSuffix "-libre" versionNameSuffix "-libre"
buildConfigField "boolean", "FULL_VERSION", "true" buildConfigField "boolean", "FULL_VERSION", "true"
buildConfigField "boolean", "GOOGLE_PLAY_VERSION", "false" buildConfigField "boolean", "CLOSED_STORE", "false"
buildConfigField "String[]", "STYLES_DISABLED", "{\"KeepassDXStyle_Dark\",\"KeepassDXStyle_Red\",\"KeepassDXStyle_Purple\"}"
buildConfigField "String[]", "ICON_PACKS_DISABLED", "{}"
} }
pro_google { pro {
applicationIdSuffix = ".pro" applicationIdSuffix = ".pro"
versionNameSuffix "-pro" versionNameSuffix "-pro"
buildConfigField "boolean", "FULL_VERSION", "true" buildConfigField "boolean", "FULL_VERSION", "true"
buildConfigField "boolean", "GOOGLE_PLAY_VERSION", "true" buildConfigField "boolean", "CLOSED_STORE", "true"
buildConfigField "String[]", "STYLES_DISABLED", "{}"
buildConfigField "String[]", "ICON_PACKS_DISABLED", "{}"
} }
free_google { free {
applicationIdSuffix = ".free" applicationIdSuffix = ".free"
versionNameSuffix "-free" versionNameSuffix "-free"
buildConfigField "boolean", "FULL_VERSION", "false" buildConfigField "boolean", "FULL_VERSION", "false"
buildConfigField "boolean", "GOOGLE_PLAY_VERSION", "true" buildConfigField "boolean", "CLOSED_STORE", "true"
buildConfigField "String[]", "STYLES_DISABLED", "{\"KeepassDXStyle_Dark\",\"KeepassDXStyle_Blue\",\"KeepassDXStyle_Red\",\"KeepassDXStyle_Purple\"}"
buildConfigField "String[]", "ICON_PACKS_DISABLED", "{}"
} }
} }
sourceSets {
libre.res.srcDir 'src/libre/res'
pro.res.srcDir 'src/pro/res'
free.res.srcDir 'src/free/res'
}
compileOptions { compileOptions {
targetCompatibility 1.8 targetCompatibility JavaVersion.VERSION_1_8
sourceCompatibility 1.8 sourceCompatibility JavaVersion.VERSION_1_8
} }
} }
def supportVersion = "27.1.0" def supportVersion = "27.1.1"
def spongycastleVersion = "1.58.0.0" def spongycastleVersion = "1.58.0.0"
def permissionDispatcherVersion = "3.1.0" def permissionDispatcherVersion = "3.1.0"
@@ -77,20 +88,28 @@ dependencies {
implementation "com.android.support:cardview-v7:$supportVersion" implementation "com.android.support:cardview-v7:$supportVersion"
implementation "com.madgag.spongycastle:core:$spongycastleVersion" implementation "com.madgag.spongycastle:core:$spongycastleVersion"
implementation "com.madgag.spongycastle:prov:$spongycastleVersion" implementation "com.madgag.spongycastle:prov:$spongycastleVersion"
// Expandable view
implementation 'net.cachapa.expandablelayout:expandablelayout:2.9.2'
// Time // Time
implementation "joda-time:joda-time:2.9.9" implementation 'joda-time:joda-time:2.9.9'
implementation "org.sufficientlysecure:html-textview:3.5" implementation 'org.sufficientlysecure:html-textview:3.5'
implementation "com.nononsenseapps:filepicker:4.1.0" implementation 'com.nononsenseapps:filepicker:4.1.0'
implementation 'com.getkeepsafe.taptargetview:taptargetview:1.11.0'
// Permissions // Permissions
implementation ("com.github.hotchemi:permissionsdispatcher:$permissionDispatcherVersion") { implementation("com.github.hotchemi:permissionsdispatcher:$permissionDispatcherVersion") {
// if you don't use android.app.Fragment you can exclude support for them // if you don't use android.app.Fragment you can exclude support for them
exclude module: "support-v13" exclude module: "support-v13"
} }
// Apache Commons Collections
implementation group: 'commons-collections', name: 'commons-collections', version: '3.2.1'
// Base64
compile group: 'biz.source_code', name: 'base64coder', version: '2010-12-19'
annotationProcessor "com.github.hotchemi:permissionsdispatcher-processor:$permissionDispatcherVersion" annotationProcessor "com.github.hotchemi:permissionsdispatcher-processor:$permissionDispatcherVersion"
implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.1' // Apache Commons Collections
implementation group: 'com.google.guava', name: 'guava', version: '23.0-android' implementation 'commons-collections:commons-collections:3.2.1'
// Base64
implementation 'biz.source_code:base64coder:2010-12-19'
implementation 'com.google.code.gson:gson:2.8.4'
implementation 'com.google.guava:guava:23.0-android'
// Icon pack, classic for all, material for libre and pro
implementation project(path: ':icon-pack-classic')
implementation project(path: ':icon-pack-material')
implementation project(path: ':magikeyboard')
implementation project(path: ':keepass-model')
} }

View File

@@ -19,8 +19,6 @@
*/ */
package com.kunzisoft.keepass.tests.database; package com.kunzisoft.keepass.tests.database;
import java.util.List;
import android.content.Context; import android.content.Context;
import android.test.AndroidTestCase; import android.test.AndroidTestCase;
@@ -30,9 +28,11 @@ import com.kunzisoft.keepass.database.PwDatabaseV3;
import com.kunzisoft.keepass.database.PwEntry; import com.kunzisoft.keepass.database.PwEntry;
import com.kunzisoft.keepass.database.PwEntryV3; import com.kunzisoft.keepass.database.PwEntryV3;
import com.kunzisoft.keepass.database.PwGroup; import com.kunzisoft.keepass.database.PwGroup;
import com.kunzisoft.keepass.database.edit.DeleteGroup; import com.kunzisoft.keepass.database.action.node.DeleteGroupRunnable;
import com.kunzisoft.keepass.search.SearchDbHelper; import com.kunzisoft.keepass.search.SearchDbHelper;
import java.util.List;
public class DeleteEntry extends AndroidTestCase { public class DeleteEntry extends AndroidTestCase {
private static final String GROUP1_NAME = "Group1"; private static final String GROUP1_NAME = "Group1";
private static final String ENTRY1_NAME = "Test1"; private static final String ENTRY1_NAME = "Test1";
@@ -60,7 +60,7 @@ public class DeleteEntry extends AndroidTestCase {
assertNotNull("Could not find group1", group1); assertNotNull("Could not find group1", group1);
// Delete the group // Delete the group
DeleteGroup task = new DeleteGroup(db, group1, null, true); DeleteGroupRunnable task = new DeleteGroupRunnable(null, db, group1, null, true);
task.run(); task.run();
// Verify the entries were deleted // Verify the entries were deleted

View File

@@ -0,0 +1,50 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:viewportWidth="108"
android:viewportHeight="108"
android:width="108dp"
android:height="108dp">
<group
android:translateY="-332">
<group
android:translateY="332">
<path
android:pathData="M65.728516 32.791016L58.052734 35.904297 56.173828 48.380859 35.306641 69.267578 35.238281 73.759766 69.478516 108 108 108 108 70.810547 73.09375 35.904297 65.728516 32.791016Z"
android:fillColor="@color/long_shadow"
android:strokeLineJoin="round"
android:strokeLineCap="round"
android:strokeMiterLimit="4" />
</group>
<group
android:scaleX="0.3939503"
android:scaleY="0.3939503"
android:translateX="33.66343"
android:translateY="233.998">
<path
android:pathData="M88.76953 339.91602L4.1718754 424.59766 4.0000004 436 15.400391 435.82813 27.240234 424 40 424l0 -12 12 0 0 -12.73438 34.01172 -33.97656A8 8 0 0 1 84 360a8 8 0 0 1 8 -8 8 8 0 0 1 5.296882 2.01367l2.787098 -2.7832 -11.31445 -11.31445z"
android:fillColor="#eaeaea"
android:strokeWidth="1"
android:strokeColor="#58000000" />
</group>
<group
android:scaleX="0.3939503"
android:scaleY="0.3939503"
android:translateX="33.66343"
android:translateY="233.998">
<path
android:pathData="M4.0000004 340L4.1718754 351.40137 88.59863 435.82812 100 436 99.828122 424.59863 15.401367 340.17188Z"
android:fillColor="#81c784" />
</group>
<group
android:scaleX="0.3939503"
android:scaleY="0.3939503"
android:translateX="33.66343"
android:translateY="233.998">
<path
android:pathData="M81.39454 332.00195a27 27 0 0 0 -19.48634 7.90625 27 27 0 0 0 0 38.1836 27 27 0 0 0 38.1836 0 27 27 0 0 0 0 -38.1836 27 27 0 0 0 -18.69726 -7.90625zM92 352a8 8 0 0 1 8 8 8 8 0 0 1 -8 8 8 8 0 0 1 -8 -8 8 8 0 0 1 8 -8z"
android:fillColor="#eaeaea"
android:strokeWidth="1"
android:strokeColor="#58000000" />
</group>
</group>
</vector>

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/green" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/green" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

View File

@@ -0,0 +1,50 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:viewportWidth="108"
android:viewportHeight="108"
android:width="108dp"
android:height="108dp">
<group
android:translateY="-332">
<group
android:translateY="332">
<path
android:pathData="M65.728516 32.791016L58.052734 35.904297 56.173828 48.380859 35.306641 69.267578 35.238281 73.759766 69.478516 108 108 108 108 70.810547 73.09375 35.904297 65.728516 32.791016Z"
android:fillColor="@color/long_shadow"
android:strokeLineJoin="round"
android:strokeLineCap="round"
android:strokeMiterLimit="4" />
</group>
<group
android:scaleX="0.3939503"
android:scaleY="0.3939503"
android:translateX="33.66343"
android:translateY="233.998">
<path
android:pathData="M88.76953 339.91602L4.1718754 424.59766 4.0000004 436 15.400391 435.82813 27.240234 424 40 424l0 -12 12 0 0 -12.73438 34.01172 -33.97656A8 8 0 0 1 84 360a8 8 0 0 1 8 -8 8 8 0 0 1 5.296882 2.01367l2.787098 -2.7832 -11.31445 -11.31445z"
android:fillColor="#eaeaea"
android:strokeWidth="1"
android:strokeColor="#58000000"/>
</group>
<group
android:scaleX="0.3939503"
android:scaleY="0.3939503"
android:translateX="33.66343"
android:translateY="233.998">
<path
android:pathData="M4.0000004 340L4.1718754 351.40137 88.59863 435.82812 100 436 99.828122 424.59863 15.401367 340.17188Z"
android:fillColor="#64b5f6" />
</group>
<group
android:scaleX="0.3939503"
android:scaleY="0.3939503"
android:translateX="33.66343"
android:translateY="233.998">
<path
android:pathData="M81.39454 332.00195a27 27 0 0 0 -19.48634 7.90625 27 27 0 0 0 0 38.1836 27 27 0 0 0 38.1836 0 27 27 0 0 0 0 -38.1836 27 27 0 0 0 -18.69726 -7.90625zM92 352a8 8 0 0 1 8 8 8 8 0 0 1 -8 8 8 8 0 0 1 -8 -8 8 8 0 0 1 8 -8z"
android:fillColor="#eaeaea"
android:strokeWidth="1"
android:strokeColor="#58000000" />
</group>
</group>
</vector>

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/green" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/green" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

View File

@@ -20,47 +20,28 @@
android:allowBackup="true" android:allowBackup="true"
android:fullBackupContent="@xml/backup" android:fullBackupContent="@xml/backup"
android:backupAgent="com.kunzisoft.keepass.backup.SettingsBackupAgent" android:backupAgent="com.kunzisoft.keepass.backup.SettingsBackupAgent"
android:theme="@style/KeepassDXStyle.Light" android:theme="@style/KeepassDXStyle.Night"
tools:replace="android:theme"> tools:replace="android:theme">
<!-- TODO backup API Key --> <!-- TODO backup API Key -->
<meta-data <meta-data
android:name="com.google.android.backup.api_key" android:name="com.google.android.backup.api_key"
android:value="" /> android:value="" />
<!-- Folder picker -->
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/nnf_provider_paths" />
</provider>
<activity <activity
android:name="com.kunzisoft.keepass.fileselect.FilePickerStylishActivity" android:name="com.kunzisoft.keepass.fileselect.FileSelectActivity"
android:label="@string/app_name"> android:theme="@style/KeepassDXStyle.SplashScreen"
<intent-filter> android:label="@string/app_name"
<action android:name="android.intent.action.GET_CONTENT" /> android:launchMode="singleTop"
<category android:name="android.intent.category.DEFAULT" /> android:configChanges="orientation|keyboardHidden"
</intent-filter> android:windowSoftInputMode="stateHidden" >
</activity>
<activity android:name=".KeePass"
android:label="@string/app_name">
<intent-filter> <intent-filter>
<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-filter> </intent-filter>
</activity> </activity>
<activity
android:name="com.kunzisoft.keepass.fileselect.FileSelectActivity"
android:launchMode="singleInstance"
android:configChanges="orientation|keyboardHidden"
android:windowSoftInputMode="stateHidden" />
<activity <activity
android:name="com.kunzisoft.keepass.activities.AboutActivity" android:name="com.kunzisoft.keepass.activities.AboutActivity"
android:launchMode="singleInstance" android:launchMode="singleTask"
android:label="@string/menu_about" /> android:label="@string/menu_about" />
<activity <activity
android:name="com.kunzisoft.keepass.password.PasswordActivity" android:name="com.kunzisoft.keepass.password.PasswordActivity"
@@ -102,6 +83,24 @@
<data android:mimeType="application/octet-stream"/> <data android:mimeType="application/octet-stream"/>
</intent-filter> </intent-filter>
</activity> </activity>
<!-- Folder picker -->
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/nnf_provider_paths" />
</provider>
<activity
android:name="com.kunzisoft.keepass.fileselect.FilePickerStylishActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.GET_CONTENT" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity <activity
android:name="com.kunzisoft.keepass.activities.GroupActivity" android:name="com.kunzisoft.keepass.activities.GroupActivity"
android:configChanges="orientation|keyboardHidden" android:configChanges="orientation|keyboardHidden"
@@ -133,13 +132,15 @@
<activity android:name="com.kunzisoft.keepass.settings.SettingsActivity" /> <activity android:name="com.kunzisoft.keepass.settings.SettingsActivity" />
<activity android:name="com.kunzisoft.keepass.autofill.AutoFillAuthActivity" <activity android:name="com.kunzisoft.keepass.autofill.AutoFillAuthActivity"
android:configChanges="orientation|keyboardHidden" /> android:configChanges="orientation|keyboardHidden" />
<activity android:name="com.kunzisoft.keepass.selection.EntrySelectionAuthActivity"
android:configChanges="orientation|keyboardHidden" />
<activity android:name="com.kunzisoft.keepass.settings.SettingsAutofillActivity" /> <activity android:name="com.kunzisoft.keepass.settings.SettingsAutofillActivity" />
<service android:name="com.kunzisoft.keepass.timeout.TimeoutService" />
<service <service
android:name="com.kunzisoft.keepass.notifications.NotificationCopyingService" android:name="com.kunzisoft.keepass.notifications.NotificationCopyingService"
android:enabled="true" android:enabled="true"
android:exported="false" /> android:exported="false" />
<!-- Receiver for Autofill -->
<service <service
android:name="com.kunzisoft.keepass.autofill.KeeAutofillService" android:name="com.kunzisoft.keepass.autofill.KeeAutofillService"
android:label="@string/autofill_service_name" android:label="@string/autofill_service_name"
@@ -147,11 +148,11 @@
<meta-data <meta-data
android:name="android.autofill" android:name="android.autofill"
android:resource="@xml/dataset_service" /> android:resource="@xml/dataset_service" />
<intent-filter> <intent-filter>
<action android:name="android.service.autofill.AutofillService" /> <action android:name="android.service.autofill.AutofillService" />
</intent-filter> </intent-filter>
</service> </service>
<meta-data android:name="com.sec.android.support.multiwindow" android:value="true" /> <meta-data android:name="com.sec.android.support.multiwindow" android:value="true" />
</application> </application>
</manifest> </manifest>

Binary file not shown.

View File

@@ -23,8 +23,11 @@ package com.kunzisoft.keepass.activities;
import android.app.Activity; import android.app.Activity;
import android.content.ActivityNotFoundException; import android.content.ActivityNotFoundException;
import android.content.Intent; import android.content.Intent;
import android.graphics.drawable.Drawable; import android.content.res.TypedArray;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.Toolbar; import android.support.v7.widget.Toolbar;
import android.util.Log; import android.util.Log;
import android.view.Menu; import android.view.Menu;
@@ -34,6 +37,8 @@ import android.widget.ImageView;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import com.getkeepsafe.taptargetview.TapTarget;
import com.getkeepsafe.taptargetview.TapTargetView;
import com.kunzisoft.keepass.R; import com.kunzisoft.keepass.R;
import com.kunzisoft.keepass.app.App; import com.kunzisoft.keepass.app.App;
import com.kunzisoft.keepass.database.Database; import com.kunzisoft.keepass.database.Database;
@@ -41,9 +46,13 @@ import com.kunzisoft.keepass.database.ExtraFields;
import com.kunzisoft.keepass.database.PwDatabase; import com.kunzisoft.keepass.database.PwDatabase;
import com.kunzisoft.keepass.database.PwEntry; import com.kunzisoft.keepass.database.PwEntry;
import com.kunzisoft.keepass.database.security.ProtectedString; import com.kunzisoft.keepass.database.security.ProtectedString;
import com.kunzisoft.keepass.icons.IconPackChooser;
import com.kunzisoft.keepass.lock.LockingActivity;
import com.kunzisoft.keepass.lock.LockingHideActivity;
import com.kunzisoft.keepass.notifications.NotificationCopyingService; import com.kunzisoft.keepass.notifications.NotificationCopyingService;
import com.kunzisoft.keepass.notifications.NotificationField; import com.kunzisoft.keepass.notifications.NotificationField;
import com.kunzisoft.keepass.settings.PreferencesUtil; import com.kunzisoft.keepass.settings.PreferencesUtil;
import com.kunzisoft.keepass.settings.SettingsAutofillActivity;
import com.kunzisoft.keepass.timeout.ClipboardHelper; import com.kunzisoft.keepass.timeout.ClipboardHelper;
import com.kunzisoft.keepass.utils.EmptyUtils; import com.kunzisoft.keepass.utils.EmptyUtils;
import com.kunzisoft.keepass.utils.MenuUtil; import com.kunzisoft.keepass.utils.MenuUtil;
@@ -65,6 +74,7 @@ public class EntryActivity extends LockingHideActivity {
private ImageView titleIconView; private ImageView titleIconView;
private TextView titleView; private TextView titleView;
private EntryContentsView entryContentsView; private EntryContentsView entryContentsView;
private Toolbar toolbar;
protected PwEntry mEntry; protected PwEntry mEntry;
private boolean mShowPassword; private boolean mShowPassword;
@@ -87,7 +97,7 @@ public class EntryActivity extends LockingHideActivity {
setContentView(R.layout.entry_view); setContentView(R.layout.entry_view);
Toolbar toolbar = findViewById(R.id.toolbar); toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar); setSupportActionBar(toolbar);
assert getSupportActionBar() != null; assert getSupportActionBar() != null;
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_close_white_24dp); getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_close_white_24dp);
@@ -142,12 +152,28 @@ public class EntryActivity extends LockingHideActivity {
// Start to manage field reference to copy a value from ref // Start to manage field reference to copy a value from ref
mEntry.startToManageFieldReferences(App.getDB().getPwDatabase()); mEntry.startToManageFieldReferences(App.getDB().getPwDatabase());
boolean containsUsernameToCopy =
mEntry.getUsername().length() > 0;
boolean containsPasswordToCopy =
(mEntry.getPassword().length() > 0
&& PreferencesUtil.allowCopyPasswordAndProtectedFields(this));
boolean containsExtraFieldToCopy =
(mEntry.allowExtraFields()
&& ((mEntry.containsCustomFields()
&& mEntry.containsCustomFieldsNotProtected())
|| (mEntry.containsCustomFields()
&& mEntry.containsCustomFieldsProtected()
&& PreferencesUtil.allowCopyPasswordAndProtectedFields(this))
)
);
// If notifications enabled in settings // If notifications enabled in settings
// Don't if application timeout // Don't if application timeout
if (firstLaunchOfActivity && !App.isShutdown() && isClipboardNotificationsEnable(getApplicationContext())) { if (firstLaunchOfActivity && !App.isShutdown() && isClipboardNotificationsEnable(getApplicationContext())) {
if (mEntry.getUsername().length() > 0 if (containsUsernameToCopy
|| (mEntry.getPassword().length() > 0 && PreferencesUtil.allowCopyPassword(this)) || containsPasswordToCopy
|| mEntry.containsCustomFields()) { || containsExtraFieldToCopy
) {
// username already copied, waiting for user's action before copy password. // username already copied, waiting for user's action before copy password.
Intent intent = new Intent(this, NotificationCopyingService.class); Intent intent = new Intent(this, NotificationCopyingService.class);
intent.setAction(NotificationCopyingService.ACTION_NEW_NOTIFICATION); intent.setAction(NotificationCopyingService.ACTION_NEW_NOTIFICATION);
@@ -156,35 +182,37 @@ public class EntryActivity extends LockingHideActivity {
// Construct notification fields // Construct notification fields
ArrayList<NotificationField> notificationFields = new ArrayList<>(); ArrayList<NotificationField> notificationFields = new ArrayList<>();
// Add username if exists to notifications // Add username if exists to notifications
if (mEntry.getUsername().length() > 0) if (containsUsernameToCopy)
notificationFields.add( notificationFields.add(
new NotificationField( new NotificationField(
NotificationField.NotificationFieldId.USERNAME, NotificationField.NotificationFieldId.USERNAME,
mEntry.getUsername(), mEntry.getUsername(),
getResources())); getResources()));
// Add password to notifications // Add password to notifications
if (PreferencesUtil.allowCopyPassword(this)) { if (containsPasswordToCopy) {
if (mEntry.getPassword().length() > 0) notificationFields.add(
notificationFields.add( new NotificationField(
new NotificationField( NotificationField.NotificationFieldId.PASSWORD,
NotificationField.NotificationFieldId.PASSWORD, mEntry.getPassword(),
mEntry.getPassword(), getResources()));
getResources()));
} }
// Add extra fields // Add extra fields
if (mEntry.allowExtraFields()) { if (containsExtraFieldToCopy) {
try { try {
mEntry.getFields().doActionToAllCustomProtectedField(new ExtraFields.ActionProtected() { mEntry.getFields().doActionToAllCustomProtectedField(new ExtraFields.ActionProtected() {
private int anonymousFieldNumber = 0; private int anonymousFieldNumber = 0;
@Override @Override
public void doAction(String key, ProtectedString value) { public void doAction(String key, ProtectedString value) {
notificationFields.add( //If value is not protected or allowed
new NotificationField( if (!value.isProtected() || PreferencesUtil.allowCopyPasswordAndProtectedFields(EntryActivity.this)) {
NotificationField.NotificationFieldId.getAnonymousFieldId()[anonymousFieldNumber], notificationFields.add(
value.toString(), new NotificationField(
key, NotificationField.NotificationFieldId.getAnonymousFieldId()[anonymousFieldNumber],
getResources())); value.toString(),
anonymousFieldNumber++; key,
getResources()));
anonymousFieldNumber++;
}
} }
}); });
} catch (ArrayIndexOutOfBoundsException e) { } catch (ArrayIndexOutOfBoundsException e) {
@@ -202,9 +230,77 @@ public class EntryActivity extends LockingHideActivity {
firstLaunchOfActivity = false; firstLaunchOfActivity = false;
} }
private void populateTitle(Drawable drawIcon, String text) { /**
titleIconView.setImageDrawable(drawIcon); * Check and display learning views
titleView.setText(text); * Displays the explanation for copying a field and editing an entry
*/
private void checkAndPerformedEducation(Menu menu) {
if (PreferencesUtil.isEducationScreensEnabled(this)) {
if (entryContentsView != null && entryContentsView.isUserNamePresent()
&& !PreferencesUtil.isEducationCopyUsernamePerformed(this)) {
TapTargetView.showFor(this,
TapTarget.forView(findViewById(R.id.entry_user_name_action_image),
getString(R.string.education_field_copy_title),
getString(R.string.education_field_copy_summary))
.textColorInt(Color.WHITE)
.tintTarget(false)
.cancelable(true),
new TapTargetView.Listener() {
@Override
public void onTargetClick(TapTargetView view) {
super.onTargetClick(view);
clipboardHelper.timeoutCopyToClipboard(mEntry.getUsername(),
getString(R.string.copy_field, getString(R.string.entry_user_name)));
}
@Override
public void onOuterCircleClick(TapTargetView view) {
super.onOuterCircleClick(view);
view.dismiss(false);
// Launch autofill settings
startActivity(new Intent(EntryActivity.this, SettingsAutofillActivity.class));
}
});
PreferencesUtil.saveEducationPreference(this,
R.string.education_copy_username_key);
} else if (!PreferencesUtil.isEducationEntryEditPerformed(this)) {
try {
TapTargetView.showFor(this,
TapTarget.forToolbarMenuItem(toolbar, R.id.menu_edit,
getString(R.string.education_entry_edit_title),
getString(R.string.education_entry_edit_summary))
.textColorInt(Color.WHITE)
.tintTarget(true)
.cancelable(true),
new TapTargetView.Listener() {
@Override
public void onTargetClick(TapTargetView view) {
super.onTargetClick(view);
MenuItem editItem = menu.findItem(R.id.menu_edit);
onOptionsItemSelected(editItem);
}
@Override
public void onOuterCircleClick(TapTargetView view) {
super.onOuterCircleClick(view);
view.dismiss(false);
// Open Keepass doc to create field references
Intent browserIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse(getString(R.string.field_references_url)));
startActivity(browserIntent);
}
});
PreferencesUtil.saveEducationPreference(this,
R.string.education_entry_edit_key);
} catch (Exception e) {
// If icon not visible
Log.w(TAG, "Can't performed education for entry's edition");
}
}
}
} }
protected void fillData() { protected void fillData() {
@@ -213,9 +309,19 @@ public class EntryActivity extends LockingHideActivity {
mEntry.startToManageFieldReferences(pm); mEntry.startToManageFieldReferences(pm);
// Assign title // Assign title icon
populateTitle(db.getDrawFactory().getIconDrawable(getResources(), mEntry.getIcon()), if (IconPackChooser.getSelectedIconPack(this).tintable()) {
mEntry.getTitle()); // Retrieve the textColor to tint the icon
int[] attrs = {R.attr.textColorInverse};
TypedArray ta = getTheme().obtainStyledAttributes(attrs);
int iconColor = ta.getColor(0, Color.WHITE);
App.getDB().getDrawFactory().assignDatabaseIconTo(this, titleIconView, mEntry.getIcon(), true, iconColor);
} else {
App.getDB().getDrawFactory().assignDatabaseIconTo(this, titleIconView, mEntry.getIcon());
}
// Assign title text
titleView.setText(mEntry.getTitle());
// Assign basic fields // Assign basic fields
entryContentsView.assignUserName(mEntry.getUsername()); entryContentsView.assignUserName(mEntry.getUsername());
@@ -225,7 +331,7 @@ public class EntryActivity extends LockingHideActivity {
); );
entryContentsView.assignPassword(mEntry.getPassword()); entryContentsView.assignPassword(mEntry.getPassword());
if (PreferencesUtil.allowCopyPassword(this)) { if (PreferencesUtil.allowCopyPasswordAndProtectedFields(this)) {
entryContentsView.assignPasswordCopyListener(view -> entryContentsView.assignPasswordCopyListener(view ->
clipboardHelper.timeoutCopyToClipboard(mEntry.getPassword(), clipboardHelper.timeoutCopyToClipboard(mEntry.getPassword(),
getString(R.string.copy_field, getString(R.string.entry_password))) getString(R.string.copy_field, getString(R.string.entry_password)))
@@ -241,14 +347,15 @@ public class EntryActivity extends LockingHideActivity {
if (mEntry.allowExtraFields()) { if (mEntry.allowExtraFields()) {
entryContentsView.clearExtraFields(); entryContentsView.clearExtraFields();
mEntry.getFields().doActionToAllCustomProtectedField((label, value) -> mEntry.getFields().doActionToAllCustomProtectedField((label, value) -> {
boolean showAction = (!value.isProtected() || PreferencesUtil.allowCopyPasswordAndProtectedFields(EntryActivity.this));
entryContentsView.addExtraField(label, value, view -> entryContentsView.addExtraField(label, value, showAction, view ->
clipboardHelper.timeoutCopyToClipboard( clipboardHelper.timeoutCopyToClipboard(
value.toString(), value.toString(),
getString(R.string.copy_field, label) getString(R.string.copy_field, label)
) )
)); );
});
} }
// Assign dates // Assign dates
@@ -290,7 +397,7 @@ public class EntryActivity extends LockingHideActivity {
super.onCreateOptionsMenu(menu); super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater(); MenuInflater inflater = getMenuInflater();
MenuUtil.donationMenuInflater(inflater, menu); MenuUtil.contributionMenuInflater(inflater, menu);
inflater.inflate(R.menu.entry, menu); inflater.inflate(R.menu.entry, menu);
inflater.inflate(R.menu.database_lock, menu); inflater.inflate(R.menu.database_lock, menu);
@@ -323,6 +430,9 @@ public class EntryActivity extends LockingHideActivity {
} }
} }
} }
// Show education views
new Handler().post(() -> checkAndPerformedEducation(menu));
return true; return true;
} }
@@ -330,8 +440,8 @@ public class EntryActivity extends LockingHideActivity {
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch ( item.getItemId() ) { switch ( item.getItemId() ) {
case R.id.menu_donate: case R.id.menu_contribute:
return MenuUtil.onDonationItemSelected(this); return MenuUtil.onContributionItemSelected(this);
case R.id.menu_toggle_pass: case R.id.menu_toggle_pass:
mShowPassword = !mShowPassword; mShowPassword = !mShowPassword;

View File

@@ -21,8 +21,9 @@ package com.kunzisoft.keepass.activities;
import android.app.Activity; import android.app.Activity;
import android.content.Intent; import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.Toolbar; import android.support.v7.widget.Toolbar;
import android.util.Log; import android.util.Log;
import android.view.Menu; import android.view.Menu;
@@ -31,11 +32,13 @@ import android.view.MenuItem;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.EditText; import android.widget.EditText;
import android.widget.ImageButton; import android.widget.ImageView;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.ScrollView; import android.widget.ScrollView;
import android.widget.Toast; import android.widget.Toast;
import com.getkeepsafe.taptargetview.TapTarget;
import com.getkeepsafe.taptargetview.TapTargetView;
import com.kunzisoft.keepass.R; import com.kunzisoft.keepass.R;
import com.kunzisoft.keepass.app.App; import com.kunzisoft.keepass.app.App;
import com.kunzisoft.keepass.database.Database; import com.kunzisoft.keepass.database.Database;
@@ -45,16 +48,20 @@ import com.kunzisoft.keepass.database.PwEntry;
import com.kunzisoft.keepass.database.PwGroup; import com.kunzisoft.keepass.database.PwGroup;
import com.kunzisoft.keepass.database.PwGroupId; import com.kunzisoft.keepass.database.PwGroupId;
import com.kunzisoft.keepass.database.PwIconStandard; import com.kunzisoft.keepass.database.PwIconStandard;
import com.kunzisoft.keepass.database.edit.AddEntry; import com.kunzisoft.keepass.database.PwNode;
import com.kunzisoft.keepass.database.edit.OnFinish; import com.kunzisoft.keepass.database.action.RunnableOnFinish;
import com.kunzisoft.keepass.database.edit.RunnableOnFinish; import com.kunzisoft.keepass.database.action.node.AddEntryRunnable;
import com.kunzisoft.keepass.database.edit.UpdateEntry; import com.kunzisoft.keepass.database.action.node.AfterActionNodeOnFinish;
import com.kunzisoft.keepass.database.action.node.UpdateEntryRunnable;
import com.kunzisoft.keepass.database.security.ProtectedString; import com.kunzisoft.keepass.database.security.ProtectedString;
import com.kunzisoft.keepass.dialogs.GeneratePasswordDialogFragment; import com.kunzisoft.keepass.dialogs.GeneratePasswordDialogFragment;
import com.kunzisoft.keepass.dialogs.IconPickerDialogFragment; import com.kunzisoft.keepass.dialogs.IconPickerDialogFragment;
import com.kunzisoft.keepass.icons.Icons; import com.kunzisoft.keepass.icons.IconPackChooser;
import com.kunzisoft.keepass.lock.LockingActivity;
import com.kunzisoft.keepass.lock.LockingHideActivity;
import com.kunzisoft.keepass.settings.PreferencesUtil; import com.kunzisoft.keepass.settings.PreferencesUtil;
import com.kunzisoft.keepass.tasks.ProgressTask; import com.kunzisoft.keepass.tasks.SaveDatabaseProgressTaskDialogFragment;
import com.kunzisoft.keepass.tasks.UpdateProgressTaskStatus;
import com.kunzisoft.keepass.utils.MenuUtil; import com.kunzisoft.keepass.utils.MenuUtil;
import com.kunzisoft.keepass.utils.Types; import com.kunzisoft.keepass.utils.Types;
import com.kunzisoft.keepass.utils.Util; import com.kunzisoft.keepass.utils.Util;
@@ -62,6 +69,10 @@ import com.kunzisoft.keepass.view.EntryEditCustomField;
import java.util.UUID; import java.util.UUID;
import javax.annotation.Nullable;
import static com.kunzisoft.keepass.dialogs.IconPickerDialogFragment.UNDEFINED_ICON_ID;
public class EntryEditActivity extends LockingHideActivity public class EntryEditActivity extends LockingHideActivity
implements IconPickerDialogFragment.IconPickerListener, implements IconPickerDialogFragment.IconPickerListener,
GeneratePasswordDialogFragment.GeneratePasswordListener { GeneratePasswordDialogFragment.GeneratePasswordListener {
@@ -81,20 +92,26 @@ public class EntryEditActivity extends LockingHideActivity
protected PwEntry mEntry; protected PwEntry mEntry;
protected PwEntry mCallbackNewEntry; protected PwEntry mCallbackNewEntry;
protected boolean mIsNew; protected boolean mIsNew;
protected int mSelectedIconID = -1; protected int mSelectedIconID = UNDEFINED_ICON_ID;
// Views // Views
private ScrollView scrollView; private ScrollView scrollView;
private EditText entryTitleView; private EditText entryTitleView;
private ImageView entryIconView;
private EditText entryUserNameView; private EditText entryUserNameView;
private EditText entryUrlView; private EditText entryUrlView;
private EditText entryPasswordView; private EditText entryPasswordView;
private EditText entryConfirmationPasswordView; private EditText entryConfirmationPasswordView;
private View generatePasswordView;
private EditText entryCommentView; private EditText entryCommentView;
private ViewGroup entryExtraFieldsContainer; private ViewGroup entryExtraFieldsContainer;
private View addNewFieldView;
private View saveView;
private int iconColor;
/** /**
* launch EntryEditActivity to update an existing entry * Launch EntryEditActivity to update an existing entry
*
* @param act from activity * @param act from activity
* @param pw Entry to update * @param pw Entry to update
*/ */
@@ -107,7 +124,8 @@ public class EntryEditActivity extends LockingHideActivity
} }
/** /**
* launch EntryEditActivity to add a new entry * Launch EntryEditActivity to add a new entry
*
* @param act from activity * @param act from activity
* @param pwGroup Group who will contains new entry * @param pwGroup Group who will contains new entry
*/ */
@@ -135,6 +153,7 @@ public class EntryEditActivity extends LockingHideActivity
scrollView.setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET); scrollView.setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);
entryTitleView = findViewById(R.id.entry_title); entryTitleView = findViewById(R.id.entry_title);
entryIconView = findViewById(R.id.icon_button);
entryUserNameView = findViewById(R.id.entry_user_name); entryUserNameView = findViewById(R.id.entry_user_name);
entryUrlView = findViewById(R.id.entry_url); entryUrlView = findViewById(R.id.entry_url);
entryPasswordView = findViewById(R.id.entry_password); entryPasswordView = findViewById(R.id.entry_password);
@@ -152,12 +171,23 @@ public class EntryEditActivity extends LockingHideActivity
Intent intent = getIntent(); Intent intent = getIntent();
byte[] uuidBytes = intent.getByteArrayExtra(KEY_ENTRY); byte[] uuidBytes = intent.getByteArrayExtra(KEY_ENTRY);
// Retrieve the textColor to tint the icon
int[] attrs = {android.R.attr.textColorPrimary};
TypedArray ta = getTheme().obtainStyledAttributes(attrs);
iconColor = ta.getColor(0, Color.WHITE);
PwDatabase pm = db.getPwDatabase(); PwDatabase pm = db.getPwDatabase();
if ( uuidBytes == null ) { if ( uuidBytes == null ) {
PwGroupId parentId = (PwGroupId) intent.getSerializableExtra(KEY_PARENT); PwGroupId parentId = (PwGroupId) intent.getSerializableExtra(KEY_PARENT);
PwGroup parent = pm.getGroupByGroupId(parentId); PwGroup parent = pm.getGroupByGroupId(parentId);
mEntry = PwEntry.getInstance(parent); mEntry = db.createEntry(parent);
mIsNew = true; mIsNew = true;
// Add the default icon
if (IconPackChooser.getSelectedIconPack(this).tintable()) {
App.getDB().getDrawFactory().assignDefaultDatabaseIconTo(this, entryIconView, true, iconColor);
} else {
App.getDB().getDrawFactory().assignDefaultDatabaseIconTo(this, entryIconView);
}
} else { } else {
UUID uuid = Types.bytestoUUID(uuidBytes); UUID uuid = Types.bytestoUUID(uuidBytes);
mEntry = pm.getEntryByUUIDId(uuid); mEntry = pm.getEntryByUUIDId(uuid);
@@ -165,81 +195,205 @@ public class EntryEditActivity extends LockingHideActivity
fillData(); fillData();
} }
View iconButton = findViewById(R.id.icon_button); // Retrieve the icon after an orientation change
iconButton.setOnClickListener(v -> if (savedInstanceState != null && savedInstanceState.containsKey(IconPickerDialogFragment.KEY_ICON_ID)) {
iconPicked(savedInstanceState);
}
// Add listener to the icon
entryIconView.setOnClickListener(v ->
IconPickerDialogFragment.launch(EntryEditActivity.this)); IconPickerDialogFragment.launch(EntryEditActivity.this));
// Generate password button // Generate password button
View generatePassword = findViewById(R.id.generate_button); generatePasswordView = findViewById(R.id.generate_button);
generatePassword.setOnClickListener(v -> { generatePasswordView.setOnClickListener(v -> openPasswordGenerator());
GeneratePasswordDialogFragment generatePasswordDialogFragment = new GeneratePasswordDialogFragment();
generatePasswordDialogFragment.show(getSupportFragmentManager(), "PasswordGeneratorFragment");
});
// Save button // Save button
View save = findViewById(R.id.entry_save); saveView = findViewById(R.id.entry_save);
save.setOnClickListener(v -> { saveView.setOnClickListener(v -> saveEntry());
if (!validateBeforeSaving()) {
return;
}
mCallbackNewEntry = populateNewEntry();
OnFinish onFinish = new AfterSave();
EntryEditActivity act = EntryEditActivity.this;
RunnableOnFinish task;
if ( mIsNew ) {
task = new AddEntry(act, App.getDB(), mCallbackNewEntry, onFinish);
} else {
task = new UpdateEntry(act, App.getDB(), mEntry, mCallbackNewEntry, onFinish);
}
ProgressTask pt = new ProgressTask(act, task, R.string.saving_database);
pt.run();
});
if (mEntry.allowExtraFields()) { if (mEntry.allowExtraFields()) {
View add = findViewById(R.id.add_new_field); addNewFieldView = findViewById(R.id.add_new_field);
add.setVisibility(View.VISIBLE); addNewFieldView.setVisibility(View.VISIBLE);
add.setOnClickListener(v -> { addNewFieldView.setOnClickListener(v -> addNewCustomField());
EntryEditCustomField ees = new EntryEditCustomField(EntryEditActivity.this);
ees.setData("", new ProtectedString(false, ""));
entryExtraFieldsContainer.addView(ees);
// Scroll bottom
scrollView.post(() -> scrollView.fullScroll(ScrollView.FOCUS_DOWN));
});
} }
}
protected boolean validateBeforeSaving() {
// Require title
String title = entryTitleView.getText().toString();
if ( title.length() == 0 ) {
Toast.makeText(this, R.string.error_title_required, Toast.LENGTH_LONG).show();
return false;
}
// Validate password
String pass = entryPasswordView.getText().toString();
String conf = entryConfirmationPasswordView.getText().toString();
if ( ! pass.equals(conf) ) {
Toast.makeText(this, R.string.error_pass_match, Toast.LENGTH_LONG).show();
return false;
}
// Validate extra fields // Verify the education views
checkAndPerformedEducation();
}
/**
* Open the password generator fragment
*/
private void openPasswordGenerator() {
GeneratePasswordDialogFragment generatePasswordDialogFragment = new GeneratePasswordDialogFragment();
generatePasswordDialogFragment.show(getSupportFragmentManager(), "PasswordGeneratorFragment");
}
/**
* Add a new view to fill in the information of the customized field
*/
private void addNewCustomField() {
EntryEditCustomField entryEditCustomField = new EntryEditCustomField(EntryEditActivity.this);
entryEditCustomField.setData("", new ProtectedString(false, ""));
boolean visibilityFontActivated = PreferencesUtil.fieldFontIsInVisibility(this);
entryEditCustomField.setFontVisibility(visibilityFontActivated);
entryExtraFieldsContainer.addView(entryEditCustomField);
// Scroll bottom
scrollView.post(() -> scrollView.fullScroll(ScrollView.FOCUS_DOWN));
}
/**
* Saves the new entry or update an existing entry in the database
*/
private void saveEntry() {
if (!validateBeforeSaving()) {
return;
}
mCallbackNewEntry = populateNewEntry();
// Open a progress dialog and save entry
AfterActionNodeOnFinish onFinish = new AfterSave();
EntryEditActivity act = EntryEditActivity.this;
RunnableOnFinish task;
if ( mIsNew ) {
task = new AddEntryRunnable(act, App.getDB(), mCallbackNewEntry, onFinish);
} else {
task = new UpdateEntryRunnable(act, App.getDB(), mEntry, mCallbackNewEntry, onFinish);
}
task.setUpdateProgressTaskStatus(
new UpdateProgressTaskStatus(this,
SaveDatabaseProgressTaskDialogFragment.start(
getSupportFragmentManager())
));
new Thread(task).start();
}
/**
* Check and display learning views
* Displays the explanation for the icon selection, the password generator and for a new field
*/
private void checkAndPerformedEducation() {
if (PreferencesUtil.isEducationScreensEnabled(this)) {
// TODO Show icon
if (!PreferencesUtil.isEducationPasswordGeneratorPerformed(this)) {
TapTargetView.showFor(this,
TapTarget.forView(generatePasswordView,
getString(R.string.education_generate_password_title),
getString(R.string.education_generate_password_summary))
.textColorInt(Color.WHITE)
.tintTarget(false)
.cancelable(true),
new TapTargetView.Listener() {
@Override
public void onTargetClick(TapTargetView view) {
super.onTargetClick(view);
openPasswordGenerator();
}
@Override
public void onOuterCircleClick(TapTargetView view) {
super.onOuterCircleClick(view);
view.dismiss(false);
}
});
PreferencesUtil.saveEducationPreference(this,
R.string.education_password_generator_key);
} else if (mEntry.allowExtraFields()
&& !mEntry.containsCustomFields()
&& !PreferencesUtil.isEducationEntryNewFieldPerformed(this)) {
TapTargetView.showFor(this,
TapTarget.forView(addNewFieldView,
getString(R.string.education_entry_new_field_title),
getString(R.string.education_entry_new_field_summary))
.textColorInt(Color.WHITE)
.tintTarget(false)
.cancelable(true),
new TapTargetView.Listener() {
@Override
public void onTargetClick(TapTargetView view) {
super.onTargetClick(view);
addNewCustomField();
}
@Override
public void onOuterCircleClick(TapTargetView view) {
super.onOuterCircleClick(view);
view.dismiss(false);
}
});
PreferencesUtil.saveEducationPreference(this,
R.string.education_entry_new_field_key);
}
}
}
/**
* Utility class to retrieve a validation or an error with a message
*/
private class ErrorValidation {
static final int unknownMessage = -1;
boolean isValidate = false;
int messageId = unknownMessage;
void showValidationErrorIfNeeded() {
if (!isValidate && messageId != unknownMessage)
Toast.makeText(EntryEditActivity.this, messageId, Toast.LENGTH_LONG).show();
}
}
/**
* Validate or not the entry form
*
* @return ErrorValidation An error with a message or a validation without message
*/
protected ErrorValidation validate() {
ErrorValidation errorValidation = new ErrorValidation();
// Require title
String title = entryTitleView.getText().toString();
if ( title.length() == 0 ) {
errorValidation.messageId = R.string.error_title_required;
return errorValidation;
}
// Validate password
String pass = entryPasswordView.getText().toString();
String conf = entryConfirmationPasswordView.getText().toString();
if ( ! pass.equals(conf) ) {
errorValidation.messageId = R.string.error_pass_match;
return errorValidation;
}
// Validate extra fields
if (mEntry.allowExtraFields()) { if (mEntry.allowExtraFields()) {
for (int i = 0; i < entryExtraFieldsContainer.getChildCount(); i++) { for (int i = 0; i < entryExtraFieldsContainer.getChildCount(); i++) {
EntryEditCustomField entryEditCustomField = (EntryEditCustomField) entryExtraFieldsContainer.getChildAt(i); EntryEditCustomField entryEditCustomField = (EntryEditCustomField) entryExtraFieldsContainer.getChildAt(i);
String key = entryEditCustomField.getLabel(); String key = entryEditCustomField.getLabel();
if (key == null || key.length() == 0) { if (key == null || key.length() == 0) {
Toast.makeText(this, R.string.error_string_key, Toast.LENGTH_LONG).show(); errorValidation.messageId = R.string.error_string_key;
return false; return errorValidation;
} }
} }
} }
return true; errorValidation.isValidate = true;
return errorValidation;
}
/**
* Launch a validation with {@link #validate()} and show the error if present
*
* @return true if the form was validate or false if not
*/
protected boolean validateBeforeSaving() {
ErrorValidation errorValidation = validate();
errorValidation.showValidationErrorIfNeeded();
return errorValidation.isValidate;
} }
protected PwEntry populateNewEntry() { protected PwEntry populateNewEntry() {
@@ -255,18 +409,8 @@ public class EntryEditActivity extends LockingHideActivity
newEntry.setLastModificationTime(new PwDate()); newEntry.setLastModificationTime(new PwDate());
newEntry.setTitle(entryTitleView.getText().toString()); newEntry.setTitle(entryTitleView.getText().toString());
if(mSelectedIconID != -1) newEntry.setIcon(retrieveIcon());
// or TODO icon factory newEntry.setIcon(App.getDB().pm.iconFactory.getIcon(mSelectedIconID));
newEntry.setIcon(new PwIconStandard(mSelectedIconID));
else {
if (mIsNew) {
newEntry.setIcon(App.getDB().getPwDatabase().getIconFactory().getFirstIcon());
}
else {
// Keep previous icon, if no new one was selected
newEntry.setIcon(mEntry.getIconStandard());
}
}
newEntry.setUrl(entryUrlView.getText().toString()); newEntry.setUrl(entryUrlView.getText().toString());
newEntry.setUsername(entryUserNameView.getText().toString()); newEntry.setUsername(entryUserNameView.getText().toString());
newEntry.setNotes(entryCommentView.getText().toString()); newEntry.setNotes(entryCommentView.getText().toString());
@@ -290,21 +434,39 @@ public class EntryEditActivity extends LockingHideActivity
return newEntry; return newEntry;
} }
/**
* Retrieve the icon by the selection, or the first icon in the list if the entry is new or the last one
* @return
*/
private PwIconStandard retrieveIcon() {
if(mSelectedIconID != UNDEFINED_ICON_ID)
return App.getDB().getPwDatabase().getIconFactory().getIcon(mSelectedIconID);
else {
if (mIsNew) {
return App.getDB().getPwDatabase().getIconFactory().getKeyIcon();
}
else {
// Keep previous icon, if no new one was selected
return mEntry.getIconStandard();
}
}
}
@Override @Override
public boolean onCreateOptionsMenu(Menu menu) { public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu); super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater(); MenuInflater inflater = getMenuInflater();
MenuUtil.donationMenuInflater(inflater, menu); MenuUtil.contributionMenuInflater(inflater, menu);
return true; return true;
} }
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch ( item.getItemId() ) { switch ( item.getItemId() ) {
case R.id.menu_donate: case R.id.menu_contribute:
return MenuUtil.onDonationItemSelected(this); return MenuUtil.onContributionItemSelected(this);
case android.R.id.home: case android.R.id.home:
finish(); finish();
@@ -314,8 +476,12 @@ public class EntryEditActivity extends LockingHideActivity
} }
protected void fillData() { protected void fillData() {
ImageButton currIconButton = findViewById(R.id.icon_button);
App.getDB().getDrawFactory().assignDrawableTo(currIconButton, getResources(), mEntry.getIcon()); if (IconPackChooser.getSelectedIconPack(this).tintable()) {
App.getDB().getDrawFactory().assignDatabaseIconTo(this, entryIconView, mEntry.getIcon(), true, iconColor);
} else {
App.getDB().getDrawFactory().assignDatabaseIconTo(this, entryIconView, mEntry.getIcon());
}
// Don't start the field reference manager, we want to see the raw ref // Don't start the field reference manager, we want to see the raw ref
mEntry.endToManageFieldReferences(); mEntry.endToManageFieldReferences();
@@ -330,10 +496,10 @@ public class EntryEditActivity extends LockingHideActivity
boolean visibilityFontActivated = PreferencesUtil.fieldFontIsInVisibility(this); boolean visibilityFontActivated = PreferencesUtil.fieldFontIsInVisibility(this);
if (visibilityFontActivated) { if (visibilityFontActivated) {
Util.applyFontVisibilityTo(entryUserNameView); Util.applyFontVisibilityTo(this, entryUserNameView);
Util.applyFontVisibilityTo(entryPasswordView); Util.applyFontVisibilityTo(this, entryPasswordView);
Util.applyFontVisibilityTo(entryConfirmationPasswordView); Util.applyFontVisibilityTo(this, entryConfirmationPasswordView);
Util.applyFontVisibilityTo(entryCommentView); Util.applyFontVisibilityTo(this, entryCommentView);
} }
if (mEntry.allowExtraFields()) { if (mEntry.allowExtraFields()) {
@@ -350,8 +516,15 @@ public class EntryEditActivity extends LockingHideActivity
@Override @Override
public void iconPicked(Bundle bundle) { public void iconPicked(Bundle bundle) {
mSelectedIconID = bundle.getInt(IconPickerDialogFragment.KEY_ICON_ID); mSelectedIconID = bundle.getInt(IconPickerDialogFragment.KEY_ICON_ID);
ImageButton currIconButton = findViewById(R.id.icon_button); entryIconView.setImageResource(IconPackChooser.getSelectedIconPack(this).iconToResId(mSelectedIconID));
currIconButton.setImageResource(Icons.iconToResId(mSelectedIconID)); }
@Override
protected void onSaveInstanceState(Bundle outState) {
if (mSelectedIconID != UNDEFINED_ICON_ID) {
outState.putInt(IconPickerDialogFragment.KEY_ICON_ID, mSelectedIconID);
super.onSaveInstanceState(outState);
}
} }
@Override @Override
@@ -359,6 +532,8 @@ public class EntryEditActivity extends LockingHideActivity
String generatedPassword = bundle.getString(GeneratePasswordDialogFragment.KEY_PASSWORD_ID); String generatedPassword = bundle.getString(GeneratePasswordDialogFragment.KEY_PASSWORD_ID);
entryPasswordView.setText(generatedPassword); entryPasswordView.setText(generatedPassword);
entryConfirmationPasswordView.setText(generatedPassword); entryConfirmationPasswordView.setText(generatedPassword);
checkAndPerformedEducation();
} }
@Override @Override
@@ -388,20 +563,20 @@ public class EntryEditActivity extends LockingHideActivity
} }
} }
private final class AfterSave extends OnFinish { private final class AfterSave extends AfterActionNodeOnFinish {
AfterSave() {
super(new Handler());
}
@Override @Override
public void run() { public void run(@Nullable PwNode oldNode, @Nullable PwNode newNode) {
if ( mSuccess ) { runOnUiThread(() -> {
finish(); if ( mSuccess ) {
} else { finish();
displayMessage(EntryEditActivity.this); } else {
} displayMessage(EntryEditActivity.this);
}
SaveDatabaseProgressTaskDialogFragment.stop(EntryEditActivity.this);
});
} }
} }
} }

View File

@@ -27,12 +27,14 @@ import android.content.ComponentName;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler; import android.os.Handler;
import android.preference.PreferenceManager; import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi; import android.support.annotation.RequiresApi;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView; import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar; import android.support.v7.widget.Toolbar;
import android.util.Log; import android.util.Log;
@@ -41,49 +43,74 @@ import android.view.MenuInflater;
import android.view.MenuItem; import android.view.MenuItem;
import android.widget.ImageView; import android.widget.ImageView;
import com.getkeepsafe.taptargetview.TapTarget;
import com.getkeepsafe.taptargetview.TapTargetView;
import com.kunzisoft.keepass.R; import com.kunzisoft.keepass.R;
import com.kunzisoft.keepass.adapters.NodeAdapter; import com.kunzisoft.keepass.adapters.NodeAdapter;
import com.kunzisoft.keepass.app.App; import com.kunzisoft.keepass.app.App;
import com.kunzisoft.keepass.autofill.AutofillHelper; import com.kunzisoft.keepass.autofill.AutofillHelper;
import com.kunzisoft.keepass.database.Database; import com.kunzisoft.keepass.database.Database;
import com.kunzisoft.keepass.database.PwDatabase;
import com.kunzisoft.keepass.database.PwEntry; import com.kunzisoft.keepass.database.PwEntry;
import com.kunzisoft.keepass.database.PwGroup; import com.kunzisoft.keepass.database.PwGroup;
import com.kunzisoft.keepass.database.PwGroupId; import com.kunzisoft.keepass.database.PwGroupId;
import com.kunzisoft.keepass.database.PwIcon;
import com.kunzisoft.keepass.database.PwIconStandard;
import com.kunzisoft.keepass.database.PwNode; import com.kunzisoft.keepass.database.PwNode;
import com.kunzisoft.keepass.database.SortNodeEnum; import com.kunzisoft.keepass.database.action.node.AddGroupRunnable;
import com.kunzisoft.keepass.database.edit.AddGroup; import com.kunzisoft.keepass.database.action.node.AfterActionNodeOnFinish;
import com.kunzisoft.keepass.database.edit.DeleteEntry; import com.kunzisoft.keepass.database.action.node.CopyEntryRunnable;
import com.kunzisoft.keepass.database.edit.DeleteGroup; import com.kunzisoft.keepass.database.action.node.DeleteEntryRunnable;
import com.kunzisoft.keepass.database.action.node.DeleteGroupRunnable;
import com.kunzisoft.keepass.database.action.node.MoveEntryRunnable;
import com.kunzisoft.keepass.database.action.node.MoveGroupRunnable;
import com.kunzisoft.keepass.database.action.node.UpdateGroupRunnable;
import com.kunzisoft.keepass.dialogs.AssignMasterKeyDialogFragment; import com.kunzisoft.keepass.dialogs.AssignMasterKeyDialogFragment;
import com.kunzisoft.keepass.dialogs.GroupEditDialogFragment; import com.kunzisoft.keepass.dialogs.GroupEditDialogFragment;
import com.kunzisoft.keepass.dialogs.IconPickerDialogFragment; import com.kunzisoft.keepass.dialogs.IconPickerDialogFragment;
import com.kunzisoft.keepass.dialogs.ReadOnlyDialog; import com.kunzisoft.keepass.dialogs.ReadOnlyDialog;
import com.kunzisoft.keepass.icons.IconPackChooser;
import com.kunzisoft.keepass.selection.EntrySelectionHelper;
import com.kunzisoft.keepass.search.SearchResultsActivity; import com.kunzisoft.keepass.search.SearchResultsActivity;
import com.kunzisoft.keepass.tasks.ProgressTask; import com.kunzisoft.keepass.settings.PreferencesUtil;
import com.kunzisoft.keepass.tasks.SaveDatabaseProgressTaskDialogFragment;
import com.kunzisoft.keepass.tasks.UIToastTask;
import com.kunzisoft.keepass.tasks.UpdateProgressTaskStatus;
import com.kunzisoft.keepass.view.AddNodeButtonView; import com.kunzisoft.keepass.view.AddNodeButtonView;
import net.cachapa.expandablelayout.ExpandableLayout;
public class GroupActivity extends ListNodesActivity public class GroupActivity extends ListNodesActivity
implements GroupEditDialogFragment.EditGroupListener, IconPickerDialogFragment.IconPickerListener { implements GroupEditDialogFragment.EditGroupListener,
IconPickerDialogFragment.IconPickerListener,
NodeAdapter.NodeMenuListener,
ListNodesFragment.OnScrollListener {
private static final String GROUP_ID_KEY = "GROUP_ID_KEY"; private static final String TAG = GroupActivity.class.getName();
private Toolbar toolbar;
private ExpandableLayout toolbarPasteExpandableLayout;
private Toolbar toolbarPaste;
private ImageView iconView;
private AddNodeButtonView addNodeButtonView; private AddNodeButtonView addNodeButtonView;
protected boolean addGroupEnabled = false; protected boolean addGroupEnabled = false;
protected boolean addEntryEnabled = false; protected boolean addEntryEnabled = false;
protected boolean isRoot = false; protected boolean isRoot = false;
protected boolean readOnly = false; protected boolean readOnly = false;
protected EditGroupDialogAction editGroupDialogAction = EditGroupDialogAction.NONE;
private enum EditGroupDialogAction { private static final String OLD_GROUP_TO_UPDATE_KEY = "OLD_GROUP_TO_UPDATE_KEY";
CREATION, UPDATE, NONE private static final String NODE_TO_COPY_KEY = "NODE_TO_COPY_KEY";
} private static final String NODE_TO_MOVE_KEY = "NODE_TO_MOVE_KEY";
private PwGroup oldGroupToUpdate;
private static final String TAG = "Group Activity:"; private PwNode nodeToCopy;
private PwNode nodeToMove;
public static void launch(Activity act) { public static void launch(Activity act) {
recordFirstTimeBeforeLaunch(act); startRecordTime(act);
launch(act, (PwGroup) null); launch(act, null);
} }
public static void launch(Activity act, PwGroup group) { public static void launch(Activity act, PwGroup group) {
@@ -96,18 +123,37 @@ public class GroupActivity extends ListNodesActivity
} }
} }
public static void launchForKeyboardResult(Activity act) {
startRecordTime(act);
launchForKeyboardResult(act, null);
}
public static void launchForKeyboardResult(Activity act, PwGroup group) {
// TODO remove
if (checkTimeIsAllowedOrFinish(act)) {
Intent intent = new Intent(act, GroupActivity.class);
if (group != null) {
intent.putExtra(GROUP_ID_KEY, group.getId());
}
EntrySelectionHelper.addEntrySelectionModeExtraInIntent(intent);
act.startActivityForResult(intent, EntrySelectionHelper.ENTRY_SELECTION_RESPONSE_REQUEST_CODE);
}
}
@RequiresApi(api = Build.VERSION_CODES.O) @RequiresApi(api = Build.VERSION_CODES.O)
public static void launch(Activity act, AssistStructure assistStructure) { public static void launchForAutofillResult(Activity act, AssistStructure assistStructure) {
if ( assistStructure != null ) { if ( assistStructure != null ) {
recordFirstTimeBeforeLaunch(act); startRecordTime(act);
launch(act, null, assistStructure); launchForAutofillResult(act, null, assistStructure);
} else { } else {
launch(act); launch(act);
} }
} }
@RequiresApi(api = Build.VERSION_CODES.O) @RequiresApi(api = Build.VERSION_CODES.O)
public static void launch(Activity act, PwGroup group, AssistStructure assistStructure) { public static void launchForAutofillResult(Activity act, PwGroup group, AssistStructure assistStructure) {
// TODO remove
if ( assistStructure != null ) { if ( assistStructure != null ) {
if (checkTimeIsAllowedOrFinish(act)) { if (checkTimeIsAllowedOrFinish(act)) {
Intent intent = new Intent(act, GroupActivity.class); Intent intent = new Intent(act, GroupActivity.class);
@@ -125,57 +171,95 @@ public class GroupActivity extends ListNodesActivity
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
Log.w(TAG, "Retrieved tree"); Log.i(TAG, "Started creating tree");
if ( mCurrentGroup == null ) { if ( mCurrentGroup == null ) {
Log.w(TAG, "Group was null"); Log.w(TAG, "Group was null");
return; return;
} }
// Construct main view // Construct main view
setContentView(getLayoutInflater().inflate(R.layout.list_nodes_with_add_button, null)); setContentView(getLayoutInflater().inflate(R.layout.list_nodes_with_add_button, null));
attachFragmentToContentView();
iconView = findViewById(R.id.icon);
addNodeButtonView = findViewById(R.id.add_node_button); addNodeButtonView = findViewById(R.id.add_node_button);
addNodeButtonView.enableAddGroup(addGroupEnabled); addNodeButtonView.enableAddGroup(addGroupEnabled);
addNodeButtonView.enableAddEntry(addEntryEnabled); addNodeButtonView.enableAddEntry(addEntryEnabled);
// Hide when scroll
RecyclerView recyclerView = findViewById(R.id.nodes_list);
recyclerView.addOnScrollListener(addNodeButtonView.hideButtonOnScrollListener());
Toolbar toolbar = findViewById(R.id.toolbar); toolbar = findViewById(R.id.toolbar);
toolbar.setTitle(""); toolbar.setTitle("");
setSupportActionBar(toolbar); setSupportActionBar(toolbar);
groupNameView = findViewById(R.id.group_name);
if ( mCurrentGroup.getParent() != null ) toolbarPasteExpandableLayout = findViewById(R.id.expandable_toolbar_paste_layout);
toolbar.setNavigationIcon(R.drawable.ic_arrow_up_white_24dp); toolbarPaste = findViewById(R.id.toolbar_paste);
toolbarPaste.inflateMenu(R.menu.node_paste_menu);
toolbarPaste.setNavigationIcon(R.drawable.ic_arrow_left_white_24dp);
toolbarPaste.setNavigationOnClickListener(view -> {
toolbarPasteExpandableLayout.collapse();
nodeToCopy = null;
nodeToMove = null;
});
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(OLD_GROUP_TO_UPDATE_KEY))
oldGroupToUpdate = (PwGroup) savedInstanceState.getSerializable(OLD_GROUP_TO_UPDATE_KEY);
if (savedInstanceState.containsKey(NODE_TO_COPY_KEY)) {
nodeToCopy = (PwNode) savedInstanceState.getSerializable(NODE_TO_COPY_KEY);
toolbarPaste.setOnMenuItemClickListener(new OnCopyMenuItemClickListener());
}
else if (savedInstanceState.containsKey(NODE_TO_MOVE_KEY)) {
nodeToMove = (PwNode) savedInstanceState.getSerializable(NODE_TO_MOVE_KEY);
toolbarPaste.setOnMenuItemClickListener(new OnMoveMenuItemClickListener());
}
}
addNodeButtonView.setAddGroupClickListener(v -> { addNodeButtonView.setAddGroupClickListener(v -> {
editGroupDialogAction = EditGroupDialogAction.CREATION; GroupEditDialogFragment.build()
GroupEditDialogFragment groupEditDialogFragment = new GroupEditDialogFragment(); .show(getSupportFragmentManager(),
groupEditDialogFragment.show(getSupportFragmentManager(), GroupEditDialogFragment.TAG_CREATE_GROUP);
GroupEditDialogFragment.TAG_CREATE_GROUP);
}); });
addNodeButtonView.setAddEntryClickListener(v -> addNodeButtonView.setAddEntryClickListener(v ->
EntryEditActivity.launch(GroupActivity.this, mCurrentGroup)); EntryEditActivity.launch(GroupActivity.this, mCurrentGroup));
setGroupTitle();
setGroupIcon();
Log.w(TAG, "Finished creating tree"); Log.i(TAG, "Finished creating tree");
if (isRoot) { if (isRoot) {
showWarnings(); showWarnings();
} }
} }
protected PwGroup initCurrentGroup() { @Override
PwGroup currentGroup; protected void onSaveInstanceState(Bundle outState) {
outState.putSerializable(GROUP_ID_KEY, mCurrentGroup.getId());
outState.putSerializable(OLD_GROUP_TO_UPDATE_KEY, oldGroupToUpdate);
if (nodeToCopy != null)
outState.putSerializable(NODE_TO_COPY_KEY, nodeToCopy);
if (nodeToMove != null)
outState.putSerializable(NODE_TO_MOVE_KEY, nodeToMove);
super.onSaveInstanceState(outState);
}
protected PwGroup retrieveCurrentGroup(@Nullable Bundle savedInstanceState) {
PwGroupId pwGroupId = null; // TODO Parcelable
if (savedInstanceState != null
&& savedInstanceState.containsKey(GROUP_ID_KEY)) {
pwGroupId = (PwGroupId) savedInstanceState.getSerializable(GROUP_ID_KEY);
} else {
if (getIntent() != null)
pwGroupId = (PwGroupId) getIntent().getSerializableExtra(GROUP_ID_KEY);
}
Database db = App.getDB(); Database db = App.getDB();
readOnly = db.isReadOnly(); readOnly = db.isReadOnly();
PwGroup root = db.getPwDatabase().getRootGroup(); PwGroup root = db.getPwDatabase().getRootGroup();
Log.w(TAG, "Creating tree view"); Log.w(TAG, "Creating tree view");
PwGroupId pwGroupId = (PwGroupId) getIntent().getSerializableExtra(GROUP_ID_KEY); PwGroup currentGroup;
if ( pwGroupId == null ) { if ( pwGroupId == null ) {
currentGroup = root; currentGroup = root;
} else { } else {
@@ -184,7 +268,7 @@ public class GroupActivity extends ListNodesActivity
if (currentGroup != null) { if (currentGroup != null) {
addGroupEnabled = !readOnly; addGroupEnabled = !readOnly;
addEntryEnabled = !readOnly; // TODO ReadOnly addEntryEnabled = !readOnly; // TODO consultation mode
isRoot = (currentGroup == root); isRoot = (currentGroup == root);
if (!currentGroup.allowAddEntryIfIsRoot()) if (!currentGroup.allowAddEntryIfIsRoot())
addEntryEnabled = !isRoot && addEntryEnabled; addEntryEnabled = !isRoot && addEntryEnabled;
@@ -194,111 +278,358 @@ public class GroupActivity extends ListNodesActivity
} }
@Override @Override
protected RecyclerView defineNodeList() { public void assignToolbarElements() {
return (RecyclerView) findViewById(R.id.nodes_list); super.assignToolbarElements();
// Assign the group icon depending of IconPack or custom icon
if ( mCurrentGroup != null ) {
if (IconPackChooser.getSelectedIconPack(this).tintable()) {
// Retrieve the textColor to tint the icon
int[] attrs = {R.attr.textColorInverse};
TypedArray ta = getTheme().obtainStyledAttributes(attrs);
int iconColor = ta.getColor(0, Color.WHITE);
App.getDB().getDrawFactory().assignDatabaseIconTo(this, iconView, mCurrentGroup.getIcon(), true, iconColor);
} else {
App.getDB().getDrawFactory().assignDatabaseIconTo(this, iconView, mCurrentGroup.getIcon());
}
if (toolbar != null) {
if ( mCurrentGroup.containsParent() )
toolbar.setNavigationIcon(R.drawable.ic_arrow_up_white_24dp);
else {
toolbar.setNavigationIcon(null);
}
}
}
} }
@Override @Override
protected void addOptionsToAdapter(NodeAdapter nodeAdapter) { public void onScrolled(int dy) {
super.addOptionsToAdapter(nodeAdapter); if (addNodeButtonView != null)
addNodeButtonView.hideButtonOnScrollListener(dy);
}
nodeAdapter.setActivateContextMenu(true); @Override
nodeAdapter.setNodeMenuListener(new NodeAdapter.NodeMenuListener() { public boolean onOpenMenuClick(PwNode node) {
@Override onNodeClick(node);
public boolean onOpenMenuClick(PwNode node) { return true;
mAdapter.registerANodeToUpdate(node); }
switch (node.getType()) {
case GROUP:
GroupActivity.launch(GroupActivity.this, (PwGroup) node);
break;
case ENTRY:
EntryActivity.launch(GroupActivity.this, (PwEntry) node);
break;
}
return true;
}
@Override @Override
public boolean onEditMenuClick(PwNode node) { public boolean onEditMenuClick(PwNode node) {
mAdapter.registerANodeToUpdate(node); switch (node.getType()) {
switch (node.getType()) { case GROUP:
case GROUP: oldGroupToUpdate = (PwGroup) node;
editGroupDialogAction = EditGroupDialogAction.UPDATE; GroupEditDialogFragment.build(node)
GroupEditDialogFragment groupEditDialogFragment = .show(getSupportFragmentManager(),
GroupEditDialogFragment.build(node);
groupEditDialogFragment.show(getSupportFragmentManager(),
GroupEditDialogFragment.TAG_CREATE_GROUP); GroupEditDialogFragment.TAG_CREATE_GROUP);
break; break;
case ENTRY: case ENTRY:
EntryEditActivity.launch(GroupActivity.this, (PwEntry) node); EntryEditActivity.launch(GroupActivity.this, (PwEntry) node);
break; break;
} }
return true; return true;
} }
@Override @Override
public boolean onDeleteMenuClick(PwNode node) { public boolean onCopyMenuClick(PwNode node) {
switch (node.getType()) {
case GROUP: toolbarPasteExpandableLayout.expand();
deleteGroup((PwGroup) node); nodeToCopy = node;
break; toolbarPaste.setOnMenuItemClickListener(new OnCopyMenuItemClickListener());
case ENTRY: return false;
deleteEntry((PwEntry) node); }
break;
} private class OnCopyMenuItemClickListener implements Toolbar.OnMenuItemClickListener{
return true;
@Override
public boolean onMenuItemClick(MenuItem item) {
toolbarPasteExpandableLayout.collapse();
switch (item.getItemId()) {
case R.id.menu_paste:
switch (nodeToCopy.getType()) {
case GROUP:
Log.e(TAG, "Copy not allowed for group");
break;
case ENTRY:
copyEntry((PwEntry) nodeToCopy, mCurrentGroup);
break;
}
nodeToCopy = null;
return true;
} }
}); return true;
}
}
private void copyEntry(PwEntry entryToCopy, PwGroup newParent) {
CopyEntryRunnable task = new CopyEntryRunnable(this, App.getDB(), entryToCopy, newParent,
new AfterAddNode());
task.setUpdateProgressTaskStatus(
new UpdateProgressTaskStatus(this,
SaveDatabaseProgressTaskDialogFragment.start(
getSupportFragmentManager())
));
new Thread(task).start();
}
@Override
public boolean onMoveMenuClick(PwNode node) {
toolbarPasteExpandableLayout.expand();
nodeToMove = node;
toolbarPaste.setOnMenuItemClickListener(new OnMoveMenuItemClickListener());
return false;
}
private class OnMoveMenuItemClickListener implements Toolbar.OnMenuItemClickListener{
@Override
public boolean onMenuItemClick(MenuItem item) {
toolbarPasteExpandableLayout.collapse();
switch (item.getItemId()) {
case R.id.menu_paste:
switch (nodeToMove.getType()) {
case GROUP:
moveGroup((PwGroup) nodeToMove, mCurrentGroup);
break;
case ENTRY:
moveEntry((PwEntry) nodeToMove, mCurrentGroup);
break;
}
nodeToMove = null;
return true;
}
return true;
}
}
private void moveGroup(PwGroup groupToMove, PwGroup newParent) {
MoveGroupRunnable task = new MoveGroupRunnable(
this,
App.getDB(),
groupToMove,
newParent,
new AfterAddNode());
task.setUpdateProgressTaskStatus(
new UpdateProgressTaskStatus(this,
SaveDatabaseProgressTaskDialogFragment.start(
getSupportFragmentManager())
));
new Thread(task).start();
}
private void moveEntry(PwEntry entryToMove, PwGroup newParent) {
MoveEntryRunnable task = new MoveEntryRunnable(
this,
App.getDB(),
entryToMove,
newParent,
new AfterAddNode());
task.setUpdateProgressTaskStatus(
new UpdateProgressTaskStatus(this,
SaveDatabaseProgressTaskDialogFragment.start(
getSupportFragmentManager())
));
new Thread(task).start();
}
@Override
public boolean onDeleteMenuClick(PwNode node) {
switch (node.getType()) {
case GROUP:
deleteGroup((PwGroup) node);
break;
case ENTRY:
deleteEntry((PwEntry) node);
break;
}
return true;
}
private void deleteGroup(PwGroup group) {
//TODO Verify trash recycle bin
DeleteGroupRunnable task = new DeleteGroupRunnable(
this,
App.getDB(),
group,
new AfterDeleteNode());
task.setUpdateProgressTaskStatus(
new UpdateProgressTaskStatus(this,
SaveDatabaseProgressTaskDialogFragment.start(
getSupportFragmentManager())
));
new Thread(task).start();
}
private void deleteEntry(PwEntry entry) {
DeleteEntryRunnable task = new DeleteEntryRunnable(
this,
App.getDB(),
entry,
new AfterDeleteNode());
task.setUpdateProgressTaskStatus(
new UpdateProgressTaskStatus(this,
SaveDatabaseProgressTaskDialogFragment.start(
getSupportFragmentManager())
));
new Thread(task).start();
} }
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
// Show button on resume // Show button on resume
addNodeButtonView.showButton(); if (addNodeButtonView != null)
addNodeButtonView.showButton();
}
/**
* Check and display learning views
* Displays the explanation for a add, search, sort a new node and lock the database
*/
private void checkAndPerformedEducation(Menu menu) {
if (PreferencesUtil.isEducationScreensEnabled(this)) {
// If no node, show education to add new one
if (listNodesFragment != null
&& listNodesFragment.isEmpty()) {
if (!PreferencesUtil.isEducationNewNodePerformed(this)) {
TapTargetView.showFor(this,
TapTarget.forView(findViewById(R.id.add_button),
getString(R.string.education_new_node_title),
getString(R.string.education_new_node_summary))
.textColorInt(Color.WHITE)
.tintTarget(false)
.cancelable(true),
new TapTargetView.Listener() {
@Override
public void onTargetClick(TapTargetView view) {
super.onTargetClick(view);
addNodeButtonView.openButtonIfClose();
}
@Override
public void onOuterCircleClick(TapTargetView view) {
super.onOuterCircleClick(view);
view.dismiss(false);
}
});
PreferencesUtil.saveEducationPreference(this,
R.string.education_new_node_key);
}
}
// Else show the search education
else if (!PreferencesUtil.isEducationSearchPerformed(this)) {
try {
TapTargetView.showFor(this,
TapTarget.forToolbarMenuItem(toolbar, R.id.menu_search,
getString(R.string.education_search_title),
getString(R.string.education_search_summary))
.textColorInt(Color.WHITE)
.tintTarget(true)
.cancelable(true),
new TapTargetView.Listener() {
@Override
public void onTargetClick(TapTargetView view) {
super.onTargetClick(view);
MenuItem searchItem = menu.findItem(R.id.menu_search);
searchItem.expandActionView();
}
@Override
public void onOuterCircleClick(TapTargetView view) {
super.onOuterCircleClick(view);
view.dismiss(false);
}
});
PreferencesUtil.saveEducationPreference(this,
R.string.education_search_key);
} catch (Exception e) {
// If icon not visible
Log.w(TAG, "Can't performed education for search");
}
}
// Else show the sort education
else if (!PreferencesUtil.isEducationSortPerformed(this)) {
try {
TapTargetView.showFor(this,
TapTarget.forToolbarMenuItem(toolbar, R.id.menu_sort,
getString(R.string.education_sort_title),
getString(R.string.education_sort_summary))
.textColorInt(Color.WHITE)
.tintTarget(true)
.cancelable(true),
new TapTargetView.Listener() {
@Override
public void onTargetClick(TapTargetView view) {
super.onTargetClick(view);
MenuItem sortItem = menu.findItem(R.id.menu_sort);
onOptionsItemSelected(sortItem);
}
@Override
public void onOuterCircleClick(TapTargetView view) {
super.onOuterCircleClick(view);
view.dismiss(false);
}
});
PreferencesUtil.saveEducationPreference(this,
R.string.education_sort_key);
} catch (Exception e) {
Log.w(TAG, "Can't performed education for sort");
}
}
// Else show the lock education
else if (!PreferencesUtil.isEducationLockPerformed(this)) {
try {
TapTargetView.showFor(this,
TapTarget.forToolbarMenuItem(toolbar, R.id.menu_lock,
getString(R.string.education_lock_title),
getString(R.string.education_lock_summary))
.textColorInt(Color.WHITE)
.tintTarget(true)
.cancelable(true),
new TapTargetView.Listener() {
@Override
public void onTargetClick(TapTargetView view) {
super.onTargetClick(view);
MenuItem lockItem = menu.findItem(R.id.menu_lock);
onOptionsItemSelected(lockItem);
}
@Override
public void onOuterCircleClick(TapTargetView view) {
super.onOuterCircleClick(view);
view.dismiss(false);
}
});
PreferencesUtil.saveEducationPreference(this,
R.string.education_lock_key);
} catch (Exception e) {
Log.w(TAG, "Can't performed education for lock");
}
}
}
} }
@Override @Override
protected void onStop() { protected void onStop() {
super.onStop(); super.onStop();
// Hide button // Hide button
addNodeButtonView.hideButton(); if (addNodeButtonView != null)
} addNodeButtonView.hideButton();
@Override
public void onSortSelected(SortNodeEnum sortNodeEnum, boolean ascending, boolean groupsBefore, boolean recycleBinBottom) {
super.onSortSelected(sortNodeEnum, ascending, groupsBefore, recycleBinBottom);
// Show button if hide after sort
addNodeButtonView.showButton();
}
protected void setGroupIcon() {
if (mCurrentGroup != null) {
ImageView iv = findViewById(R.id.icon);
App.getDB().getDrawFactory().assignDrawableTo(iv, getResources(), mCurrentGroup.getIcon());
}
}
private void deleteEntry(PwEntry entry) {
Handler handler = new Handler();
DeleteEntry task = new DeleteEntry(this, App.getDB(), entry,
new AfterDeleteNode(handler, entry));
ProgressTask pt = new ProgressTask(this, task, R.string.saving_database);
pt.run();
}
private void deleteGroup(PwGroup group) {
//TODO Verify trash recycle bin
Handler handler = new Handler();
DeleteGroup task = new DeleteGroup(this, App.getDB(), group,
new AfterDeleteNode(handler, group));
ProgressTask pt = new ProgressTask(this, task, R.string.saving_database);
pt.run();
} }
@Override @Override
public boolean onCreateOptionsMenu(Menu menu) { public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater(); MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.search, menu); inflater.inflate(R.menu.search, menu);
@@ -320,6 +651,11 @@ public class GroupActivity extends ListNodesActivity
searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default
} }
super.onCreateOptionsMenu(menu);
// Launch education screen
new Handler().post(() -> checkAndPerformedEducation(menu));
return true; return true;
} }
@@ -333,6 +669,7 @@ public class GroupActivity extends ListNodesActivity
// manually launch the real search activity // manually launch the real search activity
final Intent searchIntent = new Intent(getApplicationContext(), SearchResultsActivity.class); final Intent searchIntent = new Intent(getApplicationContext(), SearchResultsActivity.class);
// add query to the Intent Extras // add query to the Intent Extras
searchIntent.setAction(Intent.ACTION_SEARCH);
searchIntent.putExtra(SearchManager.QUERY, query); searchIntent.putExtra(SearchManager.QUERY, query);
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.O if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
&& autofillHelper.getAssistStructure() != null ) { && autofillHelper.getAssistStructure() != null ) {
@@ -376,28 +713,146 @@ public class GroupActivity extends ListNodesActivity
} }
@Override @Override
public void approveEditGroup(Bundle bundle) { public void approveEditGroup(GroupEditDialogFragment.EditGroupDialogAction action,
String GroupName = bundle.getString(GroupEditDialogFragment.KEY_NAME); String name,
int GroupIconID = bundle.getInt(GroupEditDialogFragment.KEY_ICON_ID); PwIcon icon) {
switch (editGroupDialogAction) { Database database = App.getDB();
PwIconStandard iconStandard = database.getPwDatabase().getIconFactory().getFolderIcon();
switch (action) {
case CREATION: case CREATION:
// If edit group creation // If group creation
Handler handler = new Handler(); // Build the group
AddGroup task = new AddGroup(this, App.getDB(), GroupName, GroupIconID, mCurrentGroup, PwGroup newGroup = database.createGroup(mCurrentGroup);
new AfterAddNode(handler), false); newGroup.setName(name);
ProgressTask pt = new ProgressTask(this, task, R.string.saving_database); try {
pt.run(); iconStandard = (PwIconStandard) icon;
} catch (Exception ignored) {} // TODO custom icon
newGroup.setIcon(iconStandard);
// If group created save it in the database
AddGroupRunnable addGroupRunnable = new AddGroupRunnable(this,
App.getDB(),
newGroup,
new AfterAddNode());
addGroupRunnable.setUpdateProgressTaskStatus(
new UpdateProgressTaskStatus(this,
SaveDatabaseProgressTaskDialogFragment.start(
getSupportFragmentManager())
));
new Thread(addGroupRunnable).start();
break; break;
case UPDATE: case UPDATE:
// If edit group update // If update add new elements
// TODO UpdateGroup if (oldGroupToUpdate != null) {
PwGroup updateGroup = oldGroupToUpdate.clone();
updateGroup.setName(name);
try {
iconStandard = (PwIconStandard) icon;
} catch (Exception ignored) {} // TODO custom icon
updateGroup.setIcon(iconStandard);
if (listNodesFragment != null)
listNodesFragment.removeNode(oldGroupToUpdate);
// If group updated save it in the database
UpdateGroupRunnable updateGroupRunnable = new UpdateGroupRunnable(this,
App.getDB(),
oldGroupToUpdate,
updateGroup,
new AfterUpdateNode());
updateGroupRunnable.setUpdateProgressTaskStatus(
new UpdateProgressTaskStatus(this,
SaveDatabaseProgressTaskDialogFragment.start(
getSupportFragmentManager())
));
new Thread(updateGroupRunnable).start();
}
break; break;
} }
editGroupDialogAction = EditGroupDialogAction.NONE; }
class AfterAddNode extends AfterActionNodeOnFinish {
public void run(PwNode oldNode, PwNode newNode) {
super.run();
runOnUiThread(() -> {
if (mSuccess) {
if (listNodesFragment != null)
listNodesFragment.addNode(newNode);
} else {
displayMessage(GroupActivity.this);
}
SaveDatabaseProgressTaskDialogFragment.stop(GroupActivity.this);
});
}
}
class AfterUpdateNode extends AfterActionNodeOnFinish {
public void run(PwNode oldNode, PwNode newNode) {
super.run();
runOnUiThread(() -> {
if (mSuccess) {
if (listNodesFragment != null)
listNodesFragment.updateNode(oldNode, newNode);
} else {
displayMessage(GroupActivity.this);
}
SaveDatabaseProgressTaskDialogFragment.stop(GroupActivity.this);
});
}
}
class AfterDeleteNode extends AfterActionNodeOnFinish {
@Override
public void run(PwNode oldNode, PwNode newNode) {
super.run();
runOnUiThread(() -> {
if ( mSuccess) {
if (listNodesFragment != null)
listNodesFragment.removeNode(oldNode);
PwGroup parent = oldNode.getParent();
Database db = App.getDB();
PwDatabase database = db.getPwDatabase();
if (db.isRecycleBinAvailable() &&
db.isRecycleBinEnabled()) {
PwGroup recycleBin = database.getRecycleBin();
// Add trash if it doesn't exists
if (parent.equals(recycleBin)
&& mCurrentGroup != null
&& mCurrentGroup.getParent() == null
&& !mCurrentGroup.equals(recycleBin)) {
if (listNodesFragment != null)
listNodesFragment.addNode(parent);
}
}
} else {
mHandler.post(new UIToastTask(GroupActivity.this, "Unrecoverable error: " + mMessage));
App.setShutdown();
finish();
}
SaveDatabaseProgressTaskDialogFragment.stop(GroupActivity.this);
});
}
} }
@Override @Override
public void cancelEditGroup(Bundle bundle) { public void cancelEditGroup(GroupEditDialogFragment.EditGroupDialogAction action,
String name,
PwIcon iconId) {
// Do nothing here // Do nothing here
} }
@@ -422,4 +877,18 @@ public class GroupActivity extends ListNodesActivity
} }
} }
} }
@Override
protected void openGroup(PwGroup group) {
super.openGroup(group);
if (addNodeButtonView != null)
addNodeButtonView.showButton();
}
@Override
public void onBackPressed() {
super.onBackPressed();
if (addNodeButtonView != null)
addNodeButtonView.showButton();
}
} }

View File

@@ -22,52 +22,44 @@ package com.kunzisoft.keepass.activities;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.app.assist.AssistStructure; import android.app.assist.AssistStructure;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri; import android.net.Uri;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler; import android.support.annotation.Nullable;
import android.preference.PreferenceManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu; import android.view.Menu;
import android.view.MenuInflater; import android.view.MenuInflater;
import android.view.MenuItem; import android.view.MenuItem;
import android.view.View;
import android.widget.TextView; import android.widget.TextView;
import com.kunzisoft.keepass.R; import com.kunzisoft.keepass.R;
import com.kunzisoft.keepass.adapters.NodeAdapter; import com.kunzisoft.keepass.adapters.NodeAdapter;
import com.kunzisoft.keepass.app.App; import com.kunzisoft.keepass.app.App;
import com.kunzisoft.keepass.autofill.AutofillHelper; import com.kunzisoft.keepass.autofill.AutofillHelper;
import com.kunzisoft.keepass.compat.EditorCompat;
import com.kunzisoft.keepass.database.Database;
import com.kunzisoft.keepass.database.PwDatabase;
import com.kunzisoft.keepass.database.PwEntry; import com.kunzisoft.keepass.database.PwEntry;
import com.kunzisoft.keepass.database.PwGroup; import com.kunzisoft.keepass.database.PwGroup;
import com.kunzisoft.keepass.database.PwNode; import com.kunzisoft.keepass.database.PwNode;
import com.kunzisoft.keepass.database.SortNodeEnum; import com.kunzisoft.keepass.database.SortNodeEnum;
import com.kunzisoft.keepass.database.edit.AfterAddNodeOnFinish;
import com.kunzisoft.keepass.database.edit.OnFinish;
import com.kunzisoft.keepass.dialogs.AssignMasterKeyDialogFragment; import com.kunzisoft.keepass.dialogs.AssignMasterKeyDialogFragment;
import com.kunzisoft.keepass.dialogs.SortDialogFragment; import com.kunzisoft.keepass.dialogs.SortDialogFragment;
import com.kunzisoft.keepass.selection.EntrySelectionHelper;
import com.kunzisoft.keepass.lock.LockingActivity;
import com.kunzisoft.keepass.password.AssignPasswordHelper; import com.kunzisoft.keepass.password.AssignPasswordHelper;
import com.kunzisoft.keepass.settings.PreferencesUtil;
import com.kunzisoft.keepass.tasks.UIToastTask;
import com.kunzisoft.keepass.utils.MenuUtil; import com.kunzisoft.keepass.utils.MenuUtil;
public abstract class ListNodesActivity extends LockingActivity public abstract class ListNodesActivity extends LockingActivity
implements AssignMasterKeyDialogFragment.AssignPasswordDialogListener, implements AssignMasterKeyDialogFragment.AssignPasswordDialogListener,
NodeAdapter.OnNodeClickCallback, NodeAdapter.NodeClickCallback,
SortDialogFragment.SortSelectionListener { SortDialogFragment.SortSelectionListener {
protected PwGroup mCurrentGroup; protected static final String GROUP_ID_KEY = "GROUP_ID_KEY";
protected NodeAdapter mAdapter;
private SharedPreferences prefs;
protected static final String LIST_NODES_FRAGMENT_TAG = "LIST_NODES_FRAGMENT_TAG";
protected ListNodesFragment listNodesFragment;
protected PwGroup mCurrentGroup;
protected TextView groupNameView;
protected boolean entrySelectionMode;
protected AutofillHelper autofillHelper; protected AutofillHelper autofillHelper;
@Override @Override
@@ -83,68 +75,90 @@ public abstract class ListNodesActivity extends LockingActivity
finish(); finish();
return; return;
} }
prefs = PreferenceManager.getDefaultSharedPreferences(this);
invalidateOptionsMenu(); invalidateOptionsMenu();
// TODO Move in search mCurrentGroup = retrieveCurrentGroup(savedInstanceState);
setContentView(R.layout.list_nodes);
mCurrentGroup = initCurrentGroup(); initializeListNodesFragment(mCurrentGroup);
mAdapter = new NodeAdapter(this);
addOptionsToAdapter(mAdapter);
entrySelectionMode = EntrySelectionHelper.isIntentInEntrySelectionMode(getIntent());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
autofillHelper = new AutofillHelper(); autofillHelper = new AutofillHelper();
autofillHelper.retrieveAssistStructure(getIntent()); autofillHelper.retrieveAssistStructure(getIntent());
} }
} }
protected abstract PwGroup initCurrentGroup(); protected abstract PwGroup retrieveCurrentGroup(@Nullable Bundle savedInstanceState);
protected abstract RecyclerView defineNodeList();
protected void addOptionsToAdapter(NodeAdapter nodeAdapter) {
mAdapter.setOnNodeClickListener(this);
}
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
// Add elements to the list // Refresh the title
mAdapter.rebuildList(mCurrentGroup); assignToolbarElements();
assignListToNodeAdapter(defineNodeList());
} }
protected void setGroupTitle() { protected void initializeListNodesFragment(PwGroup currentGroup) {
if ( mCurrentGroup != null ) { listNodesFragment = (ListNodesFragment) getSupportFragmentManager()
String name = mCurrentGroup.getName(); .findFragmentByTag(LIST_NODES_FRAGMENT_TAG);
TextView tv = findViewById(R.id.group_name); if (listNodesFragment == null)
if ( name != null && name.length() > 0 ) { listNodesFragment = ListNodesFragment.newInstance(currentGroup.getId());
if ( tv != null ) { }
tv.setText(name);
} /**
} else { * Attach the fragment's list of node.
if ( tv != null ) { * <br />
tv.setText(getText(R.string.root)); * <strong>R.id.nodes_list_fragment_container</strong> must be the id of the container
} */
} protected void attachFragmentToContentView() {
} getSupportFragmentManager().beginTransaction().replace(
R.id.nodes_list_fragment_container,
listNodesFragment,
LIST_NODES_FRAGMENT_TAG)
.commit();
}
public void assignToolbarElements() {
if (mCurrentGroup != null) {
String title = mCurrentGroup.getName();
if (title != null && title.length() > 0) {
if (groupNameView != null) {
groupNameView.setText(title);
groupNameView.invalidate();
}
} else {
if (groupNameView != null) {
groupNameView.setText(getText(R.string.root));
groupNameView.invalidate();
}
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
MenuUtil.contributionMenuInflater(inflater, menu);
inflater.inflate(R.menu.default_menu, menu);
return true;
} }
protected void assignListToNodeAdapter(RecyclerView recyclerView) { @Override
recyclerView.setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET); public boolean onOptionsItemSelected(MenuItem item) {
recyclerView.setLayoutManager(new LinearLayoutManager(this)); switch ( item.getItemId() ) {
recyclerView.setAdapter(mAdapter); default:
// Check the time lock before launching settings
MenuUtil.onDefaultMenuOptionsItemSelected(this, item, true);
return super.onOptionsItemSelected(item);
}
} }
@Override @Override
public void onNodeClick(PwNode node) { public void onNodeClick(PwNode node) {
mAdapter.registerANodeToUpdate(node);
// Add event when we have Autofill // Add event when we have Autofill
AssistStructure assistStructure = null; AssistStructure assistStructure = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
@@ -152,7 +166,7 @@ public abstract class ListNodesActivity extends LockingActivity
if (assistStructure != null) { if (assistStructure != null) {
switch (node.getType()) { switch (node.getType()) {
case GROUP: case GROUP:
GroupActivity.launch(this, (PwGroup) node, assistStructure); openGroup((PwGroup) node);
break; break;
case ENTRY: case ENTRY:
// Build response with the entry selected // Build response with the entry selected
@@ -163,80 +177,49 @@ public abstract class ListNodesActivity extends LockingActivity
} }
} }
if ( assistStructure == null ){ if ( assistStructure == null ){
switch (node.getType()) { if (entrySelectionMode) {
case GROUP: switch (node.getType()) {
GroupActivity.launch(this, (PwGroup) node); case GROUP:
break; openGroup((PwGroup) node);
case ENTRY: break;
EntryActivity.launch(this, (PwEntry) node); case ENTRY:
break; EntrySelectionHelper.buildResponseWhenEntrySelected(this, (PwEntry) node);
finish();
break;
}
} else {
switch (node.getType()) {
case GROUP:
openGroup((PwGroup) node);
break;
case ENTRY:
EntryActivity.launch(this, (PwEntry) node);
break;
}
} }
} }
} }
@Override protected void openGroup(PwGroup group) {
public boolean onCreateOptionsMenu(Menu menu) { // Check Timeout
super.onCreateOptionsMenu(menu); if (checkTimeIsAllowedOrFinish(this)) {
startRecordTime(this);
MenuInflater inflater = getMenuInflater();
MenuUtil.donationMenuInflater(inflater, menu);
inflater.inflate(R.menu.tree, menu);
inflater.inflate(R.menu.default_menu, menu);
return true; ListNodesFragment newListNodeFragment = ListNodesFragment.newInstance(group.getId());
} getSupportFragmentManager().beginTransaction()
.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left,
@Override R.anim.slide_in_left, R.anim.slide_out_right)
public void onSortSelected(SortNodeEnum sortNodeEnum, boolean ascending, boolean groupsBefore, boolean recycleBinBottom) { .replace(R.id.nodes_list_fragment_container,
// Toggle setting newListNodeFragment,
Editor editor = prefs.edit(); LIST_NODES_FRAGMENT_TAG)
editor.putString(getString(R.string.sort_node_key), sortNodeEnum.name()); .addToBackStack(LIST_NODES_FRAGMENT_TAG)
editor.putBoolean(getString(R.string.sort_ascending_key), ascending); .commit();
editor.putBoolean(getString(R.string.sort_group_before_key), groupsBefore); listNodesFragment = newListNodeFragment;
editor.putBoolean(getString(R.string.sort_recycle_bin_bottom_key), recycleBinBottom); mCurrentGroup = group;
EditorCompat.apply(editor); assignToolbarElements();
}
// Tell the adapter to refresh it's list
mAdapter.notifyChangeSort(sortNodeEnum, ascending, groupsBefore);
mAdapter.rebuildList(mCurrentGroup);
} }
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch ( item.getItemId() ) {
case R.id.menu_sort:
SortDialogFragment sortDialogFragment;
PwDatabase database = App.getDB().getPwDatabase();
/*
// TODO Recycle bin bottom
if (database.isRecycleBinAvailable() && database.isRecycleBinEnabled()) {
sortDialogFragment =
SortDialogFragment.getInstance(
PrefsUtil.getListSort(this),
PrefsUtil.getAscendingSort(this),
PrefsUtil.getGroupsBeforeSort(this),
PrefsUtil.getRecycleBinBottomSort(this));
} else {
*/
sortDialogFragment =
SortDialogFragment.getInstance(
PreferencesUtil.getListSort(this),
PreferencesUtil.getAscendingSort(this),
PreferencesUtil.getGroupsBeforeSort(this));
//}
sortDialogFragment.show(getSupportFragmentManager(), "sortDialog");
return true;
default:
// Check the time lock before launching settings
MenuUtil.onDefaultMenuOptionsItemSelected(this, item, true);
return super.onOptionsItemSelected(item);
}
}
@Override @Override
public void onAssignKeyDialogPositiveClick( public void onAssignKeyDialogPositiveClick(
boolean masterPasswordChecked, String masterPassword, boolean masterPasswordChecked, String masterPassword,
@@ -244,7 +227,7 @@ public abstract class ListNodesActivity extends LockingActivity
AssignPasswordHelper assignPasswordHelper = AssignPasswordHelper assignPasswordHelper =
new AssignPasswordHelper(this, new AssignPasswordHelper(this,
masterPassword, keyFile); masterPasswordChecked, masterPassword, keyFileChecked, keyFile);
assignPasswordHelper.assignPasswordInDatabase(null); assignPasswordHelper.assignPasswordInDatabase(null);
} }
@@ -255,29 +238,17 @@ public abstract class ListNodesActivity extends LockingActivity
} }
@Override
public void onSortSelected(SortNodeEnum sortNodeEnum, boolean ascending, boolean groupsBefore, boolean recycleBinBottom) {
if (listNodesFragment != null)
listNodesFragment.onSortSelected(sortNodeEnum, ascending, groupsBefore, recycleBinBottom);
}
@Override @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) { protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) { EntrySelectionHelper.onActivityResultSetResultAndFinish(this, requestCode, resultCode, data);
case EntryEditActivity.ADD_OR_UPDATE_ENTRY_REQUEST_CODE:
if (resultCode == EntryEditActivity.ADD_ENTRY_RESULT_CODE ||
resultCode == EntryEditActivity.UPDATE_ENTRY_RESULT_CODE) {
PwNode newNode = (PwNode) data.getSerializableExtra(EntryEditActivity.ADD_OR_UPDATE_ENTRY_KEY);
if (newNode != null) {
if (resultCode == EntryEditActivity.ADD_ENTRY_RESULT_CODE)
mAdapter.addNode(newNode);
if (resultCode == EntryEditActivity.UPDATE_ENTRY_RESULT_CODE) {
//mAdapter.updateLastNodeRegister(newNode);
mAdapter.rebuildList(mCurrentGroup);
}
} else {
Log.e(this.getClass().getName(), "New node can be retrieve in Activity Result");
}
}
break;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
AutofillHelper.onActivityResultSetResultAndFinish(this, requestCode, resultCode, data); AutofillHelper.onActivityResultSetResultAndFinish(this, requestCode, resultCode, data);
} }
@@ -302,52 +273,18 @@ public abstract class ListNodesActivity extends LockingActivity
} }
} }
class AfterAddNode extends AfterAddNodeOnFinish { @Override
AfterAddNode(Handler handler) { public void onBackPressed() {
super(handler); if (checkTimeIsAllowedOrFinish(this)) {
} startRecordTime(this);
public void run(PwNode pwNode) { super.onBackPressed();
super.run();
if (mSuccess) {
mAdapter.addNode(pwNode);
} else {
displayMessage(ListNodesActivity.this);
}
}
}
class AfterDeleteNode extends OnFinish { listNodesFragment = (ListNodesFragment) getSupportFragmentManager().findFragmentByTag(LIST_NODES_FRAGMENT_TAG);
private PwNode pwNode; // to refresh fragment
listNodesFragment.rebuildList();
AfterDeleteNode(Handler handler, PwNode pwNode) { mCurrentGroup = listNodesFragment.getMainGroup();
super(handler); assignToolbarElements();
this.pwNode = pwNode;
}
@Override
public void run() {
if ( mSuccess) {
mAdapter.removeNode(pwNode);
PwGroup parent = pwNode.getParent();
Database db = App.getDB();
PwDatabase database = db.getPwDatabase();
if (db.isRecycleBinAvailable() &&
db.isRecycleBinEnabled()) {
PwGroup recycleBin = database.getRecycleBin();
// Add trash if it doesn't exists
if (parent.equals(recycleBin)
&& mCurrentGroup != null
&& mCurrentGroup.getParent() == null
&& !mCurrentGroup.equals(recycleBin)) {
mAdapter.addNode(parent);
}
}
} else {
mHandler.post(new UIToastTask(ListNodesActivity.this, "Unrecoverable error: " + mMessage));
App.setShutdown();
finish();
}
} }
} }
} }

View File

@@ -0,0 +1,283 @@
package com.kunzisoft.keepass.activities;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.kunzisoft.keepass.R;
import com.kunzisoft.keepass.adapters.NodeAdapter;
import com.kunzisoft.keepass.app.App;
import com.kunzisoft.keepass.database.Database;
import com.kunzisoft.keepass.database.PwDatabase;
import com.kunzisoft.keepass.database.PwGroup;
import com.kunzisoft.keepass.database.PwGroupId;
import com.kunzisoft.keepass.database.PwNode;
import com.kunzisoft.keepass.database.SortNodeEnum;
import com.kunzisoft.keepass.dialogs.SortDialogFragment;
import com.kunzisoft.keepass.settings.PreferencesUtil;
import com.kunzisoft.keepass.stylish.StylishFragment;
public class ListNodesFragment extends StylishFragment implements
SortDialogFragment.SortSelectionListener {
private static final String TAG = ListNodesFragment.class.getName();
private static final String GROUP_ID_KEY = "GROUP_ID_KEY";
private NodeAdapter.NodeClickCallback nodeClickCallback;
private NodeAdapter.NodeMenuListener nodeMenuListener;
private OnScrollListener onScrollListener;
private RecyclerView listView;
protected PwGroup mCurrentGroup;
protected NodeAdapter mAdapter;
// Preferences for sorting
private SharedPreferences prefs;
public static ListNodesFragment newInstance(PwGroupId groupId) {
Bundle bundle=new Bundle();
if (groupId != null) {
bundle.putSerializable(GROUP_ID_KEY, groupId);
}
ListNodesFragment listNodesFragment = new ListNodesFragment();
listNodesFragment.setArguments(bundle);
return listNodesFragment;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
nodeClickCallback = (NodeAdapter.NodeClickCallback) context;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(context.toString()
+ " must implement " + NodeAdapter.NodeClickCallback.class.getName());
}
try {
nodeMenuListener = (NodeAdapter.NodeMenuListener) context;
} catch (ClassCastException e) {
nodeMenuListener = null;
// Context menu can be omit
Log.w(TAG, context.toString()
+ " must implement " + NodeAdapter.NodeMenuListener.class.getName());
}
try {
onScrollListener = (OnScrollListener) context;
} catch (ClassCastException e) {
onScrollListener = null;
// Context menu can be omit
Log.w(TAG, context.toString()
+ " must implement " + RecyclerView.OnScrollListener.class.getName());
}
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
mCurrentGroup = initCurrentGroup();
if (getActivity() != null) {
mAdapter = new NodeAdapter(getContextThemed(), getActivity().getMenuInflater());
mAdapter.setOnNodeClickListener(nodeClickCallback);
if (nodeMenuListener != null) {
mAdapter.setActivateContextMenu(true);
mAdapter.setNodeMenuListener(nodeMenuListener);
}
}
prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
}
protected PwGroup initCurrentGroup() { // TODO Change by parcelable
Database db = App.getDB();
PwGroup root = db.getPwDatabase().getRootGroup();
PwGroup currentGroup = null;
if (getArguments() != null) {
// Contains only the group id, so the group must be retrieve
if (getArguments().containsKey(GROUP_ID_KEY)) {
PwGroupId pwGroupId = (PwGroupId) getArguments().getSerializable(GROUP_ID_KEY);
if ( pwGroupId != null )
currentGroup = db.getPwDatabase().getGroupByGroupId(pwGroupId);
}
}
if ( currentGroup == null ) {
currentGroup = root;
}
return currentGroup;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
// To apply theme
View rootView = inflater.cloneInContext(getContextThemed())
.inflate(R.layout.list_nodes_fragment, container, false);
listView = rootView.findViewById(R.id.nodes_list);
if (onScrollListener != null) {
listView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
onScrollListener.onScrolled(dy);
}
});
}
return rootView;
}
@Override
public void onResume() {
super.onResume();
rebuildList();
}
public void rebuildList() {
// Add elements to the list
mAdapter.rebuildList(mCurrentGroup);
assignListToNodeAdapter(listView);
}
protected void assignListToNodeAdapter(RecyclerView recyclerView) {
recyclerView.setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(mAdapter);
}
@Override
public void onSortSelected(SortNodeEnum sortNodeEnum, boolean ascending, boolean groupsBefore, boolean recycleBinBottom) {
// Toggle setting
SharedPreferences.Editor editor = prefs.edit();
editor.putString(getString(R.string.sort_node_key), sortNodeEnum.name());
editor.putBoolean(getString(R.string.sort_ascending_key), ascending);
editor.putBoolean(getString(R.string.sort_group_before_key), groupsBefore);
editor.putBoolean(getString(R.string.sort_recycle_bin_bottom_key), recycleBinBottom);
editor.apply();
// Tell the adapter to refresh it's list
mAdapter.notifyChangeSort(sortNodeEnum, ascending, groupsBefore);
mAdapter.rebuildList(mCurrentGroup);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.tree, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch ( item.getItemId() ) {
case R.id.menu_sort:
SortDialogFragment sortDialogFragment;
PwDatabase database = App.getDB().getPwDatabase();
/*
// TODO Recycle bin bottom
if (database.isRecycleBinAvailable() && database.isRecycleBinEnabled()) {
sortDialogFragment =
SortDialogFragment.getInstance(
PrefsUtil.getListSort(this),
PrefsUtil.getAscendingSort(this),
PrefsUtil.getGroupsBeforeSort(this),
PrefsUtil.getRecycleBinBottomSort(this));
} else {
*/
sortDialogFragment =
SortDialogFragment.getInstance(
PreferencesUtil.getListSort(getContext()),
PreferencesUtil.getAscendingSort(getContext()),
PreferencesUtil.getGroupsBeforeSort(getContext()));
//}
sortDialogFragment.show(getChildFragmentManager(), "sortDialog");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case EntryEditActivity.ADD_OR_UPDATE_ENTRY_REQUEST_CODE:
if (resultCode == EntryEditActivity.ADD_ENTRY_RESULT_CODE ||
resultCode == EntryEditActivity.UPDATE_ENTRY_RESULT_CODE) {
PwNode newNode = (PwNode) data.getSerializableExtra(EntryEditActivity.ADD_OR_UPDATE_ENTRY_KEY);
if (newNode != null) {
if (resultCode == EntryEditActivity.ADD_ENTRY_RESULT_CODE)
mAdapter.addNode(newNode);
if (resultCode == EntryEditActivity.UPDATE_ENTRY_RESULT_CODE) {
//mAdapter.updateLastNodeRegister(newNode);
mAdapter.rebuildList(mCurrentGroup);
}
} else {
Log.e(this.getClass().getName(), "New node can be retrieve in Activity Result");
}
}
break;
}
}
public boolean isEmpty() {
return mAdapter == null || mAdapter.getItemCount() <= 0;
}
public void addNode(PwNode newNode) {
mAdapter.addNode(newNode);
}
public void updateNode(PwNode oldNode, PwNode newNode) {
mAdapter.updateNode(oldNode, newNode);
}
public void removeNode(PwNode pwNode) {
mAdapter.removeNode(pwNode);
}
public PwGroup getMainGroup() {
return mCurrentGroup;
}
public interface OnScrollListener {
/**
* Callback method to be invoked when the RecyclerView has been scrolled. This will be
* called after the scroll has completed.
*
* @param dy The amount of vertical scroll.
*/
void onScrolled(int dy);
}
}

View File

@@ -20,8 +20,6 @@
package com.kunzisoft.keepass.adapters; package com.kunzisoft.keepass.adapters;
import android.view.View; import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.kunzisoft.keepass.R; import com.kunzisoft.keepass.R;
@@ -30,7 +28,7 @@ class EntryViewHolder extends BasicViewHolder {
EntryViewHolder(View itemView) { EntryViewHolder(View itemView) {
super(itemView); super(itemView);
container = itemView.findViewById(R.id.entry_container); container = itemView.findViewById(R.id.entry_container);
icon = (ImageView) itemView.findViewById(R.id.entry_icon); icon = itemView.findViewById(R.id.entry_icon);
text = (TextView) itemView.findViewById(R.id.entry_text); text = itemView.findViewById(R.id.entry_text);
} }
} }

View File

@@ -20,8 +20,6 @@
package com.kunzisoft.keepass.adapters; package com.kunzisoft.keepass.adapters;
import android.view.View; import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.kunzisoft.keepass.R; import com.kunzisoft.keepass.R;
@@ -30,7 +28,7 @@ class GroupViewHolder extends BasicViewHolder {
GroupViewHolder(View itemView) { GroupViewHolder(View itemView) {
super(itemView); super(itemView);
container = itemView.findViewById(R.id.group_container); container = itemView.findViewById(R.id.group_container);
icon = (ImageView) itemView.findViewById(R.id.group_icon); icon = itemView.findViewById(R.id.group_icon);
text = (TextView) itemView.findViewById(R.id.group_text); text = itemView.findViewById(R.id.group_text);
} }
} }

View File

@@ -20,13 +20,16 @@
package com.kunzisoft.keepass.adapters; package com.kunzisoft.keepass.adapters;
import android.content.Context; import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.util.SortedList; import android.support.v7.util.SortedList;
import android.support.v7.widget.RecyclerView; import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.util.SortedListAdapterCallback; import android.support.v7.widget.util.SortedListAdapterCallback;
import android.util.Log; import android.util.TypedValue;
import android.view.ContextMenu; import android.view.ContextMenu;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.Menu; import android.view.MenuInflater;
import android.view.MenuItem; import android.view.MenuItem;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
@@ -36,6 +39,7 @@ import com.kunzisoft.keepass.app.App;
import com.kunzisoft.keepass.database.PwGroup; import com.kunzisoft.keepass.database.PwGroup;
import com.kunzisoft.keepass.database.PwNode; import com.kunzisoft.keepass.database.PwNode;
import com.kunzisoft.keepass.database.SortNodeEnum; import com.kunzisoft.keepass.database.SortNodeEnum;
import com.kunzisoft.keepass.icons.IconPackChooser;
import com.kunzisoft.keepass.settings.PreferencesUtil; import com.kunzisoft.keepass.settings.PreferencesUtil;
public class NodeAdapter extends RecyclerView.Adapter<BasicViewHolder> { public class NodeAdapter extends RecyclerView.Adapter<BasicViewHolder> {
@@ -44,29 +48,30 @@ public class NodeAdapter extends RecyclerView.Adapter<BasicViewHolder> {
private Context context; private Context context;
private LayoutInflater inflater; private LayoutInflater inflater;
private MenuInflater menuInflater;
private float textSize; private float textSize;
private float iconSize;
private SortNodeEnum listSort; private SortNodeEnum listSort;
private boolean groupsBeforeSort; private boolean groupsBeforeSort;
private boolean ascendingSort; private boolean ascendingSort;
private OnNodeClickCallback onNodeClickCallback; private NodeClickCallback nodeClickCallback;
private int nodePositionToUpdate;
private NodeMenuListener nodeMenuListener; private NodeMenuListener nodeMenuListener;
private boolean activateContextMenu; private boolean activateContextMenu;
private int iconGroupColor;
private int iconEntryColor;
/** /**
* Create node list adapter with contextMenu or not * Create node list adapter with contextMenu or not
* @param context Context to use * @param context Context to use
*/ */
public NodeAdapter(final Context context) { public NodeAdapter(final Context context, MenuInflater menuInflater) {
this.inflater = LayoutInflater.from(context); this.inflater = LayoutInflater.from(context);
this.menuInflater = menuInflater;
this.context = context; this.context = context;
this.textSize = PreferencesUtil.getListTextSize(context); assignPreferences();
this.listSort = PreferencesUtil.getListSort(context);
this.groupsBeforeSort = PreferencesUtil.getGroupsBeforeSort(context);
this.ascendingSort = PreferencesUtil.getAscendingSort(context);
this.activateContextMenu = false; this.activateContextMenu = false;
this.nodePositionToUpdate = -1;
this.nodeSortedList = new SortedList<>(PwNode.class, new SortedListAdapterCallback<PwNode>(this) { this.nodeSortedList = new SortedList<>(PwNode.class, new SortedListAdapterCallback<PwNode>(this) {
@Override public int compare(PwNode item1, PwNode item2) { @Override public int compare(PwNode item1, PwNode item2) {
@@ -81,17 +86,42 @@ public class NodeAdapter extends RecyclerView.Adapter<BasicViewHolder> {
return item1.equals(item2); return item1.equals(item2);
} }
}); });
// Retrieve the color to tint the icon
int[] attrTextColorPrimary = {android.R.attr.textColorPrimary};
TypedArray taTextColorPrimary = context.getTheme().obtainStyledAttributes(attrTextColorPrimary);
this.iconGroupColor = taTextColorPrimary.getColor(0, Color.BLACK);
taTextColorPrimary.recycle();
int[] attrTextColor = {android.R.attr.textColor}; // In two times to fix bug compilation
TypedArray taTextColor = context.getTheme().obtainStyledAttributes(attrTextColor);
this.iconEntryColor = taTextColor.getColor(0, Color.BLACK);
taTextColor.recycle();
} }
public void setActivateContextMenu(boolean activate) { public void setActivateContextMenu(boolean activate) {
this.activateContextMenu = activate; this.activateContextMenu = activate;
} }
private void assignPreferences() {
this.textSize = PreferencesUtil.getListTextSize(context);
// Retrieve the icon size
int iconDefaultSize = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
context.getResources().getInteger(R.integer.list_icon_size_default),
context.getResources().getDisplayMetrics()
);
this.iconSize = iconDefaultSize * textSize / Float.parseFloat(context.getString(R.string.list_size_default));
this.listSort = PreferencesUtil.getListSort(context);
this.groupsBeforeSort = PreferencesUtil.getGroupsBeforeSort(context);
this.ascendingSort = PreferencesUtil.getAscendingSort(context);
}
/** /**
* Rebuild the list by clear and build children from the group * Rebuild the list by clear and build children from the group
*/ */
public void rebuildList(PwGroup group) { public void rebuildList(PwGroup group) {
this.nodeSortedList.clear(); this.nodeSortedList.clear();
assignPreferences();
if (group != null) { if (group != null) {
this.nodeSortedList.addAll(group.getDirectChildren()); this.nodeSortedList.addAll(group.getDirectChildren());
} }
@@ -106,43 +136,25 @@ public class NodeAdapter extends RecyclerView.Adapter<BasicViewHolder> {
} }
/** /**
* Register a node to update before an action * Remove a node in the list
* Call updateLastNodeRegister() after the action to update the node
* @param node Node to register
*/
public void registerANodeToUpdate(PwNode node) {
nodePositionToUpdate = nodeSortedList.indexOf(node);
}
/**
* Update the last Node register in the list
* Work if only registerANodeToUpdate(PwNode node) is called before
*/
public void updateLastNodeRegister(PwNode node) {
// Don't really update here, sorted list knows each original ref, so we just notify a change
try {
if (nodePositionToUpdate != -1) {
// Don't know why but there is a bug to remove a node after this update
nodeSortedList.updateItemAt(nodePositionToUpdate, node);
nodeSortedList.recalculatePositionOfItemAt(nodePositionToUpdate);
nodePositionToUpdate = -1;
}
else {
Log.e(NodeAdapter.class.getName(), "registerANodeToUpdate must be called before updateLastNodeRegister");
}
} catch (IndexOutOfBoundsException e) {
Log.e(NodeAdapter.class.getName(), e.getMessage());
}
}
/**
* Remove node in the list
* @param node Node to delete * @param node Node to delete
*/ */
public void removeNode(PwNode node) { public void removeNode(PwNode node) {
nodeSortedList.remove(node); nodeSortedList.remove(node);
} }
/**
* Update a node in the list
* @param oldNode Node before the update
* @param newNode Node after the update
*/
public void updateNode(PwNode oldNode, PwNode newNode) {
nodeSortedList.beginBatchedUpdates();
nodeSortedList.remove(oldNode);
nodeSortedList.add(newNode);
nodeSortedList.endBatchedUpdates();
}
/** /**
* Notify a change sort of the list * Notify a change sort of the list
*/ */
@@ -157,8 +169,9 @@ public class NodeAdapter extends RecyclerView.Adapter<BasicViewHolder> {
return nodeSortedList.get(position).getType().ordinal(); return nodeSortedList.get(position).getType().ordinal();
} }
@NonNull
@Override @Override
public BasicViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { public BasicViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
BasicViewHolder basicViewHolder; BasicViewHolder basicViewHolder;
View view; View view;
if (viewType == PwNode.Type.GROUP.ordinal()) { if (viewType == PwNode.Type.GROUP.ordinal()) {
@@ -172,11 +185,23 @@ public class NodeAdapter extends RecyclerView.Adapter<BasicViewHolder> {
} }
@Override @Override
public void onBindViewHolder(BasicViewHolder holder, int position) { public void onBindViewHolder(@NonNull BasicViewHolder holder, int position) {
PwNode subNode = nodeSortedList.get(position); PwNode subNode = nodeSortedList.get(position);
// Assign image // Assign image
App.getDB().getDrawFactory().assignDrawableTo(holder.icon, if (IconPackChooser.getSelectedIconPack(context).tintable()) {
context.getResources(), subNode.getIcon()); int iconColor = Color.BLACK;
switch (subNode.getType()) {
case GROUP:
iconColor = iconGroupColor;
break;
case ENTRY:
iconColor = iconEntryColor;
break;
}
App.getDB().getDrawFactory().assignDatabaseIconTo(context, holder.icon, subNode.getIcon(), true, iconColor);
} else {
App.getDB().getDrawFactory().assignDatabaseIconTo(context, holder.icon, subNode.getIcon());
}
// Assign text // Assign text
holder.text.setText(subNode.getDisplayTitle()); holder.text.setText(subNode.getDisplayTitle());
// Assign click // Assign click
@@ -187,7 +212,10 @@ public class NodeAdapter extends RecyclerView.Adapter<BasicViewHolder> {
holder.container.setOnCreateContextMenuListener( holder.container.setOnCreateContextMenuListener(
new ContextMenuBuilder(subNode, nodeMenuListener)); new ContextMenuBuilder(subNode, nodeMenuListener));
} }
// Assign text size // Assign image and text size
// Relative size of the icon
holder.icon.getLayoutParams().height = ((int) iconSize);
holder.icon.getLayoutParams().width = ((int) iconSize);
holder.text.setTextSize(textSize); holder.text.setTextSize(textSize);
} }
@@ -199,8 +227,8 @@ public class NodeAdapter extends RecyclerView.Adapter<BasicViewHolder> {
/** /**
* Assign a listener when a node is clicked * Assign a listener when a node is clicked
*/ */
public void setOnNodeClickListener(OnNodeClickCallback onNodeClickCallback) { public void setOnNodeClickListener(NodeClickCallback nodeClickCallback) {
this.onNodeClickCallback = onNodeClickCallback; this.nodeClickCallback = nodeClickCallback;
} }
/** /**
@@ -213,7 +241,7 @@ public class NodeAdapter extends RecyclerView.Adapter<BasicViewHolder> {
/** /**
* Callback listener to redefine to do an action when a node is click * Callback listener to redefine to do an action when a node is click
*/ */
public interface OnNodeClickCallback { public interface NodeClickCallback {
void onNodeClick(PwNode node); void onNodeClick(PwNode node);
} }
@@ -223,6 +251,8 @@ public class NodeAdapter extends RecyclerView.Adapter<BasicViewHolder> {
public interface NodeMenuListener { public interface NodeMenuListener {
boolean onOpenMenuClick(PwNode node); boolean onOpenMenuClick(PwNode node);
boolean onEditMenuClick(PwNode node); boolean onEditMenuClick(PwNode node);
boolean onCopyMenuClick(PwNode node);
boolean onMoveMenuClick(PwNode node);
boolean onDeleteMenuClick(PwNode node); boolean onDeleteMenuClick(PwNode node);
} }
@@ -238,8 +268,8 @@ public class NodeAdapter extends RecyclerView.Adapter<BasicViewHolder> {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
if (onNodeClickCallback != null) if (nodeClickCallback != null)
onNodeClickCallback.onNodeClick(node); nodeClickCallback.onNodeClick(node);
} }
} }
@@ -248,10 +278,6 @@ public class NodeAdapter extends RecyclerView.Adapter<BasicViewHolder> {
*/ */
private class ContextMenuBuilder implements View.OnCreateContextMenuListener { private class ContextMenuBuilder implements View.OnCreateContextMenuListener {
private static final int MENU_OPEN = Menu.FIRST;
private static final int MENU_EDIT = MENU_OPEN + 1;
private static final int MENU_DELETE = MENU_EDIT + 1;
private PwNode node; private PwNode node;
private NodeMenuListener menuListener; private NodeMenuListener menuListener;
@@ -262,14 +288,30 @@ public class NodeAdapter extends RecyclerView.Adapter<BasicViewHolder> {
@Override @Override
public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) { public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
MenuItem clearMenu = contextMenu.add(Menu.NONE, MENU_OPEN, Menu.NONE, R.string.menu_open); menuInflater.inflate(R.menu.node_menu, contextMenu);
clearMenu.setOnMenuItemClickListener(mOnMyActionClickListener);
// TODO COPY For Group
if (node.getType().equals(PwNode.Type.GROUP)) {
contextMenu.removeItem(R.id.menu_copy);
}
MenuItem menuItem = contextMenu.findItem(R.id.menu_open);
menuItem.setOnMenuItemClickListener(mOnMyActionClickListener);
if (!App.getDB().isReadOnly() && !node.equals(App.getDB().getPwDatabase().getRecycleBin())) { if (!App.getDB().isReadOnly() && !node.equals(App.getDB().getPwDatabase().getRecycleBin())) {
// TODO make edit for group // Edition
// clearMenu = contextMenu.add(Menu.NONE, MENU_EDIT, Menu.NONE, R.string.menu_edit); menuItem = contextMenu.findItem(R.id.menu_edit);
// clearMenu.setOnMenuItemClickListener(mOnMyActionClickListener); menuItem.setOnMenuItemClickListener(mOnMyActionClickListener);
clearMenu = contextMenu.add(Menu.NONE, MENU_DELETE, Menu.NONE, R.string.menu_delete); // Copy (not for group)
clearMenu.setOnMenuItemClickListener(mOnMyActionClickListener); if (node.getType().equals(PwNode.Type.ENTRY)) {
menuItem = contextMenu.findItem(R.id.menu_copy);
menuItem.setOnMenuItemClickListener(mOnMyActionClickListener);
}
// Move
menuItem = contextMenu.findItem(R.id.menu_move);
menuItem.setOnMenuItemClickListener(mOnMyActionClickListener);
// Deletion
menuItem = contextMenu.findItem(R.id.menu_delete);
menuItem.setOnMenuItemClickListener(mOnMyActionClickListener);
} }
} }
@@ -279,11 +321,15 @@ public class NodeAdapter extends RecyclerView.Adapter<BasicViewHolder> {
if (menuListener == null) if (menuListener == null)
return false; return false;
switch ( item.getItemId() ) { switch ( item.getItemId() ) {
case MENU_OPEN: case R.id.menu_open:
return menuListener.onOpenMenuClick(node); return menuListener.onOpenMenuClick(node);
case MENU_EDIT: case R.id.menu_edit:
return menuListener.onEditMenuClick(node); return menuListener.onEditMenuClick(node);
case MENU_DELETE: case R.id.menu_copy:
return menuListener.onCopyMenuClick(node);
case R.id.menu_move:
return menuListener.onMoveMenuClick(node);
case R.id.menu_delete:
return menuListener.onDeleteMenuClick(node); return menuListener.onDeleteMenuClick(node);
default: default:
return false; return false;

View File

@@ -41,7 +41,7 @@ public class App extends MultiDexApplication {
} }
return db; return db;
} }
public static RecentFileHistory getFileHistory() { public static RecentFileHistory getFileHistory() {
return fileHistory; return fileHistory;
} }

View File

@@ -28,18 +28,19 @@ import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi; import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import com.kunzisoft.keepass.KeePass;
import com.kunzisoft.keepass.fileselect.FileSelectActivity; import com.kunzisoft.keepass.fileselect.FileSelectActivity;
@RequiresApi(api = Build.VERSION_CODES.O) @RequiresApi(api = Build.VERSION_CODES.O)
public class AutoFillAuthActivity extends KeePass { public class AutoFillAuthActivity extends AppCompatActivity {
private AutofillHelper autofillHelper; private AutofillHelper autofillHelper;
@Override @Override
protected void onCreate(@Nullable Bundle savedInstanceState) { protected void onCreate(@Nullable Bundle savedInstanceState) {
autofillHelper = new AutofillHelper(); autofillHelper = new AutofillHelper();
startFileSelectActivity();
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
} }
@@ -48,13 +49,12 @@ public class AutoFillAuthActivity extends KeePass {
return PendingIntent.getActivity(context, 0, return PendingIntent.getActivity(context, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT).getIntentSender(); intent, PendingIntent.FLAG_CANCEL_CURRENT).getIntentSender();
} }
@Override
protected void startFileSelectActivity() { protected void startFileSelectActivity() {
// Pass extra for Autofill (EXTRA_ASSIST_STRUCTURE) // Pass extra for Autofill (EXTRA_ASSIST_STRUCTURE)
AssistStructure assistStructure = autofillHelper.retrieveAssistStructure(getIntent()); AssistStructure assistStructure = autofillHelper.retrieveAssistStructure(getIntent());
if (assistStructure != null) { if (assistStructure != null) {
FileSelectActivity.launch(this, assistStructure); FileSelectActivity.launchForAutofillResult(this, assistStructure);
} else { } else {
setResult(RESULT_CANCELED); setResult(RESULT_CANCELED);
finish(); finish();

View File

@@ -36,6 +36,7 @@ import android.widget.RemoteViews;
import com.kunzisoft.keepass.R; import com.kunzisoft.keepass.R;
import com.kunzisoft.keepass.database.PwEntry; import com.kunzisoft.keepass.database.PwEntry;
import com.kunzisoft.keepass.selection.EntrySelectionHelper;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@@ -64,6 +65,7 @@ public class AutofillHelper {
public static void addAssistStructureExtraInIntent(Intent intent, AssistStructure assistStructure) { public static void addAssistStructureExtraInIntent(Intent intent, AssistStructure assistStructure) {
if (assistStructure != null) { if (assistStructure != null) {
EntrySelectionHelper.addEntrySelectionModeExtraInIntent(intent);
intent.putExtra(android.view.autofill.AutofillManager.EXTRA_ASSIST_STRUCTURE, assistStructure); intent.putExtra(android.view.autofill.AutofillManager.EXTRA_ASSIST_STRUCTURE, assistStructure);
} }
} }
@@ -144,7 +146,7 @@ public class AutofillHelper {
/** /**
* Utility method to loop and close each activity with return data * Utility method to loop and close each activity with return data
*/ */
public static void onActivityResultSetResult(Activity activity, int requestCode, int resultCode, Intent data) { public static void onActivityResultSetResultAndFinish(Activity activity, int requestCode, int resultCode, Intent data) {
if (requestCode == AUTOFILL_RESPONSE_REQUEST_CODE) { if (requestCode == AUTOFILL_RESPONSE_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) { if (resultCode == Activity.RESULT_OK) {
activity.setResult(resultCode, data); activity.setResult(resultCode, data);
@@ -152,15 +154,6 @@ public class AutofillHelper {
if (resultCode == Activity.RESULT_CANCELED) { if (resultCode == Activity.RESULT_CANCELED) {
activity.setResult(Activity.RESULT_CANCELED); activity.setResult(Activity.RESULT_CANCELED);
} }
}
}
/**
* Utility method to loop and close each activity with return data
*/
public static void onActivityResultSetResultAndFinish(Activity activity, int requestCode, int resultCode, Intent data) {
if (requestCode == AUTOFILL_RESPONSE_REQUEST_CODE) {
onActivityResultSetResult(activity, requestCode, resultCode, data);
activity.finish(); activity.finish();
} }
} }

View File

@@ -1,66 +0,0 @@
/*
* Copyright 2017 Brian Pellin, Jeremy Jamet / Kunzisoft.
*
* This file is part of KeePass DX.
*
* KeePass DX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* KeePass DX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with KeePass DX. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.kunzisoft.keepass.compat;
import android.content.Context;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
@SuppressWarnings({"unchecked", "rawtypes"})
public class BackupManagerCompat {
private static Class classBackupManager;
private static Constructor constructorBackupManager;
private static Method dataChanged;
private Object backupManager;
static {
try {
classBackupManager = Class.forName("android.app.backup.BackupManager");
constructorBackupManager = classBackupManager.getConstructor(Context.class);
dataChanged = classBackupManager.getMethod("dataChanged", (Class[]) null);
} catch (Exception e) {
// Do nothing, class does not exist
}
}
public BackupManagerCompat(Context ctx) {
if (constructorBackupManager != null) {
try {
backupManager = constructorBackupManager.newInstance(ctx);
} catch (Exception e) {
// Do nothing
}
}
}
public void dataChanged() {
if (backupManager != null && dataChanged != null) {
try {
dataChanged.invoke(backupManager, (Object[]) null);
} catch (Exception e) {
// Do nothing
}
}
}
}

View File

@@ -1,53 +0,0 @@
/*
* Copyright 2017 Brian Pellin, Jeremy Jamet / Kunzisoft.
*
* This file is part of KeePass DX.
*
* KeePass DX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* KeePass DX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with KeePass DX. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.kunzisoft.keepass.compat;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import java.lang.reflect.Constructor;
// This compatiblity hack can go away when support for Android 1.5 api level 3 is dropped
public class BitmapDrawableCompat {
private static Constructor<BitmapDrawable> constResBitmap;
static {
try {
constResBitmap = BitmapDrawable.class.getConstructor(Resources.class, Bitmap.class);
// This constructor is support in this api version
} catch (Exception e) {
// This constructor is not supported
}
}
public static BitmapDrawable getBitmapDrawable(Resources res, Bitmap bitmap) {
if (constResBitmap != null) {
try {
return constResBitmap.newInstance(res, bitmap);
} catch (Exception e) {
// Do nothing, fall through to the safe constructor
}
}
return new BitmapDrawable(bitmap);
}
}

View File

@@ -1,70 +0,0 @@
/*
* Copyright 2017 Brian Pellin, Jeremy Jamet / Kunzisoft.
*
* This file is part of KeePass DX.
*
* KeePass DX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* KeePass DX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with KeePass DX. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.kunzisoft.keepass.compat;
import android.os.Build;
import java.lang.reflect.Field;
public class BuildCompat {
private static Field manufacturer;
private static String manuText;
public static final int VERSION_CODE_GINGERBREAD = 9;
public static final int VERSION_CODE_ICE_CREAM_SANDWICH = 14;
public static final int VERSION_CODE_JELLY_BEAN = 16;
public static final int VERSION_CODE_JELLY_BEAN_MR2 = 18;
public static final int VERSION_KITKAT = 19;
public static final int VERSION_CODE_M = 23;
private static Field versionSDK;
private static int versionInt;
static {
// MANUFACTURER is only available in API version 4 and later
try {
manufacturer = Build.class.getField("MANUFACTURER");
manuText = (String) manufacturer.get(null);
} catch (Exception e) {
manuText = "";
}
// SDK is only available in API version 4 and later
try {
versionSDK = Build.VERSION.class.getField("SDK_INT");
versionInt = versionSDK.getInt(null);
} catch (Exception e) {
try {
versionInt = Integer.parseInt(Build.VERSION.SDK);
} catch (Exception nfe) {
versionInt = -1;
}
}
}
public static String getManufacturer() {
return manuText;
}
public static int getSdkVersion() {
return versionInt;
}
}

View File

@@ -25,9 +25,6 @@ import android.net.Uri;
import java.lang.reflect.Method; import java.lang.reflect.Method;
public class ClipDataCompat { public class ClipDataCompat {
private static Class clipData;
private static Class clipDataItem;
private static Class clipDescription;
private static Method getClipDataFromIntent; private static Method getClipDataFromIntent;
private static Method getDescription; private static Method getDescription;
private static Method getItemCount; private static Method getItemCount;
@@ -39,14 +36,14 @@ public class ClipDataCompat {
static { static {
try { try {
clipData = Class.forName("android.content.ClipData"); Class clipData = Class.forName("android.content.ClipData");
getDescription = clipData.getMethod("getDescription", (Class[])null); getDescription = clipData.getMethod("getDescription", (Class[])null);
getItemCount = clipData.getMethod("getItemCount", (Class[])null); getItemCount = clipData.getMethod("getItemCount", (Class[])null);
getItemAt = clipData.getMethod("getItemAt", new Class[]{int.class}); getItemAt = clipData.getMethod("getItemAt", new Class[]{int.class});
clipDescription = Class.forName("android.content.ClipDescription"); Class clipDescription = Class.forName("android.content.ClipDescription");
getLabel = clipDescription.getMethod("getLabel", (Class[])null); getLabel = clipDescription.getMethod("getLabel", (Class[])null);
clipDataItem = Class.forName("android.content.ClipData$Item"); Class clipDataItem = Class.forName("android.content.ClipData$Item");
getUri = clipDataItem.getMethod("getUri", (Class[])null); getUri = clipDataItem.getMethod("getUri", (Class[])null);
getClipDataFromIntent = Intent.class.getMethod("getClipData", (Class[])null); getClipDataFromIntent = Intent.class.getMethod("getClipData", (Class[])null);
@@ -58,7 +55,6 @@ public class ClipDataCompat {
} }
public static Uri getUriFromIntent(Intent i, String key) { public static Uri getUriFromIntent(Intent i, String key) {
boolean clipDataSucceeded = false;
if (initSucceded) { if (initSucceded) {
try { try {
Object clip = getClipDataFromIntent.invoke(i); Object clip = getClipDataFromIntent.invoke(i);

View File

@@ -1,52 +0,0 @@
/*
* Copyright 2017 Brian Pellin, Jeremy Jamet / Kunzisoft.
*
* This file is part of KeePass DX.
*
* KeePass DX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* KeePass DX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with KeePass DX. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.kunzisoft.keepass.compat;
import android.content.ContentResolver;
import android.net.Uri;
import java.lang.reflect.Method;
public class ContentResolverCompat {
public static boolean available;
private static Class contentResolver;
private static Method takePersistableUriPermission;
static {
try {
contentResolver = ContentResolver.class;
takePersistableUriPermission = contentResolver.getMethod("takePersistableUriPermission", new Class[]{Uri.class, int.class});
available = true;
} catch (Exception e) {
available = false;
}
}
public static void takePersistableUriPermission(ContentResolver resolver, Uri uri, int modeFlags) {
if (available) {
try {
takePersistableUriPermission.invoke(resolver, new Object[]{uri, modeFlags});
} catch (Exception e) {
// Fail silently
}
}
}
}

View File

@@ -1,53 +0,0 @@
/*
* Copyright 2017 Brian Pellin, Jeremy Jamet / Kunzisoft.
*
* This file is part of KeePass DX.
*
* KeePass DX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* KeePass DX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with KeePass DX. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.kunzisoft.keepass.compat;
import android.app.Activity;
import android.content.SharedPreferences;
import java.lang.reflect.Method;
public class EditorCompat {
private static Method apply;
static {
try {
apply = Activity.class.getMethod("apply", (Class<SharedPreferences.Editor>[]) null);
} catch (Exception e) {
// Substitute commit for apply when not available (API level < 9)
try {
apply = Activity.class.getMethod("commit", (Class<SharedPreferences.Editor>[]) null);
} catch (Exception f) {
// Should be impossible, but leave apply null in this case
}
}
}
public static void apply(SharedPreferences.Editor edit) {
try {
apply.invoke(edit, (Object[]) null);
} catch (Exception e) {
// Shouldn't be possible, but call commit directly if this happens
edit.commit();
}
}
}

View File

@@ -44,7 +44,6 @@ public final class PRNGFixes {
private static final byte[] BUILD_FINGERPRINT_AND_DEVICE_SERIAL = private static final byte[] BUILD_FINGERPRINT_AND_DEVICE_SERIAL =
getBuildFingerprintAndDeviceSerial(); getBuildFingerprintAndDeviceSerial();
private static int sdkVersion = BuildCompat.getSdkVersion();
/** Hidden constructor to prevent instantiation. */ /** Hidden constructor to prevent instantiation. */
private PRNGFixes() {} private PRNGFixes() {}
@@ -67,11 +66,11 @@ public final class PRNGFixes {
private static boolean supportedOnThisDevice() { private static boolean supportedOnThisDevice() {
// Blacklist on samsung devices // Blacklist on samsung devices
if (StrUtil.indexOfIgnoreCase(BuildCompat.getManufacturer(), "samsung", Locale.ENGLISH) >= 0) { if (StrUtil.indexOfIgnoreCase(Build.MANUFACTURER, "samsung", Locale.ENGLISH) >= 0) {
return false; return false;
} }
if (sdkVersion > BuildCompat.VERSION_CODE_JELLY_BEAN_MR2) { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
return false; return false;
} }
@@ -126,8 +125,8 @@ public final class PRNGFixes {
* @throws SecurityException if the fix is needed but could not be applied. * @throws SecurityException if the fix is needed but could not be applied.
*/ */
private static void applyOpenSSLFix() throws SecurityException { private static void applyOpenSSLFix() throws SecurityException {
if ((sdkVersion < BuildCompat.VERSION_CODE_JELLY_BEAN) if ((Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN)
|| (sdkVersion > BuildCompat.VERSION_CODE_JELLY_BEAN_MR2)) { || (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2)) {
// No need to apply the fix // No need to apply the fix
return; return;
} }
@@ -162,7 +161,7 @@ public final class PRNGFixes {
*/ */
private static void installLinuxPRNGSecureRandom() private static void installLinuxPRNGSecureRandom()
throws SecurityException { throws SecurityException {
if (sdkVersion > BuildCompat.VERSION_CODE_JELLY_BEAN_MR2) { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
// No need to apply the fix // No need to apply the fix
return; return;
} }

View File

@@ -22,6 +22,7 @@ package com.kunzisoft.keepass.compat;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.os.Build;
import android.preference.PreferenceManager; import android.preference.PreferenceManager;
import com.kunzisoft.keepass.R; import com.kunzisoft.keepass.R;
@@ -45,7 +46,7 @@ public class StorageAF {
} }
} }
public static boolean supportsStorageFramework() { return BuildCompat.getSdkVersion() >= BuildCompat.VERSION_KITKAT; } public static boolean supportsStorageFramework() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; }
public static boolean useStorageFramework(Context ctx) { public static boolean useStorageFramework(Context ctx) {
if (!supportsStorageFramework()) { return false; } if (!supportsStorageFramework()) { return false; }

View File

@@ -19,6 +19,9 @@
*/ */
package com.kunzisoft.keepass.crypto.keyDerivation; package com.kunzisoft.keepass.crypto.keyDerivation;
import android.content.res.Resources;
import com.kunzisoft.keepass.R;
import com.kunzisoft.keepass.crypto.CryptoUtil; import com.kunzisoft.keepass.crypto.CryptoUtil;
import com.kunzisoft.keepass.crypto.finalkey.FinalKey; import com.kunzisoft.keepass.crypto.finalkey.FinalKey;
import com.kunzisoft.keepass.crypto.finalkey.FinalKeyFactory; import com.kunzisoft.keepass.crypto.finalkey.FinalKeyFactory;
@@ -30,8 +33,8 @@ import java.util.UUID;
public class AesKdf extends KdfEngine { public class AesKdf extends KdfEngine {
public static final int DEFAULT_ROUNDS = 6000; private static final int DEFAULT_ROUNDS = 6000;
public static final String DEFAULT_NAME = "AES-KDF"; private static final String DEFAULT_NAME = "AES-KDF";
public static final UUID CIPHER_UUID = Types.bytestoUUID( public static final UUID CIPHER_UUID = Types.bytestoUUID(
new byte[]{(byte) 0xC9, (byte) 0xD9, (byte) 0xF3, (byte) 0x9A, (byte) 0x62, (byte) 0x8A, (byte) 0x44, (byte) 0x60, new byte[]{(byte) 0xC9, (byte) 0xD9, (byte) 0xF3, (byte) 0x9A, (byte) 0x62, (byte) 0x8A, (byte) 0x44, (byte) 0x60,
@@ -41,17 +44,22 @@ public class AesKdf extends KdfEngine {
public static final String ParamRounds = "R"; public static final String ParamRounds = "R";
public static final String ParamSeed = "S"; public static final String ParamSeed = "S";
public AesKdf() { AesKdf() {
uuid = CIPHER_UUID; setUUID(CIPHER_UUID);
} }
public String getName() { @Override
return DEFAULT_NAME; public String getName(Resources resources) {
if (resources == null)
return DEFAULT_NAME;
return resources.getString(R.string.kdf_AES);
} }
@Override @Override
public KdfParameters getDefaultParameters() { public KdfParameters getDefaultParameters() {
KdfParameters p = super.getDefaultParameters(); KdfParameters p = new KdfParameters(uuid);
p.setParamUUID();
p.setUInt32(ParamRounds, DEFAULT_ROUNDS); p.setUInt32(ParamRounds, DEFAULT_ROUNDS);
return p; return p;
@@ -93,4 +101,9 @@ public class AesKdf extends KdfEngine {
public void setKeyRounds(KdfParameters p, long keyRounds) { public void setKeyRounds(KdfParameters p, long keyRounds) {
p.setUInt64(ParamRounds, keyRounds); p.setUInt64(ParamRounds, keyRounds);
} }
@Override
public long getDefaultKeyRounds() {
return DEFAULT_ROUNDS;
}
} }

View File

@@ -19,6 +19,9 @@
*/ */
package com.kunzisoft.keepass.crypto.keyDerivation; package com.kunzisoft.keepass.crypto.keyDerivation;
import android.content.res.Resources;
import com.kunzisoft.keepass.R;
import com.kunzisoft.keepass.utils.Types; import com.kunzisoft.keepass.utils.Types;
import java.io.IOException; import java.io.IOException;
@@ -26,21 +29,22 @@ import java.security.SecureRandom;
import java.util.UUID; import java.util.UUID;
public class Argon2Kdf extends KdfEngine { public class Argon2Kdf extends KdfEngine {
public static final UUID CIPHER_UUID = Types.bytestoUUID( public static final UUID CIPHER_UUID = Types.bytestoUUID(
new byte[]{(byte) 0xEF, (byte) 0x63, (byte) 0x6D, (byte) 0xDF, (byte) 0x8C, (byte) 0x29, (byte) 0x44, (byte) 0x4B, new byte[]{(byte) 0xEF, (byte) 0x63, (byte) 0x6D, (byte) 0xDF, (byte) 0x8C, (byte) 0x29, (byte) 0x44, (byte) 0x4B,
(byte) 0x91, (byte) 0xF7, (byte) 0xA9, (byte) 0xA4, (byte)0x03, (byte) 0xE3, (byte) 0x0A, (byte) 0x0C (byte) 0x91, (byte) 0xF7, (byte) 0xA9, (byte) 0xA4, (byte)0x03, (byte) 0xE3, (byte) 0x0A, (byte) 0x0C
}); });
public static final String ParamSalt = "S"; // byte[] private static final String ParamSalt = "S"; // byte[]
public static final String ParamParallelism = "P"; // UInt32 private static final String ParamParallelism = "P"; // UInt32
public static final String ParamMemory = "M"; // UInt64 private static final String ParamMemory = "M"; // UInt64
public static final String ParamIterations = "I"; // UInt64 private static final String ParamIterations = "I"; // UInt64
public static final String ParamVersion = "V"; // UInt32 private static final String ParamVersion = "V"; // UInt32
public static final String ParamSecretKey = "K"; // byte[] private static final String ParamSecretKey = "K"; // byte[]
public static final String ParamAssocData = "A"; // byte[] private static final String ParamAssocData = "A"; // byte[]
public static final long MinVersion = 0x10; private static final long MinVersion = 0x10;
public static final long MaxVersion = 0x13; private static final long MaxVersion = 0x13;
private static final int MinSalt = 8; private static final int MinSalt = 8;
private static final int MaxSalt = Integer.MAX_VALUE; private static final int MaxSalt = Integer.MAX_VALUE;
@@ -58,22 +62,28 @@ public class Argon2Kdf extends KdfEngine {
private static final long DefaultMemory = 1024 * 1024; private static final long DefaultMemory = 1024 * 1024;
private static final long DefaultParallelism = 2; private static final long DefaultParallelism = 2;
public Argon2Kdf() { private static final String DEFAULT_NAME = "Argon2";
uuid = CIPHER_UUID;
Argon2Kdf() {
setUUID(CIPHER_UUID);
} }
@Override @Override
public String getName() { public String getName(Resources resources) {
return "Argon2"; if (resources == null)
return DEFAULT_NAME;
return resources.getString(R.string.kdf_Argon2);
} }
@Override @Override
public KdfParameters getDefaultParameters() { public KdfParameters getDefaultParameters() {
KdfParameters p = super.getDefaultParameters(); KdfParameters p = new KdfParameters(uuid);
p.setUInt32(ParamVersion, MaxVersion); p.setParamUUID();
p.setUInt64(ParamMemory, DefaultMemory);
p.setUInt32(ParamParallelism, DefaultParallelism); p.setUInt32(ParamParallelism, DefaultParallelism);
p.setUInt64(ParamMemory, DefaultMemory);
p.setUInt64(ParamIterations, DefaultIterations);
p.setUInt32(ParamVersion, MaxVersion);
return p; return p;
} }
@@ -113,4 +123,35 @@ public class Argon2Kdf extends KdfEngine {
p.setUInt64(ParamIterations, keyRounds); p.setUInt64(ParamIterations, keyRounds);
} }
@Override
public long getDefaultKeyRounds() {
return DefaultIterations;
}
@Override
public long getMemoryUsage(KdfParameters p) {
return p.getUInt64(ParamMemory);
}
public void setMemoryUsage(KdfParameters p, long memory) {
p.setUInt64(ParamMemory, memory);
}
public long getDefaultMemoryUsage() {
return DefaultMemory;
}
@Override
public int getParallelism(KdfParameters p) {
return (int) p.getUInt32(ParamParallelism); // TODO Verify
}
public void setParallelism(KdfParameters p, int parallelism) {
p.setUInt32(ParamParallelism, parallelism);
}
public int getDefaultParallelism() {
return (int) DefaultParallelism; // TODO Verify
}
} }

View File

@@ -19,24 +19,59 @@
*/ */
package com.kunzisoft.keepass.crypto.keyDerivation; package com.kunzisoft.keepass.crypto.keyDerivation;
import com.kunzisoft.keepass.database.ObjectNameResource;
import java.io.IOException; import java.io.IOException;
import java.util.UUID; import java.util.UUID;
public abstract class KdfEngine { public abstract class KdfEngine implements ObjectNameResource{
public UUID uuid;
public KdfParameters getDefaultParameters() { public static final int UNKNOW_VALUE = -1;
return new KdfParameters(uuid); public static final String UNKNOW_VALUE_STRING = String.valueOf(-1);
protected UUID uuid;
public UUID getUUID() {
return uuid;
} }
public void setUUID(UUID uuid) {
this.uuid = uuid;
}
public abstract KdfParameters getDefaultParameters();
public abstract byte[] transform(byte[] masterKey, KdfParameters p) throws IOException; public abstract byte[] transform(byte[] masterKey, KdfParameters p) throws IOException;
public abstract void randomize(KdfParameters p); public abstract void randomize(KdfParameters p);
public abstract String getName();
public abstract long getKeyRounds(KdfParameters p); public abstract long getKeyRounds(KdfParameters p);
public abstract void setKeyRounds(KdfParameters p, long keyRounds); public abstract void setKeyRounds(KdfParameters p, long keyRounds);
public abstract long getDefaultKeyRounds();
public long getMemoryUsage(KdfParameters p) {
return UNKNOW_VALUE;
}
public void setMemoryUsage(KdfParameters p, long memory) {
// Do nothing by default
}
public long getDefaultMemoryUsage() {
return UNKNOW_VALUE;
}
public int getParallelism(KdfParameters p) {
return UNKNOW_VALUE;
}
public void setParallelism(KdfParameters p, int parallelism) {
// Do nothing by default
}
public int getDefaultParallelism() {
return UNKNOW_VALUE;
}
} }

View File

@@ -19,31 +19,37 @@
*/ */
package com.kunzisoft.keepass.crypto.keyDerivation; package com.kunzisoft.keepass.crypto.keyDerivation;
import com.kunzisoft.keepass.database.exception.UnknownKDF;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID;
public class KdfFactory { public class KdfFactory {
public static List<KdfEngine> kdfList = new ArrayList<>(); public static AesKdf aesKdf = new AesKdf();
public static Argon2Kdf argon2Kdf = new Argon2Kdf();
public static List<KdfEngine> kdfListV3 = new ArrayList<>();
public static List<KdfEngine> kdfListV4 = new ArrayList<>();
static { static {
kdfList.add(new AesKdf()); kdfListV3.add(aesKdf);
kdfList.add(new Argon2Kdf());
kdfListV4.add(aesKdf);
kdfListV4.add(argon2Kdf);
} }
public static KdfParameters getDefaultParameters() { public static KdfEngine getEngineV4(KdfParameters kdfParameters) throws UnknownKDF {
return kdfList.get(0).getDefaultParameters(); UnknownKDF unknownKDFException = new UnknownKDF();
} if (kdfParameters == null) {
throw unknownKDFException;
public static KdfEngine get(UUID uuid) { }
for (KdfEngine engine: kdfList) { for (KdfEngine engine: kdfListV4) {
if (engine.uuid.equals(uuid)) { if (engine.getUUID().equals(kdfParameters.getUUID())) {
return engine; return engine;
} }
} }
throw unknownKDFException;
return null;
} }
} }

View File

@@ -31,34 +31,36 @@ import java.util.UUID;
public class KdfParameters extends VariantDictionary { public class KdfParameters extends VariantDictionary {
public UUID kdfUUID; private UUID kdfUUID;
private static final String ParamUUID = "$UUID"; private static final String ParamUUID = "$UUID";
public KdfParameters(UUID uuid) { KdfParameters(UUID uuid) {
kdfUUID = uuid; kdfUUID = uuid;
} }
public UUID getUUID() {
return kdfUUID;
}
protected void setParamUUID() {
setByteArray(ParamUUID, Types.UUIDtoBytes(kdfUUID));
}
public static KdfParameters deserialize(byte[] data) throws IOException { public static KdfParameters deserialize(byte[] data) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(data); ByteArrayInputStream bis = new ByteArrayInputStream(data);
LEDataInputStream lis = new LEDataInputStream(bis); LEDataInputStream lis = new LEDataInputStream(bis);
VariantDictionary d = VariantDictionary.deserialize(lis); VariantDictionary d = VariantDictionary.deserialize(lis);
if (d == null) { if (d == null) {
assert(false);
return null; return null;
} }
UUID uuid = Types.bytestoUUID(d.getByteArray(ParamUUID)); UUID uuid = Types.bytestoUUID(d.getByteArray(ParamUUID));
if (uuid == null) {
assert(false);
return null;
}
KdfParameters kdfP = new KdfParameters(uuid); KdfParameters kdfP = new KdfParameters(uuid);
kdfP.copyTo(d); kdfP.copyTo(d);
return kdfP; return kdfP;
} }
public static byte[] serialize(KdfParameters kdf) throws IOException { public static byte[] serialize(KdfParameters kdf) throws IOException {

View File

@@ -20,23 +20,21 @@
package com.kunzisoft.keepass.database; package com.kunzisoft.keepass.database;
import android.content.Context; import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources; import android.content.res.Resources;
import android.net.Uri; import android.net.Uri;
import android.preference.PreferenceManager;
import android.util.Log; import android.util.Log;
import com.kunzisoft.keepass.R; import com.kunzisoft.keepass.crypto.keyDerivation.KdfEngine;
import com.kunzisoft.keepass.crypto.keyDerivation.KdfFactory;
import com.kunzisoft.keepass.database.exception.ContentFileNotFoundException; import com.kunzisoft.keepass.database.exception.ContentFileNotFoundException;
import com.kunzisoft.keepass.database.exception.InvalidDBException; import com.kunzisoft.keepass.database.exception.InvalidDBException;
import com.kunzisoft.keepass.database.exception.InvalidPasswordException;
import com.kunzisoft.keepass.database.exception.PwDbOutputException; import com.kunzisoft.keepass.database.exception.PwDbOutputException;
import com.kunzisoft.keepass.database.load.Importer; import com.kunzisoft.keepass.database.load.Importer;
import com.kunzisoft.keepass.database.load.ImporterFactory; import com.kunzisoft.keepass.database.load.ImporterFactory;
import com.kunzisoft.keepass.database.save.PwDbOutput; import com.kunzisoft.keepass.database.save.PwDbOutput;
import com.kunzisoft.keepass.icons.DrawableFactory; import com.kunzisoft.keepass.icons.IconDrawableFactory;
import com.kunzisoft.keepass.search.SearchDbHelper; import com.kunzisoft.keepass.search.SearchDbHelper;
import com.kunzisoft.keepass.tasks.UpdateStatus; import com.kunzisoft.keepass.tasks.ProgressTaskUpdater;
import com.kunzisoft.keepass.utils.UriUtil; import com.kunzisoft.keepass.utils.UriUtil;
import java.io.BufferedInputStream; import java.io.BufferedInputStream;
@@ -47,6 +45,11 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.SyncFailedException; import java.io.SyncFailedException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.annotation.Nullable;
public class Database { public class Database {
@@ -59,7 +62,7 @@ public class Database {
private boolean readOnly = false; private boolean readOnly = false;
private boolean passwordEncodingError = false; private boolean passwordEncodingError = false;
private DrawableFactory drawFactory = new DrawableFactory(); private IconDrawableFactory drawFactory = new IconDrawableFactory();
private boolean loaded = false; private boolean loaded = false;
@@ -87,7 +90,7 @@ public class Database {
return passwordEncodingError; return passwordEncodingError;
} }
public DrawableFactory getDrawFactory() { public IconDrawableFactory getDrawFactory() {
return drawFactory; return drawFactory;
} }
@@ -99,19 +102,11 @@ public class Database {
loaded = true; loaded = true;
} }
public void loadData(Context ctx, InputStream is, String password, InputStream keyInputStream) throws IOException, InvalidDBException { public void loadData(Context ctx, Uri uri, String password, Uri keyfile, ProgressTaskUpdater status) throws IOException, FileNotFoundException, InvalidDBException {
loadData(ctx, is, password, keyInputStream, new UpdateStatus(), !Importer.DEBUG);
}
public void loadData(Context ctx, Uri uri, String password, Uri keyfile) throws IOException, FileNotFoundException, InvalidDBException {
loadData(ctx, uri, password, keyfile, new UpdateStatus(), !Importer.DEBUG);
}
public void loadData(Context ctx, Uri uri, String password, Uri keyfile, UpdateStatus status) throws IOException, FileNotFoundException, InvalidDBException {
loadData(ctx, uri, password, keyfile, status, !Importer.DEBUG); loadData(ctx, uri, password, keyfile, status, !Importer.DEBUG);
} }
public void loadData(Context ctx, Uri uri, String password, Uri keyfile, UpdateStatus status, boolean debug) throws IOException, FileNotFoundException, InvalidDBException { private void loadData(Context ctx, Uri uri, String password, Uri keyfile, ProgressTaskUpdater status, boolean debug) throws IOException, FileNotFoundException, InvalidDBException {
mUri = uri; mUri = uri;
readOnly = false; readOnly = false;
if (uri.getScheme().equals("file")) { if (uri.getScheme().equals("file")) {
@@ -119,26 +114,10 @@ public class Database {
readOnly = !file.canWrite(); readOnly = !file.canWrite();
} }
try { passUrisAsInputStreams(ctx, uri, password, keyfile, status, debug);
passUrisAsInputStreams(ctx, uri, password, keyfile, status, debug, 0);
} catch (InvalidPasswordException e) {
// Retry with rounds fix
try {
passUrisAsInputStreams(ctx, uri, password, keyfile, status, debug, getFixRounds(ctx));
} catch (Exception e2) {
// Rethrow original exception
throw e;
}
}
} }
private long getFixRounds(Context ctx) { private void passUrisAsInputStreams(Context ctx, Uri uri, String password, Uri keyfile, ProgressTaskUpdater status, boolean debug) throws IOException, FileNotFoundException, InvalidDBException {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
return prefs.getLong(ctx.getString(R.string.roundsFix_key), ctx.getResources().getInteger(R.integer.roundsFix_default));
}
private void passUrisAsInputStreams(Context ctx, Uri uri, String password, Uri keyfile, UpdateStatus status, boolean debug, long roundsFix) throws IOException, FileNotFoundException, InvalidDBException {
InputStream is, kfIs; InputStream is, kfIs;
try { try {
is = UriUtil.getUriInputStream(ctx, uri); is = UriUtil.getUriInputStream(ctx, uri);
@@ -153,18 +132,14 @@ public class Database {
Log.e("KPD", "Database::loadData", e); Log.e("KPD", "Database::loadData", e);
throw ContentFileNotFoundException.getInstance(keyfile); throw ContentFileNotFoundException.getInstance(keyfile);
} }
loadData(ctx, is, password, kfIs, status, debug, roundsFix); loadData(ctx, is, password, kfIs, status, debug);
} }
public void loadData(Context ctx, InputStream is, String password, InputStream kfIs, boolean debug) throws IOException, InvalidDBException { public void loadData(Context ctx, InputStream is, String password, InputStream keyFileInputStream, boolean debug) throws IOException, InvalidDBException {
loadData(ctx, is, password, kfIs, new UpdateStatus(), debug); loadData(ctx, is, password, keyFileInputStream, null, debug);
} }
public void loadData(Context ctx, InputStream is, String password, InputStream kfIs, UpdateStatus status, boolean debug) throws IOException, InvalidDBException { private void loadData(Context ctx, InputStream is, String password, InputStream keyFileInputStream, ProgressTaskUpdater progressTaskUpdater, boolean debug) throws IOException, InvalidDBException {
loadData(ctx, is, password, kfIs, status, debug, 0);
}
public void loadData(Context ctx, InputStream is, String password, InputStream kfIs, UpdateStatus status, boolean debug, long roundsFix) throws IOException, InvalidDBException {
BufferedInputStream bis = new BufferedInputStream(is); BufferedInputStream bis = new BufferedInputStream(is);
if ( ! bis.markSupported() ) { if ( ! bis.markSupported() ) {
@@ -174,11 +149,11 @@ public class Database {
// We'll end up reading 8 bytes to identify the header. Might as well use two extra. // We'll end up reading 8 bytes to identify the header. Might as well use two extra.
bis.mark(10); bis.mark(10);
Importer imp = ImporterFactory.createImporter(bis, debug); Importer databaseImporter = ImporterFactory.createImporter(bis, debug);
bis.reset(); // Return to the start bis.reset(); // Return to the start
pm = imp.openDatabase(bis, password, kfIs, status, roundsFix); pm = databaseImporter.openDatabase(bis, password, keyFileInputStream, progressTaskUpdater);
if ( pm != null ) { if ( pm != null ) {
try { try {
switch (pm.getVersion()) { switch (pm.getVersion()) {
@@ -222,19 +197,26 @@ public class Database {
saveData(ctx, mUri); saveData(ctx, mUri);
} }
public void saveData(Context ctx, Uri uri) throws IOException, PwDbOutputException { private void saveData(Context ctx, Uri uri) throws IOException, PwDbOutputException {
String errorMessage = "Failed to store database.";
if (uri.getScheme().equals("file")) { if (uri.getScheme().equals("file")) {
String filename = uri.getPath(); String filename = uri.getPath();
File tempFile = new File(filename + ".tmp"); File tempFile = new File(filename + ".tmp");
FileOutputStream fos = new FileOutputStream(tempFile);
//BufferedOutputStream bos = new BufferedOutputStream(fos);
//PwDbV3Output pmo = new PwDbV3Output(pm, bos, App.getCalendar()); FileOutputStream fos = null;
PwDbOutput pmo = PwDbOutput.getInstance(pm, fos); try {
pmo.output(); fos = new FileOutputStream(tempFile);
//bos.flush(); PwDbOutput pmo = PwDbOutput.getInstance(pm, fos);
//bos.close(); if (pmo != null)
fos.close(); pmo.output();
} catch (Exception e) {
Log.e(TAG, errorMessage, e);
throw new IOException(errorMessage, e);
} finally {
if (fos != null)
fos.close();
}
// Force data to disk before continuing // Force data to disk before continuing
try { try {
@@ -246,26 +228,30 @@ public class Database {
File orig = new File(filename); File orig = new File(filename);
if (!tempFile.renameTo(orig)) { if (!tempFile.renameTo(orig)) {
throw new IOException("Failed to store database."); throw new IOException(errorMessage);
} }
} }
else { else {
OutputStream os; OutputStream os = null;
try { try {
os = ctx.getContentResolver().openOutputStream(uri); os = ctx.getContentResolver().openOutputStream(uri);
PwDbOutput pmo = PwDbOutput.getInstance(pm, os);
if (pmo != null)
pmo.output();
} catch (Exception e) { } catch (Exception e) {
throw new IOException("Failed to store database."); Log.e(TAG, errorMessage, e);
throw new IOException(errorMessage, e);
} finally {
if (os != null)
os.close();
} }
PwDbOutput pmo = PwDbOutput.getInstance(pm, os);
pmo.output();
os.close();
} }
mUri = uri; mUri = uri;
} }
// TODO Clear database when lock broadcast is receive in backstage
public void clear() { public void clear() {
drawFactory.clear(); drawFactory.clearCache();
pm = null; pm = null;
mUri = null; mUri = null;
@@ -348,16 +334,88 @@ public class Database {
} }
} }
public PwEncryptionAlgorithm getEncryptionAlgorithm() {
return getPwDatabase().getEncryptionAlgorithm();
}
public List<PwEncryptionAlgorithm> getAvailableEncryptionAlgorithms() {
switch (getPwDatabase().getVersion()) {
case V4:
return ((PwDatabaseV4) getPwDatabase()).getAvailableEncryptionAlgorithms();
case V3:
return ((PwDatabaseV3) getPwDatabase()).getAvailableEncryptionAlgorithms();
}
return new ArrayList<>();
}
public boolean allowEncryptionAlgorithmModification() {
return getAvailableEncryptionAlgorithms().size() > 1;
}
public void assignEncryptionAlgorithm(PwEncryptionAlgorithm algorithm) {
switch (getPwDatabase().getVersion()) {
case V4:
((PwDatabaseV4) getPwDatabase()).setEncryptionAlgorithm(algorithm);
((PwDatabaseV4) getPwDatabase()).setDataEngine(algorithm.getCipherEngine());
((PwDatabaseV4) getPwDatabase()).setDataCipher(algorithm.getDataCipher());
}
}
public String getEncryptionAlgorithmName(Resources resources) { public String getEncryptionAlgorithmName(Resources resources) {
return getPwDatabase().getEncryptionAlgorithm().getName(resources); return getPwDatabase().getEncryptionAlgorithm().getName(resources);
} }
public String getKeyDerivationName() { public List<KdfEngine> getAvailableKdfEngines() {
return getPwDatabase().getKeyDerivationName(); switch (getPwDatabase().getVersion()) {
case V4:
return KdfFactory.kdfListV4;
case V3:
return KdfFactory.kdfListV3;
}
return new ArrayList<>();
}
public boolean allowKdfModification() {
return getAvailableKdfEngines().size() > 1;
}
public KdfEngine getKdfEngine() {
switch (getPwDatabase().getVersion()) {
case V4:
KdfEngine kdfEngine = ((PwDatabaseV4) getPwDatabase()).getKdfEngine();
if (kdfEngine == null)
return KdfFactory.aesKdf;
return kdfEngine;
default:
case V3:
return KdfFactory.aesKdf;
}
}
public void assignKdfEngine(KdfEngine kdfEngine) {
switch (getPwDatabase().getVersion()) {
case V4:
PwDatabaseV4 db = ((PwDatabaseV4) getPwDatabase());
if (db.getKdfParameters() == null
|| !db.getKdfParameters().getUUID().equals(kdfEngine.getDefaultParameters().getUUID()))
db.setKdfParameters(kdfEngine.getDefaultParameters());
setNumberKeyEncryptionRounds(kdfEngine.getDefaultKeyRounds());
setMemoryUsage(kdfEngine.getDefaultMemoryUsage());
setParallelism(kdfEngine.getDefaultParallelism());
break;
}
}
public String getKeyDerivationName(Resources resources) {
KdfEngine kdfEngine = getKdfEngine();
if (kdfEngine != null) {
return kdfEngine.getName(resources);
}
return "";
} }
public String getNumberKeyEncryptionRoundsAsString() { public String getNumberKeyEncryptionRoundsAsString() {
return Long.toString(getPwDatabase().getNumberKeyEncryptionRounds()); return Long.toString(getNumberKeyEncryptionRounds());
} }
public long getNumberKeyEncryptionRounds() { public long getNumberKeyEncryptionRounds() {
@@ -368,6 +426,75 @@ public class Database {
getPwDatabase().setNumberKeyEncryptionRounds(numberRounds); getPwDatabase().setNumberKeyEncryptionRounds(numberRounds);
} }
public String getMemoryUsageAsString() {
return Long.toString(getMemoryUsage());
}
public long getMemoryUsage() {
switch (getPwDatabase().getVersion()) {
case V4:
return ((PwDatabaseV4) getPwDatabase()).getMemoryUsage();
}
return KdfEngine.UNKNOW_VALUE;
}
public void setMemoryUsage(long memory) {
switch (getPwDatabase().getVersion()) {
case V4:
((PwDatabaseV4) getPwDatabase()).setMemoryUsage(memory);
}
}
public String getParallelismAsString() {
return Integer.toString(getParallelism());
}
public int getParallelism() {
switch (getPwDatabase().getVersion()) {
case V4:
return ((PwDatabaseV4) getPwDatabase()).getParallelism();
}
return KdfEngine.UNKNOW_VALUE;
}
public void setParallelism(int parallelism) {
switch (getPwDatabase().getVersion()) {
case V4:
((PwDatabaseV4) getPwDatabase()).setParallelism(parallelism);
}
}
public PwEntry createEntry(PwGroup parent) {
PwEntry newPwEntry = null;
try {
switch (getPwDatabase().getVersion()) {
case V3:
newPwEntry = new PwEntryV3((PwGroupV3) parent);
case V4:
newPwEntry = new PwEntryV4((PwGroupV4) parent);
}
} catch (Exception e) {
Log.e(TAG, "This version of PwEntry can't be created", e);
}
return newPwEntry;
}
public PwGroup createGroup(PwGroup parent) {
PwGroup newPwGroup = null;
try {
switch (getPwDatabase().getVersion()) {
case V3:
newPwGroup = new PwGroupV3((PwGroupV3) parent);
case V4:
newPwGroup = new PwGroupV4((PwGroupV4) parent);
}
newPwGroup.setId(pm.newGroupId());
} catch (Exception e) {
Log.e(TAG, "This version of PwGroup can't be created", e);
}
return newPwGroup;
}
public void addEntryTo(PwEntry entry, PwGroup parent) { public void addEntryTo(PwEntry entry, PwGroup parent) {
try { try {
switch (getPwDatabase().getVersion()) { switch (getPwDatabase().getVersion()) {
@@ -501,6 +628,59 @@ public class Database {
} }
} }
public void updateGroup(PwGroup oldGroup, PwGroup newGroup) {
try {
switch (getPwDatabase().getVersion()) {
case V3:
((PwGroupV3) oldGroup).updateWith((PwGroupV3) newGroup);
break;
case V4:
((PwGroupV4) oldGroup).updateWith((PwGroupV4) newGroup);
break;
}
} catch (Exception e) {
Log.e(TAG, "This version of PwEntry can't be updated", e);
}
}
/**
* @return A duplicate entry with the same values, a new UUID,
* @param entryToCopy
* @param newParent
*/
public @Nullable PwEntry copyEntry(PwEntry entryToCopy, PwGroup newParent) {
try {
// TODO encapsulate
switch (getPwDatabase().getVersion()) {
case V3:
PwEntryV3 entryV3Copied = ((PwEntryV3) entryToCopy).clone();
entryV3Copied.setUUID(UUID.randomUUID());
entryV3Copied.setParent((PwGroupV3) newParent);
addEntryTo(entryV3Copied, newParent);
return entryV3Copied;
case V4:
PwEntryV4 entryV4Copied = ((PwEntryV4) entryToCopy).clone();
entryV4Copied.setUUID(UUID.randomUUID());
entryV4Copied.setParent((PwGroupV4) newParent);
addEntryTo(entryV4Copied, newParent);
return entryV4Copied;
}
} catch (Exception e) {
Log.e(TAG, "This version of PwEntry can't be updated", e);
}
return null;
}
public void moveEntry(PwEntry entryToMove, PwGroup newParent) {
removeEntryFrom(entryToMove, entryToMove.parent);
addEntryTo(entryToMove, newParent);
}
public void moveGroup(PwGroup groupToMove, PwGroup newParent) {
removeGroupFrom(groupToMove, groupToMove.parent);
addGroupTo(groupToMove, newParent);
}
public void deleteEntry(PwEntry entry) { public void deleteEntry(PwEntry entry) {
try { try {
switch (getPwDatabase().getVersion()) { switch (getPwDatabase().getVersion()) {

View File

@@ -57,7 +57,7 @@ public class EntrySearchV4 {
boolean negate = false; boolean negate = false;
if (sp.searchString.startsWith("-")) { if (sp.searchString.startsWith("-")) {
sp.searchString.substring(1); // TODO Verify bug or no need ? sp.searchString = sp.searchString.substring(1);
negate = sp.searchString.length() > 0; negate = sp.searchString.length() > 0;
} }

View File

@@ -44,6 +44,22 @@ public class ExtraFields implements Serializable, Cloneable {
return !getCustomProtectedFields().keySet().isEmpty(); return !getCustomProtectedFields().keySet().isEmpty();
} }
public boolean containsCustomFieldsProtected() {
for (Map.Entry<String, ProtectedString> field : getCustomProtectedFields().entrySet()) {
if (field.getValue().isProtected())
return true;
}
return false;
}
public boolean containsCustomFieldsNotProtected() {
for (Map.Entry<String, ProtectedString> field : getCustomProtectedFields().entrySet()) {
if (!field.getValue().isProtected())
return true;
}
return false;
}
public String getProtectedStringValue(String key) { public String getProtectedStringValue(String key) {
ProtectedString value = fields.get(key); ProtectedString value = fields.get(key);
if ( value == null ) return ""; if ( value == null ) return "";

View File

@@ -17,16 +17,13 @@
* along with KeePass DX. If not, see <http://www.gnu.org/licenses/>. * along with KeePass DX. If not, see <http://www.gnu.org/licenses/>.
* *
*/ */
package com.kunzisoft.keepass.database.edit; package com.kunzisoft.keepass.database;
import android.os.Handler; import android.content.res.Resources;
import com.kunzisoft.keepass.database.PwNode; /**
* Interface to generify items with a name resource, that can be (for example) visible in a list
public abstract class AfterAddNodeOnFinish extends OnFinish { */
public AfterAddNodeOnFinish(Handler handler) { public interface ObjectNameResource {
super(handler); String getName(Resources resources);
}
public abstract void run(PwNode pwNode);
} }

View File

@@ -19,11 +19,8 @@
*/ */
package com.kunzisoft.keepass.database; package com.kunzisoft.keepass.database;
import com.kunzisoft.keepass.crypto.finalkey.FinalKey;
import com.kunzisoft.keepass.crypto.finalkey.FinalKeyFactory;
import com.kunzisoft.keepass.database.exception.InvalidKeyFileException; import com.kunzisoft.keepass.database.exception.InvalidKeyFileException;
import com.kunzisoft.keepass.database.exception.KeyFileEmptyException; import com.kunzisoft.keepass.database.exception.KeyFileEmptyException;
import com.kunzisoft.keepass.stream.NullOutputStream;
import com.kunzisoft.keepass.utils.Util; import com.kunzisoft.keepass.utils.Util;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
@@ -31,7 +28,6 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.security.DigestOutputStream;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.HashMap; import java.util.HashMap;
@@ -100,42 +96,10 @@ public abstract class PwDatabase<PwGroupDB extends PwGroup<PwGroupDB, PwGroupDB,
return finalKey; return finalKey;
} }
public void makeFinalKey(byte[] masterSeed, byte[] masterSeed2, long numRounds) throws IOException {
// Write checksum Checksum
MessageDigest md;
try {
md = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new IOException("SHA-256 not implemented here.");
}
NullOutputStream nos = new NullOutputStream();
DigestOutputStream dos = new DigestOutputStream(nos, md);
byte[] transformedMasterKey = transformMasterKey(masterSeed2, masterKey, numRounds);
dos.write(masterSeed);
dos.write(transformedMasterKey);
finalKey = md.digest();
}
/**
* Encrypt the master key a few times to make brute-force key-search harder
* @throws IOException
*/
protected static byte[] transformMasterKey( byte[] pKeySeed, byte[] pKey, long rounds ) throws IOException {
FinalKey key = FinalKeyFactory.createFinalKey();
return key.transformMasterKey(pKeySeed, pKey, rounds);
}
public abstract byte[] getMasterKey(String key, InputStream keyInputStream) throws InvalidKeyFileException, IOException; public abstract byte[] getMasterKey(String key, InputStream keyInputStream) throws InvalidKeyFileException, IOException;
public void setMasterKey(String key, InputStream keyInputStream) public void retrieveMasterKey(String key, InputStream keyInputStream)
throws InvalidKeyFileException, IOException { throws InvalidKeyFileException, IOException {
assert(key != null);
masterKey = getMasterKey(key, keyInputStream); masterKey = getMasterKey(key, keyInputStream);
} }
@@ -220,6 +184,9 @@ public abstract class PwDatabase<PwGroupDB extends PwGroup<PwGroupDB, PwGroupDB,
} }
public boolean validatePasswordEncoding(String key) { public boolean validatePasswordEncoding(String key) {
if (key == null)
return false;
String encoding = getPasswordEncoding(); String encoding = getPasswordEncoding();
byte[] bKey; byte[] bKey;
@@ -243,10 +210,8 @@ public abstract class PwDatabase<PwGroupDB extends PwGroup<PwGroupDB, PwGroupDB,
protected abstract String getPasswordEncoding(); protected abstract String getPasswordEncoding();
public byte[] getPasswordKey(String key) throws IOException { public byte[] getPasswordKey(String key) throws IOException {
assert(key!=null); if ( key == null)
throw new IllegalArgumentException( "Key cannot be empty." ); // TODO
if ( key.length() == 0 )
throw new IllegalArgumentException( "Key cannot be empty." );
MessageDigest md; MessageDigest md;
try { try {
@@ -281,7 +246,7 @@ public abstract class PwDatabase<PwGroupDB extends PwGroup<PwGroupDB, PwGroupDB,
this.algorithm = algorithm; this.algorithm = algorithm;
} }
public abstract String getKeyDerivationName(); public abstract List<PwEncryptionAlgorithm> getAvailableEncryptionAlgorithms();
public abstract List<PwGroupDB> getGrpRoots(); public abstract List<PwGroupDB> getGrpRoots();

View File

@@ -45,12 +45,16 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
package com.kunzisoft.keepass.database; package com.kunzisoft.keepass.database;
// Java import com.kunzisoft.keepass.crypto.finalkey.FinalKey;
import com.kunzisoft.keepass.crypto.keyDerivation.AesKdf; import com.kunzisoft.keepass.crypto.finalkey.FinalKeyFactory;
import com.kunzisoft.keepass.database.exception.InvalidKeyFileException; import com.kunzisoft.keepass.database.exception.InvalidKeyFileException;
import com.kunzisoft.keepass.stream.NullOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.security.DigestOutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Random; import java.util.Random;
@@ -71,13 +75,6 @@ public class PwDatabaseV3 extends PwDatabase<PwGroupV3, PwEntryV3> {
private int numKeyEncRounds; private int numKeyEncRounds;
private void initAndAddGroup(String name, int iconId, PwGroupV3 parent) {
PwGroupV3 group = createGroup();
group.initNewGroup(name, newGroupId());
group.setIcon(iconFactory.getIcon(iconId));
addGroupTo(group, parent);
}
@Override @Override
public void initNew(String dbPath) { public void initNew(String dbPath) {
algorithm = PwEncryptionAlgorithm.AES_Rijndael; algorithm = PwEncryptionAlgorithm.AES_Rijndael;
@@ -90,15 +87,25 @@ public class PwDatabaseV3 extends PwDatabase<PwGroupV3, PwEntryV3> {
initAndAddGroup("eMail", 19, rootGroup); initAndAddGroup("eMail", 19, rootGroup);
} }
private void initAndAddGroup(String name, int iconId, PwGroupV3 parent) {
PwGroupV3 group = createGroup();
group.setId(newGroupId());
group.setName(name);
group.setIcon(iconFactory.getIcon(iconId));
addGroupTo(group, parent);
}
@Override @Override
public PwVersion getVersion() { public PwVersion getVersion() {
return PwVersion.V3; return PwVersion.V3;
} }
@Override @Override
public String getKeyDerivationName() { public List<PwEncryptionAlgorithm> getAvailableEncryptionAlgorithms() {
return AesKdf.DEFAULT_NAME; List<PwEncryptionAlgorithm> list = new ArrayList<>();
} list.add(PwEncryptionAlgorithm.AES_Rijndael);
return list;
}
@Override @Override
public List<PwGroupV3> getGroups() { public List<PwGroupV3> getGroups() {
@@ -235,20 +242,50 @@ public class PwDatabaseV3 extends PwDatabase<PwGroupV3, PwEntryV3> {
return newId; return newId;
} }
@Override
public byte[] getMasterKey(String key, InputStream keyInputStream) public byte[] getMasterKey(String key, InputStream keyInputStream)
throws InvalidKeyFileException, IOException { throws InvalidKeyFileException, IOException {
if (key != null && key.length() > 0 && keyInputStream != null) { if (key != null && keyInputStream != null) {
return getCompositeKey(key, keyInputStream); return getCompositeKey(key, keyInputStream);
} else if (key != null && key.length() > 0) { } else if (key != null) { // key.length() >= 0
return getPasswordKey(key); return getPasswordKey(key);
} else if (keyInputStream != null) { } else if (keyInputStream != null) { // key == null
return getFileKey(keyInputStream); return getFileKey(keyInputStream);
} else { } else {
throw new IllegalArgumentException("Key cannot be empty."); throw new IllegalArgumentException("Key cannot be empty.");
} }
} }
/**
* Encrypt the master key a few times to make brute-force key-search harder
* @throws IOException
*/
private static byte[] transformMasterKey( byte[] pKeySeed, byte[] pKey, long rounds ) throws IOException {
FinalKey key = FinalKeyFactory.createFinalKey();
return key.transformMasterKey(pKeySeed, pKey, rounds);
}
public void makeFinalKey(byte[] masterSeed, byte[] masterSeed2, long numRounds) throws IOException {
// Write checksum Checksum
MessageDigest md;
try {
md = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new IOException("SHA-256 not implemented here.");
}
NullOutputStream nos = new NullOutputStream();
DigestOutputStream dos = new DigestOutputStream(nos, md);
byte[] transformedMasterKey = transformMasterKey(masterSeed2, masterKey, numRounds);
dos.write(masterSeed);
dos.write(transformedMasterKey);
finalKey = md.digest();
}
@Override @Override
protected String getPasswordEncoding() { protected String getPasswordEncoding() {
return "ISO-8859-1"; return "ISO-8859-1";
@@ -287,7 +324,6 @@ public class PwDatabaseV3 extends PwDatabase<PwGroupV3, PwEntryV3> {
// Add tree to root groups // Add tree to root groups
groups.add(newGroup); groups.add(newGroup);
} }
@Override @Override

View File

@@ -19,17 +19,18 @@
*/ */
package com.kunzisoft.keepass.database; package com.kunzisoft.keepass.database;
import android.util.Log;
import android.webkit.URLUtil; import android.webkit.URLUtil;
import com.kunzisoft.keepass.collections.VariantDictionary; import com.kunzisoft.keepass.collections.VariantDictionary;
import com.kunzisoft.keepass.crypto.CryptoUtil; import com.kunzisoft.keepass.crypto.CryptoUtil;
import com.kunzisoft.keepass.crypto.engine.AesEngine; import com.kunzisoft.keepass.crypto.engine.AesEngine;
import com.kunzisoft.keepass.crypto.engine.CipherEngine; import com.kunzisoft.keepass.crypto.engine.CipherEngine;
import com.kunzisoft.keepass.crypto.keyDerivation.AesKdf;
import com.kunzisoft.keepass.crypto.keyDerivation.KdfEngine; import com.kunzisoft.keepass.crypto.keyDerivation.KdfEngine;
import com.kunzisoft.keepass.crypto.keyDerivation.KdfFactory; import com.kunzisoft.keepass.crypto.keyDerivation.KdfFactory;
import com.kunzisoft.keepass.crypto.keyDerivation.KdfParameters; import com.kunzisoft.keepass.crypto.keyDerivation.KdfParameters;
import com.kunzisoft.keepass.database.exception.InvalidKeyFileException; import com.kunzisoft.keepass.database.exception.InvalidKeyFileException;
import com.kunzisoft.keepass.database.exception.UnknownKDF;
import com.kunzisoft.keepass.utils.EmptyUtils; import com.kunzisoft.keepass.utils.EmptyUtils;
import org.w3c.dom.Document; import org.w3c.dom.Document;
@@ -50,6 +51,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import javax.annotation.Nullable;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
@@ -57,6 +59,7 @@ import biz.source_code.base64Coder.Base64Coder;
public class PwDatabaseV4 extends PwDatabase<PwGroupV4, PwEntryV4> { public class PwDatabaseV4 extends PwDatabase<PwGroupV4, PwEntryV4> {
private static final String TAG = PwDatabaseV4.class.getName();
private static final int DEFAULT_HISTORY_MAX_ITEMS = 10; // -1 unlimited private static final int DEFAULT_HISTORY_MAX_ITEMS = 10; // -1 unlimited
private static final long DEFAULT_HISTORY_MAX_SIZE = 6 * 1024 * 1024; // -1 unlimited private static final long DEFAULT_HISTORY_MAX_SIZE = 6 * 1024 * 1024; // -1 unlimited
@@ -66,9 +69,10 @@ public class PwDatabaseV4 extends PwDatabase<PwGroupV4, PwEntryV4> {
private UUID dataCipher = AesEngine.CIPHER_UUID; private UUID dataCipher = AesEngine.CIPHER_UUID;
private CipherEngine dataEngine = new AesEngine(); private CipherEngine dataEngine = new AesEngine();
private PwCompressionAlgorithm compressionAlgorithm = PwCompressionAlgorithm.Gzip; private PwCompressionAlgorithm compressionAlgorithm = PwCompressionAlgorithm.Gzip;
private KdfEngine kdfEngine; private KdfParameters kdfParameters;
private long numKeyEncRounds;
private VariantDictionary publicCustomData = new VariantDictionary();
private long numKeyEncRounds = AesKdf.DEFAULT_ROUNDS; // By default take the AES rounds
protected String name = "KeePass DX database"; protected String name = "KeePass DX database";
private PwDate nameChanged = new PwDate(); private PwDate nameChanged = new PwDate();
private PwDate settingsChanged = new PwDate(); private PwDate settingsChanged = new PwDate();
@@ -98,9 +102,7 @@ public class PwDatabaseV4 extends PwDatabase<PwGroupV4, PwEntryV4> {
private List<PwIconCustom> customIcons = new ArrayList<>(); private List<PwIconCustom> customIcons = new ArrayList<>();
private Map<String, String> customData = new HashMap<>(); private Map<String, String> customData = new HashMap<>();
private KdfParameters kdfParameters = KdfFactory.getDefaultParameters(); private BinaryPool binPool = new BinaryPool();
private VariantDictionary publicCustomData = new VariantDictionary();
private BinaryPool binPool = new BinaryPool();
public String localizedAppName = "KeePassDX"; // TODO resource public String localizedAppName = "KeePassDX"; // TODO resource
@@ -131,9 +133,17 @@ public class PwDatabaseV4 extends PwDatabase<PwGroupV4, PwEntryV4> {
public void setDataEngine(CipherEngine dataEngine) { public void setDataEngine(CipherEngine dataEngine) {
this.dataEngine = dataEngine; this.dataEngine = dataEngine;
this.algorithm = dataEngine.getPwEncryptionAlgorithm();
} }
@Override
public List<PwEncryptionAlgorithm> getAvailableEncryptionAlgorithms() {
List<PwEncryptionAlgorithm> list = new ArrayList<>();
list.add(PwEncryptionAlgorithm.AES_Rijndael);
list.add(PwEncryptionAlgorithm.Twofish);
list.add(PwEncryptionAlgorithm.ChaCha20);
return list;
}
public PwCompressionAlgorithm getCompressionAlgorithm() { public PwCompressionAlgorithm getCompressionAlgorithm() {
return compressionAlgorithm; return compressionAlgorithm;
} }
@@ -142,6 +152,23 @@ public class PwDatabaseV4 extends PwDatabase<PwGroupV4, PwEntryV4> {
this.compressionAlgorithm = compressionAlgorithm; this.compressionAlgorithm = compressionAlgorithm;
} }
public @Nullable KdfEngine getKdfEngine() {
try {
return KdfFactory.getEngineV4(kdfParameters);
} catch (UnknownKDF unknownKDF) {
Log.i(TAG, "Unable to retrieve KDF engine", unknownKDF);
return null;
}
}
public KdfParameters getKdfParameters() {
return kdfParameters;
}
public void setKdfParameters(KdfParameters kdfParameters) {
this.kdfParameters = kdfParameters;
}
@Override @Override
public long getNumberKeyEncryptionRounds() { public long getNumberKeyEncryptionRounds() {
if (getKdfEngine() != null && getKdfParameters() != null) if (getKdfEngine() != null && getKdfParameters() != null)
@@ -156,7 +183,31 @@ public class PwDatabaseV4 extends PwDatabase<PwGroupV4, PwEntryV4> {
numKeyEncRounds = rounds; numKeyEncRounds = rounds;
} }
public PwDate getNameChanged() { public long getMemoryUsage() {
if (getKdfEngine() != null && getKdfParameters() != null) {
return getKdfEngine().getMemoryUsage(getKdfParameters());
}
return KdfEngine.UNKNOW_VALUE;
}
public void setMemoryUsage(long memory) {
if (getKdfEngine() != null && getKdfParameters() != null)
getKdfEngine().setMemoryUsage(getKdfParameters(), memory);
}
public int getParallelism() {
if (getKdfEngine() != null && getKdfParameters() != null) {
return getKdfEngine().getParallelism(getKdfParameters());
}
return KdfEngine.UNKNOW_VALUE;
}
public void setParallelism(int parallelism) {
if (getKdfEngine() != null && getKdfParameters() != null)
getKdfEngine().setParallelism(getKdfParameters(), parallelism);
}
public PwDate getNameChanged() {
return nameChanged; return nameChanged;
} }
@@ -326,27 +377,17 @@ public class PwDatabaseV4 extends PwDatabase<PwGroupV4, PwEntryV4> {
this.customData.put(label, value); this.customData.put(label, value);
} }
public KdfEngine getKdfEngine() {
return kdfEngine;
}
@Override
public String getKeyDerivationName() {
return kdfEngine.getName();
}
@Override @Override
public byte[] getMasterKey(String key, InputStream keyInputStream) public byte[] getMasterKey(String key, InputStream keyInputStream)
throws InvalidKeyFileException, IOException { throws InvalidKeyFileException, IOException {
assert(key != null);
byte[] fKey = new byte[]{}; byte[] fKey = new byte[]{};
if ( key.length() > 0 && keyInputStream != null) { if (key != null && keyInputStream != null) {
return getCompositeKey(key, keyInputStream); return getCompositeKey(key, keyInputStream);
} else if ( key.length() > 0 ) { } else if (key != null) { // key.length() >= 0
fKey = getPasswordKey(key); fKey = getPasswordKey(key);
} else if ( keyInputStream != null) { } else if (keyInputStream != null) { // key == null
fKey = getFileKey(keyInputStream); fKey = getFileKey(keyInputStream);
} }
@@ -360,47 +401,11 @@ public class PwDatabaseV4 extends PwDatabase<PwGroupV4, PwEntryV4> {
return md.digest(fKey); return md.digest(fKey);
} }
@Override public void makeFinalKey(byte[] masterSeed) throws IOException {
public void makeFinalKey(byte[] masterSeed, byte[] masterSeed2, long numRounds) throws IOException {
byte[] transformedMasterKey = transformMasterKey(masterSeed2, masterKey, numRounds); KdfEngine kdfEngine = KdfFactory.getEngineV4(kdfParameters);
byte[] transformedMasterKey = kdfEngine.transform(masterKey, kdfParameters);
byte[] cmpKey = new byte[65];
System.arraycopy(masterSeed, 0, cmpKey, 0, 32);
System.arraycopy(transformedMasterKey, 0, cmpKey, 32, 32);
finalKey = CryptoUtil.resizeKey(cmpKey, 0, 64, dataEngine.keyLength());
MessageDigest md;
try {
md = MessageDigest.getInstance("SHA-512");
cmpKey[64] = 1;
hmacKey = md.digest(cmpKey);
} catch (NoSuchAlgorithmException e) {
throw new IOException("No SHA-512 implementation");
} finally {
Arrays.fill(cmpKey, (byte)0);
}
}
public void makeFinalKey(byte[] masterSeed, KdfParameters kdfP) throws IOException {
makeFinalKey(masterSeed, kdfP, 0);
}
public void makeFinalKey(byte[] masterSeed, KdfParameters kdfP, long roundsFix)
throws IOException {
kdfEngine = KdfFactory.get(kdfP.kdfUUID);
if (kdfEngine == null) {
throw new IOException("Unknown key derivation function");
}
// Set to 6000 rounds to open corrupted database
if (roundsFix > 0 && kdfP.kdfUUID.equals(AesKdf.CIPHER_UUID)) {
kdfP.setUInt32(AesKdf.ParamRounds, roundsFix);
numKeyEncRounds = roundsFix;
}
byte[] transformedMasterKey = kdfEngine.transform(masterKey, kdfP);
if (transformedMasterKey.length != 32) { if (transformedMasterKey.length != 32) {
transformedMasterKey = CryptoUtil.hashSha256(transformedMasterKey); transformedMasterKey = CryptoUtil.hashSha256(transformedMasterKey);
} }
@@ -550,15 +555,15 @@ public class PwDatabaseV4 extends PwDatabase<PwGroupV4, PwEntryV4> {
super.populateGlobals(currentGroup); super.populateGlobals(currentGroup);
} }
/** Ensure that the recycle bin tree exists, if enabled and create it /**
* if it doesn't exist * Ensure that the recycle bin tree exists, if enabled and create it
* * if it doesn't exist
*/ */
private void ensureRecycleBin() { private void ensureRecycleBin() {
if (getRecycleBin() == null) { if (getRecycleBin() == null) {
// Create recycle bin // Create recycle bin
PwGroupV4 recycleBin = new PwGroupV4(RECYCLEBIN_NAME, iconFactory.getIcon(PwIconStandard.TRASH_BIN)); PwGroupV4 recycleBin = new PwGroupV4(RECYCLEBIN_NAME, iconFactory.getTrashIcon());
recycleBin.setEnableAutoType(false); recycleBin.setEnableAutoType(false);
recycleBin.setEnableSearching(false); recycleBin.setEnableSearching(false);
recycleBin.setExpanded(false); recycleBin.setExpanded(false);
@@ -682,8 +687,7 @@ public class PwDatabaseV4 extends PwDatabase<PwGroupV4, PwEntryV4> {
@Override @Override
public void undoDeleteEntry(PwEntryV4 entry, PwGroupV4 origParent) { public void undoDeleteEntry(PwEntryV4 entry, PwGroupV4 origParent) {
super.undoDeleteEntry(entry, origParent); super.undoDeleteEntry(entry, origParent);
// TODO undo delete entry deletedObjects.remove(new PwDeletedObject(entry.getUUID()));
deletedObjects.remove(entry);
} }
@Override @Override
@@ -696,14 +700,6 @@ public class PwDatabaseV4 extends PwDatabase<PwGroupV4, PwEntryV4> {
return groups.get(recycleId); return groups.get(recycleId);
} }
public KdfParameters getKdfParameters() {
return kdfParameters;
}
public void setKdfParameters(KdfParameters kdfParameters) {
this.kdfParameters = kdfParameters;
}
public VariantDictionary getPublicCustomData() { public VariantDictionary getPublicCustomData() {
return publicCustomData; return publicCustomData;
} }
@@ -740,9 +736,7 @@ public class PwDatabaseV4 extends PwDatabase<PwGroupV4, PwEntryV4> {
@Override @Override
public void initNew(String dbPath) { public void initNew(String dbPath) {
String filename = URLUtil.guessFileName(dbPath, null, null); rootGroup = new PwGroupV4(dbNameFromPath(dbPath), iconFactory.getFolderIcon());
rootGroup = new PwGroupV4(dbNameFromPath(dbPath), iconFactory.getIcon(PwIconStandard.FOLDER));
groups.put(rootGroup.getId(), rootGroup); groups.put(rootGroup.getId(), rootGroup);
} }
@@ -760,64 +754,4 @@ public class PwDatabaseV4 extends PwDatabase<PwGroupV4, PwEntryV4> {
return filename.substring(0, lastExtDot); return filename.substring(0, lastExtDot);
} }
private class GroupHasCustomData extends GroupHandler<PwGroupV4> {
public boolean hasCustomData = false;
@Override
public boolean operate(PwGroupV4 group) {
if (group == null) {
return true;
}
if (group.containsCustomData()) {
hasCustomData = true;
return false;
}
return true;
}
}
private class EntryHasCustomData extends EntryHandler<PwEntryV4> {
public boolean hasCustomData = false;
@Override
public boolean operate(PwEntryV4 entry) {
if (entry == null) {
return true;
}
if (entry.containsCustomData()) {
hasCustomData = true;
return false;
}
return true;
}
}
public int getMinKdbxVersion() {
if (!AesKdf.CIPHER_UUID.equals(kdfParameters.kdfUUID)) {
return PwDbHeaderV4.FILE_VERSION_32;
}
if (publicCustomData.size() > 0) {
return PwDbHeaderV4.FILE_VERSION_32;
}
EntryHasCustomData entryHandler = new EntryHasCustomData();
GroupHasCustomData groupHandler = new GroupHasCustomData();
if (rootGroup == null ) {
return PwDbHeaderV4.FILE_VERSION_32_3;
}
rootGroup.preOrderTraverseTree(groupHandler, entryHandler);
if (groupHandler.hasCustomData || entryHandler.hasCustomData) {
return PwDbHeaderV4.FILE_VERSION_32;
}
return PwDbHeaderV4.FILE_VERSION_32_3;
}
} }

View File

@@ -20,6 +20,7 @@
package com.kunzisoft.keepass.database; package com.kunzisoft.keepass.database;
import com.kunzisoft.keepass.crypto.keyDerivation.AesKdf; import com.kunzisoft.keepass.crypto.keyDerivation.AesKdf;
import com.kunzisoft.keepass.crypto.keyDerivation.KdfFactory;
import com.kunzisoft.keepass.crypto.keyDerivation.KdfParameters; import com.kunzisoft.keepass.crypto.keyDerivation.KdfParameters;
import com.kunzisoft.keepass.database.exception.InvalidDBVersionException; import com.kunzisoft.keepass.database.exception.InvalidDBVersionException;
import com.kunzisoft.keepass.stream.CopyInputStream; import com.kunzisoft.keepass.stream.CopyInputStream;
@@ -41,11 +42,10 @@ import javax.crypto.spec.SecretKeySpec;
public class PwDbHeaderV4 extends PwDbHeader { public class PwDbHeaderV4 extends PwDbHeader {
public static final int DBSIG_PRE2 = 0xB54BFB66; public static final int DBSIG_PRE2 = 0xB54BFB66;
public static final int DBSIG_2 = 0xB54BFB67; public static final int DBSIG_2 = 0xB54BFB67;
private static final int FILE_VERSION_CRITICAL_MASK = 0xFFFF0000; private static final int FILE_VERSION_CRITICAL_MASK = 0xFFFF0000;
public static final int FILE_VERSION_32_3 = 0x00030001; public static final int FILE_VERSION_32_3 = 0x00030001;
public static final int FILE_VERSION_32_4 = 0x00040000; public static final int FILE_VERSION_32_4 = 0x00040000;
public static final int FILE_VERSION_32 = FILE_VERSION_32_4;
public class PwDbHeaderV4Fields { public class PwDbHeaderV4Fields {
public static final byte EndOfHeader = 0; public static final byte EndOfHeader = 0;
@@ -91,12 +91,83 @@ public class PwDbHeaderV4 extends PwDbHeader {
public CrsAlgorithm innerRandomStream; public CrsAlgorithm innerRandomStream;
public long version; public long version;
public PwDbHeaderV4(PwDatabaseV4 d) { public PwDbHeaderV4(PwDatabaseV4 databaseV4) {
db = d; this.db = databaseV4;
version = d.getMinKdbxVersion(); this.version = getMinKdbxVersion(databaseV4); // Only for writing
masterSeed = new byte[32]; this.masterSeed = new byte[32];
} }
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
private class GroupHasCustomData extends GroupHandler<PwGroupV4> {
boolean hasCustomData = false;
@Override
public boolean operate(PwGroupV4 group) {
if (group == null) {
return true;
}
if (group.containsCustomData()) {
hasCustomData = true;
return false;
}
return true;
}
}
private class EntryHasCustomData extends EntryHandler<PwEntryV4> {
boolean hasCustomData = false;
@Override
public boolean operate(PwEntryV4 entry) {
if (entry == null) {
return true;
}
if (entry.containsCustomData()) {
hasCustomData = true;
return false;
}
return true;
}
}
private int getMinKdbxVersion(PwDatabaseV4 databaseV4) {
// Return v4 if AES is not use
if (databaseV4.getKdfParameters() != null
&& !databaseV4.getKdfParameters().getUUID().equals(AesKdf.CIPHER_UUID)) {
return PwDbHeaderV4.FILE_VERSION_32_4;
}
// Return V4 if custom data are present
if (databaseV4.containsPublicCustomData()) {
return PwDbHeaderV4.FILE_VERSION_32_4;
}
EntryHasCustomData entryHandler = new EntryHasCustomData();
GroupHasCustomData groupHandler = new GroupHasCustomData();
if (databaseV4.getRootGroup() == null ) {
return PwDbHeaderV4.FILE_VERSION_32_3;
}
databaseV4.getRootGroup().preOrderTraverseTree(groupHandler, entryHandler);
if (groupHandler.hasCustomData || entryHandler.hasCustomData) {
return PwDbHeaderV4.FILE_VERSION_32_4;
}
return PwDbHeaderV4.FILE_VERSION_32_3;
}
/** Assumes the input stream is at the beginning of the .kdbx file /** Assumes the input stream is at the beginning of the .kdbx file
* @param is * @param is
* @throws IOException * @throws IOException
@@ -122,7 +193,7 @@ public class PwDbHeaderV4 extends PwDbHeader {
throw new InvalidDBVersionException(); throw new InvalidDBVersionException();
} }
version = lis.readUInt(); version = lis.readUInt(); // Erase previous value
if ( ! validVersion(version) ) { if ( ! validVersion(version) ) {
throw new InvalidDBVersionException(); throw new InvalidDBVersionException();
} }
@@ -138,7 +209,7 @@ public class PwDbHeaderV4 extends PwDbHeader {
private boolean readHeaderField(LEDataInputStream dis) throws IOException { private boolean readHeaderField(LEDataInputStream dis) throws IOException {
byte fieldID = (byte) dis.read(); byte fieldID = (byte) dis.read();
int fieldSize; int fieldSize;
if (version < FILE_VERSION_32_4) { if (version < FILE_VERSION_32_4) {
fieldSize = dis.readUShort(); fieldSize = dis.readUShort();
@@ -149,13 +220,13 @@ public class PwDbHeaderV4 extends PwDbHeader {
byte[] fieldData = null; byte[] fieldData = null;
if ( fieldSize > 0 ) { if ( fieldSize > 0 ) {
fieldData = new byte[fieldSize]; fieldData = new byte[fieldSize];
int readSize = dis.read(fieldData); int readSize = dis.read(fieldData);
if ( readSize != fieldSize ) { if ( readSize != fieldSize ) {
throw new IOException("Header ended early."); throw new IOException("Header ended early.");
} }
} }
switch ( fieldID ) { switch ( fieldID ) {
case PwDbHeaderV4Fields.EndOfHeader: case PwDbHeaderV4Fields.EndOfHeader:
return true; return true;
@@ -173,24 +244,13 @@ public class PwDbHeaderV4 extends PwDbHeader {
break; break;
case PwDbHeaderV4Fields.TransformSeed: case PwDbHeaderV4Fields.TransformSeed:
assert(version < PwDbHeaderV4.FILE_VERSION_32_4); // TODO file > FILEVERSION if(version < PwDbHeaderV4.FILE_VERSION_32_4)
AesKdf kdfS = new AesKdf(); setTransformSeed(fieldData);
if (!db.getKdfParameters().kdfUUID.equals(kdfS.uuid)) {
db.setKdfParameters(kdfS.getDefaultParameters());
}
db.getKdfParameters().setByteArray(AesKdf.ParamSeed, fieldData);
break; break;
case PwDbHeaderV4Fields.TransformRounds: case PwDbHeaderV4Fields.TransformRounds:
assert(version < PwDbHeaderV4.FILE_VERSION_32_4); if(version < PwDbHeaderV4.FILE_VERSION_32_4)
AesKdf kdfR = new AesKdf(); setTransformRound(fieldData);
if (!db.getKdfParameters().kdfUUID.equals(kdfR.uuid)) {
db.setKdfParameters(kdfR.getDefaultParameters());
}
long rounds = LEDataInputStream.readLong(fieldData, 0);
db.getKdfParameters().setUInt64(AesKdf.ParamRounds, rounds);
db.setNumberKeyEncryptionRounds(rounds);
break; break;
case PwDbHeaderV4Fields.EncryptionIV: case PwDbHeaderV4Fields.EncryptionIV:
@@ -198,8 +258,8 @@ public class PwDbHeaderV4 extends PwDbHeader {
break; break;
case PwDbHeaderV4Fields.InnerRandomstreamKey: case PwDbHeaderV4Fields.InnerRandomstreamKey:
assert(version < PwDbHeaderV4.FILE_VERSION_32_4); if(version < PwDbHeaderV4.FILE_VERSION_32_4)
innerRandomStreamKey = fieldData; innerRandomStreamKey = fieldData;
break; break;
case PwDbHeaderV4Fields.StreamStartBytes: case PwDbHeaderV4Fields.StreamStartBytes:
@@ -207,8 +267,8 @@ public class PwDbHeaderV4 extends PwDbHeader {
break; break;
case PwDbHeaderV4Fields.InnerRandomStreamID: case PwDbHeaderV4Fields.InnerRandomStreamID:
assert(version < PwDbHeaderV4.FILE_VERSION_32_4); if(version < PwDbHeaderV4.FILE_VERSION_32_4)
setRandomStreamID(fieldData); setRandomStreamID(fieldData);
break; break;
case PwDbHeaderV4Fields.KdfParameters: case PwDbHeaderV4Fields.KdfParameters:
@@ -224,6 +284,12 @@ public class PwDbHeaderV4 extends PwDbHeader {
return false; return false;
} }
private void assignAesKdfEngineIfNotExists() {
if (db.getKdfParameters() == null || !db.getKdfParameters().getUUID().equals(KdfFactory.aesKdf.getUUID())) {
db.setKdfParameters(KdfFactory.aesKdf.getDefaultParameters());
}
}
private void setCipher(byte[] pbId) throws IOException { private void setCipher(byte[] pbId) throws IOException {
if ( pbId == null || pbId.length != 16 ) { if ( pbId == null || pbId.length != 16 ) {
@@ -232,6 +298,18 @@ public class PwDbHeaderV4 extends PwDbHeader {
db.setDataCipher(Types.bytestoUUID(pbId)); db.setDataCipher(Types.bytestoUUID(pbId));
} }
private void setTransformSeed(byte[] seed) {
assignAesKdfEngineIfNotExists();
db.getKdfParameters().setByteArray(AesKdf.ParamSeed, seed);
}
private void setTransformRound(byte[] roundsByte) {
assignAesKdfEngineIfNotExists();
long rounds = LEDataInputStream.readLong(roundsByte, 0);
db.getKdfParameters().setUInt64(AesKdf.ParamRounds, rounds);
db.setNumberKeyEncryptionRounds(rounds);
}
private void setCompressionFlags(byte[] pbFlags) throws IOException { private void setCompressionFlags(byte[] pbFlags) throws IOException {
if ( pbFlags == null || pbFlags.length != 4 ) { if ( pbFlags == null || pbFlags.length != 4 ) {
@@ -244,23 +322,6 @@ public class PwDbHeaderV4 extends PwDbHeader {
} }
db.setCompressionAlgorithm(PwCompressionAlgorithm.fromId(flag)); db.setCompressionAlgorithm(PwCompressionAlgorithm.fromId(flag));
}
private void setTransformRounds(byte[] rounds) throws IOException {
if ( rounds == null || rounds.length != 8 ) {
throw new IOException("Invalid rounds.");
}
long rnd = LEDataInputStream.readLong(rounds, 0);
if ( rnd < 0 || rnd > Integer.MAX_VALUE ) {
//TODO: Actually support really large numbers
throw new IOException("Rounds higher than " + Integer.MAX_VALUE + " are not currently supported.");
}
db.setNumberKeyEncryptionRounds(rnd);
} }
public void setRandomStreamID(byte[] streamID) throws IOException { public void setRandomStreamID(byte[] streamID) throws IOException {
@@ -276,25 +337,22 @@ public class PwDbHeaderV4 extends PwDbHeader {
innerRandomStream = CrsAlgorithm.fromId(id); innerRandomStream = CrsAlgorithm.fromId(id);
} }
/** Determines if this is a supported version. /**
* Determines if this is a supported version.
* *
* A long is needed here to represent the unsigned int since we perform * A long is needed here to represent the unsigned int since we perform arithmetic on it.
* arithmetic on it. * @param version Database version
* @param version * @return true if it's a supported version
* @return
*/ */
private boolean validVersion(long version) { private boolean validVersion(long version) {
return ! ((version & FILE_VERSION_CRITICAL_MASK) > (FILE_VERSION_32_4 & FILE_VERSION_CRITICAL_MASK));
return ! ((version & FILE_VERSION_CRITICAL_MASK) > (FILE_VERSION_32 & FILE_VERSION_CRITICAL_MASK));
} }
public static boolean matchesHeader(int sig1, int sig2) { public static boolean matchesHeader(int sig1, int sig2) {
return (sig1 == PWM_DBSIG_1) && ( (sig2 == DBSIG_2) || (sig2 == DBSIG_2) ); return (sig1 == PWM_DBSIG_1) && ( (sig2 == DBSIG_PRE2) || (sig2 == DBSIG_2) );
} }
public static byte[] computeHeaderHmac(byte[] header, byte[] key) throws IOException{ public static byte[] computeHeaderHmac(byte[] header, byte[] key) throws IOException{
byte[] headerHmac;
byte[] blockKey = HmacBlockStream.GetHmacKey64(key, Types.ULONG_MAX_VALUE); byte[] blockKey = HmacBlockStream.GetHmacKey64(key, Types.ULONG_MAX_VALUE);
Mac hmac; Mac hmac;
@@ -312,8 +370,7 @@ public class PwDbHeaderV4 extends PwDbHeader {
} }
public byte[] getTransformSeed() { public byte[] getTransformSeed() {
assert(version < FILE_VERSION_32_4); // version < FILE_VERSION_32_4)
return db.getKdfParameters().getByteArray(AesKdf.ParamSeed);
return db.getKdfParameters().getByteArray(AesKdf.ParamSeed);
} }
} }

View File

@@ -22,8 +22,14 @@ package com.kunzisoft.keepass.database;
import android.content.res.Resources; import android.content.res.Resources;
import com.kunzisoft.keepass.R; import com.kunzisoft.keepass.R;
import com.kunzisoft.keepass.crypto.engine.AesEngine;
import com.kunzisoft.keepass.crypto.engine.ChaCha20Engine;
import com.kunzisoft.keepass.crypto.engine.CipherEngine;
import com.kunzisoft.keepass.crypto.engine.TwofishEngine;
public enum PwEncryptionAlgorithm { import java.util.UUID;
public enum PwEncryptionAlgorithm implements ObjectNameResource {
AES_Rijndael, AES_Rijndael,
Twofish, Twofish,
@@ -33,11 +39,35 @@ public enum PwEncryptionAlgorithm {
switch (this) { switch (this) {
default: default:
case AES_Rijndael: case AES_Rijndael:
return resources.getString(R.string.rijndael); return resources.getString(R.string.encryption_rijndael);
case Twofish: case Twofish:
return resources.getString(R.string.twofish); return resources.getString(R.string.encryption_twofish);
case ChaCha20: case ChaCha20:
return resources.getString(R.string.chacha20); return resources.getString(R.string.encryption_chacha20);
}
}
public CipherEngine getCipherEngine() {
switch (this) {
default:
case AES_Rijndael:
return new AesEngine();
case Twofish:
return new TwofishEngine();
case ChaCha20:
return new ChaCha20Engine();
}
}
public UUID getDataCipher() {
switch (this) {
default:
case AES_Rijndael:
return AesEngine.CIPHER_UUID;
case Twofish:
return TwofishEngine.CIPHER_UUID;
case ChaCha20:
return ChaCha20Engine.CIPHER_UUID;
} }
} }
} }

View File

@@ -24,7 +24,7 @@ import com.kunzisoft.keepass.database.security.ProtectedString;
import java.util.UUID; import java.util.UUID;
public abstract class PwEntry<Parent extends PwGroup> extends PwNode<Parent> implements Cloneable { public abstract class PwEntry<Parent extends PwGroup> extends PwNode<Parent> {
private static final String PMS_TAN_ENTRY = "<TAN>"; private static final String PMS_TAN_ENTRY = "<TAN>";
@@ -36,35 +36,12 @@ public abstract class PwEntry<Parent extends PwGroup> extends PwNode<Parent> imp
uuid = UUID.randomUUID(); uuid = UUID.randomUUID();
} }
public static PwEntry getInstance(PwGroup parent) {
if (parent instanceof PwGroupV3) {
return new PwEntryV3((PwGroupV3)parent);
}
else if (parent instanceof PwGroupV4) {
return new PwEntryV4((PwGroupV4)parent);
}
else {
throw new RuntimeException("Unknown PwGroup instance.");
}
}
@Override @Override
public PwEntry clone() { public PwEntry clone() {
PwEntry newEntry; // uuid is clone automatically (IMMUTABLE)
try { return (PwEntry) super.clone();
newEntry = (PwEntry) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException("Clone should be supported");
}
return newEntry;
} }
@Override
protected void addCloneAttributesToNewEntry(PwEntry newEntry) {
super.addCloneAttributesToNewEntry(newEntry);
// uuid is clone automatically (IMMUTABLE)
}
@Override @Override
public Type getType() { public Type getType() {
return Type.ENTRY; return Type.ENTRY;
@@ -140,6 +117,22 @@ public abstract class PwEntry<Parent extends PwGroup> extends PwNode<Parent> imp
return getFields().containsCustomFields(); return getFields().containsCustomFields();
} }
/**
* If entry contains extra fields that are protected
* @return true if there is extra fields protected
*/
public boolean containsCustomFieldsProtected() {
return getFields().containsCustomFieldsProtected();
}
/**
* If entry contains extra fields that are not protected
* @return true if there is extra fields not protected
*/
public boolean containsCustomFieldsNotProtected() {
return getFields().containsCustomFieldsNotProtected();
}
/** /**
* Add an extra field to the list (standard or custom) * Add an extra field to the list (standard or custom)
* @param label Label of field, must be unique * @param label Label of field, must be unique

View File

@@ -98,6 +98,7 @@ public class PwEntryV3 extends PwEntry<PwGroupV3> {
} }
protected void updateWith(PwEntryV3 source) { protected void updateWith(PwEntryV3 source) {
super.assign(source);
groupId = source.groupId; groupId = source.groupId;
title = source.title; title = source.title;
@@ -118,10 +119,8 @@ public class PwEntryV3 extends PwEntry<PwGroupV3> {
@Override @Override
public PwEntryV3 clone() { public PwEntryV3 clone() {
PwEntryV3 newEntry = (PwEntryV3) super.clone();
// Attributes in parent // Attributes in parent
addCloneAttributesToNewEntry(newEntry); PwEntryV3 newEntry = (PwEntryV3) super.clone();
// Attributes here // Attributes here
// newEntry.parent stay the same in copy // newEntry.parent stay the same in copy
@@ -200,7 +199,7 @@ public class PwEntryV3 extends PwEntry<PwGroupV3> {
public void populateBlankFields(PwDatabaseV3 db) { public void populateBlankFields(PwDatabaseV3 db) {
// TODO verify and remove // TODO verify and remove
if (icon == null) { if (icon == null) {
icon = db.getIconFactory().getFirstIcon(); icon = db.getIconFactory().getKeyIcon();
} }
if (username == null) { if (username == null) {

View File

@@ -89,11 +89,9 @@ public class PwEntryV4 extends PwEntry<PwGroupV4> implements ITimeLogger {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public PwEntryV4 clone() { public PwEntryV4 clone() {
// Attributes in parent
PwEntryV4 newEntry = (PwEntryV4) super.clone(); PwEntryV4 newEntry = (PwEntryV4) super.clone();
// Attributes in parent
addCloneAttributesToNewEntry(newEntry);
// Attributes here // Attributes here
newEntry.customIcon = new PwIconCustom(this.customIcon); newEntry.customIcon = new PwIconCustom(this.customIcon);
// newEntry.usageCount stay the same in copy // newEntry.usageCount stay the same in copy

View File

@@ -30,9 +30,15 @@ public abstract class PwGroup<Parent extends PwGroup, ChildGroup extends PwGroup
protected List<ChildGroup> childGroups = new ArrayList<>(); protected List<ChildGroup> childGroups = new ArrayList<>();
protected List<ChildEntry> childEntries = new ArrayList<>(); protected List<ChildEntry> childEntries = new ArrayList<>();
public void initNewGroup(String nm, PwGroupId newId) { @Override
setId(newId); public PwGroup clone() {
name = nm; // name is clone automatically (IMMUTABLE)
return (PwGroup) super.clone();
}
protected void assign(PwGroup<Parent, ChildGroup, ChildEntry> source) {
super.assign(source);
name = source.name;
} }
public List<ChildGroup> getChildGroups() { public List<ChildGroup> getChildGroups() {

View File

@@ -40,6 +40,26 @@ public class PwGroupV3 extends PwGroup<PwGroupV3, PwGroupV3, PwEntryV3> {
super(); super();
} }
public PwGroupV3(PwGroupV3 p) {
construct(p);
}
protected void updateWith(PwGroupV3 source) {
super.assign(source);
groupId = source.groupId;
level = source.level;
flags = source.flags;
}
@SuppressWarnings("unchecked")
@Override
public PwGroupV3 clone() {
// newGroup.groupId stay the same in copy
// newGroup.level stay the same in copy
// newGroup.flags stay the same in copy
return (PwGroupV3) super.clone();
}
@Override @Override
public void setParent(PwGroupV3 parent) { public void setParent(PwGroupV3 parent) {
super.setParent(parent); super.setParent(parent);
@@ -89,7 +109,7 @@ public class PwGroupV3 extends PwGroup<PwGroupV3, PwGroupV3, PwEntryV3> {
public void populateBlankFields(PwDatabaseV3 db) { public void populateBlankFields(PwDatabaseV3 db) {
// TODO populate blanck field // TODO populate blanck field
if (icon == null) { if (icon == null) {
icon = db.getIconFactory().getFirstIcon(); icon = db.getIconFactory().getFolderIcon();
} }
if (name == null) { if (name == null) {

View File

@@ -45,6 +45,11 @@ public class PwGroupV4 extends PwGroup<PwGroupV4, PwGroupV4, PwEntryV4> implemen
public PwGroupV4() { public PwGroupV4() {
super(); super();
} }
public PwGroupV4(PwGroupV4 p) {
construct(p);
parentGroupLastMod = new PwDate();
}
public PwGroupV4(String name, PwIconStandard icon) { public PwGroupV4(String name, PwIconStandard icon) {
this.uuid = UUID.randomUUID(); this.uuid = UUID.randomUUID();
@@ -52,10 +57,47 @@ public class PwGroupV4 extends PwGroup<PwGroupV4, PwGroupV4, PwEntryV4> implemen
this.icon = icon; this.icon = icon;
} }
protected void updateWith(PwGroupV4 source) {
super.assign(source);
uuid = source.uuid;
customIcon = source.customIcon;
usageCount = source.usageCount;
parentGroupLastMod = source.parentGroupLastMod;
customData = source.customData;
expires = source.expires;
notes = source.notes;
isExpanded = source.isExpanded;
defaultAutoTypeSequence = source.defaultAutoTypeSequence;
enableAutoType = source.enableAutoType;
enableSearching = source.enableSearching;
lastTopVisibleEntry = source.lastTopVisibleEntry;
}
@SuppressWarnings("unchecked")
@Override @Override
public void initNewGroup(String nm, PwGroupId newId) { public PwGroupV4 clone() {
super.initNewGroup(nm, newId); // Attributes in parent
parentGroupLastMod = new PwDate(); PwGroupV4 newGroup = (PwGroupV4) super.clone();
// Attributes here
// newGroup.uuid stay the same in copy
newGroup.customIcon = new PwIconCustom(this.customIcon);
// newGroup.usageCount stay the same in copy
newGroup.parentGroupLastMod = this.parentGroupLastMod.clone();
// TODO customData make copy from hashmap newGroup.customData = (HashMap<String, String>) this.customData.clone();
// newGroup.expires stay the same in copy
// newGroup.notes stay the same in copy
// newGroup.isExpanded stay the same in copy
// newGroup.defaultAutoTypeSequence stay the same in copy
// newGroup.enableAutoType stay the same in copy
// newGroup.enableSearching stay the same in copy
// newGroup.lastTopVisibleEntry stay the same in copy
return newGroup;
} }
public void addGroup(PwGroupV4 subGroup) { public void addGroup(PwGroupV4 subGroup) {

View File

@@ -37,20 +37,23 @@ public class PwIconFactory {
*/ */
private ReferenceMap customCache = new ReferenceMap(AbstractReferenceMap.HARD, AbstractReferenceMap.WEAK); private ReferenceMap customCache = new ReferenceMap(AbstractReferenceMap.HARD, AbstractReferenceMap.WEAK);
public PwIconStandard getFirstIcon() { public PwIconStandard getKeyIcon() {
return getIcon(0); return getIcon(PwIconStandard.KEY);
} }
public PwIconStandard getTrashIcon() {
return getIcon(PwIconStandard.TRASH);
}
public PwIconStandard getFolderIcon() {
return getIcon(PwIconStandard.FOLDER);
}
public PwIconStandard getIcon(int iconId) { public PwIconStandard getIcon(int iconId) {
PwIconStandard icon = (PwIconStandard) cache.get(iconId); PwIconStandard icon = (PwIconStandard) cache.get(iconId);
if (icon == null) { if (icon == null) {
if (iconId == 1) { icon = new PwIconStandard(iconId);
icon = PwIconStandard.FIRST;
}
else {
icon = new PwIconStandard(iconId);
}
cache.put(iconId, icon); cache.put(iconId, icon);
} }

View File

@@ -22,12 +22,10 @@ package com.kunzisoft.keepass.database;
public class PwIconStandard extends PwIcon { public class PwIconStandard extends PwIcon {
public final int iconId; public final int iconId;
// The first is number 0 public static final int KEY = 0;
public static PwIconStandard FIRST = new PwIconStandard(0); public static final int TRASH = 43;
public static final int TRASH_BIN = 43;
public static final int FOLDER = 48; public static final int FOLDER = 48;
public PwIconStandard(int iconId) { public PwIconStandard(int iconId) {
this.iconId = iconId; this.iconId = iconId;
} }

View File

@@ -27,11 +27,11 @@ import java.io.Serializable;
/** /**
* Abstract class who manage Groups and Entries * Abstract class who manage Groups and Entries
*/ */
public abstract class PwNode<Parent extends PwGroup> implements ISmallTimeLogger, Serializable { public abstract class PwNode<Parent extends PwGroup> implements ISmallTimeLogger, Serializable, Cloneable {
protected Parent parent = null; protected Parent parent = null;
protected PwIconStandard icon = PwIconStandard.FIRST; protected PwIconStandard icon = new PwIconStandard(0);
protected PwDate creation = new PwDate(); protected PwDate creation = new PwDate();
protected PwDate lastMod = new PwDate(); protected PwDate lastMod = new PwDate();
@@ -53,15 +53,23 @@ public abstract class PwNode<Parent extends PwGroup> implements ISmallTimeLogger
this.expireDate = source.expireDate; this.expireDate = source.expireDate;
} }
protected void addCloneAttributesToNewEntry(PwEntry newEntry) { @Override
// newEntry.parent stay the same in copy public PwNode clone() {
PwNode newNode;
try {
newNode = (PwNode) super.clone();
// newNode.parent stay the same in copy
newEntry.icon = new PwIconStandard(this.icon); newNode.icon = new PwIconStandard(this.icon);
newEntry.creation = creation.clone(); newNode.creation = creation.clone();
newEntry.lastMod = lastMod.clone(); newNode.lastMod = lastMod.clone();
newEntry.lastAccess = lastAccess.clone(); newNode.lastAccess = lastAccess.clone();
newEntry.expireDate = expireDate.clone(); newNode.expireDate = expireDate.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException("Clone should be supported");
}
return newNode;
} }
/** /**
@@ -111,6 +119,13 @@ public abstract class PwNode<Parent extends PwGroup> implements ISmallTimeLogger
parent = prt; parent = prt;
} }
/**
* @return true if parent is present (can be a root or a detach element)
*/
public boolean containsParent() {
return getParent() != null;
}
public PwDate getCreationTime() { public PwDate getCreationTime() {
return creation; return creation;
} }

View File

@@ -0,0 +1,47 @@
package com.kunzisoft.keepass.database.action;
import android.content.Context;
import com.kunzisoft.keepass.database.Database;
public abstract class ActionWithSaveDatabaseRunnable extends RunnableOnFinish {
protected Context mContext;
protected boolean mDontSave;
protected Database mDatabase;
public ActionWithSaveDatabaseRunnable(Context context, Database database, OnFinishRunnable finish, boolean dontSave) {
super(finish);
this.mDatabase = database;
this.mContext = context;
this.mDontSave = dontSave;
this.mFinish = new AfterActionRunnable(finish);
}
@Override
public void run() {
// Commit to disk
SaveDatabaseRunnable save = new SaveDatabaseRunnable(mContext, mDatabase, mFinish, mDontSave);
save.run();
}
public void runWithoutSaveDatabase() {
mFinish.run();
}
abstract protected void onFinish(boolean success, String message);
private class AfterActionRunnable extends OnFinishRunnable {
AfterActionRunnable(OnFinishRunnable finish) {
super(finish);
}
@Override
public void run() {
onFinish(mSuccess, mMessage);
super.run();
}
}
}

View File

@@ -0,0 +1,91 @@
/*
* Copyright 2017 Brian Pellin, Jeremy Jamet / Kunzisoft.
*
* This file is part of KeePass DX.
*
* KeePass DX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* KeePass DX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with KeePass DX. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.kunzisoft.keepass.database.action;
import android.content.Context;
import android.net.Uri;
import com.kunzisoft.keepass.database.Database;
import com.kunzisoft.keepass.database.PwDatabase;
import com.kunzisoft.keepass.database.exception.InvalidKeyFileException;
import com.kunzisoft.keepass.utils.UriUtil;
import java.io.IOException;
import java.io.InputStream;
public class AssignPasswordInDatabaseRunnable extends ActionWithSaveDatabaseRunnable {
private String mPassword;
private Uri mKeyfile;
private byte[] mBackupKey;
public AssignPasswordInDatabaseRunnable(Context ctx, Database db, String password, Uri keyfile, OnFinishRunnable finish) {
this(ctx, db, password, keyfile, finish, false);
}
public AssignPasswordInDatabaseRunnable(Context ctx, Database db, String password, Uri keyfile, OnFinishRunnable finish, boolean dontSave) {
super(ctx, db, finish, dontSave);
this.mPassword = password;
this.mKeyfile = keyfile;
}
@Override
public void run() {
PwDatabase pm = mDatabase.getPwDatabase();
mBackupKey = new byte[pm.getMasterKey().length];
System.arraycopy(pm.getMasterKey(), 0, mBackupKey, 0, mBackupKey.length);
// Set key
try {
InputStream is = UriUtil.getUriInputStream(mContext, mKeyfile);
pm.retrieveMasterKey(mPassword, is);
// Save Database
super.run();
} catch (InvalidKeyFileException|IOException e) {
erase(mBackupKey);
finish(false, e.getMessage());
super.runWithoutSaveDatabase();
}
}
@Override
protected void onFinish(boolean success, String message) {
if (!success) {
// Erase the current master key
erase(mDatabase.getPwDatabase().getMasterKey());
mDatabase.getPwDatabase().setMasterKey(mBackupKey);
}
}
/**
* Overwrite the array as soon as we don't need it to avoid keeping the extra data in memory
*/
private void erase(byte[] array) {
if ( array == null ) return;
for ( int i = 0; i < array.length; i++ ) {
array[i] = 0;
}
}
}

View File

@@ -17,7 +17,7 @@
* along with KeePass DX. If not, see <http://www.gnu.org/licenses/>. * along with KeePass DX. If not, see <http://www.gnu.org/licenses/>.
* *
*/ */
package com.kunzisoft.keepass.database.edit; package com.kunzisoft.keepass.database.action;
import android.content.Context; import android.content.Context;
@@ -26,18 +26,18 @@ import com.kunzisoft.keepass.database.Database;
import com.kunzisoft.keepass.database.PwDatabase; import com.kunzisoft.keepass.database.PwDatabase;
import com.kunzisoft.keepass.utils.UriUtil; import com.kunzisoft.keepass.utils.UriUtil;
public class CreateDB extends RunnableOnFinish { public class CreateDatabaseRunnable extends RunnableOnFinish {
private String mFilename;
private boolean mDontSave;
private Context ctx;
public CreateDB(Context ctx, String filename, OnFinish finish, boolean dontSave) { private Context mContext;
private boolean mDontSave;
private String mFilename;
public CreateDatabaseRunnable(Context mContext, String filename, OnFinishRunnable finish, boolean dontSave) {
super(finish); super(finish);
mFilename = filename; this.mContext = mContext;
mDontSave = dontSave; this.mDontSave = dontSave;
this.ctx = ctx; this.mFilename = filename;
} }
@Override @Override
@@ -56,8 +56,9 @@ public class CreateDB extends RunnableOnFinish {
App.clearShutdown(); App.clearShutdown();
// Commit changes // Commit changes
SaveDB save = new SaveDB(ctx, db, mFinish, mDontSave); SaveDatabaseRunnable save = new SaveDatabaseRunnable(mContext, db, mFinish, mDontSave);
mFinish = null; mFinish = null;
save.run(); save.run();
} }
} }

View File

@@ -17,17 +17,18 @@
* along with KeePass DX. If not, see <http://www.gnu.org/licenses/>. * along with KeePass DX. If not, see <http://www.gnu.org/licenses/>.
* *
*/ */
package com.kunzisoft.keepass.database.edit; package com.kunzisoft.keepass.database.action;
import android.net.Uri; import android.net.Uri;
import java.io.Serializable; import java.io.Serializable;
public class FileOnFinish extends OnFinish implements Serializable { public class FileOnFinishRunnable extends OnFinishRunnable implements Serializable {
private Uri mFilename = null; private Uri mFilename = null;
protected FileOnFinish mOnFinish; protected FileOnFinishRunnable mOnFinish;
public FileOnFinish(FileOnFinish finish) { public FileOnFinishRunnable(FileOnFinishRunnable finish) {
super(finish); super(finish);
mOnFinish = finish; mOnFinish = finish;

View File

@@ -17,12 +17,14 @@
* along with KeePass DX. If not, see <http://www.gnu.org/licenses/>. * along with KeePass DX. If not, see <http://www.gnu.org/licenses/>.
* *
*/ */
package com.kunzisoft.keepass.database.edit; package com.kunzisoft.keepass.database.action;
import android.content.Context; import android.content.Context;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.net.Uri; import android.net.Uri;
import android.preference.PreferenceManager; import android.preference.PreferenceManager;
import android.support.annotation.StringRes;
import android.util.Log;
import com.kunzisoft.keepass.R; import com.kunzisoft.keepass.R;
import com.kunzisoft.keepass.app.App; import com.kunzisoft.keepass.app.App;
@@ -40,71 +42,77 @@ import com.kunzisoft.keepass.database.exception.KeyFileEmptyException;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
public class LoadDB extends RunnableOnFinish { public class LoadDatabaseRunnable extends RunnableOnFinish {
private static final String TAG = LoadDatabaseRunnable.class.getName();
private Context mContext;
private Database mDatabase;
private Uri mUri; private Uri mUri;
private String mPass; private String mPass;
private Uri mKey; private Uri mKey;
private Database mDb;
private Context mCtx;
private boolean mRememberKeyfile; private boolean mRememberKeyfile;
public LoadDB(Database db, Context ctx, Uri uri, String pass, Uri key, OnFinish finish) { public LoadDatabaseRunnable(Context context, Database database, Uri uri, String pass, Uri key, OnFinishRunnable finish) {
super(finish); super(finish);
mDb = db; this.mContext = context;
mCtx = ctx; this.mDatabase = database;
mUri = uri; this.mUri = uri;
mPass = pass; this.mPass = pass;
mKey = key; this.mKey = key;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
mRememberKeyfile = prefs.getBoolean(ctx.getString(R.string.keyfile_key), ctx.getResources().getBoolean(R.bool.keyfile_default)); this.mRememberKeyfile = prefs.getBoolean(context.getString(R.string.keyfile_key), context.getResources().getBoolean(R.bool.keyfile_default));
} }
@Override @Override
public void run() { public void run() {
try { try {
mDb.loadData(mCtx, mUri, mPass, mKey, mStatus); mDatabase.loadData(mContext, mUri, mPass, mKey, mStatus);
saveFileData(mUri, mKey); saveFileData(mUri, mKey);
} catch (ArcFourException e) { } catch (ArcFourException e) {
finish(false, mCtx.getString(R.string.error_arc4)); catchError(e, R.string.error_arc4);
return; return;
} catch (InvalidPasswordException e) { } catch (InvalidPasswordException e) {
finish(false, mCtx.getString(R.string.InvalidPassword)); catchError(e, R.string.InvalidPassword);
return; return;
} catch (ContentFileNotFoundException e) { } catch (ContentFileNotFoundException e) {
finish(false, mCtx.getString(R.string.file_not_found_content)); catchError(e, R.string.file_not_found_content);
return; return;
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
finish(false, mCtx.getString(R.string.file_not_found)); catchError(e, R.string.file_not_found);
return; return;
} catch (IOException e) { } catch (IOException e) {
Log.e(TAG, "Database can't be read", e);
finish(false, e.getMessage()); finish(false, e.getMessage());
return; return;
} catch (KeyFileEmptyException e) { } catch (KeyFileEmptyException e) {
finish(false, mCtx.getString(R.string.keyfile_is_empty)); catchError(e, R.string.keyfile_is_empty);
return; return;
} catch (InvalidAlgorithmException e) { } catch (InvalidAlgorithmException e) {
finish(false, mCtx.getString(R.string.invalid_algorithm)); catchError(e, R.string.invalid_algorithm);
return; return;
} catch (InvalidKeyFileException e) { } catch (InvalidKeyFileException e) {
finish(false, mCtx.getString(R.string.keyfile_does_not_exist)); catchError(e, R.string.keyfile_does_not_exist);
return; return;
} catch (InvalidDBSignatureException e) { } catch (InvalidDBSignatureException e) {
finish(false, mCtx.getString(R.string.invalid_db_sig)); catchError(e, R.string.invalid_db_sig);
return; return;
} catch (InvalidDBVersionException e) { } catch (InvalidDBVersionException e) {
finish(false, mCtx.getString(R.string.unsupported_db_version)); catchError(e, R.string.unsupported_db_version);
return; return;
} catch (InvalidDBException e) { } catch (InvalidDBException e) {
finish(false, mCtx.getString(R.string.error_invalid_db)); catchError(e, R.string.error_invalid_db);
return; return;
} catch (OutOfMemoryError e) { } catch (OutOfMemoryError e) {
finish(false, mCtx.getString(R.string.error_out_of_memory)); String errorMessage = mContext.getString(R.string.error_out_of_memory);
Log.e(TAG, errorMessage, e);
finish(false, errorMessage);
return; return;
} catch (Exception e) { } catch (Exception e) {
Log.e(TAG, "Database can't be load", e);
finish(false, e.getMessage()); finish(false, e.getMessage());
return; return;
} }
@@ -112,6 +120,12 @@ public class LoadDB extends RunnableOnFinish {
finish(true); finish(true);
} }
private void catchError(Exception e, @StringRes int messageId) {
String errorMessage = mContext.getString(messageId);
Log.e(TAG, errorMessage, e);
finish(false, errorMessage);
}
private void saveFileData(Uri uri, Uri key) { private void saveFileData(Uri uri, Uri key) {
if ( ! mRememberKeyfile ) { if ( ! mRememberKeyfile ) {
key = null; key = null;
@@ -120,6 +134,4 @@ public class LoadDB extends RunnableOnFinish {
App.getFileHistory().createFile(uri, key); App.getFileHistory().createFile(uri, key);
} }
} }

View File

@@ -17,7 +17,7 @@
* along with KeePass DX. If not, see <http://www.gnu.org/licenses/>. * along with KeePass DX. If not, see <http://www.gnu.org/licenses/>.
* *
*/ */
package com.kunzisoft.keepass.database.edit; package com.kunzisoft.keepass.database.action;
import android.content.Context; import android.content.Context;
import android.os.Handler; import android.os.Handler;
@@ -29,27 +29,27 @@ import android.widget.Toast;
* @author bpellin * @author bpellin
* *
*/ */
public class OnFinish implements Runnable { public class OnFinishRunnable implements Runnable {
protected boolean mSuccess; protected boolean mSuccess;
protected String mMessage; protected String mMessage;
protected OnFinish mOnFinish; protected OnFinishRunnable mOnFinish;
protected Handler mHandler; protected Handler mHandler;
public OnFinish() { public OnFinishRunnable() {
} }
public OnFinish(Handler handler) { public OnFinishRunnable(Handler handler) {
mOnFinish = null; mOnFinish = null;
mHandler = handler; mHandler = handler;
} }
public OnFinish(OnFinish finish, Handler handler) { public OnFinishRunnable(OnFinishRunnable finish, Handler handler) {
mOnFinish = finish; mOnFinish = finish;
mHandler = handler; mHandler = handler;
} }
public OnFinish(OnFinish finish) { public OnFinishRunnable(OnFinishRunnable finish) {
mOnFinish = finish; mOnFinish = finish;
mHandler = null; mHandler = null;
} }
@@ -75,11 +75,30 @@ public class OnFinish implements Runnable {
} }
} }
} }
/**
* ONLY to use in UIThread, typically in an Activity, Fragment or a Service
* @param ctx Context to show the message
*/
protected void displayMessage(Context ctx) { protected void displayMessage(Context ctx) {
if ( mMessage != null && mMessage.length() > 0 ) { if ( mMessage != null && mMessage.length() > 0 ) {
Toast.makeText(ctx, mMessage, Toast.LENGTH_LONG).show(); Toast.makeText(ctx, mMessage, Toast.LENGTH_LONG).show();
} }
} }
public boolean isSuccess() {
return mSuccess;
}
public void setSuccess(boolean mSuccess) {
this.mSuccess = mSuccess;
}
public String getMessage() {
return mMessage;
}
public void setMessage(String mMessage) {
this.mMessage = mMessage;
}
} }

View File

@@ -17,17 +17,17 @@
* along with KeePass DX. If not, see <http://www.gnu.org/licenses/>. * along with KeePass DX. If not, see <http://www.gnu.org/licenses/>.
* *
*/ */
package com.kunzisoft.keepass.database.edit; package com.kunzisoft.keepass.database.action;
import com.kunzisoft.keepass.tasks.UpdateStatus; import com.kunzisoft.keepass.tasks.ProgressTaskUpdater;
public abstract class RunnableOnFinish implements Runnable { public abstract class RunnableOnFinish implements Runnable {
public OnFinish mFinish; public OnFinishRunnable mFinish;
public UpdateStatus mStatus; public ProgressTaskUpdater mStatus;
public RunnableOnFinish(OnFinish finish) { public RunnableOnFinish(OnFinishRunnable finish) {
mFinish = finish; mFinish = finish;
} }
@@ -45,7 +45,7 @@ public abstract class RunnableOnFinish implements Runnable {
} }
} }
public void setStatus(UpdateStatus status) { public void setUpdateProgressTaskStatus(ProgressTaskUpdater status) {
mStatus = status; mStatus = status;
} }

View File

@@ -17,7 +17,7 @@
* along with KeePass DX. If not, see <http://www.gnu.org/licenses/>. * along with KeePass DX. If not, see <http://www.gnu.org/licenses/>.
* *
*/ */
package com.kunzisoft.keepass.database.edit; package com.kunzisoft.keepass.database.action;
import android.content.Context; import android.content.Context;
@@ -26,25 +26,22 @@ import com.kunzisoft.keepass.database.exception.PwDbOutputException;
import java.io.IOException; import java.io.IOException;
public class SaveDB extends RunnableOnFinish { public class SaveDatabaseRunnable extends RunnableOnFinish {
private Database mDb;
private boolean mDontSave;
private Context mCtx;
public SaveDB(Context ctx, Database db, OnFinish finish, boolean dontSave) { private Context mContext;
private Database mDatabase;
private boolean mDontSave;
public SaveDatabaseRunnable(Context context, Database database, OnFinishRunnable finish, boolean dontSave) {
super(finish); super(finish);
mDb = db; this.mContext = context;
mDontSave = dontSave; this.mDatabase = database;
mCtx = ctx; this.mDontSave = dontSave;
} }
public SaveDB(Context ctx, Database db, OnFinish finish) { public SaveDatabaseRunnable(Context ctx, Database db, OnFinishRunnable finish) {
super(finish); this(ctx, db, finish, false);
mDb = db;
mDontSave = false;
mCtx = ctx;
} }
@Override @Override
@@ -52,17 +49,14 @@ public class SaveDB extends RunnableOnFinish {
if ( ! mDontSave ) { if ( ! mDontSave ) {
try { try {
mDb.saveData(mCtx); mDatabase.saveData(mContext);
} catch (IOException e) { } catch (IOException e) {
finish(false, e.getMessage()); finish(false, e.getMessage());
return; return;
} catch (PwDbOutputException e) { } catch (PwDbOutputException e) {
// TODO: Restore // TODO: Restore
throw new RuntimeException(e);
/*
finish(false, e.getMessage()); finish(false, e.getMessage());
return; return;
*/
} }
} }

View File

@@ -0,0 +1,33 @@
package com.kunzisoft.keepass.database.action.node;
import android.content.Context;
import com.kunzisoft.keepass.database.Database;
import com.kunzisoft.keepass.database.PwNode;
import com.kunzisoft.keepass.database.action.ActionWithSaveDatabaseRunnable;
abstract class ActionNodeDatabaseRunnable extends ActionWithSaveDatabaseRunnable {
private AfterActionNodeOnFinish callbackRunnable;
public ActionNodeDatabaseRunnable(Context context, Database db, AfterActionNodeOnFinish finish, boolean dontSave) {
super(context, db, finish, dontSave);
this.callbackRunnable = finish;
}
/**
* Callback method who return the node(s) modified after an action
* - Add : @param oldNode NULL, @param newNode CreatedNode
* - Copy : @param oldNode NodeToCopy, @param newNode NodeCopied
* - Delete : @param oldNode NodeToDelete, @param NULL
* - Move : @param oldNode NULL, @param NodeToMove
* - Update : @param oldNode NodeToUpdate, @param NodeUpdated
*/
protected void callbackNodeAction(boolean success, String message, PwNode oldNode, PwNode newNode) {
if (callbackRunnable != null) {
callbackRunnable.setSuccess(success);
callbackRunnable.setMessage(message);
callbackRunnable.run(oldNode, newNode);
}
}
}

View File

@@ -17,51 +17,40 @@
* along with KeePass DX. If not, see <http://www.gnu.org/licenses/>. * along with KeePass DX. If not, see <http://www.gnu.org/licenses/>.
* *
*/ */
package com.kunzisoft.keepass.database.edit; package com.kunzisoft.keepass.database.action.node;
import android.content.Context; import android.content.Context;
import com.kunzisoft.keepass.database.Database; import com.kunzisoft.keepass.database.Database;
import com.kunzisoft.keepass.database.PwEntry; import com.kunzisoft.keepass.database.PwEntry;
public class AddEntry extends RunnableOnFinish { public class AddEntryRunnable extends ActionNodeDatabaseRunnable {
protected Database mDb; private PwEntry mNewEntry;
private PwEntry mEntry;
private Context ctx; public AddEntryRunnable(Context ctx, Database db, PwEntry entryToAdd, AfterActionNodeOnFinish finish) {
this(ctx, db, entryToAdd, finish, false);
public AddEntry(Context ctx, Database db, PwEntry entry, OnFinish finish) { }
super(finish);
public AddEntryRunnable(Context ctx, Database db, PwEntry entryToAdd, AfterActionNodeOnFinish finish, boolean dontSave) {
this.mDb = db; super(ctx, db, finish, dontSave);
this.mEntry = entry;
this.ctx = ctx; this.mNewEntry = entryToAdd;
this.mFinish = new AfterAdd(mFinish);
} }
@Override @Override
public void run() { public void run() {
mDb.addEntryTo(mEntry, mEntry.getParent()); mDatabase.addEntryTo(mNewEntry, mNewEntry.getParent());
// Commit to disk // Commit to disk
SaveDB save = new SaveDB(ctx, mDb, mFinish); super.run();
save.run();
} }
private class AfterAdd extends OnFinish {
AfterAdd(OnFinish finish) { @Override
super(finish); protected void onFinish(boolean success, String message) {
} if ( !success ) {
mDatabase.removeEntryFrom(mNewEntry, mNewEntry.getParent());
@Override
public void run() {
if ( !mSuccess ) {
mDb.removeEntryFrom(mEntry, mEntry.getParent());
}
// TODO if add entry callback
super.run();
} }
callbackNodeAction(success, message, null, mNewEntry);
} }
} }

View File

@@ -0,0 +1,56 @@
/*
* Copyright 2017 Brian Pellin, Jeremy Jamet / Kunzisoft.
*
* This file is part of KeePass DX.
*
* KeePass DX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* KeePass DX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with KeePass DX. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.kunzisoft.keepass.database.action.node;
import android.content.Context;
import com.kunzisoft.keepass.database.Database;
import com.kunzisoft.keepass.database.PwGroup;
public class AddGroupRunnable extends ActionNodeDatabaseRunnable {
private PwGroup mNewGroup;
public AddGroupRunnable(Context ctx, Database db, PwGroup newGroup, AfterActionNodeOnFinish afterAddNode) {
this(ctx, db, newGroup, afterAddNode, false);
}
public AddGroupRunnable(Context ctx, Database db, PwGroup newGroup, AfterActionNodeOnFinish afterAddNode, boolean dontSave) {
super(ctx, db, afterAddNode, dontSave);
this.mNewGroup = newGroup;
}
@Override
public void run() {
mDatabase.addGroupTo(mNewGroup, mNewGroup.getParent());
// Commit to disk
super.run();
}
@Override
protected void onFinish(boolean success, String message) {
if ( !success ) {
mDatabase.removeGroupFrom(mNewGroup, mNewGroup.getParent());
}
callbackNodeAction(success, message, null, mNewGroup);
}
}

View File

@@ -0,0 +1,36 @@
/*
* Copyright 2018 Jeremy Jamet / Kunzisoft.
*
* This file is part of KeePass DX.
*
* KeePass DX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* KeePass DX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with KeePass DX. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.kunzisoft.keepass.database.action.node;
import android.os.Handler;
import com.kunzisoft.keepass.database.PwNode;
import com.kunzisoft.keepass.database.action.OnFinishRunnable;
import javax.annotation.Nullable;
public abstract class AfterActionNodeOnFinish extends OnFinishRunnable {
public AfterActionNodeOnFinish() {
super(new Handler());
}
public abstract void run(@Nullable PwNode oldNode, @Nullable PwNode newNode);
}

View File

@@ -0,0 +1,75 @@
/*
* Copyright 2018 Jeremy Jamet / Kunzisoft.
*
* This file is part of KeePass DX.
*
* KeePass DX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* KeePass DX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with KeePass DX. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.kunzisoft.keepass.database.action.node;
import android.content.Context;
import android.util.Log;
import com.kunzisoft.keepass.database.Database;
import com.kunzisoft.keepass.database.PwEntry;
import com.kunzisoft.keepass.database.PwGroup;
public class CopyEntryRunnable extends ActionNodeDatabaseRunnable {
private static final String TAG = CopyEntryRunnable.class.getName();
private PwEntry mEntryToCopy;
private PwEntry mEntryCopied;
private PwGroup mNewParent;
public CopyEntryRunnable(Context context, Database db, PwEntry oldE, PwGroup newParent, AfterActionNodeOnFinish afterAddNode) {
this(context, db, oldE, newParent, afterAddNode, false);
}
public CopyEntryRunnable(Context context, Database db, PwEntry oldE, PwGroup newParent, AfterActionNodeOnFinish afterAddNode, boolean dontSave) {
super(context, db, afterAddNode, dontSave);
this.mEntryToCopy = oldE;
this.mNewParent = newParent;
}
@Override
public void run() {
// Update entry with new values
mEntryCopied = mDatabase.copyEntry(mEntryToCopy, mNewParent);
if (mEntryCopied != null) {
mEntryCopied.touch(true, true);
// Commit to disk
super.run();
} else {
Log.e(TAG, "Unable to create a copy of the entry");
}
}
@Override
protected void onFinish(boolean success, String message) {
if ( !success ) {
// If we fail to save, try to delete the copy
try {
mDatabase.deleteEntry(mEntryCopied);
} catch (Exception e) {
Log.i(TAG, "Unable to delete the copied entry");
}
}
callbackNodeAction(success, message, mEntryToCopy, mEntryCopied);
}
}

View File

@@ -0,0 +1,73 @@
/*
* Copyright 2017 Brian Pellin, Jeremy Jamet / Kunzisoft.
*
* This file is part of KeePass DX.
*
* KeePass DX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* KeePass DX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with KeePass DX. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.kunzisoft.keepass.database.action.node;
import android.content.Context;
import com.kunzisoft.keepass.database.Database;
import com.kunzisoft.keepass.database.PwEntry;
import com.kunzisoft.keepass.database.PwGroup;
public class DeleteEntryRunnable extends ActionNodeDatabaseRunnable {
private PwEntry mEntryToDelete;
private PwGroup mParent;
private boolean mRecycle;
public DeleteEntryRunnable(Context ctx, Database db, PwEntry entry, AfterActionNodeOnFinish finish) {
this(ctx, db, entry, finish, false);
}
public DeleteEntryRunnable(Context ctx, Database db, PwEntry entry, AfterActionNodeOnFinish finish, boolean dontSave) {
super(ctx, db, finish, dontSave);
this.mEntryToDelete = entry;
}
@Override
public void run() {
mParent = mEntryToDelete.getParent();
// Remove Entry from parent
mRecycle = mDatabase.canRecycle(mEntryToDelete);
if (mRecycle) {
mDatabase.recycle(mEntryToDelete);
}
else {
mDatabase.deleteEntry(mEntryToDelete);
}
// Commit database
super.run();
}
@Override
protected void onFinish(boolean success, String message) {
if ( !success ) {
if (mRecycle) {
mDatabase.undoRecycle(mEntryToDelete, mParent);
}
else {
mDatabase.undoDeleteEntry(mEntryToDelete, mParent);
}
}
callbackNodeAction(success, message, mEntryToDelete, null);
}
}

View File

@@ -0,0 +1,96 @@
/*
* Copyright 2017 Brian Pellin, Jeremy Jamet / Kunzisoft.
*
* This file is part of KeePass DX.
*
* KeePass DX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* KeePass DX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with KeePass DX. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.kunzisoft.keepass.database.action.node;
import android.content.Context;
import com.kunzisoft.keepass.app.App;
import com.kunzisoft.keepass.database.Database;
import com.kunzisoft.keepass.database.PwEntry;
import com.kunzisoft.keepass.database.PwGroup;
import java.util.ArrayList;
import java.util.List;
public class DeleteGroupRunnable extends ActionNodeDatabaseRunnable {
private PwGroup<PwGroup, PwGroup, PwEntry> mGroupToDelete;
private PwGroup mParent;
private boolean mRecycle;
public DeleteGroupRunnable(Context ctx, Database db, PwGroup<PwGroup, PwGroup, PwEntry> group, AfterActionNodeOnFinish finish) {
this(ctx, db, group, finish, false);
}
public DeleteGroupRunnable(Context ctx, Database db, PwGroup<PwGroup, PwGroup, PwEntry> group, AfterActionNodeOnFinish finish, boolean dontSave) {
super(ctx, db, finish, dontSave);
mGroupToDelete = group;
}
@Override
public void run() {
mParent = mGroupToDelete.getParent();
// Remove Group from parent
mRecycle = mDatabase.canRecycle(mGroupToDelete);
if (mRecycle) {
mDatabase.recycle(mGroupToDelete);
}
else {
// TODO tests
// Remove child entries
List<PwEntry> childEnt = new ArrayList<>(mGroupToDelete.getChildEntries()); // TODO new Methods
for ( int i = 0; i < childEnt.size(); i++ ) {
DeleteEntryRunnable task = new DeleteEntryRunnable(mContext, mDatabase, childEnt.get(i), null, true);
task.run();
}
// Remove child groups
List<PwGroup> childGrp = new ArrayList<>(mGroupToDelete.getChildGroups());
for ( int i = 0; i < childGrp.size(); i++ ) {
DeleteGroupRunnable task = new DeleteGroupRunnable(mContext, mDatabase, childGrp.get(i), null, true);
task.run();
}
mDatabase.deleteGroup(mGroupToDelete);
// Remove from PwDatabaseV3
// TODO ENcapsulate
mDatabase.getPwDatabase().getGroups().remove(mGroupToDelete);
}
// Commit Database
super.run();
}
@Override
protected void onFinish(boolean success, String message) {
if ( !success ) {
if (mRecycle) {
mDatabase.undoRecycle(mGroupToDelete, mParent);
}
else {
// Let's not bother recovering from a failure to save a deleted tree. It is too much work.
App.setShutdown();
// TODO TEST pm.undoDeleteGroup(mGroup, mParent);
}
}
callbackNodeAction(success, message, mGroupToDelete, null);
}
}

View File

@@ -0,0 +1,77 @@
/*
* Copyright 2018 Jeremy Jamet / Kunzisoft.
*
* This file is part of KeePass DX.
*
* KeePass DX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* KeePass DX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with KeePass DX. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.kunzisoft.keepass.database.action.node;
import android.content.Context;
import android.util.Log;
import com.kunzisoft.keepass.database.Database;
import com.kunzisoft.keepass.database.PwEntry;
import com.kunzisoft.keepass.database.PwGroup;
public class MoveEntryRunnable extends ActionNodeDatabaseRunnable {
private static final String TAG = MoveEntryRunnable.class.getName();
private PwEntry mEntryToMove;
private PwGroup mOldParent;
private PwGroup mNewParent;
public MoveEntryRunnable(Context context, Database db, PwEntry oldE, PwGroup newParent, AfterActionNodeOnFinish afterAddNode) {
this(context, db, oldE, newParent, afterAddNode, false);
}
public MoveEntryRunnable(Context context, Database db, PwEntry oldE, PwGroup newParent, AfterActionNodeOnFinish afterAddNode, boolean dontSave) {
super(context, db, afterAddNode, dontSave);
this.mEntryToMove = oldE;
this.mNewParent = newParent;
}
@Override
public void run() {
// Move entry in new parent
mOldParent = mEntryToMove.getParent();
mDatabase.moveEntry(mEntryToMove, mNewParent);
if (mEntryToMove != null) {
mEntryToMove.touch(true, true);
// Commit to disk
super.run();
} else {
Log.e(TAG, "Unable to create a copy of the entry");
}
}
@Override
protected void onFinish(boolean success, String message) {
if ( !success ) {
// If we fail to save, try to remove in the first place
try {
mDatabase.moveEntry(mEntryToMove, mOldParent);
} catch (Exception e) {
Log.i(TAG, "Unable to replace the entry");
}
}
callbackNodeAction(success, message, null, mEntryToMove);
}
}

View File

@@ -0,0 +1,86 @@
/*
* Copyright 2018 Jeremy Jamet / Kunzisoft.
*
* This file is part of KeePass DX.
*
* KeePass DX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* KeePass DX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with KeePass DX. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.kunzisoft.keepass.database.action.node;
import android.content.Context;
import android.util.Log;
import com.kunzisoft.keepass.R;
import com.kunzisoft.keepass.database.Database;
import com.kunzisoft.keepass.database.PwGroup;
public class MoveGroupRunnable extends ActionNodeDatabaseRunnable {
private static final String TAG = MoveGroupRunnable.class.getName();
private PwGroup mGroupToMove;
private PwGroup mOldParent;
private PwGroup mNewParent;
public MoveGroupRunnable(Context context, Database db, PwGroup groupToMove, PwGroup newParent, AfterActionNodeOnFinish afterAddNode) {
this(context, db, groupToMove, newParent, afterAddNode, false);
}
public MoveGroupRunnable(Context context, Database db, PwGroup groupToMove, PwGroup newParent, AfterActionNodeOnFinish afterAddNode, boolean dontSave) {
super(context, db, afterAddNode, dontSave);
this.mGroupToMove = groupToMove;
this.mNewParent = newParent;
}
@Override
public void run() {
mOldParent = mGroupToMove.getParent();
// Move group in new parent if not in the current group
if (!mGroupToMove.equals(mNewParent)
&& !mNewParent.isContainedIn(mGroupToMove)) {
mDatabase.moveGroup(mGroupToMove, mNewParent);
if (mGroupToMove != null) {
mGroupToMove.touch(true, true);
// Commit to disk
super.run();
} else {
Log.e(TAG, "Unable to create a copy of the group");
}
} else {
// Only finish thread
mFinish.setResult(false);
String message = mContext.getString(R.string.error_move_folder_in_itself);
Log.e(TAG, message);
mFinish.setMessage(message);
mFinish.run();
}
}
@Override
protected void onFinish(boolean success, String message) {
if ( !success ) {
// If we fail to save, try to move in the first place
try {
mDatabase.moveGroup(mGroupToMove, mOldParent);
} catch (Exception e) {
Log.i(TAG, "Unable to replace the group");
}
}
callbackNodeAction(success, message, null, mGroupToMove);
}
}

View File

@@ -0,0 +1,63 @@
/*
* Copyright 2017 Brian Pellin, Jeremy Jamet / Kunzisoft.
*
* This file is part of KeePass DX.
*
* KeePass DX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* KeePass DX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with KeePass DX. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.kunzisoft.keepass.database.action.node;
import android.content.Context;
import com.kunzisoft.keepass.database.Database;
import com.kunzisoft.keepass.database.PwEntry;
public class UpdateEntryRunnable extends ActionNodeDatabaseRunnable {
private PwEntry mOldEntry;
private PwEntry mNewEntry;
private PwEntry mBackupEntry;
public UpdateEntryRunnable(Context ctx, Database db, PwEntry oldE, PwEntry newE, AfterActionNodeOnFinish finish) {
this(ctx, db, oldE, newE, finish, false);
}
public UpdateEntryRunnable(Context ctx, Database db, PwEntry oldE, PwEntry newE, AfterActionNodeOnFinish finish, boolean dontSave) {
super(ctx, db, finish, dontSave);
this.mOldEntry = oldE;
this.mNewEntry = newE;
// Keep backup of original values in case save fails
this.mBackupEntry = mOldEntry.clone();
}
@Override
public void run() {
// Update entry with new values
mDatabase.updateEntry(mOldEntry, mNewEntry);
mOldEntry.touch(true, true);
super.run();
}
@Override
protected void onFinish(boolean success, String message) {
if ( !success ) {
// If we fail to save, back out changes to global structure
mDatabase.updateEntry(mOldEntry, mBackupEntry);
}
callbackNodeAction(success, message, mOldEntry, mNewEntry);
}
}

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