diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..697c8a67a --- /dev/null +++ b/.editorconfig @@ -0,0 +1,22 @@ +# EditorConfig +# http://EditorConfig.org + +# top-most EditorConfig file +root = true + +# LF end-of-line, insert an empty new line and UTF-8 +[*] +end_of_line = lf +insert_final_newline = true +charset = utf-8 +indent_style = space +indent_size = 4 +continuation_indent_size = 4 +max_line_length = 160 + +[*.xml] +continuation_indent_size = 4 + +[*.kt] +ij_kotlin_name_count_to_use_star_import = 5 +ij_kotlin_name_count_to_use_star_import_for_members = 5 diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 000000000..05a411d76 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,3 @@ +github: [tibbi] +patreon: tiborkaputa +custom: ["https://www.paypal.me/simplemobiletools"] diff --git a/.gitignore b/.gitignore index 7051e766d..21da4996b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,10 +1,13 @@ *.iml +*.aab .gradle /local.properties -/gradle.properties /.idea/ .DS_Store /build /captures -release.keystore -signing.properties +keystore.jks +keystore.properties +fastlane/fastlane.json +Gemfile +Gemfile.lock diff --git a/CHANGELOG.md b/CHANGELOG.md index 6b11644ef..017d51994 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,405 @@ Changelog ========== +Version 6.17.0 *(2023-09-19)* +---------------------------- + + * Show smaller preview of notes at Open Note dialog + * Added some stability translation improvements + +Version 6.16.5 *(2023-08-30)* +---------------------------- + + * Show smaller preview of notes at Open Note dialog + * Added some stability translation improvements + +Version 6.16.4 *(2023-08-16)* +---------------------------- + + * Added some stability translation improvements + +Version 6.16.3 *(2023-08-15)* +---------------------------- + + * Added some stability translation improvements + +Version 6.16.2 *(2023-08-14)* +---------------------------- + + * Added some stability translation improvements + +Version 6.16.1 *(2023-08-03)* +---------------------------- + + * Avoid showing locked note contents at the Open Note dialog + +Version 6.16.0 *(2023-08-02)* +---------------------------- + + * Properly handle importing both txt and json files + * Redesigned the Open Note dialog + * Fix sorting of checklist items and notes with accents + * Add support for periodic automatic backups + * Added some UI, stability and translation improvements + +Version 6.15.6 *(2023-07-17)* +---------------------------- + + * Moved note exporting and importing to app settings + * Added some stability and translation improvements + +Version 6.15.5 *(2023-05-12)* +---------------------------- + + * Improved the UX at importing files + * Added some stability and translation improvements + +Version 6.15.4 *(2023-03-27)* +---------------------------- + + * Improve exporting of password protected notes + * Allow creating note shortcuts + * Added some stability, translation and UX improvements + +Version 6.15.3 *(2023-03-07)* +---------------------------- + + * Added some stability, translation and UX improvements + +Version 6.15.2 *(2023-01-28)* +---------------------------- + + * Allow adding new checklist items at the top at custom sorting + * Make horizontal swiping between notes more reliable + * Allow clicking on top note titles + * Added some stability, translation and UX improvements + +Version 6.15.1 *(2022-12-26)* +---------------------------- + + * Fixed a note scrolling glitch + +Version 6.15.0 *(2022-12-25)* +---------------------------- + + * Use Material You theme by default on Android 12+ + * Increased minimal required Android OS version to 6 + * Added some UI, translation and stability improvements + +Version 6.14.1 *(2022-10-10)* +---------------------------- + + * Adding a Get Simple Phone button into the About section + * Added some translation, stability and UX improvements + +Version 6.14.0 *(2022-08-24)* +---------------------------- + + * Added Monochrome icon and Language picker support on Android 13+ + * Added some translation and stability improvements + +Version 6.13.0 *(2022-07-12)* +---------------------------- + + * Adding some more materialish design, especially for System theme users + * Added some translation and stability improvements + +Version 6.12.3 *(2022-06-26)* +---------------------------- + + * Added some translation, stability and UX improvements + +Version 6.12.2 *(2022-06-14)* +---------------------------- + + * Change batch note exporting from json to txt + * Added some stability, UX and translation improvements + +Version 6.12.1 *(2022-05-23)* +---------------------------- + + * Added some stability, UX and translation improvements + +Version 6.12.0 *(2022-04-03)* +---------------------------- + + * Added Material You support on Android 12+ + * Added some translation and stability improvements + +Version 6.11.1 *(2022-03-17)* +---------------------------- + + * Fixed synced checklist item visibility at widgets (by Aga-C) + * Added some translation and stability improvements + +Version 6.11.0 *(2022-03-10)* +---------------------------- + + * Allow exporting and importing all notes at once on Android 10+ (by Aga-C) + * Fix checklist file synchronization (by Aga-C) + * Added a Privacy policy + * Added some translation, UX and stability improvements + +Version 6.10.2 *(2022-02-08)* +---------------------------- + + * Allow quick note creation from homescreen shortcuts (by Aga-C) + * Added some translation, stability and UX improvements + +Version 6.10.1 *(2021-12-25)* +---------------------------- + + * Do not show the "Remove done items" checklist menu button as an icon + * Added many translation improvements + +Version 6.10.0 *(2021-11-18)* +---------------------------- + + * Redesigned some screens, added an Auto theme + * Added many translation, stability and UX improvements + +Version 6.9.1 *(2021-10-12)* +---------------------------- + + * Fixed some sorting related glitches + +Version 6.9.0 *(2021-10-08)* +---------------------------- + + * Allow changing checklist item sorting + * Make it easier to add multiple checklist items at once + * Some stability, translation and UX improvements + +Version 6.8.2 *(2021-09-13)* +---------------------------- + + * Added biometric protection on Android 11+ + * Fixed a glitch with note content vanishing on export error + +Version 6.8.1 *(2021-08-23)* +---------------------------- + + * Fixed a glitch related to saving notes into files + * Some translation improvements + +Version 6.8.0 *(2021-05-21)* +---------------------------- + + * Allow locking notes with passwords + * Adding a 60% and 90% font size + * Some stability and translation improvements + +Version 6.7.1 *(2021-04-20)* +---------------------------- + + * Fixed some issues related to notes being synced with files + * Some stability and translation improvements + +Version 6.7.0 *(2021-03-21)* +---------------------------- + + * Removed the Storage permission on Android 9+, notes synced to files have to be set up again + * Limit file size to 1 MB in all cases + * Some design, stability and translation improvements + +Version 6.6.2 *(2021-02-20)* +---------------------------- + + * Added a White theme with special handling + * Some stability and translation improvements + +Version 6.6.1 *(2021-01-22)* +---------------------------- + + * Allow quickly moving checklist items at the top or bottom (by tanvir-ahmod) + * Fixing a glitch at sharing checklists + * Make sure undo/redo work properly + * Some translation and stability improvements + +Version 6.6.0 *(2021-01-10)* +---------------------------- + + * Properly handle importing checklist type of files + * Adding a way to quickly remove done checklist items (by tanvir-ahmod) + * Some stability, translation and UX improvements + +Version 6.5.6 *(2020-11-04)* +---------------------------- + + * Properly handle printing text with hashtag in it + * Added some translation and stability improvements + +Version 6.5.5 *(2020-10-29)* +---------------------------- + + * Allow printing notes + * Added some translation and stability improvements + +Version 6.5.4 *(2020-09-19)* +---------------------------- + + * Allow creating a new note from the Open Note dialog + * Added some translation and UX improvements + +Version 6.5.3 *(2020-05-30)* +---------------------------- + + * Adding a crashfix + +Version 6.5.2 *(2020-05-28)* +---------------------------- + + * Add a bigger range of available font sizes + * Use a nicer app icon on older devices + * Fix bad looking text on checklist items + * A couple other UI, stability and translation improvements + +Version 6.5.1 *(2020-04-20)* +---------------------------- + + * Fix showing the keyboard on startup, if selected so + * Added rounded corners at the widget + * Show a hint at the main screens textview, if empty + +Version 6.5.0 *(2020-03-29)* +---------------------------- + + * Added Search at plain text notes + * Limiting some features on new installs to slowly get rid of the Storage permission + * Handling some file related intents with Scoped Storage + * Couple translation and UI improvements + +Version 6.4.1 *(2020-03-08)* +---------------------------- + + * Allow importing text as checklist items split at new lines + * Fixed some crashes at importing text with special characters + * Other stability and translation improvements + +Version 6.4.0 *(2020-01-30)* +---------------------------- + + * Properly color some elements at using light themes + * Some translation improvements + +Version 6.3.1 *(2020-01-04)* +---------------------------- + + * Fixed some B&W theme related issues + * Added some UI refreshments and translation improvements + +Version 6.3.0 *(2019-12-08)* +---------------------------- + + * Allow reordering checklist items by dragging, once selection mode by long pressing is activated + * Added a new settings item for moving undone checklist items at the top automatically + * Properly apply the selected gravity and font size at checklist items + * Allow just changing a letter case at renaming a note + * Some other UX, stability and translation improvements + +Version 6.2.1 *(2019-10-28)* +---------------------------- + + * Show the widget color changing button in the app settings only if there aren't multiple widgets active + * Fixed some smaller glitches + * Some stability and translation improvements + +Version 6.2.0 *(2019-09-16)* +---------------------------- + + * Fixed a glitch with note content getting trimmed in some cases + +Version 6.1.7 *(2019-08-19)* +---------------------------- + + * Allow using different text and background color per widget + * Fixed some light theme related issues + +Version 6.1.6 *(2019-07-26)* +---------------------------- + + * Fixed widget scrolling + +Version 6.1.5 *(2019-07-25)* +---------------------------- + + * Fixed widget text being cut in some cases (by herou) + * Added some dark theme related improvements + * Allow customizing the bottom navigation bar color + +Version 6.1.4 *(2019-06-14)* +---------------------------- + + * Reduced the max file size to be imported from 10 MB to 1 MB + * Some stability and translation improvements + +Version 6.1.3 *(2019-03-09)* +---------------------------- + + * Fixed saving notes to files on SD cards + * Allow syncing notes with files at mass exporting + +Version 6.1.2 *(2019-01-26)* +---------------------------- + + * Fixed some checklist widget related glitches + +Version 6.1.1 *(2018-12-27)* +---------------------------- + + * Allow adding multiple checklist items at once + * Fix exporting notes on SD cards + * Added some warnings related to some launchers not handling icon customization properly + * Some translation improvements + +Version 6.1.0 *(2018-12-09)* +---------------------------- + + * Added a Checklist type of note + * Fixed some glitches around creating new notes from files/texts + +Version 6.0.1 *(2018-11-16)* +---------------------------- + + * Fixed a glitch with disappearing note value under some circumstances + * Some translation and stability improvements + +Version 6.0.0 *(2018-11-08)* +---------------------------- + + * Initial Pro version + +Version 5.0.3 *(2018-11-28)* +---------------------------- + + * Make sure the "Upgrade to Pro" popup isn't shown at first launch + * This version of the app is no longer maintained, please upgrade to the Pro version. It is free till Nov 15 2018. You can find the Upgrade button at the top of the app Settings. + +Version 5.0.2 *(2018-11-07)* +---------------------------- + + * Couple stability and translation improvements + +Version 5.0.1 *(2018-10-26)* +---------------------------- + + * Improve the "Export as file" function, allow keeping the note in sync with file + * Couple stability and translation improvements + +Version 5.0.0 *(2018-10-19)* +---------------------------- + + * Increase the minimal required Android OS version to 5 + * Replaced G+ button with Reddit + * Adding an option to use Incognito mode of keyboards + +Version 4.3.0 *(2018-09-13)* +---------------------------- + + * Allow creating separate widgets per notes + * Added a discard dialog at unsaved changes with autosave disabled + * Some bugfixes and UX improvements + Version 4.2.0 *(2018-08-10)* ---------------------------- diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000..0730468ba --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,8 @@ +### Reporting +Before you report something, read the reporting rules [here](https://github.com/SimpleMobileTools/General-Discussion#how-do-i-suggest-an-improvement-ask-a-question-or-report-an-issue) please. + +### Contributing as a developer +Some instructions about code style and everything that has to be done to increase the change of your code getting accepted can be found at the [General Discussion](https://github.com/SimpleMobileTools/General-Discussion#contribution-rules-for-developers) section. + +### Contributing as a non developer +In case you just want to for example improve a translation, you can find the way of doing it [here](https://github.com/SimpleMobileTools/General-Discussion#how-can-i-suggest-an-edit-to-a-file). diff --git a/LICENSE b/LICENSE index ff97af7d9..f288702d2 100644 --- a/LICENSE +++ b/LICENSE @@ -1,201 +1,674 @@ - 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 2017 SimpleMobileTools - - 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. + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program 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. + + This program 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 this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md index 652cffe3c..08ca2c6dc 100644 --- a/README.md +++ b/README.md @@ -1,37 +1,38 @@ # Simple Notes -Logo +Logo -A simple textfield for adding quick notes. +★ Need to take a quick note to make a shopping list, reminder for an address, or a startup idea? Then look no further as this is the simple organizer tool you've been looking for : Simple Notes: To-do list organizer and planner! The best of note taking apps and sticky notes free for android mobile phones. No complicated setup steps needed, just tap the screen and type in what you came for and create notes, quick lists, checklist or backup for any idea. With your simple personal notebook you can remember anything fast! Shopping list for groceries, to-do list for your daily agenda and easier note-taking to make setting up meetings a walk in the park ★ -Need to take a quick note of something to buy, an address, or a startup idea? Then this is the app you've been looking for! No complicated setup steps needed, just type in what you came for. Comes with autosave, so you will not discard your changes by mistake. Supports creating multiple independent notes. +Simple notes planner is quick, simple to use organizer and remarkable note-taking colorful widget and it will serve as an invaluable tool helping you to remember necessary pieces of information or shopping list in the mall! -You can access the note in no time by using the customizable and resizable widget, which opens the app on click. +Our reminder agenda planner tool allows you to keep track of your duties, create daily sticky ideas and shopping list for items or ideas with unprecedented simplicity, notability and unrivaled time-saving value. Manage your schedule with proper and good notes - use one of our note-taking apps - Simple Notes or Simple Notes Pro :) + +Simple Notes Pro: To-do list organizer and planner note-taking reminder tool comes with an autosave so you will not discard your changes by mistake. It also supports creating multiple independent plain text notes and lists very fast. + +You can easily access your lists and organize your to-do list not notepad in no time by using the customizable and resizable widget, which opens the goodnotes organization apps on tap. + +It is user friendly and contains absolutely no ads or unnecessary permissions - no strings attached. It is fully opensource goodnotes widget, provides customizable colors which can be adjusted with quick and fast tweaking. + +Simple Notes: To-do list organizer and planner is the best item organizer and note taking apps you can use with no ads. If you need a high quality organizer for quick, reliable & good notepad, a simple shopping list reminder that is truly easy to use. Download our note-taking apps right now :) Have your own personal memo apps in your pocket every day and have a backup planner so you will not have to worry about forgetting an important meeting or your shopping list :) + +It comes with material design and dark theme by default, provides great user experience for easy usage. The lack of internet access gives you more privacy, security and stability than other apps. Contains no ads or unnecessary permissions. It is fully opensource, provides customizable colors. -This app is just one piece of a bigger series of apps. You can find the rest of them at http://www.simplemobiletools.com +Get it on F-Droid -Get it on Google Play -Get it on F-Droid +Support us: +IBAN: SK4083300000002000965231 +Bitcoin: 19Hc8A7sWGud8sP19VXDC5a5j28UyJfpyJ +Ethereum: 0xB7a2DD6f2408Bce77334655CF5E7639aE31feb30 +Litecoin: LYACbHTKaM9ZubKQGxJ4NRyVy1gHUuztRP +Bitcoin Cash: qz6dvmhq5vzkcsypxpp2mnur30muxdah4gvulx3y85 +Tether: 0x250f9cC32863E59b87037a14955Ed64F879653F0 +PayPal +Patreon
-App image -App image -App image +App image +App image +App image
- -License -------- - Copyright 2016-present SimpleMobileTools - - 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. diff --git a/app/build.gradle b/app/build.gradle deleted file mode 100644 index 55b792cc3..000000000 --- a/app/build.gradle +++ /dev/null @@ -1,65 +0,0 @@ -apply plugin: 'com.android.application' -apply plugin: 'kotlin-android' -apply plugin: 'kotlin-android-extensions' - -android { - compileSdkVersion 28 - buildToolsVersion "28.0.2" - - defaultConfig { - applicationId "com.simplemobiletools.notes" - minSdkVersion 16 - targetSdkVersion 28 - versionCode 50 - versionName "4.2.0" - setProperty("archivesBaseName", "notes") - } - - signingConfigs { - release - } - - buildTypes { - debug { - applicationIdSuffix ".debug" - } - release { - minifyEnabled true - proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' - signingConfig signingConfigs.release - } - } - - sourceSets { - main.java.srcDirs += 'src/main/kotlin' - } - - lintOptions { - checkReleaseBuilds false - abortOnError false - } -} - -dependencies { - implementation 'com.simplemobiletools:commons:4.7.5' - implementation 'com.facebook.stetho:stetho:1.5.0' -} - -Properties props = new Properties() -def propFile = new File('signing.properties') -if (propFile.canRead()) { - props.load(new FileInputStream(propFile)) - - if (props != null && props.containsKey('STORE_FILE') && props.containsKey('KEY_ALIAS') && props.containsKey('PASSWORD')) { - android.signingConfigs.release.storeFile = file(props['STORE_FILE']) - android.signingConfigs.release.storePassword = props['PASSWORD'] - android.signingConfigs.release.keyAlias = props['KEY_ALIAS'] - android.signingConfigs.release.keyPassword = props['PASSWORD'] - } else { - println 'signing.properties found but some entries are missing' - android.buildTypes.release.signingConfig = null - } -} else { - println 'signing.properties not found' - android.buildTypes.release.signingConfig = null -} diff --git a/app/build.gradle.kts b/app/build.gradle.kts new file mode 100644 index 000000000..8e504b5ac --- /dev/null +++ b/app/build.gradle.kts @@ -0,0 +1,106 @@ +import java.io.FileInputStream +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile +import org.jetbrains.kotlin.konan.properties.Properties + +plugins { + alias(libs.plugins.android) + alias(libs.plugins.kotlinAndroid) + alias(libs.plugins.ksp) + alias(libs.plugins.kotlinSerialization) + base +} + +base { + archivesName.set("notes") +} + +val keystorePropertiesFile: File = rootProject.file("keystore.properties") +val keystoreProperties = Properties() +if (keystorePropertiesFile.exists()) { + keystoreProperties.load(FileInputStream(keystorePropertiesFile)) +} + +android { + compileSdk = project.libs.versions.app.build.compileSDKVersion.get().toInt() + + defaultConfig { + applicationId = libs.versions.app.version.appId.get() + minSdk = project.libs.versions.app.build.minimumSDK.get().toInt() + targetSdk = project.libs.versions.app.build.targetSDK.get().toInt() + versionName = project.libs.versions.app.version.versionName.get() + versionCode = project.libs.versions.app.version.versionCode.get().toInt() + ksp { + arg("room.schemaLocation", "$projectDir/schemas") + } + } + + signingConfigs { + if (keystorePropertiesFile.exists()) { + register("release") { + keyAlias = keystoreProperties.getProperty("keyAlias") + keyPassword = keystoreProperties.getProperty("keyPassword") + storeFile = file(keystoreProperties.getProperty("storeFile")) + storePassword = keystoreProperties.getProperty("storePassword") + } + } + } + + buildFeatures { + viewBinding = true + buildConfig = true + } + + buildTypes { + debug { + applicationIdSuffix = ".debug" + } + release { + isMinifyEnabled = true + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro" + ) + if (keystorePropertiesFile.exists()) { + signingConfig = signingConfigs.getByName("release") + } + } + } + + flavorDimensions.add("variants") + productFlavors { + register("core") + register("fdroid") + register("prepaid") + } + + sourceSets { + getByName("main").java.srcDirs("src/main/kotlin") + } + + compileOptions { + val currentJavaVersionFromLibs = JavaVersion.valueOf(libs.versions.app.build.javaVersion.get().toString()) + sourceCompatibility = currentJavaVersionFromLibs + targetCompatibility = currentJavaVersionFromLibs + } + + tasks.withType { + kotlinOptions.jvmTarget = project.libs.versions.app.build.kotlinJVMTarget.get() + } + + namespace = libs.versions.app.version.appId.get() + + lint { + checkReleaseBuilds = false + abortOnError = false + } +} + +dependencies { + implementation(libs.simple.tools.commons) + implementation(libs.androidx.constraintlayout) + implementation(libs.androidx.documentfile) + implementation(libs.kotlinx.serialization.json) + + implementation(libs.bundles.room) + ksp(libs.androidx.room.compiler) +} diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro index e69de29bb..10b9d3110 100644 --- a/app/proguard-rules.pro +++ b/app/proguard-rules.pro @@ -0,0 +1,33 @@ +-keep class com.simplemobiletools.notes.pro.models.* { + ; +} + +# Keep `Companion` object fields of serializable classes. +# This avoids serializer lookup through `getDeclaredClasses` as done for named companion objects. +-if @kotlinx.serialization.Serializable class ** +-keepclassmembers class <1> { + static <1>$Companion Companion; +} + +# Keep `serializer()` on companion objects (both default and named) of serializable classes. +-if @kotlinx.serialization.Serializable class ** { + static **$* *; +} +-keepclassmembers class <2>$<3> { + kotlinx.serialization.KSerializer serializer(...); +} + +# Keep `INSTANCE.serializer()` of serializable objects. +-if @kotlinx.serialization.Serializable class ** { + public static ** INSTANCE; +} +-keepclassmembers class <1> { + public static <1> INSTANCE; + kotlinx.serialization.KSerializer serializer(...); +} + +# Needed for using TypeToken with Gson +# Taken from: https://r8.googlesource.com/r8/+/refs/heads/main/compatibility-faq.md#troubleshooting-gson-gson +-keepattributes Signature +-keep class com.google.gson.reflect.TypeToken { *; } +-keep class * extends com.google.gson.reflect.TypeToken diff --git a/app/schemas/com.simplemobiletools.notes.pro.databases.NotesDatabase/4.json b/app/schemas/com.simplemobiletools.notes.pro.databases.NotesDatabase/4.json new file mode 100644 index 000000000..976d803f3 --- /dev/null +++ b/app/schemas/com.simplemobiletools.notes.pro.databases.NotesDatabase/4.json @@ -0,0 +1,140 @@ +{ + "formatVersion": 1, + "database": { + "version": 4, + "identityHash": "e470b6e1411ee6659417cf4dbe54f453", + "entities": [ + { + "tableName": "notes", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `title` TEXT NOT NULL, `value` TEXT NOT NULL, `type` INTEGER NOT NULL, `path` TEXT NOT NULL, `protection_type` INTEGER NOT NULL, `protection_hash` TEXT NOT NULL)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "path", + "columnName": "path", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "protectionType", + "columnName": "protection_type", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "protectionHash", + "columnName": "protection_hash", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_notes_id", + "unique": true, + "columnNames": [ + "id" + ], + "orders": [], + "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_notes_id` ON `${TABLE_NAME}` (`id`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "widgets", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `widget_id` INTEGER NOT NULL, `note_id` INTEGER NOT NULL, `widget_bg_color` INTEGER NOT NULL, `widget_text_color` INTEGER NOT NULL, `widget_show_title` INTEGER NOT NULL)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "widgetId", + "columnName": "widget_id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "noteId", + "columnName": "note_id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "widgetBgColor", + "columnName": "widget_bg_color", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "widgetTextColor", + "columnName": "widget_text_color", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "widgetShowTitle", + "columnName": "widget_show_title", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_widgets_widget_id", + "unique": true, + "columnNames": [ + "widget_id" + ], + "orders": [], + "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_widgets_widget_id` ON `${TABLE_NAME}` (`widget_id`)" + } + ], + "foreignKeys": [] + } + ], + "views": [], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'e470b6e1411ee6659417cf4dbe54f453')" + ] + } +} \ No newline at end of file diff --git a/app/src/fdroid/res/values/bools.xml b/app/src/fdroid/res/values/bools.xml new file mode 100644 index 000000000..ac02880ed --- /dev/null +++ b/app/src/fdroid/res/values/bools.xml @@ -0,0 +1,6 @@ + + + true + true + true + diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 2592348ac..67cc4ec4f 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -1,337 +1,393 @@ - - + android:name="android.permission.WRITE_EXTERNAL_STORAGE" + android:maxSdkVersion="28" /> + + + + + + + + + + + + android:exported="false" + android:launchMode="singleTask" + android:theme="@style/SplashTheme" /> + android:name=".activities.MainActivity" + android:configChanges="orientation" + android:exported="true" + android:launchMode="singleTask"> - - - + + + - - - + + + - + + android:parentActivityName=".activities.MainActivity" /> - - - - + android:parentActivityName=".activities.SettingsActivity" /> + android:parentActivityName=".activities.MainActivity"> + + + + + + + android:exported="true" + android:permission="android.permission.BIND_REMOTEVIEWS" /> - + + android:resource="@xml/widget_info" /> + + + + + + + + + + + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/activities/MainActivity.kt b/app/src/main/kotlin/com/simplemobiletools/notes/activities/MainActivity.kt deleted file mode 100644 index b953ea5ae..000000000 --- a/app/src/main/kotlin/com/simplemobiletools/notes/activities/MainActivity.kt +++ /dev/null @@ -1,638 +0,0 @@ -package com.simplemobiletools.notes.activities - -import android.content.Intent -import android.net.Uri -import android.os.Bundle -import android.support.v4.view.ViewPager -import android.text.method.ArrowKeyMovementMethod -import android.text.method.LinkMovementMethod -import android.util.TypedValue -import android.view.ActionMode -import android.view.Gravity -import android.view.Menu -import android.view.MenuItem -import com.simplemobiletools.commons.dialogs.ConfirmationAdvancedDialog -import com.simplemobiletools.commons.dialogs.FilePickerDialog -import com.simplemobiletools.commons.dialogs.RadioGroupDialog -import com.simplemobiletools.commons.extensions.* -import com.simplemobiletools.commons.helpers.* -import com.simplemobiletools.commons.models.FAQItem -import com.simplemobiletools.commons.models.FileDirItem -import com.simplemobiletools.commons.models.RadioItem -import com.simplemobiletools.commons.models.Release -import com.simplemobiletools.commons.views.MyEditText -import com.simplemobiletools.notes.BuildConfig -import com.simplemobiletools.notes.R -import com.simplemobiletools.notes.adapters.NotesPagerAdapter -import com.simplemobiletools.notes.dialogs.* -import com.simplemobiletools.notes.extensions.config -import com.simplemobiletools.notes.extensions.dbHelper -import com.simplemobiletools.notes.extensions.getTextSize -import com.simplemobiletools.notes.extensions.updateWidget -import com.simplemobiletools.notes.helpers.MIME_TEXT_PLAIN -import com.simplemobiletools.notes.helpers.OPEN_NOTE_ID -import com.simplemobiletools.notes.helpers.TYPE_NOTE -import com.simplemobiletools.notes.models.Note -import kotlinx.android.synthetic.main.activity_main.* -import java.io.File -import java.nio.charset.Charset - -class MainActivity : SimpleActivity(), ViewPager.OnPageChangeListener { - private var mAdapter: NotesPagerAdapter? = null - - lateinit var mCurrentNote: Note - private var mNotes = ArrayList() - - private var noteViewWithTextSelected: MyEditText? = null - private var wasInit = false - private var storedEnableLineWrap = true - private var showSaveButton = false - private var showUndoButton = false - private var showRedoButton = false - private var saveNoteButton: MenuItem? = null - - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_main) - appLaunched(BuildConfig.APPLICATION_ID) - - initViewPager() - - pager_title_strip.setTextSize(TypedValue.COMPLEX_UNIT_PX, getTextSize()) - pager_title_strip.layoutParams.height = (pager_title_strip.height + resources.getDimension(R.dimen.activity_margin) * 2).toInt() - checkWhatsNewDialog() - - intent.apply { - if (action == Intent.ACTION_SEND && type == MIME_TEXT_PLAIN) { - getStringExtra(Intent.EXTRA_TEXT)?.let { - handleText(it) - intent.removeExtra(Intent.EXTRA_TEXT) - } - } - - if (action == Intent.ACTION_VIEW) { - handleUri(data) - intent.removeCategory(Intent.CATEGORY_DEFAULT) - intent.action = null - } - } - - storeStateVariables() - if (config.showNotePicker && savedInstanceState == null) { - displayOpenNoteDialog() - } - - wasInit = true - checkAppOnSDCard() - } - - override fun onResume() { - super.onResume() - if (storedEnableLineWrap != config.enableLineWrap) { - initViewPager() - } - - invalidateOptionsMenu() - pager_title_strip.apply { - setTextSize(TypedValue.COMPLEX_UNIT_PX, getTextSize()) - setGravity(Gravity.CENTER_VERTICAL) - setNonPrimaryAlpha(0.4f) - setTextColor(config.textColor) - } - updateTextColors(view_pager) - } - - override fun onPause() { - super.onPause() - storeStateVariables() - } - - override fun onCreateOptionsMenu(menu: Menu): Boolean { - menuInflater.inflate(R.menu.menu, menu) - menu.apply { - findItem(R.id.undo).isVisible = showUndoButton - findItem(R.id.redo).isVisible = showRedoButton - } - - return true - } - - override fun onPrepareOptionsMenu(menu: Menu): Boolean { - val shouldBeVisible = mNotes.size > 1 - menu.apply { - findItem(R.id.rename_note).isVisible = shouldBeVisible - findItem(R.id.open_note).isVisible = shouldBeVisible - findItem(R.id.delete_note).isVisible = shouldBeVisible - findItem(R.id.export_all_notes).isVisible = shouldBeVisible - - saveNoteButton = findItem(R.id.save_note) - saveNoteButton!!.isVisible = !config.autosaveNotes && showSaveButton - } - - pager_title_strip.beVisibleIf(shouldBeVisible) - return super.onPrepareOptionsMenu(menu) - } - - override fun onOptionsItemSelected(item: MenuItem): Boolean { - if (config.autosaveNotes) { - saveCurrentNote(false) - } - - when (item.itemId) { - R.id.open_note -> displayOpenNoteDialog() - R.id.save_note -> saveNote() - R.id.undo -> undo() - R.id.redo -> redo() - R.id.new_note -> displayNewNoteDialog() - R.id.rename_note -> displayRenameDialog() - R.id.share -> shareText() - R.id.open_file -> tryOpenFile() - R.id.import_folder -> tryOpenFolder() - R.id.export_as_file -> tryExportAsFile() - R.id.export_all_notes -> tryExportAllNotes() - R.id.delete_note -> displayDeleteNotePrompt() - R.id.settings -> startActivity(Intent(applicationContext, SettingsActivity::class.java)) - R.id.about -> launchAbout() - else -> return super.onOptionsItemSelected(item) - } - return true - } - - // https://code.google.com/p/android/issues/detail?id=191430 quickfix - override fun onActionModeStarted(mode: ActionMode?) { - super.onActionModeStarted(mode) - if (wasInit) { - currentNotesView()?.apply { - if (config.clickableLinks || movementMethod is LinkMovementMethod) { - movementMethod = ArrowKeyMovementMethod.getInstance() - noteViewWithTextSelected = this - } - } - } - } - - override fun onActionModeFinished(mode: ActionMode?) { - super.onActionModeFinished(mode) - if (config.clickableLinks) { - noteViewWithTextSelected?.movementMethod = LinkMovementMethod.getInstance() - } - } - - override fun onBackPressed() { - if (!config.autosaveNotes && mAdapter?.anyHasUnsavedChanges() == true) { - ConfirmationAdvancedDialog(this, "", R.string.unsaved_changes_warning, R.string.save, R.string.discard) { - if (it) { - mAdapter?.saveAllFragmentTexts() - super.onBackPressed() - } else { - super.onBackPressed() - } - } - } else { - super.onBackPressed() - } - } - - private fun storeStateVariables() { - config.apply { - storedEnableLineWrap = enableLineWrap - } - } - - private fun handleText(text: String) { - val notes = dbHelper.getNotes() - val list = arrayListOf().apply { - add(RadioItem(0, getString(R.string.create_new_note))) - notes.forEachIndexed { index, note -> - add(RadioItem(index + 1, note.title)) - } - } - - RadioGroupDialog(this, list, -1, R.string.add_to_note) { - if (it as Int == 0) { - displayNewNoteDialog(text) - } else { - updateSelectedNote(notes[it - 1].id) - addTextToCurrentNote(if (mCurrentNote.value.isEmpty()) text else "\n$text") - } - } - } - - private fun handleUri(uri: Uri) { - val id = dbHelper.getNoteId(uri.path) - - if (dbHelper.isValidId(id)) { - updateSelectedNote(id) - return - } - - handlePermission(PERMISSION_WRITE_STORAGE) { - if (it) { - importFileWithSync(uri) - } - } - } - - private fun initViewPager() { - mNotes = dbHelper.getNotes() - mCurrentNote = mNotes[0] - var wantedNoteId = intent.getIntExtra(OPEN_NOTE_ID, -1) - if (wantedNoteId == -1) { - wantedNoteId = config.currentNoteId - } - - val itemIndex = getNoteIndexWithId(wantedNoteId) - - mAdapter = NotesPagerAdapter(supportFragmentManager, mNotes, this) - view_pager.apply { - adapter = mAdapter - currentItem = itemIndex - addOnPageChangeListener(this@MainActivity) - } - - if (!config.showKeyboard) { - hideKeyboard() - } - } - - private fun currentNotesView() = if (view_pager == null) { - null - } else { - mAdapter?.getCurrentNotesView(view_pager.currentItem) - } - - private fun displayRenameDialog() { - RenameNoteDialog(this, mCurrentNote) { - mCurrentNote = it - initViewPager() - } - } - - private fun updateSelectedNote(id: Int) { - config.currentNoteId = id - val index = getNoteIndexWithId(id) - view_pager.currentItem = index - mCurrentNote = mNotes[index] - } - - private fun displayNewNoteDialog(value: String = "") { - NewNoteDialog(this, dbHelper) { - val newNote = Note(0, it, value, TYPE_NOTE) - addNewNote(newNote) - } - } - - private fun addNewNote(note: Note) { - val id = dbHelper.insertNote(note) - mNotes = dbHelper.getNotes() - showSaveButton = false - invalidateOptionsMenu() - initViewPager() - updateSelectedNote(id) - view_pager.onGlobalLayout { - mAdapter?.focusEditText(getNoteIndexWithId(id)) - } - } - - private fun launchAbout() { - val licenses = LICENSE_STETHO or LICENSE_RTL or LICENSE_LEAK_CANARY - - val faqItems = arrayListOf( - FAQItem(R.string.faq_1_title_commons, R.string.faq_1_text_commons), - FAQItem(R.string.faq_4_title_commons, R.string.faq_4_text_commons), - FAQItem(R.string.faq_2_title_commons, R.string.faq_2_text_commons) - ) - - startAboutActivity(R.string.app_name, licenses, BuildConfig.VERSION_NAME, faqItems, true) - } - - private fun tryOpenFile() { - handlePermission(PERMISSION_WRITE_STORAGE) { - if (it) { - openFile() - } - } - } - - private fun openFile() { - FilePickerDialog(this) { - openFile(it, true) { - OpenFileDialog(this, it.path) { - addNewNote(it) - } - } - } - } - - private fun openFile(path: String, checkTitle: Boolean, onChecksPassed: (file: File) -> Unit) { - val file = File(path) - if (path.isMediaFile()) { - toast(R.string.invalid_file_format) - } else if (file.length() > 10 * 1000 * 1000) { - toast(R.string.file_too_large) - } else if (checkTitle && dbHelper.doesTitleExist(path.getFilenameFromPath())) { - toast(R.string.title_taken) - } else { - onChecksPassed(file) - } - } - - private fun openFolder(path: String, onChecksPassed: (file: File) -> Unit) { - val file = File(path) - if (file.isDirectory) { - onChecksPassed(file) - } - } - - private fun importFileWithSync(uri: Uri) { - when (uri.scheme) { - "file" -> openPath(uri.path) - "content" -> { - val realPath = getRealPathFromURI(uri) - if (realPath != null) { - openPath(realPath) - } else { - R.string.unknown_error_occurred - } - } - } - } - - private fun openPath(path: String) { - openFile(path, false) { - var title = path.getFilenameFromPath() - if (dbHelper.doesTitleExist(title)) - title += " (file)" - - val note = Note(0, title, "", TYPE_NOTE, path) - addNewNote(note) - } - } - - private fun tryOpenFolder() { - handlePermission(PERMISSION_READ_STORAGE) { - if (it) { - openFolder() - } - } - } - - private fun openFolder() { - FilePickerDialog(this, pickFile = false) { - openFolder(it) { - ImportFolderDialog(this, it.path) { - mNotes = dbHelper.getNotes() - showSaveButton = false - invalidateOptionsMenu() - initViewPager() - updateSelectedNote(it) - view_pager.onGlobalLayout { - mAdapter?.focusEditText(getNoteIndexWithId(it)) - } - } - } - } - } - - private fun tryExportAsFile() { - handlePermission(PERMISSION_WRITE_STORAGE) { - if (it) { - exportAsFile() - } - } - } - - private fun exportAsFile() { - ExportFileDialog(this, mCurrentNote) { - if (getCurrentNoteText()?.isNotEmpty() == true) { - exportNoteValueToFile(it, getCurrentNoteText()!!, true) - } - } - } - - private fun tryExportAllNotes() { - handlePermission(PERMISSION_WRITE_STORAGE) { - if (it) { - exportAllNotes() - } - } - } - - private fun exportAllNotes() { - ExportFilesDialog(this, mNotes) { parent, extension -> - var failCount = 0 - mNotes = dbHelper.getNotes() - mNotes.forEachIndexed { index, note -> - val filename = if (extension.isEmpty()) note.title else "${note.title}.$extension" - val file = File(parent, filename) - if (!filename.isAValidFilename()) { - toast(String.format(getString(R.string.filename_invalid_characters_placeholder, filename))) - } else { - exportNoteValueToFile(file.absolutePath, note.value, false) { - if (!it) { - failCount++ - } - - if (index == mNotes.size - 1) { - toast(if (failCount == 0) R.string.exporting_successful else R.string.exporting_some_entries_failed) - } - } - } - } - } - } - - fun exportNoteValueToFile(path: String, content: String, showSuccessToasts: Boolean, callback: ((success: Boolean) -> Unit)? = null) { - try { - if (getIsPathDirectory(path)) { - toast(R.string.name_taken) - return - } - - if (needsStupidWritePermissions(path)) { - handleSAFDialog(path) { - var document = getDocumentFile(path) ?: return@handleSAFDialog - if (!getDoesFilePathExist(path)) { - document = document.createFile("", path.getFilenameFromPath()) - } - contentResolver.openOutputStream(document.uri).apply { - write(content.toByteArray(Charset.forName("UTF-8")), 0, content.length) - flush() - close() - } - if (showSuccessToasts) { - noteExportedSuccessfully(path.getFilenameFromPath()) - } - callback?.invoke(true) - } - } else { - val file = File(path) - file.printWriter().use { out -> - out.write(content) - } - if (showSuccessToasts) { - noteExportedSuccessfully(path.getFilenameFromPath()) - } - callback?.invoke(true) - } - } catch (e: Exception) { - showErrorToast(e) - callback?.invoke(false) - } - } - - private fun noteExportedSuccessfully(title: String) { - val message = String.format(getString(R.string.note_exported_successfully), title) - toast(message) - } - - fun noteSavedSuccessfully(title: String) { - if (config.displaySuccess) { - val message = String.format(getString(R.string.note_saved_successfully), title) - toast(message) - } - } - - private fun getCurrentNoteText() = (view_pager.adapter as NotesPagerAdapter).getCurrentNoteViewText(view_pager.currentItem) - - private fun addTextToCurrentNote(text: String) = (view_pager.adapter as NotesPagerAdapter).appendText(view_pager.currentItem, text) - - private fun saveCurrentNote(force: Boolean) = (view_pager.adapter as NotesPagerAdapter).saveCurrentNote(view_pager.currentItem, force) - - private fun displayDeleteNotePrompt() { - DeleteNoteDialog(this, mCurrentNote) { - deleteNote(it) - } - } - - fun deleteNote(deleteFile: Boolean) { - if (mNotes.size <= 1) { - return - } - - if (!deleteFile) { - doDeleteNote(mCurrentNote, deleteFile) - } else { - handleSAFDialog(mCurrentNote.path) { - doDeleteNote(mCurrentNote, deleteFile) - } - } - } - - private fun doDeleteNote(note: Note, deleteFile: Boolean) { - dbHelper.deleteNote(mCurrentNote.id) - mNotes = dbHelper.getNotes() - - val firstNoteId = mNotes[0].id - updateSelectedNote(firstNoteId) - if (config.widgetNoteId == note.id) { - config.widgetNoteId = mCurrentNote.id - updateWidget() - } - invalidateOptionsMenu() - initViewPager() - - if (deleteFile) { - deleteFile(FileDirItem(note.path, note.title)) { - if (!it) { - toast(R.string.unknown_error_occurred) - } - } - } - } - - private fun displayOpenNoteDialog() { - OpenNoteDialog(this) { - updateSelectedNote(it) - } - } - - private fun saveNote() { - saveCurrentNote(true) - showSaveButton = false - invalidateOptionsMenu() - } - - private fun undo() { - mAdapter?.undo(view_pager.currentItem) - } - - private fun redo() { - mAdapter?.redo(view_pager.currentItem) - } - - private fun getNoteIndexWithId(id: Int): Int { - for (i in 0 until mNotes.count()) { - if (mNotes[i].id == id) { - mCurrentNote = mNotes[i] - return i - } - } - return 0 - } - - private fun shareText() { - val text = getCurrentNoteText() - if (text == null || text.isEmpty()) { - toast(R.string.cannot_share_empty_text) - return - } - - val res = resources - val shareTitle = res.getString(R.string.share_via) - Intent().apply { - action = Intent.ACTION_SEND - putExtra(Intent.EXTRA_SUBJECT, mCurrentNote.title) - putExtra(Intent.EXTRA_TEXT, text) - type = "text/plain" - startActivity(Intent.createChooser(this, shareTitle)) - } - } - - override fun onPageScrollStateChanged(state: Int) { - } - - override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { - } - - override fun onPageSelected(position: Int) { - mCurrentNote = mNotes[position] - config.currentNoteId = mCurrentNote.id - } - - fun currentNoteTextChanged(newText: String, showUndo: Boolean, showRedo: Boolean) { - var shouldRecreateMenu = false - if (showUndo != showUndoButton) { - showUndoButton = showUndo - shouldRecreateMenu = true - } - - if (showRedo != showRedoButton) { - showRedoButton = showRedo - shouldRecreateMenu = true - } - - if (!config.autosaveNotes) { - showSaveButton = newText != mCurrentNote.value - if (showSaveButton != saveNoteButton?.isVisible) { - shouldRecreateMenu = true - } - } - - if (shouldRecreateMenu) { - invalidateOptionsMenu() - } - } - - private fun checkWhatsNewDialog() { - arrayListOf().apply { - add(Release(25, R.string.release_25)) - add(Release(28, R.string.release_28)) - add(Release(29, R.string.release_29)) - add(Release(39, R.string.release_39)) - add(Release(45, R.string.release_45)) - add(Release(49, R.string.release_49)) - checkWhatsNew(this, BuildConfig.VERSION_CODE) - } - } -} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/activities/SettingsActivity.kt b/app/src/main/kotlin/com/simplemobiletools/notes/activities/SettingsActivity.kt deleted file mode 100644 index 4ae4ccc76..000000000 --- a/app/src/main/kotlin/com/simplemobiletools/notes/activities/SettingsActivity.kt +++ /dev/null @@ -1,241 +0,0 @@ -package com.simplemobiletools.notes.activities - -import android.content.Intent -import android.content.res.Resources -import android.os.Bundle -import android.view.View -import com.simplemobiletools.commons.dialogs.RadioGroupDialog -import com.simplemobiletools.commons.extensions.* -import com.simplemobiletools.commons.helpers.IS_CUSTOMIZING_COLORS -import com.simplemobiletools.commons.models.RadioItem -import com.simplemobiletools.notes.R -import com.simplemobiletools.notes.extensions.config -import com.simplemobiletools.notes.extensions.dbHelper -import com.simplemobiletools.notes.extensions.updateWidget -import com.simplemobiletools.notes.helpers.* -import com.simplemobiletools.notes.models.Note -import kotlinx.android.synthetic.main.activity_settings.* -import java.util.* - -class SettingsActivity : SimpleActivity() { - lateinit var res: Resources - var notes = ArrayList() - - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_settings) - res = resources - notes = dbHelper.getNotes() - } - - override fun onResume() { - super.onResume() - - setupPurchaseThankYou() - setupCustomizeColors() - setupUseEnglish() - setupAvoidWhatsNew() - setupAutosaveNotes() - setupDisplaySuccess() - setupClickableLinks() - setupMonospacedFont() - setupShowKeyboard() - setupShowNotePicker() - setupShowWordCount() - setupEnableLineWrap() - setupFontSize() - setupGravity() - setupWidgetNote() - setupCursorPlacement() - setupCustomizeWidgetColors() - updateTextColors(settings_scrollview) - setupSectionColors() - } - - private fun setupSectionColors() { - val adjustedPrimaryColor = getAdjustedPrimaryColor() - arrayListOf(text_label, startup_label, saving_label, widgets_label).forEach { - it.setTextColor(adjustedPrimaryColor) - } - } - - private fun setupPurchaseThankYou() { - settings_purchase_thank_you_holder.beVisibleIf(config.appRunCount > 10 && !isThankYouInstalled()) - settings_purchase_thank_you_holder.setOnClickListener { - launchPurchaseThankYouIntent() - } - } - - private fun setupCustomizeColors() { - settings_customize_colors_holder.setOnClickListener { - startCustomizationActivity() - } - } - - private fun setupUseEnglish() { - settings_use_english_holder.beVisibleIf(config.wasUseEnglishToggled || Locale.getDefault().language != "en") - settings_use_english.isChecked = config.useEnglish - settings_use_english_holder.setOnClickListener { - settings_use_english.toggle() - config.useEnglish = settings_use_english.isChecked - System.exit(0) - } - } - - private fun setupAvoidWhatsNew() { - settings_avoid_whats_new.isChecked = config.avoidWhatsNew - settings_avoid_whats_new_holder.setOnClickListener { - settings_avoid_whats_new.toggle() - config.avoidWhatsNew = settings_avoid_whats_new.isChecked - } - } - - private fun setupAutosaveNotes() { - settings_autosave_notes.isChecked = config.autosaveNotes - settings_autosave_notes_holder.setOnClickListener { - settings_autosave_notes.toggle() - config.autosaveNotes = settings_autosave_notes.isChecked - } - } - - private fun setupDisplaySuccess() { - settings_display_success.isChecked = config.displaySuccess - settings_display_success_holder.setOnClickListener { - settings_display_success.toggle() - config.displaySuccess = settings_display_success.isChecked - } - } - - private fun setupClickableLinks() { - settings_clickable_links.isChecked = config.clickableLinks - settings_clickable_links_holder.setOnClickListener { - settings_clickable_links.toggle() - config.clickableLinks = settings_clickable_links.isChecked - } - } - - private fun setupMonospacedFont() { - settings_monospaced_font.isChecked = config.monospacedFont - settings_monospaced_font_holder.setOnClickListener { - settings_monospaced_font.toggle() - config.monospacedFont = settings_monospaced_font.isChecked - } - } - - private fun setupShowKeyboard() { - settings_show_keyboard.isChecked = config.showKeyboard - settings_show_keyboard_holder.setOnClickListener { - settings_show_keyboard.toggle() - config.showKeyboard = settings_show_keyboard.isChecked - } - } - - private fun setupShowNotePicker() { - settings_show_note_picker_holder.beVisibleIf(notes.size > 1) - settings_show_note_picker.isChecked = config.showNotePicker - settings_show_note_picker_holder.setOnClickListener { - settings_show_note_picker.toggle() - config.showNotePicker = settings_show_note_picker.isChecked - } - } - - private fun setupShowWordCount() { - settings_show_word_count.isChecked = config.showWordCount - settings_show_word_count_holder.setOnClickListener { - settings_show_word_count.toggle() - config.showWordCount = settings_show_word_count.isChecked - } - } - - private fun setupEnableLineWrap() { - settings_enable_line_wrap.isChecked = config.enableLineWrap - settings_enable_line_wrap_holder.setOnClickListener { - settings_enable_line_wrap.toggle() - config.enableLineWrap = settings_enable_line_wrap.isChecked - } - } - - private fun setupFontSize() { - settings_font_size.text = getFontSizeText() - settings_font_size_holder.setOnClickListener { - val items = arrayListOf( - RadioItem(FONT_SIZE_SMALL, res.getString(R.string.small)), - RadioItem(FONT_SIZE_MEDIUM, res.getString(R.string.medium)), - RadioItem(FONT_SIZE_LARGE, res.getString(R.string.large)), - RadioItem(FONT_SIZE_EXTRA_LARGE, res.getString(R.string.extra_large))) - - RadioGroupDialog(this@SettingsActivity, items, config.fontSize) { - config.fontSize = it as Int - settings_font_size.text = getFontSizeText() - updateWidget() - } - } - } - - private fun getFontSizeText() = getString(when (config.fontSize) { - FONT_SIZE_SMALL -> R.string.small - FONT_SIZE_MEDIUM -> R.string.medium - FONT_SIZE_LARGE -> R.string.large - else -> R.string.extra_large - }) - - private fun setupGravity() { - settings_gravity.text = getGravityText() - settings_gravity_holder.setOnClickListener { - val items = arrayListOf( - RadioItem(GRAVITY_LEFT, res.getString(R.string.left)), - RadioItem(GRAVITY_CENTER, res.getString(R.string.center)), - RadioItem(GRAVITY_RIGHT, res.getString(R.string.right))) - - RadioGroupDialog(this@SettingsActivity, items, config.gravity) { - config.gravity = it as Int - settings_gravity.text = getGravityText() - updateWidget() - } - } - } - - private fun getGravityText() = getString(when (config.gravity) { - GRAVITY_LEFT -> R.string.left - GRAVITY_CENTER -> R.string.center - else -> R.string.right - }) - - private fun setupWidgetNote() { - if (notes.size <= 1) { - settings_widget_note_holder.visibility = View.GONE - return - } - - settings_widget_note.text = getCurrentWidgetNoteTitle(config.widgetNoteId, notes) - settings_widget_note_holder.setOnClickListener { - val items = notes.map { RadioItem(it.id, it.title) } as ArrayList - - RadioGroupDialog(this@SettingsActivity, items, config.widgetNoteId) { - config.widgetNoteId = it as Int - settings_widget_note.text = getCurrentWidgetNoteTitle(it, notes) - updateWidget() - } - } - } - - private fun setupCursorPlacement() { - settings_cursor_placement.isChecked = config.placeCursorToEnd - settings_cursor_placement_holder.setOnClickListener { - settings_cursor_placement.toggle() - config.placeCursorToEnd = settings_cursor_placement.isChecked - } - } - - private fun getCurrentWidgetNoteTitle(currentNoteId: Int, notes: List) = - notes.firstOrNull { it.id == currentNoteId }?.title ?: "" - - private fun setupCustomizeWidgetColors() { - settings_customize_widget_colors_holder.setOnClickListener { - Intent(this, WidgetConfigureActivity::class.java).apply { - putExtra(IS_CUSTOMIZING_COLORS, true) - startActivity(this) - } - } - } -} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/activities/WidgetConfigureActivity.kt b/app/src/main/kotlin/com/simplemobiletools/notes/activities/WidgetConfigureActivity.kt deleted file mode 100644 index 10bbf6bfe..000000000 --- a/app/src/main/kotlin/com/simplemobiletools/notes/activities/WidgetConfigureActivity.kt +++ /dev/null @@ -1,147 +0,0 @@ -package com.simplemobiletools.notes.activities - -import android.app.Activity -import android.appwidget.AppWidgetManager -import android.content.Intent -import android.graphics.Color -import android.os.Bundle -import android.util.TypedValue -import android.widget.RemoteViews -import android.widget.SeekBar -import com.simplemobiletools.commons.dialogs.ColorPickerDialog -import com.simplemobiletools.commons.extensions.adjustAlpha -import com.simplemobiletools.commons.extensions.setBackgroundColor -import com.simplemobiletools.commons.extensions.setFillWithStroke -import com.simplemobiletools.commons.helpers.IS_CUSTOMIZING_COLORS -import com.simplemobiletools.notes.R -import com.simplemobiletools.notes.extensions.config -import com.simplemobiletools.notes.extensions.getTextSize -import com.simplemobiletools.notes.helpers.MyWidgetProvider -import kotlinx.android.synthetic.main.widget_config.* - -class WidgetConfigureActivity : SimpleActivity() { - private var mBgAlpha = 0f - private var mWidgetId = 0 - private var mBgColor = 0 - private var mBgColorWithoutTransparency = 0 - private var mTextColor = 0 - - public override fun onCreate(savedInstanceState: Bundle?) { - useDynamicTheme = false - super.onCreate(savedInstanceState) - setResult(RESULT_CANCELED) - setContentView(R.layout.widget_config) - initVariables() - - val isCustomizingColors = intent.extras?.getBoolean(IS_CUSTOMIZING_COLORS) ?: false - mWidgetId = intent.extras?.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID) ?: AppWidgetManager.INVALID_APPWIDGET_ID - - if (mWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID && !isCustomizingColors) { - finish() - } - - config_save.setOnClickListener { saveConfig() } - config_bg_color.setOnClickListener { pickBackgroundColor() } - config_text_color.setOnClickListener { pickTextColor() } - } - - override fun onResume() { - super.onResume() - notes_view.setTextSize(TypedValue.COMPLEX_UNIT_PX, applicationContext.getTextSize()) - } - - private fun initVariables() { - mBgColor = config.widgetBgColor - if (mBgColor == 1) { - mBgColor = Color.BLACK - mBgAlpha = .2f - } else { - mBgAlpha = Color.alpha(mBgColor) / 255.toFloat() - } - - mBgColorWithoutTransparency = Color.rgb(Color.red(mBgColor), Color.green(mBgColor), Color.blue(mBgColor)) - config_bg_seekbar.apply { - setOnSeekBarChangeListener(bgSeekbarChangeListener) - progress = (mBgAlpha * 100).toInt() - } - updateBackgroundColor() - - mTextColor = config.widgetTextColor - updateTextColor() - } - - private fun saveConfig() { - val views = RemoteViews(packageName, R.layout.activity_main) - views.setBackgroundColor(R.id.notes_view, mBgColor) - AppWidgetManager.getInstance(this).updateAppWidget(mWidgetId, views) - - storeWidgetBackground() - requestWidgetUpdate() - - Intent().apply { - putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mWidgetId) - setResult(Activity.RESULT_OK, this) - } - finish() - } - - private fun storeWidgetBackground() { - config.apply { - widgetBgColor = mBgColor - widgetTextColor = mTextColor - } - } - - private fun requestWidgetUpdate() { - Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE, null, this, MyWidgetProvider::class.java).apply { - putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, intArrayOf(mWidgetId)) - sendBroadcast(this) - } - } - - private fun updateBackgroundColor() { - mBgColor = mBgColorWithoutTransparency.adjustAlpha(mBgAlpha) - notes_view.setBackgroundColor(mBgColor) - config_save.setBackgroundColor(mBgColor) - config_bg_color.setFillWithStroke(mBgColor, Color.BLACK) - } - - private fun updateTextColor() { - config_save.setTextColor(mTextColor) - notes_view.setTextColor(mTextColor) - config_text_color.setFillWithStroke(mTextColor, Color.BLACK) - } - - private fun pickBackgroundColor() { - ColorPickerDialog(this, mBgColorWithoutTransparency) { wasPositivePressed, color -> - if (wasPositivePressed) { - mBgColorWithoutTransparency = color - updateBackgroundColor() - } - } - } - - private fun pickTextColor() { - ColorPickerDialog(this, mTextColor) { wasPositivePressed, color -> - if (wasPositivePressed) { - mTextColor = color - updateTextColor() - } - } - } - - private val bgSeekbarChangeListener = object : SeekBar.OnSeekBarChangeListener { - override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { - mBgAlpha = progress.toFloat() / 100.toFloat() - updateBackgroundColor() - } - - override fun onStartTrackingTouch(seekBar: SeekBar) { - - } - - override fun onStopTrackingTouch(seekBar: SeekBar) { - - } - } -} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/adapters/NotesPagerAdapter.kt b/app/src/main/kotlin/com/simplemobiletools/notes/adapters/NotesPagerAdapter.kt deleted file mode 100644 index 0896f0377..000000000 --- a/app/src/main/kotlin/com/simplemobiletools/notes/adapters/NotesPagerAdapter.kt +++ /dev/null @@ -1,71 +0,0 @@ -package com.simplemobiletools.notes.adapters - -import android.app.Activity -import android.os.Bundle -import android.support.v4.app.FragmentManager -import android.support.v4.app.FragmentStatePagerAdapter -import android.view.ViewGroup -import com.simplemobiletools.commons.extensions.showErrorToast -import com.simplemobiletools.notes.fragments.NoteFragment -import com.simplemobiletools.notes.helpers.NOTE_ID -import com.simplemobiletools.notes.models.Note - -class NotesPagerAdapter(fm: FragmentManager, val notes: List, val activity: Activity) : FragmentStatePagerAdapter(fm) { - private var fragments: HashMap = LinkedHashMap() - - override fun getCount() = notes.size - - override fun getItem(position: Int): NoteFragment { - val bundle = Bundle() - val id = notes[position].id - bundle.putInt(NOTE_ID, id) - - if (fragments.containsKey(position)) { - return fragments[position]!! - } - - val fragment = NoteFragment() - fragment.arguments = bundle - fragments[position] = fragment - return fragment - } - - override fun getPageTitle(position: Int) = notes[position].title - - fun getCurrentNotesView(position: Int) = fragments[position]?.getNotesView() - - fun getCurrentNoteViewText(position: Int) = fragments[position]?.getCurrentNoteViewText() - - fun appendText(position: Int, text: String) = fragments[position]?.getNotesView()?.append(text) - - fun saveCurrentNote(position: Int, force: Boolean) = fragments[position]?.saveText(force) - - fun focusEditText(position: Int) = fragments[position]?.focusEditText() - - fun anyHasUnsavedChanges() = fragments.values.any { it.hasUnsavedChanges() } - - fun saveAllFragmentTexts() = fragments.values.forEach { it.saveText(false) } - - fun undo(position: Int) = fragments[position]?.undo() - - fun redo(position: Int) = fragments[position]?.redo() - - override fun finishUpdate(container: ViewGroup) { - try { - super.finishUpdate(container) - } catch (e: Exception) { - activity.showErrorToast(e) - } - } - - override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) { - super.destroyItem(container, position, `object`) - fragments.remove(position) - } - - override fun instantiateItem(container: ViewGroup, position: Int): Any { - val fragment = super.instantiateItem(container, position) as NoteFragment - fragments[position] = fragment - return fragment - } -} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/adapters/WidgetAdapter.kt b/app/src/main/kotlin/com/simplemobiletools/notes/adapters/WidgetAdapter.kt deleted file mode 100644 index 3977e7de9..000000000 --- a/app/src/main/kotlin/com/simplemobiletools/notes/adapters/WidgetAdapter.kt +++ /dev/null @@ -1,68 +0,0 @@ -package com.simplemobiletools.notes.adapters - -import android.content.Context -import android.content.Intent -import android.view.View -import android.widget.RemoteViews -import android.widget.RemoteViewsService -import com.simplemobiletools.commons.extensions.setText -import com.simplemobiletools.commons.extensions.setTextSize -import com.simplemobiletools.notes.R -import com.simplemobiletools.notes.R.id.widget_text_holder -import com.simplemobiletools.notes.extensions.config -import com.simplemobiletools.notes.extensions.dbHelper -import com.simplemobiletools.notes.extensions.getTextSize -import com.simplemobiletools.notes.helpers.GRAVITY_CENTER -import com.simplemobiletools.notes.helpers.GRAVITY_RIGHT -import com.simplemobiletools.notes.helpers.OPEN_NOTE_ID - -class WidgetAdapter(val context: Context) : RemoteViewsService.RemoteViewsFactory { - private val textIds = arrayOf(R.id.widget_text_left, R.id.widget_text_center, R.id.widget_text_right) - private val widgetTextColor = context.config.widgetTextColor - - override fun getViewAt(position: Int): RemoteViews { - val views = RemoteViews(context.packageName, R.layout.widget_text_layout).apply { - val note = context.dbHelper.getNote(context.config.widgetNoteId) - if (note != null) { - val noteText = note.getNoteStoredValue() ?: "" - val textSize = context.getTextSize() / context.resources.displayMetrics.density - for (id in textIds) { - setText(id, noteText) - setTextColor(id, widgetTextColor) - setTextSize(id, textSize) - setViewVisibility(id, View.GONE) - } - } - - Intent().apply { - putExtra(OPEN_NOTE_ID, context.config.widgetNoteId) - setOnClickFillInIntent(widget_text_holder, this) - } - - setViewVisibility(getProperTextView(context), View.VISIBLE) - } - return views - } - - private fun getProperTextView(context: Context) = when (context.config.gravity) { - GRAVITY_CENTER -> R.id.widget_text_center - GRAVITY_RIGHT -> R.id.widget_text_right - else -> R.id.widget_text_left - } - - override fun onCreate() {} - - override fun getLoadingView() = null - - override fun getItemId(position: Int) = position.toLong() - - override fun onDataSetChanged() {} - - override fun hasStableIds() = true - - override fun getCount() = 1 - - override fun getViewTypeCount() = 1 - - override fun onDestroy() {} -} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/dialogs/DeleteNoteDialog.kt b/app/src/main/kotlin/com/simplemobiletools/notes/dialogs/DeleteNoteDialog.kt deleted file mode 100644 index 550288b06..000000000 --- a/app/src/main/kotlin/com/simplemobiletools/notes/dialogs/DeleteNoteDialog.kt +++ /dev/null @@ -1,36 +0,0 @@ -package com.simplemobiletools.notes.dialogs - -import android.support.v7.app.AlertDialog -import com.simplemobiletools.commons.extensions.beVisible -import com.simplemobiletools.commons.extensions.setupDialogStuff -import com.simplemobiletools.notes.R -import com.simplemobiletools.notes.activities.SimpleActivity -import com.simplemobiletools.notes.models.Note -import kotlinx.android.synthetic.main.dialog_delete_note.view.* - -class DeleteNoteDialog(val activity: SimpleActivity, val note: Note, val callback: (deleteFile: Boolean) -> Unit) { - var dialog: AlertDialog? = null - - init { - val message = String.format(activity.getString(R.string.delete_note_prompt_message), note.title) - val view = activity.layoutInflater.inflate(R.layout.dialog_delete_note, null).apply { - if (note.path.isNotEmpty()) { - delete_note_checkbox.text = String.format(activity.getString(R.string.delete_file_itself), note.path) - delete_note_checkbox.beVisible() - } - delete_note_description.text = message - } - - AlertDialog.Builder(activity) - .setPositiveButton(R.string.ok, { dialog, which -> dialogConfirmed(view.delete_note_checkbox.isChecked) }) - .setNegativeButton(R.string.cancel, null) - .create().apply { - activity.setupDialogStuff(view, this) - } - } - - private fun dialogConfirmed(deleteFile: Boolean) { - callback(deleteFile && note.path.isNotEmpty()) - dialog?.dismiss() - } -} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/dialogs/ExportFileDialog.kt b/app/src/main/kotlin/com/simplemobiletools/notes/dialogs/ExportFileDialog.kt deleted file mode 100644 index b342ff524..000000000 --- a/app/src/main/kotlin/com/simplemobiletools/notes/dialogs/ExportFileDialog.kt +++ /dev/null @@ -1,59 +0,0 @@ -package com.simplemobiletools.notes.dialogs - -import android.support.v7.app.AlertDialog -import com.simplemobiletools.commons.dialogs.FilePickerDialog -import com.simplemobiletools.commons.extensions.* -import com.simplemobiletools.notes.R -import com.simplemobiletools.notes.activities.SimpleActivity -import com.simplemobiletools.notes.extensions.config -import com.simplemobiletools.notes.models.Note -import kotlinx.android.synthetic.main.dialog_export_file.view.* -import java.io.File - -class ExportFileDialog(val activity: SimpleActivity, val note: Note, val callback: (exportPath: String) -> Unit) { - - init { - var realPath = File(note.path).parent ?: activity.config.lastUsedSavePath - val view = activity.layoutInflater.inflate(R.layout.dialog_export_file, null).apply { - file_path.text = activity.humanizePath(realPath) - - file_name.setText(note.title) - file_extension.setText(activity.config.lastUsedExtension) - file_path.setOnClickListener { - FilePickerDialog(activity, realPath, false, false, true) { - file_path.text = activity.humanizePath(it) - realPath = it - } - } - } - - AlertDialog.Builder(activity) - .setPositiveButton(R.string.ok, null) - .setNegativeButton(R.string.cancel, null) - .create().apply { - activity.setupDialogStuff(view, this, R.string.export_as_file) { - showKeyboard(view.file_name) - getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { - val filename = view.file_name.value - val extension = view.file_extension.value - - if (filename.isEmpty()) { - activity.toast(R.string.filename_cannot_be_empty) - return@setOnClickListener - } - - val fullFilename = if (extension.isEmpty()) filename else "$filename.$extension" - if (!fullFilename.isAValidFilename()) { - activity.toast(String.format(activity.getString(R.string.filename_invalid_characters_placeholder, fullFilename))) - return@setOnClickListener - } - - activity.config.lastUsedExtension = extension - activity.config.lastUsedSavePath = realPath - callback("$realPath/$fullFilename") - dismiss() - } - } - } - } -} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/dialogs/ExportFilesDialog.kt b/app/src/main/kotlin/com/simplemobiletools/notes/dialogs/ExportFilesDialog.kt deleted file mode 100644 index 8b195ed84..000000000 --- a/app/src/main/kotlin/com/simplemobiletools/notes/dialogs/ExportFilesDialog.kt +++ /dev/null @@ -1,48 +0,0 @@ -package com.simplemobiletools.notes.dialogs - -import android.support.v7.app.AlertDialog -import com.simplemobiletools.commons.dialogs.FilePickerDialog -import com.simplemobiletools.commons.extensions.humanizePath -import com.simplemobiletools.commons.extensions.setupDialogStuff -import com.simplemobiletools.commons.extensions.showKeyboard -import com.simplemobiletools.commons.extensions.value -import com.simplemobiletools.notes.R -import com.simplemobiletools.notes.activities.SimpleActivity -import com.simplemobiletools.notes.extensions.config -import com.simplemobiletools.notes.models.Note -import kotlinx.android.synthetic.main.dialog_export_files.view.* - -class ExportFilesDialog(val activity: SimpleActivity, val notes: ArrayList, val callback: (parent: String, extension: String) -> Unit) { - init { - var realPath = activity.config.lastUsedSavePath - val view = activity.layoutInflater.inflate(R.layout.dialog_export_files, null).apply { - folder_path.text = activity.humanizePath(realPath) - - file_extension.setText(activity.config.lastUsedExtension) - folder_path.setOnClickListener { - FilePickerDialog(activity, realPath, false, false, true) { - folder_path.text = activity.humanizePath(it) - realPath = it - } - } - } - - AlertDialog.Builder(activity) - .setPositiveButton(R.string.ok, null) - .setNegativeButton(R.string.cancel, null) - .create().apply { - activity.setupDialogStuff(view, this, R.string.export_as_file) { - showKeyboard(view.file_extension) - getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { - activity.handleSAFDialog(realPath) { - val extension = view.file_extension.value - activity.config.lastUsedExtension = extension - activity.config.lastUsedSavePath = realPath - callback(realPath, extension) - dismiss() - } - } - } - } - } -} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/dialogs/ImportFolderDialog.kt b/app/src/main/kotlin/com/simplemobiletools/notes/dialogs/ImportFolderDialog.kt deleted file mode 100644 index e072f854f..000000000 --- a/app/src/main/kotlin/com/simplemobiletools/notes/dialogs/ImportFolderDialog.kt +++ /dev/null @@ -1,75 +0,0 @@ -package com.simplemobiletools.notes.dialogs - -import android.support.v7.app.AlertDialog -import android.view.ViewGroup -import com.simplemobiletools.commons.extensions.getFilenameFromPath -import com.simplemobiletools.commons.extensions.humanizePath -import com.simplemobiletools.commons.extensions.isMediaFile -import com.simplemobiletools.commons.extensions.setupDialogStuff -import com.simplemobiletools.notes.R -import com.simplemobiletools.notes.activities.SimpleActivity -import com.simplemobiletools.notes.extensions.dbHelper -import com.simplemobiletools.notes.helpers.TYPE_NOTE -import com.simplemobiletools.notes.models.Note -import kotlinx.android.synthetic.main.dialog_import_folder.view.* -import java.io.File - -class ImportFolderDialog(val activity: SimpleActivity, val path: String, val callback: (id: Int) -> Unit) : AlertDialog.Builder(activity) { - private var dialog: AlertDialog - - init { - val view = (activity.layoutInflater.inflate(R.layout.dialog_import_folder, null) as ViewGroup).apply { - open_file_filename.text = activity.humanizePath(path) - } - - dialog = AlertDialog.Builder(activity) - .setPositiveButton(R.string.ok, null) - .setNegativeButton(R.string.cancel, null) - .create().apply { - activity.setupDialogStuff(view, this, R.string.import_folder) { - getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { - val updateFilesOnEdit = view.open_file_type.checkedRadioButtonId == R.id.open_file_update_file - saveFolder(updateFilesOnEdit) - } - } - } - } - - private fun saveFolder(updateFilesOnEdit: Boolean) { - val folder = File(path) - var lastSavedNoteId = -1 - folder.listFiles { file -> - val filename = file.path.getFilenameFromPath() - when { - file.isDirectory -> false - filename.isMediaFile() -> false - file.length() > 10 * 1000 * 1000 -> false - activity.dbHelper.doesTitleExist(filename) -> false - else -> true - } - }.forEach { - val storePath = if (updateFilesOnEdit) it.absolutePath else "" - val title = it.absolutePath.getFilenameFromPath() - val value = if (updateFilesOnEdit) "" else it.readText() - - if (updateFilesOnEdit) { - activity.handleSAFDialog(path) { - lastSavedNoteId = saveNote(title, value, storePath) - } - } else { - lastSavedNoteId = saveNote(title, value, storePath) - } - } - - if (lastSavedNoteId != -1) { - callback(lastSavedNoteId) - } - - dialog.dismiss() - } - - private fun saveNote(title: String, value: String, path: String): Int { - val note = Note(0, title, value, TYPE_NOTE, path) - return activity.dbHelper.insertNote(note) - } -} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/dialogs/NewNoteDialog.kt b/app/src/main/kotlin/com/simplemobiletools/notes/dialogs/NewNoteDialog.kt deleted file mode 100644 index 213d0c507..000000000 --- a/app/src/main/kotlin/com/simplemobiletools/notes/dialogs/NewNoteDialog.kt +++ /dev/null @@ -1,38 +0,0 @@ -package com.simplemobiletools.notes.dialogs - -import android.app.Activity -import android.content.DialogInterface.BUTTON_POSITIVE -import android.support.v7.app.AlertDialog -import com.simplemobiletools.commons.extensions.setupDialogStuff -import com.simplemobiletools.commons.extensions.showKeyboard -import com.simplemobiletools.commons.extensions.toast -import com.simplemobiletools.commons.extensions.value -import com.simplemobiletools.notes.R -import com.simplemobiletools.notes.helpers.DBHelper -import kotlinx.android.synthetic.main.dialog_new_note.view.* - -class NewNoteDialog(val activity: Activity, val db: DBHelper, callback: (title: String) -> Unit) { - init { - val view = activity.layoutInflater.inflate(R.layout.dialog_new_note, null) - - AlertDialog.Builder(activity) - .setPositiveButton(R.string.ok, null) - .setNegativeButton(R.string.cancel, null) - .create().apply { - activity.setupDialogStuff(view, this, R.string.new_note) { - showKeyboard(view.note_name) - getButton(BUTTON_POSITIVE).setOnClickListener { - val title = view.note_name.value - when { - title.isEmpty() -> activity.toast(R.string.no_title) - db.doesTitleExist(title) -> activity.toast(R.string.title_taken) - else -> { - callback(title) - dismiss() - } - } - } - } - } - } -} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/dialogs/OpenFileDialog.kt b/app/src/main/kotlin/com/simplemobiletools/notes/dialogs/OpenFileDialog.kt deleted file mode 100644 index 14e190b86..000000000 --- a/app/src/main/kotlin/com/simplemobiletools/notes/dialogs/OpenFileDialog.kt +++ /dev/null @@ -1,52 +0,0 @@ -package com.simplemobiletools.notes.dialogs - -import android.support.v7.app.AlertDialog -import android.view.ViewGroup -import com.simplemobiletools.commons.extensions.getFilenameFromPath -import com.simplemobiletools.commons.extensions.humanizePath -import com.simplemobiletools.commons.extensions.setupDialogStuff -import com.simplemobiletools.notes.R -import com.simplemobiletools.notes.R.id.open_file_update_file -import com.simplemobiletools.notes.activities.SimpleActivity -import com.simplemobiletools.notes.helpers.TYPE_NOTE -import com.simplemobiletools.notes.models.Note -import kotlinx.android.synthetic.main.dialog_open_file.view.* -import java.io.File - -class OpenFileDialog(val activity: SimpleActivity, val path: String, val callback: (note: Note) -> Unit) : AlertDialog.Builder(activity) { - private var dialog: AlertDialog - - init { - val view = (activity.layoutInflater.inflate(R.layout.dialog_open_file, null) as ViewGroup).apply { - open_file_filename.text = activity.humanizePath(path) - } - - dialog = AlertDialog.Builder(activity) - .setPositiveButton(R.string.ok, null) - .setNegativeButton(R.string.cancel, null) - .create().apply { - activity.setupDialogStuff(view, this, R.string.open_file) { - getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { - val updateFileOnEdit = view.open_file_type.checkedRadioButtonId == open_file_update_file - val storePath = if (updateFileOnEdit) path else "" - val storeContent = if (updateFileOnEdit) "" else File(path).readText() - - if (updateFileOnEdit) { - activity.handleSAFDialog(path) { - saveNote(storeContent, storePath) - } - } else { - saveNote(storeContent, storePath) - } - } - } - } - } - - private fun saveNote(storeContent: String, storePath: String) { - val filename = path.getFilenameFromPath() - val note = Note(0, filename, storeContent, TYPE_NOTE, storePath) - callback(note) - dialog.dismiss() - } -} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/dialogs/OpenNoteDialog.kt b/app/src/main/kotlin/com/simplemobiletools/notes/dialogs/OpenNoteDialog.kt deleted file mode 100644 index f23d7b695..000000000 --- a/app/src/main/kotlin/com/simplemobiletools/notes/dialogs/OpenNoteDialog.kt +++ /dev/null @@ -1,53 +0,0 @@ -package com.simplemobiletools.notes.dialogs - -import android.app.Activity -import android.support.v7.app.AlertDialog -import android.view.ViewGroup -import android.widget.RadioGroup -import com.simplemobiletools.commons.extensions.applyColorFilter -import com.simplemobiletools.commons.extensions.beVisibleIf -import com.simplemobiletools.commons.extensions.setupDialogStuff -import com.simplemobiletools.commons.extensions.toast -import com.simplemobiletools.notes.R -import com.simplemobiletools.notes.extensions.config -import com.simplemobiletools.notes.extensions.dbHelper -import kotlinx.android.synthetic.main.dialog_open_note.view.* -import kotlinx.android.synthetic.main.open_note_item.view.* - -class OpenNoteDialog(val activity: Activity, val callback: (checkedId: Int) -> Unit) { - lateinit var dialog: AlertDialog - - init { - val view = activity.layoutInflater.inflate(R.layout.dialog_open_note, null) - val textColor = activity.config.textColor - val notes = activity.dbHelper.getNotes() - notes.forEach { - activity.layoutInflater.inflate(R.layout.open_note_item, null).apply { - val note = it - open_note_item_radio_button.apply { - text = note.title - isChecked = note.id == activity.config.currentNoteId - id = note.id - - setOnClickListener { - callback(id) - dialog.dismiss() - } - } - open_note_item_icon.apply { - beVisibleIf(note.path.isNotEmpty()) - applyColorFilter(textColor) - setOnClickListener { - activity.toast(note.path) - } - } - view.dialog_open_note_linear.addView(this, RadioGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)) - } - } - - dialog = AlertDialog.Builder(activity) - .create().apply { - activity.setupDialogStuff(view, this, R.string.pick_a_note) - } - } -} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/dialogs/RenameNoteDialog.kt b/app/src/main/kotlin/com/simplemobiletools/notes/dialogs/RenameNoteDialog.kt deleted file mode 100644 index c28cf7660..000000000 --- a/app/src/main/kotlin/com/simplemobiletools/notes/dialogs/RenameNoteDialog.kt +++ /dev/null @@ -1,65 +0,0 @@ -package com.simplemobiletools.notes.dialogs - -import android.content.DialogInterface.BUTTON_POSITIVE -import android.support.v7.app.AlertDialog -import com.simplemobiletools.commons.extensions.* -import com.simplemobiletools.notes.R -import com.simplemobiletools.notes.activities.SimpleActivity -import com.simplemobiletools.notes.extensions.dbHelper -import com.simplemobiletools.notes.models.Note -import kotlinx.android.synthetic.main.dialog_new_note.view.* -import java.io.File - -class RenameNoteDialog(val activity: SimpleActivity, val note: Note, callback: (note: Note) -> Unit) { - - init { - val view = activity.layoutInflater.inflate(R.layout.dialog_rename_note, null) - view.note_name.setText(note.title) - - AlertDialog.Builder(activity) - .setPositiveButton(R.string.ok, null) - .setNegativeButton(R.string.cancel, null) - .create().apply { - activity.setupDialogStuff(view, this, R.string.rename_note) { - showKeyboard(view.note_name) - getButton(BUTTON_POSITIVE).setOnClickListener { - val title = view.note_name.value - when { - title.isEmpty() -> activity.toast(R.string.no_title) - activity.dbHelper.doesTitleExist(title) -> activity.toast(R.string.title_taken) - else -> { - note.title = title - val path = note.path - if (path.isNotEmpty()) { - if (title.isEmpty()) { - activity.toast(R.string.filename_cannot_be_empty) - return@setOnClickListener - } - - val file = File(path) - val newFile = File(file.parent, title) - if (!newFile.name.isAValidFilename()) { - activity.toast(R.string.invalid_name) - return@setOnClickListener - } - - activity.renameFile(file.absolutePath, newFile.absolutePath) { - if (it) { - note.path = newFile.absolutePath - activity.dbHelper.updateNotePath(note) - } else { - activity.toast(R.string.rename_file_error) - return@renameFile - } - } - } - activity.dbHelper.updateNoteTitle(note) - dismiss() - callback(note) - } - } - } - } - } - } -} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/extensions/Context.kt b/app/src/main/kotlin/com/simplemobiletools/notes/extensions/Context.kt deleted file mode 100644 index ad9520ab3..000000000 --- a/app/src/main/kotlin/com/simplemobiletools/notes/extensions/Context.kt +++ /dev/null @@ -1,31 +0,0 @@ -package com.simplemobiletools.notes.extensions - -import android.appwidget.AppWidgetManager -import android.content.ComponentName -import android.content.Context -import android.content.Intent -import com.simplemobiletools.notes.R -import com.simplemobiletools.notes.helpers.* - -val Context.config: Config get() = Config.newInstance(applicationContext) - -val Context.dbHelper: DBHelper get() = DBHelper.newInstance(applicationContext) - -fun Context.getTextSize() = - when (config.fontSize) { - FONT_SIZE_SMALL -> resources.getDimension(R.dimen.smaller_text_size) - FONT_SIZE_LARGE -> resources.getDimension(R.dimen.big_text_size) - FONT_SIZE_EXTRA_LARGE -> resources.getDimension(R.dimen.extra_big_text_size) - else -> resources.getDimension(R.dimen.bigger_text_size) - } - -fun Context.updateWidget() { - val widgetIDs = AppWidgetManager.getInstance(this).getAppWidgetIds(ComponentName(this, MyWidgetProvider::class.java)) - if (widgetIDs.isNotEmpty()) { - Intent(this, MyWidgetProvider::class.java).apply { - action = AppWidgetManager.ACTION_APPWIDGET_UPDATE - putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, widgetIDs) - sendBroadcast(this) - } - } -} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/fragments/NoteFragment.kt b/app/src/main/kotlin/com/simplemobiletools/notes/fragments/NoteFragment.kt deleted file mode 100644 index 9bfd84a43..000000000 --- a/app/src/main/kotlin/com/simplemobiletools/notes/fragments/NoteFragment.kt +++ /dev/null @@ -1,261 +0,0 @@ -package com.simplemobiletools.notes.fragments - -import android.annotation.SuppressLint -import android.graphics.Typeface -import android.os.Bundle -import android.support.v4.app.Fragment -import android.text.Editable -import android.text.Selection -import android.text.TextWatcher -import android.text.style.UnderlineSpan -import android.text.util.Linkify -import android.util.TypedValue -import android.view.Gravity -import android.view.LayoutInflater -import android.view.View -import android.view.ViewGroup -import com.simplemobiletools.commons.extensions.beGone -import com.simplemobiletools.commons.extensions.beVisible -import com.simplemobiletools.commons.extensions.onGlobalLayout -import com.simplemobiletools.notes.R -import com.simplemobiletools.notes.activities.MainActivity -import com.simplemobiletools.notes.extensions.config -import com.simplemobiletools.notes.extensions.dbHelper -import com.simplemobiletools.notes.extensions.getTextSize -import com.simplemobiletools.notes.extensions.updateWidget -import com.simplemobiletools.notes.helpers.* -import com.simplemobiletools.notes.models.Note -import com.simplemobiletools.notes.models.TextHistory -import com.simplemobiletools.notes.models.TextHistoryItem -import kotlinx.android.synthetic.main.fragment_note.* -import kotlinx.android.synthetic.main.fragment_note.view.* -import kotlinx.android.synthetic.main.note_view_horiz_scrollable.view.* -import java.io.File - -// text history handling taken from https://gist.github.com/zeleven/0cfa738c1e8b65b23ff7df1fc30c9f7e -class NoteFragment : Fragment() { - private val TEXT = "text" - - private var textHistory = TextHistory() - private var isUndoOrRedo = false - private var noteId = 0 - lateinit var note: Note - lateinit var view: ViewGroup - private lateinit var db: DBHelper - - override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { - view = inflater.inflate(R.layout.fragment_note, container, false) as ViewGroup - noteId = arguments!!.getInt(NOTE_ID) - db = context!!.dbHelper - note = db.getNote(noteId) ?: return view - retainInstance = true - - val layoutToInflate = if (context!!.config.enableLineWrap) R.layout.note_view_static else R.layout.note_view_horiz_scrollable - inflater.inflate(layoutToInflate, view.notes_relative_layout, true) - if (context!!.config.clickableLinks) { - view.notes_view.apply { - linksClickable = true - autoLinkMask = Linkify.WEB_URLS or Linkify.EMAIL_ADDRESSES - movementMethod = MyMovementMethod.getInstance() - } - } - - view.notes_horizontal_scrollview?.onGlobalLayout { - view.notes_view.minWidth = view.notes_horizontal_scrollview.width - } - - return view - } - - override fun onResume() { - super.onResume() - - val config = context!!.config - view.notes_view.apply { - typeface = if (config.monospacedFont) Typeface.MONOSPACE else Typeface.DEFAULT - - val fileContents = note.getNoteStoredValue() - if (fileContents == null) { - (activity as MainActivity).deleteNote(false) - return - } - - setColors(config.textColor, config.primaryColor, config.backgroundColor) - setTextSize(TypedValue.COMPLEX_UNIT_PX, context.getTextSize()) - gravity = getTextGravity() - if (text.toString() != fileContents) { - setText(fileContents) - setSelection(if (config.placeCursorToEnd) text.length else 0) - } - } - - if (config.showWordCount) { - view.notes_counter.beVisible() - view.notes_counter.setTextColor(config.textColor) - setWordCounter(view.notes_view.text.toString()) - } else { - view.notes_counter.beGone() - } - - view.notes_view.addTextChangedListener(textWatcher) - } - - override fun onPause() { - super.onPause() - if (context!!.config.autosaveNotes) { - saveText(false) - } - view.notes_view.removeTextChangedListener(textWatcher) - } - - override fun setMenuVisibility(menuVisible: Boolean) { - super.setMenuVisibility(menuVisible) - if (!menuVisible && noteId != 0 && context?.config?.autosaveNotes == true) { - saveText(false) - } - - if (menuVisible && noteId != 0) { - val currentText = getCurrentNoteViewText() - if (currentText != null) { - (activity as MainActivity).currentNoteTextChanged(currentText, isUndoAvailable(), isRedoAvailable()) - } - } - } - - override fun onSaveInstanceState(outState: Bundle) { - super.onSaveInstanceState(outState) - outState.putString(TEXT, getCurrentNoteViewText()) - } - - override fun onViewStateRestored(savedInstanceState: Bundle?) { - super.onViewStateRestored(savedInstanceState) - if (savedInstanceState != null) { - note.value = savedInstanceState.getString(TEXT) ?: "" - view.notes_view.setText(note.value) - } - } - - fun getNotesView() = view.notes_view - - fun saveText(force: Boolean) { - if (note.path.isNotEmpty() && !File(note.path).exists()) { - return - } - - if (context == null || activity == null) { - return - } - - val newText = getCurrentNoteViewText() - val oldText = note.getNoteStoredValue() - if (newText != null && (newText != oldText || force)) { - note.value = newText - saveNoteValue(note) - context!!.updateWidget() - } - } - - fun hasUnsavedChanges() = getCurrentNoteViewText() != note.getNoteStoredValue() - - fun focusEditText() { - view.notes_view.requestFocus() - } - - private fun saveNoteValue(note: Note) { - if (note.path.isEmpty()) { - db.updateNoteValue(note) - (activity as MainActivity).noteSavedSuccessfully(note.title) - } else { - val currentText = getCurrentNoteViewText() - if (currentText != null) { - (activity as MainActivity).exportNoteValueToFile(note.path, currentText, true) - } - } - } - - fun getCurrentNoteViewText() = view.notes_view?.text?.toString() - - @SuppressLint("RtlHardcoded") - private fun getTextGravity() = when (context!!.config.gravity) { - GRAVITY_CENTER -> Gravity.CENTER_HORIZONTAL - GRAVITY_RIGHT -> Gravity.RIGHT - else -> Gravity.LEFT - } - - private fun setWordCounter(text: String) { - val words = text.replace("\n", " ").split(" ") - notes_counter.text = words.count { it.isNotEmpty() }.toString() - } - - fun undo() { - val edit = textHistory.getPrevious() ?: return - - val text = view.notes_view.editableText - val start = edit.start - val end = start + if (edit.after != null) edit.after.length else 0 - - isUndoOrRedo = true - text.replace(start, end, edit.before) - isUndoOrRedo = false - - for (span in text.getSpans(0, text.length, UnderlineSpan::class.java)) { - text.removeSpan(span) - } - - Selection.setSelection(text, if (edit.before == null) { - start - } else { - start + edit.before.length - }) - } - - fun redo() { - val edit = textHistory.getNext() ?: return - - val text = view.notes_view.editableText - val start = edit.start - val end = start + if (edit.before != null) edit.before.length else 0 - - isUndoOrRedo = true - text.replace(start, end, edit.after) - isUndoOrRedo = false - - for (o in text.getSpans(0, text.length, UnderlineSpan::class.java)) { - text.removeSpan(o) - } - - Selection.setSelection(text, if (edit.after == null) { - start - } else { - start + edit.after.length - }) - } - - fun isUndoAvailable() = textHistory.position > 0 - - fun isRedoAvailable() = textHistory.position < textHistory.history.size - - private var textWatcher: TextWatcher = object : TextWatcher { - private var beforeChange: CharSequence? = null - private var afterChange: CharSequence? = null - - override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { - if (!isUndoOrRedo) { - beforeChange = s.subSequence(start, start + count) - } - } - - override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { - if (!isUndoOrRedo) { - afterChange = s.subSequence(start, start + count) - textHistory.add(TextHistoryItem(start, beforeChange!!, afterChange!!)) - } - } - - override fun afterTextChanged(editable: Editable) { - val text = editable.toString() - setWordCounter(text) - (activity as MainActivity).currentNoteTextChanged(text, isUndoAvailable(), isRedoAvailable()) - } - } -} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/helpers/Constants.kt b/app/src/main/kotlin/com/simplemobiletools/notes/helpers/Constants.kt deleted file mode 100644 index 7406cb066..000000000 --- a/app/src/main/kotlin/com/simplemobiletools/notes/helpers/Constants.kt +++ /dev/null @@ -1,39 +0,0 @@ -package com.simplemobiletools.notes.helpers - -const val NOTE_ID = "note_id" -const val OPEN_NOTE_ID = "open_note_id" - -// shared preferences -const val CURRENT_NOTE_ID = "current_note_id" -const val AUTOSAVE_NOTES = "autosave_notes" -const val DISPLAY_SUCCESS = "display_success" -const val CLICKABLE_LINKS = "clickable_links" -const val WIDGET_NOTE_ID = "widget_note_id" -const val MONOSPACED_FONT = "monospaced_font" -const val SHOW_KEYBOARD = "show_keyboard" -const val SHOW_NOTE_PICKER = "show_note_picker" -const val SHOW_WORD_COUNT = "show_word_count" -const val FONT_SIZE = "font_size" -const val GRAVITY = "gravity" -const val CURSOR_PLACEMENT = "cursor_placement" -const val LAST_USED_EXTENSION = "last_used_extension" -const val LAST_USED_SAVE_PATH = "last_used_save_path" -const val ENABLE_LINE_WRAP = "enable_line_wrap" - -// gravity -const val GRAVITY_LEFT = 0 -const val GRAVITY_CENTER = 1 -const val GRAVITY_RIGHT = 2 - -// font sizes -const val FONT_SIZE_SMALL = 0 -const val FONT_SIZE_MEDIUM = 1 -const val FONT_SIZE_LARGE = 2 -const val FONT_SIZE_EXTRA_LARGE = 3 - -// note types -const val TYPE_NOTE = 0 -const val TYPE_CHECKLIST = 1 - -// mime types -const val MIME_TEXT_PLAIN = "text/plain" diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/helpers/DBHelper.kt b/app/src/main/kotlin/com/simplemobiletools/notes/helpers/DBHelper.kt deleted file mode 100644 index e1a647954..000000000 --- a/app/src/main/kotlin/com/simplemobiletools/notes/helpers/DBHelper.kt +++ /dev/null @@ -1,182 +0,0 @@ -package com.simplemobiletools.notes.helpers - -import android.content.ContentValues -import android.content.Context -import android.database.Cursor -import android.database.sqlite.SQLiteDatabase -import android.database.sqlite.SQLiteDatabase.CONFLICT_IGNORE -import android.database.sqlite.SQLiteOpenHelper -import com.simplemobiletools.commons.extensions.getIntValue -import com.simplemobiletools.commons.extensions.getStringValue -import com.simplemobiletools.notes.R -import com.simplemobiletools.notes.models.Note -import java.io.File -import java.util.* - -class DBHelper private constructor(private val mContext: Context) : SQLiteOpenHelper(mContext, DB_NAME, null, DB_VERSION) { - private val mDb: SQLiteDatabase = writableDatabase - - companion object { - private const val DB_NAME = "notes.db" - private const val DB_VERSION = 3 - private const val TABLE_NAME = "notes" - - private const val COL_ID = "id" - private const val COL_TITLE = "title" - private const val COL_VALUE = "value" - private const val COL_TYPE = "type" - private const val COL_PATH = "path" - - fun newInstance(context: Context) = DBHelper(context) - } - - override fun onCreate(db: SQLiteDatabase) { - db.execSQL("CREATE TABLE $TABLE_NAME ($COL_ID INTEGER PRIMARY KEY AUTOINCREMENT, $COL_TITLE TEXT UNIQUE, $COL_VALUE TEXT, $COL_TYPE INTEGER DEFAULT 0, $COL_PATH TEXT)") - insertFirstNote(db) - } - - override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { - if (oldVersion < 2) { - db.execSQL("ALTER TABLE $TABLE_NAME ADD COLUMN $COL_TYPE INTEGER DEFAULT 0") - } - - if (oldVersion < 3) { - db.execSQL("ALTER TABLE $TABLE_NAME ADD COLUMN $COL_PATH TEXT DEFAULT ''") - } - } - - private fun insertFirstNote(db: SQLiteDatabase) { - val generalNote = mContext.resources.getString(R.string.general_note) - val note = Note(1, generalNote, "", TYPE_NOTE) - insertNote(note, db) - } - - private fun insertNote(note: Note, db: SQLiteDatabase) { - val values = fillContentValues(note) - db.insert(TABLE_NAME, null, values) - } - - fun insertNote(note: Note): Int { - val values = fillContentValues(note) - return mDb.insertWithOnConflict(TABLE_NAME, null, values, CONFLICT_IGNORE).toInt() - } - - private fun fillContentValues(note: Note): ContentValues { - return ContentValues().apply { - put(COL_TITLE, note.title) - put(COL_VALUE, note.value) - put(COL_PATH, note.path) - put(COL_TYPE, 0) - } - } - - fun deleteNote(id: Int) { - mDb.delete(TABLE_NAME, "$COL_ID = $id", null) - } - - fun doesTitleExist(title: String): Boolean { - val cols = arrayOf(COL_ID) - val selection = "$COL_TITLE = ? COLLATE NOCASE" - val selectionArgs = arrayOf(title) - var cursor: Cursor? = null - try { - cursor = mDb.query(TABLE_NAME, cols, selection, selectionArgs, null, null, null) - return cursor.count == 1 - } finally { - cursor?.close() - } - } - - fun getNotes(): ArrayList { - val notes = ArrayList() - val cols = arrayOf(COL_ID, COL_TITLE, COL_VALUE, COL_TYPE, COL_PATH) - var cursor: Cursor? = null - try { - cursor = mDb.query(TABLE_NAME, cols, null, null, null, null, "$COL_TITLE COLLATE NOCASE ASC") - if (cursor?.moveToFirst() == true) { - do { - try { - val id = cursor.getIntValue(COL_ID) - val title = cursor.getStringValue(COL_TITLE) - val value = cursor.getStringValue(COL_VALUE) - val type = cursor.getIntValue(COL_TYPE) - val path = cursor.getStringValue(COL_PATH) ?: "" - if (path.isNotEmpty() && !File(path).exists()) { - deleteNote(id) - continue - } - - val note = Note(id, title, value, type, path) - notes.add(note) - } catch (e: Exception) { - continue - } - } while (cursor.moveToNext()) - } - } finally { - cursor?.close() - } - - return notes - } - - fun getNote(id: Int): Note? { - val cols = arrayOf(COL_TITLE, COL_VALUE, COL_TYPE, COL_PATH) - val selection = "$COL_ID = ?" - val selectionArgs = arrayOf(id.toString()) - var note: Note? = null - var cursor: Cursor? = null - try { - cursor = mDb.query(TABLE_NAME, cols, selection, selectionArgs, null, null, null) - if (cursor?.moveToFirst() == true) { - val title = cursor.getStringValue(COL_TITLE) - val value = cursor.getStringValue(COL_VALUE) - val type = cursor.getIntValue(COL_TYPE) - val path = cursor.getStringValue(COL_PATH) ?: "" - note = Note(id, title, value, type, path) - } - } finally { - cursor?.close() - } - return note - } - - fun getNoteId(path: String): Int { - val cols = arrayOf(COL_ID) - val selection = "$COL_PATH = ?" - val selectionArgs = arrayOf(path) - var cursor: Cursor? = null - try { - cursor = mDb.query(TABLE_NAME, cols, selection, selectionArgs, null, null, null) - if (cursor?.moveToFirst() == true) { - return cursor.getIntValue(COL_ID) - } - } finally { - cursor?.close() - } - return 0 - } - - fun updateNoteValue(note: Note) { - val values = ContentValues().apply { put(COL_VALUE, note.value) } - updateNote(note.id, values) - } - - fun updateNoteTitle(note: Note) { - val values = ContentValues().apply { put(COL_TITLE, note.title) } - updateNote(note.id, values) - } - - fun updateNotePath(note: Note) { - val values = ContentValues().apply { put(COL_PATH, note.path) } - updateNote(note.id, values) - } - - private fun updateNote(id: Int, values: ContentValues) { - val selection = "$COL_ID = ?" - val selectionArgs = arrayOf(id.toString()) - mDb.update(TABLE_NAME, values, selection, selectionArgs) - } - - fun isValidId(id: Int) = id > 0 -} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/helpers/MyWidgetProvider.kt b/app/src/main/kotlin/com/simplemobiletools/notes/helpers/MyWidgetProvider.kt deleted file mode 100644 index eca1698a9..000000000 --- a/app/src/main/kotlin/com/simplemobiletools/notes/helpers/MyWidgetProvider.kt +++ /dev/null @@ -1,54 +0,0 @@ -package com.simplemobiletools.notes.helpers - -import android.app.PendingIntent -import android.appwidget.AppWidgetManager -import android.appwidget.AppWidgetProvider -import android.content.ComponentName -import android.content.Context -import android.content.Intent -import android.net.Uri -import android.widget.RemoteViews -import com.simplemobiletools.commons.extensions.getLaunchIntent -import com.simplemobiletools.commons.extensions.setBackgroundColor -import com.simplemobiletools.notes.R -import com.simplemobiletools.notes.activities.SplashActivity -import com.simplemobiletools.notes.extensions.config -import com.simplemobiletools.notes.services.WidgetService - -class MyWidgetProvider : AppWidgetProvider() { - override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) { - performUpdate(context) - } - - private fun performUpdate(context: Context) { - val appWidgetManager = AppWidgetManager.getInstance(context) - appWidgetManager.getAppWidgetIds(getComponentName(context)).forEach { - val views = RemoteViews(context.packageName, R.layout.widget) - views.setBackgroundColor(R.id.notes_widget_holder, context.config.widgetBgColor) - setupAppOpenIntent(context, views, R.id.notes_widget_holder) - - Intent(context, WidgetService::class.java).apply { - data = Uri.parse(this.toUri(Intent.URI_INTENT_SCHEME)) - views.setRemoteAdapter(R.id.notes_widget_listview, this) - } - - val widgetId = context.config.widgetNoteId - val startActivityIntent = context.getLaunchIntent() ?: Intent(context, SplashActivity::class.java) - val startActivityPendingIntent = PendingIntent.getActivity(context, widgetId, startActivityIntent, PendingIntent.FLAG_UPDATE_CURRENT) - views.setPendingIntentTemplate(R.id.notes_widget_listview, startActivityPendingIntent) - - appWidgetManager.updateAppWidget(it, views) - appWidgetManager.notifyAppWidgetViewDataChanged(it, R.id.notes_widget_listview) - } - } - - private fun getComponentName(context: Context) = ComponentName(context, MyWidgetProvider::class.java) - - private fun setupAppOpenIntent(context: Context, views: RemoteViews, id: Int) { - val widgetId = context.config.widgetNoteId - val intent = context.getLaunchIntent() ?: Intent(context, SplashActivity::class.java) - intent.putExtra(OPEN_NOTE_ID, widgetId) - val pendingIntent = PendingIntent.getActivity(context, widgetId, intent, 0) - views.setOnClickPendingIntent(id, pendingIntent) - } -} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/models/Note.kt b/app/src/main/kotlin/com/simplemobiletools/notes/models/Note.kt deleted file mode 100644 index cc35314d5..000000000 --- a/app/src/main/kotlin/com/simplemobiletools/notes/models/Note.kt +++ /dev/null @@ -1,18 +0,0 @@ -package com.simplemobiletools.notes.models - -import java.io.File -import java.io.FileNotFoundException - -data class Note(var id: Int, var title: String, var value: String, val type: Int, var path: String = "") { - fun getNoteStoredValue(): String? { - return if (path.isNotEmpty()) { - return try { - File(path).readText() - } catch (e: FileNotFoundException) { - null - } - } else { - value - } - } -} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/App.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/App.kt similarity index 56% rename from app/src/main/kotlin/com/simplemobiletools/notes/App.kt rename to app/src/main/kotlin/com/simplemobiletools/notes/pro/App.kt index 73197703a..5885e823d 100644 --- a/app/src/main/kotlin/com/simplemobiletools/notes/App.kt +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/App.kt @@ -1,16 +1,11 @@ -package com.simplemobiletools.notes +package com.simplemobiletools.notes.pro import android.app.Application -import com.facebook.stetho.Stetho import com.simplemobiletools.commons.extensions.checkUseEnglish class App : Application() { override fun onCreate() { super.onCreate() - if (BuildConfig.DEBUG) { - Stetho.initializeWithDefaults(this) - } - checkUseEnglish() } } diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/activities/MainActivity.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/activities/MainActivity.kt new file mode 100644 index 000000000..77414759e --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/activities/MainActivity.kt @@ -0,0 +1,1300 @@ +package com.simplemobiletools.notes.pro.activities + +import android.accounts.NetworkErrorException +import android.annotation.SuppressLint +import android.app.Activity +import android.content.ActivityNotFoundException +import android.content.Context +import android.content.Intent +import android.content.pm.ShortcutInfo +import android.content.pm.ShortcutManager +import android.graphics.drawable.Icon +import android.graphics.drawable.LayerDrawable +import android.net.Uri +import android.os.Bundle +import android.print.PrintAttributes +import android.print.PrintManager +import android.text.method.ArrowKeyMovementMethod +import android.text.method.LinkMovementMethod +import android.util.TypedValue +import android.view.ActionMode +import android.view.Gravity +import android.view.MenuItem +import android.view.inputmethod.EditorInfo +import android.webkit.WebResourceRequest +import android.webkit.WebView +import android.webkit.WebViewClient +import android.widget.ImageView +import android.widget.TextView +import android.widget.Toast +import androidx.viewpager.widget.ViewPager +import com.simplemobiletools.commons.dialogs.* +import com.simplemobiletools.commons.extensions.* +import com.simplemobiletools.commons.helpers.* +import com.simplemobiletools.commons.models.FAQItem +import com.simplemobiletools.commons.models.FileDirItem +import com.simplemobiletools.commons.models.RadioItem +import com.simplemobiletools.commons.models.Release +import com.simplemobiletools.commons.views.MyEditText +import com.simplemobiletools.notes.pro.BuildConfig +import com.simplemobiletools.notes.pro.R +import com.simplemobiletools.notes.pro.adapters.NotesPagerAdapter +import com.simplemobiletools.notes.pro.databases.NotesDatabase +import com.simplemobiletools.notes.pro.databinding.ActivityMainBinding +import com.simplemobiletools.notes.pro.dialogs.* +import com.simplemobiletools.notes.pro.extensions.* +import com.simplemobiletools.notes.pro.fragments.TextFragment +import com.simplemobiletools.notes.pro.helpers.* +import com.simplemobiletools.notes.pro.models.Note +import com.simplemobiletools.notes.pro.models.NoteType +import java.io.File +import java.nio.charset.Charset +import java.util.* + +class MainActivity : SimpleActivity() { + private val EXPORT_FILE_SYNC = 1 + private val EXPORT_FILE_NO_SYNC = 2 + + private val IMPORT_FILE_SYNC = 1 + private val IMPORT_FILE_NO_SYNC = 2 + + private val PICK_OPEN_FILE_INTENT = 1 + private val PICK_EXPORT_FILE_INTENT = 2 + + private lateinit var mCurrentNote: Note + private var mNotes = listOf() + private var mAdapter: NotesPagerAdapter? = null + private var noteViewWithTextSelected: MyEditText? = null + private var saveNoteButton: MenuItem? = null + + private var wasInit = false + private var storedEnableLineWrap = true + private var showSaveButton = false + private var showUndoButton = false + private var showRedoButton = false + private var searchIndex = 0 + private var searchMatches = emptyList() + private var isSearchActive = false + + private lateinit var searchQueryET: MyEditText + private lateinit var searchPrevBtn: ImageView + private lateinit var searchNextBtn: ImageView + private lateinit var searchClearBtn: ImageView + + private val binding by viewBinding(ActivityMainBinding::inflate) + + override fun onCreate(savedInstanceState: Bundle?) { + isMaterialActivity = true + super.onCreate(savedInstanceState) + setContentView(binding.root) + appLaunched(BuildConfig.APPLICATION_ID) + setupOptionsMenu() + refreshMenuItems() + + updateMaterialActivityViews(binding.mainCoordinator, null, useTransparentNavigation = false, useTopSearchMenu = false) + + searchQueryET = findViewById(com.simplemobiletools.commons.R.id.search_query) + searchPrevBtn = findViewById(com.simplemobiletools.commons.R.id.search_previous) + searchNextBtn = findViewById(com.simplemobiletools.commons.R.id.search_next) + searchClearBtn = findViewById(com.simplemobiletools.commons.R.id.search_clear) + + val noteToOpen = intent.getLongExtra(OPEN_NOTE_ID, -1L) + initViewPager(noteToOpen) + binding.pagerTabStrip.drawFullUnderline = false + val textSize = getPercentageFontSize() + binding.pagerTabStrip.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize) + binding.pagerTabStrip.layoutParams.height = + (textSize + resources.getDimension(com.simplemobiletools.commons.R.dimen.medium_margin) * 2).toInt() + (binding.pagerTabStrip.layoutParams as ViewPager.LayoutParams).isDecor = true + + val hasNoIntent = intent.action.isNullOrEmpty() && noteToOpen == -1L + + checkWhatsNewDialog() + checkIntents(intent) + + storeStateVariables() + if (config.showNotePicker && savedInstanceState == null && hasNoIntent) { + displayOpenNoteDialog() + } + + wasInit = true + + checkAppOnSDCard() + setupSearchButtons() + + if (isPackageInstalled("com.simplemobiletools.notes")) { + val dialogText = getString(com.simplemobiletools.commons.R.string.upgraded_from_free_notes) + ConfirmationDialog(this, dialogText, 0, com.simplemobiletools.commons.R.string.ok, 0, false) {} + } + } + + override fun onResume() { + super.onResume() + setupToolbar(binding.mainToolbar) + if (storedEnableLineWrap != config.enableLineWrap) { + initViewPager() + } + + NotesHelper(this).getNotes { lastestNotes -> + if (mNotes.size != lastestNotes.size) { + initViewPager() + } + } + + refreshMenuItems() + binding.pagerTabStrip.apply { + val textSize = getPercentageFontSize() + setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize) + layoutParams.height = + (textSize + resources.getDimension(com.simplemobiletools.commons.R.dimen.medium_margin) * 2).toInt() + setGravity(Gravity.CENTER_VERTICAL) + setNonPrimaryAlpha(0.4f) + setTextColor(getProperPrimaryColor()) + tabIndicatorColor = getProperPrimaryColor() + } + updateTextColors(binding.viewPager) + + checkShortcuts() + + binding.searchWrapper.setBackgroundColor(getProperStatusBarColor()) + val contrastColor = getProperPrimaryColor().getContrastColor() + arrayListOf(searchPrevBtn, searchNextBtn, searchClearBtn).forEach { + it.applyColorFilter(contrastColor) + } + + updateTopBarColors(binding.mainToolbar, getProperBackgroundColor()) + } + + override fun onPause() { + super.onPause() + storeStateVariables() + } + + override fun onDestroy() { + super.onDestroy() + if (!isChangingConfigurations) { + NotesDatabase.destroyInstance() + } + } + + private fun refreshMenuItems() { + val multipleNotesExist = mNotes.size > 1 + val isCurrentItemChecklist = isCurrentItemChecklist() + + binding.mainToolbar.menu.apply { + findItem(R.id.undo).apply { + isVisible = showUndoButton && mCurrentNote.type == NoteType.TYPE_TEXT + icon?.alpha = if (isEnabled) 255 else 127 + } + + findItem(R.id.redo).apply { + isVisible = showRedoButton && mCurrentNote.type == NoteType.TYPE_TEXT + icon?.alpha = if (isEnabled) 255 else 127 + } + + findItem(R.id.rename_note).isVisible = multipleNotesExist + findItem(R.id.open_note).isVisible = multipleNotesExist + findItem(R.id.delete_note).isVisible = multipleNotesExist + findItem(R.id.open_search).isVisible = !isCurrentItemChecklist + findItem(R.id.remove_done_items).isVisible = isCurrentItemChecklist + findItem(R.id.sort_checklist).isVisible = isCurrentItemChecklist + findItem(R.id.import_folder).isVisible = !isQPlus() + findItem(R.id.lock_note).isVisible = mNotes.isNotEmpty() && (::mCurrentNote.isInitialized && !mCurrentNote.isLocked()) + findItem(R.id.unlock_note).isVisible = mNotes.isNotEmpty() && (::mCurrentNote.isInitialized && mCurrentNote.isLocked()) + findItem(R.id.more_apps_from_us).isVisible = !resources.getBoolean(com.simplemobiletools.commons.R.bool.hide_google_relations) + + saveNoteButton = findItem(R.id.save_note) + saveNoteButton!!.isVisible = + !config.autosaveNotes && showSaveButton && (::mCurrentNote.isInitialized && mCurrentNote.type == NoteType.TYPE_TEXT) + } + + binding.pagerTabStrip.beVisibleIf(multipleNotesExist) + } + + private fun setupOptionsMenu() { + binding.mainToolbar.setOnMenuItemClickListener { menuItem -> + if (config.autosaveNotes && menuItem.itemId != R.id.undo && menuItem.itemId != R.id.redo) { + saveCurrentNote(false) + } + + val fragment = getCurrentFragment() + when (menuItem.itemId) { + R.id.open_search -> fragment?.handleUnlocking { openSearch() } + R.id.open_note -> displayOpenNoteDialog() + R.id.save_note -> fragment?.handleUnlocking { saveNote() } + R.id.undo -> undo() + R.id.redo -> redo() + R.id.new_note -> displayNewNoteDialog() + R.id.rename_note -> fragment?.handleUnlocking { displayRenameDialog() } + R.id.share -> fragment?.handleUnlocking { shareText() } + R.id.cab_create_shortcut -> createShortcut() + R.id.lock_note -> lockNote() + R.id.unlock_note -> unlockNote() + R.id.open_file -> tryOpenFile() + R.id.import_folder -> openFolder() + R.id.export_as_file -> fragment?.handleUnlocking { tryExportAsFile() } + R.id.print -> fragment?.handleUnlocking { printText() } + R.id.delete_note -> fragment?.handleUnlocking { displayDeleteNotePrompt() } + R.id.more_apps_from_us -> launchMoreAppsFromUsIntent() + R.id.settings -> launchSettings() + R.id.about -> launchAbout() + R.id.remove_done_items -> fragment?.handleUnlocking { removeDoneItems() } + R.id.sort_checklist -> fragment?.handleUnlocking { displaySortChecklistDialog() } + else -> return@setOnMenuItemClickListener false + } + return@setOnMenuItemClickListener true + } + } + + // https://code.google.com/p/android/issues/detail?id=191430 quickfix + override fun onActionModeStarted(mode: ActionMode?) { + super.onActionModeStarted(mode) + if (wasInit) { + currentNotesView()?.apply { + if (config.clickableLinks || movementMethod is LinkMovementMethod || movementMethod is MyMovementMethod) { + movementMethod = ArrowKeyMovementMethod.getInstance() + noteViewWithTextSelected = this + } + } + } + } + + override fun onActionModeFinished(mode: ActionMode?) { + super.onActionModeFinished(mode) + if (config.clickableLinks) { + noteViewWithTextSelected?.movementMethod = MyMovementMethod.getInstance() + } + } + + override fun onBackPressed() { + if (!config.autosaveNotes && mAdapter?.anyHasUnsavedChanges() == true) { + ConfirmationAdvancedDialog( + this, + "", + R.string.unsaved_changes_warning, + com.simplemobiletools.commons.R.string.save, + com.simplemobiletools.commons.R.string.discard + ) { + if (it) { + mAdapter?.saveAllFragmentTexts() + } + super.onBackPressed() + } + } else if (isSearchActive) { + closeSearch() + } else { + super.onBackPressed() + } + } + + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + val wantedNoteId = intent.getLongExtra(OPEN_NOTE_ID, -1L) + binding.viewPager.currentItem = getWantedNoteIndex(wantedNoteId) + checkIntents(intent) + } + + override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) { + super.onActivityResult(requestCode, resultCode, resultData) + if (requestCode == PICK_OPEN_FILE_INTENT && resultCode == RESULT_OK && resultData != null && resultData.data != null) { + importUri(resultData.data!!) + } else if (requestCode == PICK_EXPORT_FILE_INTENT && resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null && mNotes.isNotEmpty()) { + val takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION + applicationContext.contentResolver.takePersistableUriPermission(resultData.data!!, takeFlags) + showExportFilePickUpdateDialog(resultData.dataString!!, getCurrentNoteValue()) + } + } + + private fun isCurrentItemChecklist() = if (::mCurrentNote.isInitialized) mCurrentNote.type == NoteType.TYPE_CHECKLIST else false + + @SuppressLint("NewApi") + private fun checkShortcuts() { + val appIconColor = config.appIconColor + if (isNougatMR1Plus() && config.lastHandledShortcutColor != appIconColor) { + val newTextNote = getNewTextNoteShortcut(appIconColor) + val newChecklist = getNewChecklistShortcut(appIconColor) + + try { + shortcutManager.dynamicShortcuts = Arrays.asList(newTextNote, newChecklist) + config.lastHandledShortcutColor = appIconColor + } catch (ignored: Exception) { + } + } + } + + @SuppressLint("NewApi") + private fun getNewTextNoteShortcut(appIconColor: Int): ShortcutInfo { + val shortLabel = getString(R.string.text_note) + val longLabel = getString(R.string.new_text_note) + val drawable = resources.getDrawable(com.simplemobiletools.commons.R.drawable.shortcut_plus) + (drawable as LayerDrawable).findDrawableByLayerId(R.id.shortcut_plus_background).applyColorFilter(appIconColor) + val bmp = drawable.convertToBitmap() + + val intent = Intent(this, MainActivity::class.java) + intent.action = Intent.ACTION_VIEW + intent.putExtra(NEW_TEXT_NOTE, true) + return ShortcutInfo.Builder(this, SHORTCUT_NEW_TEXT_NOTE) + .setShortLabel(shortLabel) + .setLongLabel(longLabel) + .setIcon(Icon.createWithBitmap(bmp)) + .setIntent(intent) + .build() + } + + @SuppressLint("NewApi") + private fun getNewChecklistShortcut(appIconColor: Int): ShortcutInfo { + val shortLabel = getString(R.string.checklist) + val longLabel = getString(R.string.new_checklist) + val drawable = resources.getDrawable(R.drawable.shortcut_check) + (drawable as LayerDrawable).findDrawableByLayerId(R.id.shortcut_plus_background).applyColorFilter(appIconColor) + val bmp = drawable.convertToBitmap() + + val intent = Intent(this, MainActivity::class.java) + intent.action = Intent.ACTION_VIEW + intent.putExtra(NEW_CHECKLIST, true) + return ShortcutInfo.Builder(this, SHORTCUT_NEW_CHECKLIST) + .setShortLabel(shortLabel) + .setLongLabel(longLabel) + .setIcon(Icon.createWithBitmap(bmp)) + .setIntent(intent) + .build() + } + + private fun checkIntents(intent: Intent) { + intent.apply { + if (action == Intent.ACTION_SEND && type == MIME_TEXT_PLAIN) { + getStringExtra(Intent.EXTRA_TEXT)?.let { + handleTextIntent(it) + intent.removeExtra(Intent.EXTRA_TEXT) + } + } + + if (action == Intent.ACTION_VIEW) { + val realPath = intent.getStringExtra(REAL_FILE_PATH) + val isFromHistory = intent.flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY != 0 + if (!isFromHistory) { + if (realPath != null && hasPermission(PERMISSION_READ_STORAGE)) { + val file = File(realPath) + handleUri(Uri.fromFile(file)) + } else if (intent.getBooleanExtra(NEW_TEXT_NOTE, false)) { + val newTextNote = Note(null, getCurrentFormattedDateTime(), "", NoteType.TYPE_TEXT, "", PROTECTION_NONE, "") + addNewNote(newTextNote) + } else if (intent.getBooleanExtra(NEW_CHECKLIST, false)) { + val newChecklist = Note(null, getCurrentFormattedDateTime(), "", NoteType.TYPE_CHECKLIST, "", PROTECTION_NONE, "") + addNewNote(newChecklist) + } else { + handleUri(data!!) + } + } + intent.removeCategory(Intent.CATEGORY_DEFAULT) + intent.action = null + intent.removeExtra(NEW_CHECKLIST) + intent.removeExtra(NEW_TEXT_NOTE) + } + } + } + + private fun storeStateVariables() { + config.apply { + storedEnableLineWrap = enableLineWrap + } + } + + private fun handleTextIntent(text: String) { + NotesHelper(this).getNotes { + val notes = it + val list = arrayListOf().apply { + add(RadioItem(0, getString(R.string.create_new_note))) + notes.forEachIndexed { index, note -> + add(RadioItem(index + 1, note.title)) + } + } + + RadioGroupDialog(this, list, -1, R.string.add_to_note) { + if (it as Int == 0) { + displayNewNoteDialog(text) + } else { + updateSelectedNote(notes[it - 1].id!!) + addTextToCurrentNote(if (mCurrentNote.value.isEmpty()) text else "\n$text") + } + } + } + } + + private fun handleUri(uri: Uri) { + NotesHelper(this).getNoteIdWithPath(uri.path!!) { + if (it != null && it > 0L) { + updateSelectedNote(it) + return@getNoteIdWithPath + } + + NotesHelper(this).getNotes { + mNotes = it + importUri(uri) + } + } + } + + private fun initViewPager(wantedNoteId: Long? = null) { + NotesHelper(this).getNotes { notes -> + notes.filter { it.shouldBeUnlocked(this) } + .forEach(::removeProtection) + + mNotes = notes + mCurrentNote = mNotes[0] + mAdapter = NotesPagerAdapter(supportFragmentManager, mNotes, this) + binding.viewPager.apply { + adapter = mAdapter + currentItem = getWantedNoteIndex(wantedNoteId) + config.currentNoteId = mCurrentNote.id!! + + onPageChangeListener { + mCurrentNote = mNotes[it] + config.currentNoteId = mCurrentNote.id!! + refreshMenuItems() + } + } + + if (!config.showKeyboard || mCurrentNote.type == NoteType.TYPE_CHECKLIST) { + hideKeyboard() + } + refreshMenuItems() + } + } + + private fun setupSearchButtons() { + searchQueryET.onTextChangeListener { + searchTextChanged(it) + } + + searchPrevBtn.setOnClickListener { + goToPrevSearchResult() + } + + searchNextBtn.setOnClickListener { + goToNextSearchResult() + } + + searchClearBtn.setOnClickListener { + closeSearch() + } + + binding.viewPager.onPageChangeListener { + currentTextFragment?.removeTextWatcher() + currentNotesView()?.let { noteView -> + noteView.text!!.clearBackgroundSpans() + } + + closeSearch() + currentTextFragment?.setTextWatcher() + } + + searchQueryET.setOnEditorActionListener(TextView.OnEditorActionListener { _, actionId, _ -> + if (actionId == EditorInfo.IME_ACTION_SEARCH) { + searchNextBtn.performClick() + return@OnEditorActionListener true + } + + false + }) + } + + private fun searchTextChanged(text: String) { + currentNotesView()?.let { noteView -> + currentTextFragment?.removeTextWatcher() + noteView.text!!.clearBackgroundSpans() + + if (text.isNotBlank() && text.length > 1) { + searchMatches = noteView.value.searchMatches(text) + noteView.highlightText(text, getProperPrimaryColor()) + } + + currentTextFragment?.setTextWatcher() + + if (searchMatches.isNotEmpty()) { + noteView.requestFocus() + noteView.setSelection(searchMatches.getOrNull(searchIndex) ?: 0) + } + + searchQueryET.postDelayed({ + searchQueryET.requestFocus() + }, 50) + } + } + + private fun goToPrevSearchResult() { + currentNotesView()?.let { noteView -> + if (searchIndex > 0) { + searchIndex-- + } else { + searchIndex = searchMatches.lastIndex + } + + selectSearchMatch(noteView) + } + } + + private fun goToNextSearchResult() { + currentNotesView()?.let { noteView -> + if (searchIndex < searchMatches.lastIndex) { + searchIndex++ + } else { + searchIndex = 0 + } + + selectSearchMatch(noteView) + } + } + + private fun getCurrentFragment() = mAdapter?.getFragment(binding.viewPager.currentItem) + + private val currentTextFragment: TextFragment? get() = mAdapter?.textFragment(binding.viewPager.currentItem) + + private fun selectSearchMatch(editText: MyEditText) { + if (searchMatches.isNotEmpty()) { + editText.requestFocus() + editText.setSelection(searchMatches.getOrNull(searchIndex) ?: 0) + } else { + hideKeyboard() + } + } + + private fun openSearch() { + isSearchActive = true + binding.searchWrapper.fadeIn() + showKeyboard(searchQueryET) + + currentNotesView()?.let { noteView -> + noteView.requestFocus() + noteView.setSelection(0) + } + + searchQueryET.postDelayed({ + searchQueryET.requestFocus() + }, 250) + } + + private fun closeSearch() { + searchQueryET.text?.clear() + isSearchActive = false + binding.searchWrapper.fadeOut() + hideKeyboard() + } + + private fun getWantedNoteIndex(wantedNoteId: Long?): Int { + intent.removeExtra(OPEN_NOTE_ID) + val noteIdToOpen = if (wantedNoteId == null || wantedNoteId == -1L) config.currentNoteId else wantedNoteId + return getNoteIndexWithId(noteIdToOpen) + } + + private fun currentNotesView() = if (binding.viewPager == null) { + null + } else { + mAdapter?.getCurrentNotesView(binding.viewPager.currentItem) + } + + private fun displayRenameDialog() { + RenameNoteDialog(this, mCurrentNote, getCurrentNoteText()) { + mCurrentNote = it + initViewPager(mCurrentNote.id) + } + } + + private fun updateSelectedNote(id: Long) { + config.currentNoteId = id + if (mNotes.isEmpty()) { + NotesHelper(this).getNotes { + mNotes = it + updateSelectedNote(id) + } + } else { + val index = getNoteIndexWithId(id) + binding.viewPager.currentItem = index + mCurrentNote = mNotes[index] + } + } + + private fun displayNewNoteDialog(value: String = "", title: String? = null, path: String = "", setChecklistAsDefault: Boolean = false) { + NewNoteDialog(this, title, setChecklistAsDefault) { + it.value = value + it.path = path + addNewNote(it) + } + } + + private fun addNewNote(note: Note) { + NotesHelper(this).insertOrUpdateNote(note) { + val newNoteId = it + showSaveButton = false + showUndoButton = false + showRedoButton = false + initViewPager(newNoteId) + updateSelectedNote(newNoteId) + binding.viewPager.onGlobalLayout { + mAdapter?.focusEditText(getNoteIndexWithId(newNoteId)) + } + } + } + + private fun launchSettings() { + hideKeyboard() + startActivity(Intent(applicationContext, SettingsActivity::class.java)) + } + + private fun launchAbout() { + val licenses = LICENSE_RTL + + val faqItems = arrayListOf( + FAQItem(com.simplemobiletools.commons.R.string.faq_1_title_commons, com.simplemobiletools.commons.R.string.faq_1_text_commons), + FAQItem(R.string.faq_1_title, R.string.faq_1_text) + ) + + if (!resources.getBoolean(com.simplemobiletools.commons.R.bool.hide_google_relations)) { + faqItems.add(FAQItem(com.simplemobiletools.commons.R.string.faq_2_title_commons, com.simplemobiletools.commons.R.string.faq_2_text_commons)) + faqItems.add(FAQItem(com.simplemobiletools.commons.R.string.faq_6_title_commons, com.simplemobiletools.commons.R.string.faq_6_text_commons)) + faqItems.add(FAQItem(com.simplemobiletools.commons.R.string.faq_7_title_commons, com.simplemobiletools.commons.R.string.faq_7_text_commons)) + faqItems.add(FAQItem(com.simplemobiletools.commons.R.string.faq_10_title_commons, com.simplemobiletools.commons.R.string.faq_10_text_commons)) + } + + startAboutActivity(R.string.app_name, licenses, BuildConfig.VERSION_NAME, faqItems, true) + } + + private fun tryOpenFile() { + hideKeyboard() + if (hasPermission(PERMISSION_READ_STORAGE)) { + openFile() + } else { + Intent(Intent.ACTION_OPEN_DOCUMENT).apply { + addCategory(Intent.CATEGORY_OPENABLE) + type = "*/*" + + try { + val mimetypes = arrayOf("text/*", "application/json") + putExtra(Intent.EXTRA_MIME_TYPES, mimetypes) + startActivityForResult(this, PICK_OPEN_FILE_INTENT) + } catch (e: ActivityNotFoundException) { + toast(com.simplemobiletools.commons.R.string.system_service_disabled, Toast.LENGTH_LONG) + } catch (e: Exception) { + showErrorToast(e) + } + } + } + } + + private fun openFile() { + FilePickerDialog(this, canAddShowHiddenButton = true) { + checkFile(it, true) { + ensureBackgroundThread { + val fileText = it.readText().trim() + val checklistItems = fileText.parseChecklistItems() + if (checklistItems != null) { + val title = it.absolutePath.getFilenameFromPath().substringBeforeLast('.') + val note = Note(null, title, fileText, NoteType.TYPE_CHECKLIST, "", PROTECTION_NONE, "") + runOnUiThread { + OpenFileDialog(this, it.path) { + displayNewNoteDialog(note.value, title = it.title, it.path, setChecklistAsDefault = true) + } + } + } else { + runOnUiThread { + OpenFileDialog(this, it.path) { + displayNewNoteDialog(it.value, title = it.title, it.path) + } + } + } + } + } + } + } + + private fun checkFile(path: String, checkTitle: Boolean, onChecksPassed: (file: File) -> Unit) { + val file = File(path) + if (path.isMediaFile()) { + toast(com.simplemobiletools.commons.R.string.invalid_file_format) + } else if (file.length() > 1000 * 1000) { + toast(R.string.file_too_large) + } else if (checkTitle && mNotes.any { it.title.equals(path.getFilenameFromPath(), true) }) { + toast(R.string.title_taken) + } else { + onChecksPassed(file) + } + } + + private fun checkUri(uri: Uri, onChecksPassed: () -> Unit) { + val inputStream = try { + contentResolver.openInputStream(uri) ?: return + } catch (e: Exception) { + showErrorToast(e) + return + } + + if (inputStream.available() > 1000 * 1000) { + toast(R.string.file_too_large) + } else { + onChecksPassed() + } + } + + private fun openFolder(path: String, onChecksPassed: (file: File) -> Unit) { + val file = File(path) + if (file.isDirectory) { + onChecksPassed(file) + } + } + + private fun importUri(uri: Uri) { + when (uri.scheme) { + "file" -> openPath(uri.path!!) + "content" -> { + val realPath = getRealPathFromURI(uri) + if (hasPermission(PERMISSION_READ_STORAGE)) { + if (realPath != null) { + openPath(realPath) + } else { + com.simplemobiletools.commons.R.string.unknown_error_occurred + } + } else if (realPath != null && realPath != "") { + checkFile(realPath, false) { + addNoteFromUri(uri, realPath.getFilenameFromPath()) + } + } else { + checkUri(uri) { + addNoteFromUri(uri) + } + } + } + } + } + + private fun addNoteFromUri(uri: Uri, filename: String? = null) { + val noteTitle = when { + filename?.isEmpty() == false -> filename + uri.toString().startsWith("content://") -> getFilenameFromContentUri(uri) ?: getNewNoteTitle() + else -> getNewNoteTitle() + } + + val inputStream = contentResolver.openInputStream(uri) + val content = inputStream?.bufferedReader().use { it!!.readText() } + val checklistItems = content.parseChecklistItems() + + // if we got here by some other app invoking the file open intent, we have no permission for updating the original file itself + // we can do it only after using "Export as file" or "Open file" from our app + val canSyncNoteWithFile = if (hasPermission(PERMISSION_WRITE_STORAGE)) { + true + } else { + try { + val takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION + applicationContext.contentResolver.takePersistableUriPermission(uri, takeFlags) + true + } catch (e: Exception) { + false + } + } + + val noteType = if (checklistItems != null) NoteType.TYPE_CHECKLIST else NoteType.TYPE_TEXT + if (!canSyncNoteWithFile) { + val note = Note(null, noteTitle, content, noteType, "", PROTECTION_NONE, "") + displayNewNoteDialog(note.value, title = noteTitle, "") + } else { + val items = arrayListOf( + RadioItem(IMPORT_FILE_SYNC, getString(R.string.update_file_at_note)), + RadioItem(IMPORT_FILE_NO_SYNC, getString(R.string.only_import_file_content)) + ) + + RadioGroupDialog(this, items) { + val syncFile = it as Int == IMPORT_FILE_SYNC + val path = if (syncFile) uri.toString() else "" + val note = Note(null, noteTitle, content, noteType, "", PROTECTION_NONE, "") + displayNewNoteDialog(note.value, title = noteTitle, path) + } + } + } + + private fun openPath(path: String) { + checkFile(path, false) { + val title = path.getFilenameFromPath() + try { + val fileText = it.readText().trim() + val checklistItems = fileText.parseChecklistItems() + val note = if (checklistItems != null) { + Note(null, title.substringBeforeLast('.'), fileText, NoteType.TYPE_CHECKLIST, "", PROTECTION_NONE, "") + } else { + Note(null, title, "", NoteType.TYPE_TEXT, path, PROTECTION_NONE, "") + } + + if (mNotes.any { it.title.equals(note.title, true) }) { + note.title += " (file)" + } + + addNewNote(note) + } catch (e: Exception) { + showErrorToast(e) + } + } + } + + private fun openFolder() { + handlePermission(PERMISSION_READ_STORAGE) { hasPermission -> + if (hasPermission) { + FilePickerDialog(this, pickFile = false, canAddShowHiddenButton = true) { + openFolder(it) { + ImportFolderDialog(this, it.path) { + NotesHelper(this).getNotes { + mNotes = it + showSaveButton = false + initViewPager() + } + } + } + } + } else { + toast(com.simplemobiletools.commons.R.string.no_storage_permissions) + } + } + } + + private fun getNewNoteTitle(): String { + val base = getString(R.string.text_note) + var i = 1 + while (true) { + val tryTitle = "$base $i" + if (mNotes.none { it.title == tryTitle }) { + return tryTitle + } + i++ + } + } + + private fun tryExportAsFile() { + hideKeyboard() + if (hasPermission(PERMISSION_WRITE_STORAGE)) { + exportAsFile() + } else { + Intent(Intent.ACTION_CREATE_DOCUMENT).apply { + type = "text/*" + putExtra(Intent.EXTRA_TITLE, "${mCurrentNote.title.removeSuffix(".txt")}.txt") + addCategory(Intent.CATEGORY_OPENABLE) + + try { + startActivityForResult(this, PICK_EXPORT_FILE_INTENT) + } catch (e: ActivityNotFoundException) { + toast(com.simplemobiletools.commons.R.string.system_service_disabled, Toast.LENGTH_LONG) + } catch (e: NetworkErrorException) { + toast(getString(R.string.cannot_load_over_internet), Toast.LENGTH_LONG) + } catch (e: Exception) { + showErrorToast(e) + } + } + } + } + + private fun exportAsFile() { + ExportFileDialog(this, mCurrentNote) { + val textToExport = if (mCurrentNote.type == NoteType.TYPE_TEXT) getCurrentNoteText() else mCurrentNote.value + if (textToExport == null || textToExport.isEmpty()) { + toast(com.simplemobiletools.commons.R.string.unknown_error_occurred) + } else if (mCurrentNote.type == NoteType.TYPE_TEXT) { + showExportFilePickUpdateDialog(it, textToExport) + } else { + tryExportNoteValueToFile(it, mCurrentNote.title, textToExport, true) + } + } + } + + private fun showExportFilePickUpdateDialog(exportPath: String, textToExport: String) { + val items = arrayListOf( + RadioItem(EXPORT_FILE_SYNC, getString(R.string.update_file_at_note)), + RadioItem(EXPORT_FILE_NO_SYNC, getString(R.string.only_export_file_content)) + ) + + RadioGroupDialog(this, items) { + val syncFile = it as Int == EXPORT_FILE_SYNC + tryExportNoteValueToFile(exportPath, mCurrentNote.title, textToExport, true) { exportedSuccessfully -> + if (exportedSuccessfully) { + if (syncFile) { + mCurrentNote.path = exportPath + mCurrentNote.value = "" + } else { + mCurrentNote.path = "" + mCurrentNote.value = textToExport + } + + getPagerAdapter().updateCurrentNoteData(binding.viewPager.currentItem, mCurrentNote.path, mCurrentNote.value) + NotesHelper(this).insertOrUpdateNote(mCurrentNote) + } + } + } + } + + fun tryExportNoteValueToFile(path: String, title: String, content: String, showSuccessToasts: Boolean, callback: ((success: Boolean) -> Unit)? = null) { + if (path.startsWith("content://")) { + exportNoteValueToUri(Uri.parse(path), title, content, showSuccessToasts, callback) + } else { + handlePermission(PERMISSION_WRITE_STORAGE) { + if (it) { + exportNoteValueToFile(path, content, showSuccessToasts, callback) + } + } + } + } + + private fun exportNoteValueToFile(path: String, content: String, showSuccessToasts: Boolean, callback: ((success: Boolean) -> Unit)? = null) { + try { + if (File(path).isDirectory) { + toast(com.simplemobiletools.commons.R.string.name_taken) + return + } + + if (needsStupidWritePermissions(path)) { + handleSAFDialog(path) { + val document = if (File(path).exists()) { + getDocumentFile(path) ?: return@handleSAFDialog + } else { + val parent = getDocumentFile(File(path).parent) ?: return@handleSAFDialog + parent.createFile("", path.getFilenameFromPath())!! + } + + contentResolver.openOutputStream(document.uri)!!.apply { + val byteArray = content.toByteArray(Charset.forName("UTF-8")) + write(byteArray, 0, byteArray.size) + flush() + close() + } + + if (showSuccessToasts) { + noteExportedSuccessfully(path.getFilenameFromPath()) + } + callback?.invoke(true) + } + } else { + val file = File(path) + file.writeText(content) + + if (showSuccessToasts) { + noteExportedSuccessfully(path.getFilenameFromPath()) + } + callback?.invoke(true) + } + } catch (e: Exception) { + showErrorToast(e) + callback?.invoke(false) + } + } + + private fun exportNoteValueToUri(uri: Uri, title: String, content: String, showSuccessToasts: Boolean, callback: ((success: Boolean) -> Unit)? = null) { + try { + val outputStream = contentResolver.openOutputStream(uri, "rwt") + outputStream!!.bufferedWriter().use { out -> + out.write(content) + } + if (showSuccessToasts) { + noteExportedSuccessfully(title) + } + callback?.invoke(true) + } catch (e: Exception) { + showErrorToast(e) + callback?.invoke(false) + } + } + + private fun noteExportedSuccessfully(title: String) { + val message = String.format(getString(R.string.note_exported_successfully), title) + toast(message) + } + + fun noteSavedSuccessfully(title: String) { + if (config.displaySuccess) { + val message = String.format(getString(R.string.note_saved_successfully), title) + toast(message) + } + } + + private fun printText() { + try { + val webView = WebView(this) + webView.webViewClient = object : WebViewClient() { + override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest) = false + + override fun onPageFinished(view: WebView, url: String) { + createWebPrintJob(view) + } + } + + webView.loadData(getPrintableText().replace("#", "%23"), "text/plain", "UTF-8") + } catch (e: Exception) { + showErrorToast(e) + } + } + + private fun createWebPrintJob(webView: WebView) { + val jobName = mCurrentNote.title + val printAdapter = webView.createPrintDocumentAdapter(jobName) + + (getSystemService(Context.PRINT_SERVICE) as? PrintManager)?.apply { + try { + print(jobName, printAdapter, PrintAttributes.Builder().build()) + } catch (e: IllegalStateException) { + showErrorToast(e) + } + } + } + + private fun getPagerAdapter() = binding.viewPager.adapter as NotesPagerAdapter + + private fun getCurrentNoteText() = getPagerAdapter().getCurrentNoteViewText(binding.viewPager.currentItem) + + private fun getCurrentNoteValue(): String { + return if (mCurrentNote.type == NoteType.TYPE_TEXT) { + getCurrentNoteText() ?: "" + } else { + getPagerAdapter().getNoteChecklistItems(binding.viewPager.currentItem) ?: "" + } + } + + private fun getPrintableText(): String { + return if (mCurrentNote.type == NoteType.TYPE_TEXT) { + getCurrentNoteText() ?: "" + } else { + var printableText = "" + getPagerAdapter().getNoteChecklistRawItems(binding.viewPager.currentItem)?.forEach { + printableText += "${it.title}\n\n" + } + printableText + } + } + + private fun addTextToCurrentNote(text: String) = getPagerAdapter().appendText(binding.viewPager.currentItem, text) + + private fun saveCurrentNote(force: Boolean) { + getPagerAdapter().saveCurrentNote(binding.viewPager.currentItem, force) + if (mCurrentNote.type == NoteType.TYPE_CHECKLIST) { + mCurrentNote.value = getPagerAdapter().getNoteChecklistItems(binding.viewPager.currentItem) ?: "" + } + } + + private fun displayDeleteNotePrompt() { + DeleteNoteDialog(this, mCurrentNote) { + deleteNote(it, mCurrentNote) + } + } + + fun deleteNote(deleteFile: Boolean, note: Note) { + if (mNotes.size <= 1 || note != mCurrentNote) { + return + } + + if (!deleteFile) { + doDeleteNote(mCurrentNote, deleteFile) + } else { + handleSAFDialog(mCurrentNote.path) { + doDeleteNote(mCurrentNote, deleteFile) + } + } + } + + private fun doDeleteNote(note: Note, deleteFile: Boolean) { + ensureBackgroundThread { + val currentNoteIndex = mNotes.indexOf(note) + val noteToRefresh = mNotes[if (currentNoteIndex > 0) currentNoteIndex - 1 else currentNoteIndex + 1] + + notesDB.deleteNote(note) + widgetsDB.deleteNoteWidgets(note.id!!) + + refreshNotes(noteToRefresh, deleteFile) + } + } + + private fun refreshNotes(note: Note, deleteFile: Boolean) { + NotesHelper(this).getNotes { + mNotes = it + val noteId = note.id + updateSelectedNote(noteId!!) + if (config.widgetNoteId == note.id) { + config.widgetNoteId = mCurrentNote.id!! + updateWidgets() + } + + initViewPager() + + if (deleteFile) { + deleteFile(FileDirItem(note.path, note.title)) { + if (!it) { + toast(com.simplemobiletools.commons.R.string.unknown_error_occurred) + } + } + } + + if (it.size == 1 && config.showNotePicker) { + config.showNotePicker = false + } + } + } + + private fun displayOpenNoteDialog() { + OpenNoteDialog(this) { noteId, newNote -> + if (newNote == null) { + updateSelectedNote(noteId) + } else { + addNewNote(newNote) + } + } + } + + private fun saveNote() { + saveCurrentNote(true) + showSaveButton = false + refreshMenuItems() + } + + private fun undo() { + mAdapter?.undo(binding.viewPager.currentItem) + } + + private fun redo() { + mAdapter?.redo(binding.viewPager.currentItem) + } + + private fun getNoteIndexWithId(id: Long): Int { + for (i in 0 until mNotes.count()) { + if (mNotes[i].id == id) { + mCurrentNote = mNotes[i] + return i + } + } + return 0 + } + + private fun shareText() { + val text = if (mCurrentNote.type == NoteType.TYPE_TEXT) getCurrentNoteText() else mCurrentNote.value + if (text.isNullOrEmpty()) { + toast(R.string.cannot_share_empty_text) + return + } + + val res = resources + val shareTitle = res.getString(com.simplemobiletools.commons.R.string.share_via) + Intent().apply { + action = Intent.ACTION_SEND + putExtra(Intent.EXTRA_SUBJECT, mCurrentNote.title) + putExtra(Intent.EXTRA_TEXT, text) + type = "text/plain" + startActivity(Intent.createChooser(this, shareTitle)) + } + } + + @SuppressLint("NewApi") + private fun createShortcut() { + val manager = getSystemService(ShortcutManager::class.java) + if (manager.isRequestPinShortcutSupported) { + val note = mCurrentNote + val drawable = resources.getDrawable(R.drawable.shortcut_note).mutate() + val appIconColor = baseConfig.appIconColor + (drawable as LayerDrawable).findDrawableByLayerId(R.id.shortcut_plus_background).applyColorFilter(appIconColor) + + val intent = Intent(this, SplashActivity::class.java) + intent.action = Intent.ACTION_VIEW + intent.putExtra(OPEN_NOTE_ID, note.id) + intent.flags = intent.flags or Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NO_HISTORY + + val shortcut = ShortcutInfo.Builder(this, note.hashCode().toString()) + .setShortLabel(mCurrentNote.title) + .setIcon(Icon.createWithBitmap(drawable.convertToBitmap())) + .setIntent(intent) + .build() + + manager.requestPinShortcut(shortcut, null) + } + } + + private fun lockNote() { + ConfirmationDialog(this, "", R.string.locking_warning, com.simplemobiletools.commons.R.string.ok, com.simplemobiletools.commons.R.string.cancel) { + SecurityDialog(this, "", SHOW_ALL_TABS) { hash, type, success -> + if (success) { + mCurrentNote.protectionHash = hash + mCurrentNote.protectionType = type + NotesHelper(this).insertOrUpdateNote(mCurrentNote) { + refreshMenuItems() + } + } + } + } + } + + private fun unlockNote() { + performSecurityCheck( + protectionType = mCurrentNote.protectionType, + requiredHash = mCurrentNote.protectionHash, + successCallback = { _, _ -> removeProtection(mCurrentNote) } + ) + } + + private fun removeProtection(note: Note) { + note.protectionHash = "" + note.protectionType = PROTECTION_NONE + NotesHelper(this).insertOrUpdateNote(note) { + if (note == mCurrentNote) { + getCurrentFragment()?.apply { + shouldShowLockedContent = true + checkLockState() + } + refreshMenuItems() + } + } + } + + fun currentNoteTextChanged(newText: String, showUndo: Boolean, showRedo: Boolean) { + if (!isSearchActive) { + var shouldRecreateMenu = false + if (showUndo != showUndoButton) { + showUndoButton = showUndo + shouldRecreateMenu = true + } + + if (showRedo != showRedoButton) { + showRedoButton = showRedo + shouldRecreateMenu = true + } + + if (!config.autosaveNotes) { + showSaveButton = newText != mCurrentNote.value + if (showSaveButton != saveNoteButton?.isVisible) { + shouldRecreateMenu = true + } + } + + if (shouldRecreateMenu) { + refreshMenuItems() + } + } + } + + private fun checkWhatsNewDialog() { + arrayListOf().apply { + add(Release(25, R.string.release_25)) + add(Release(28, R.string.release_28)) + add(Release(29, R.string.release_29)) + add(Release(39, R.string.release_39)) + add(Release(45, R.string.release_45)) + add(Release(49, R.string.release_49)) + add(Release(51, R.string.release_51)) + add(Release(57, R.string.release_57)) + add(Release(62, R.string.release_62)) + add(Release(64, R.string.release_64)) + add(Release(67, R.string.release_67)) + add(Release(81, R.string.release_81)) + add(Release(86, R.string.release_86)) + checkWhatsNew(this, BuildConfig.VERSION_CODE) + } + } + + private fun removeDoneItems() { + getPagerAdapter().removeDoneCheckListItems(binding.viewPager.currentItem) + } + + private fun displaySortChecklistDialog() { + SortChecklistDialog(this) { + getPagerAdapter().refreshChecklist(binding.viewPager.currentItem) + updateWidgets() + } + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/activities/SettingsActivity.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/activities/SettingsActivity.kt new file mode 100644 index 000000000..11ed19aa7 --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/activities/SettingsActivity.kt @@ -0,0 +1,398 @@ +package com.simplemobiletools.notes.pro.activities + +import android.content.Intent +import android.net.Uri +import android.os.Bundle +import android.view.Menu +import androidx.activity.result.contract.ActivityResultContracts +import androidx.core.text.TextUtilsCompat +import androidx.core.view.ViewCompat +import com.simplemobiletools.commons.dialogs.RadioGroupDialog +import com.simplemobiletools.commons.extensions.* +import com.simplemobiletools.commons.helpers.* +import com.simplemobiletools.commons.models.RadioItem +import com.simplemobiletools.notes.pro.R +import com.simplemobiletools.notes.pro.databinding.ActivitySettingsBinding +import com.simplemobiletools.notes.pro.dialogs.ExportNotesDialog +import com.simplemobiletools.notes.pro.dialogs.ManageAutoBackupsDialog +import com.simplemobiletools.notes.pro.extensions.* +import com.simplemobiletools.notes.pro.helpers.* +import com.simplemobiletools.notes.pro.models.Note +import com.simplemobiletools.notes.pro.models.Widget +import kotlinx.serialization.SerializationException +import kotlinx.serialization.encodeToString +import kotlinx.serialization.json.Json +import java.util.Locale +import kotlin.system.exitProcess + +class SettingsActivity : SimpleActivity() { + private val notesFileType = "application/json" + private val binding by viewBinding(ActivitySettingsBinding::inflate) + + override fun onCreate(savedInstanceState: Bundle?) { + isMaterialActivity = true + super.onCreate(savedInstanceState) + setContentView(binding.root) + + updateMaterialActivityViews(binding.settingsCoordinator, binding.settingsHolder, useTransparentNavigation = true, useTopSearchMenu = false) + setupMaterialScrollListener(binding.settingsNestedScrollview, binding.settingsToolbar) + } + + override fun onResume() { + super.onResume() + setupToolbar(binding.settingsToolbar, NavigationIcon.Arrow) + + setupCustomizeColors() + setupUseEnglish() + setupLanguage() + setupAutosaveNotes() + setupDisplaySuccess() + setupClickableLinks() + setupMonospacedFont() + setupShowKeyboard() + setupShowNotePicker() + setupShowWordCount() + setupEnableLineWrap() + setupFontSize() + setupGravity() + setupCursorPlacement() + setupIncognitoMode() + setupCustomizeWidgetColors() + setupNotesExport() + setupNotesImport() + setupEnableAutomaticBackups() + setupManageAutomaticBackups() + updateTextColors(binding.settingsNestedScrollview) + + arrayOf( + binding.settingsColorCustomizationSectionLabel, + binding.settingsGeneralSettingsLabel, + binding.settingsTextLabel, + binding.settingsStartupLabel, + binding.settingsSavingLabel, + binding.settingsMigratingLabel, + binding.settingsBackupsLabel, + ).forEach { + it.setTextColor(getProperPrimaryColor()) + } + } + + override fun onCreateOptionsMenu(menu: Menu): Boolean { + updateMenuItemColors(menu) + return super.onCreateOptionsMenu(menu) + } + + private val getContent = registerForActivityResult(ActivityResultContracts.GetContent()) { uri -> + if (uri != null) { + toast(com.simplemobiletools.commons.R.string.importing) + importNotes(uri) + } + } + + private val saveDocument = registerForActivityResult(ActivityResultContracts.CreateDocument(notesFileType)) { uri -> + if (uri != null) { + toast(com.simplemobiletools.commons.R.string.exporting) + NotesHelper(this).getNotes { notes -> + requestUnlockNotes(notes) { unlockedNotes -> + val notLockedNotes = notes.filterNot { it.isLocked() } + val notesToExport = unlockedNotes + notLockedNotes + exportNotes(notesToExport, uri) + } + } + } + } + + private fun setupCustomizeColors() { + binding.settingsColorCustomizationHolder.setOnClickListener { + startCustomizationActivity() + } + } + + private fun setupUseEnglish() { + binding.settingsUseEnglishHolder.beVisibleIf((config.wasUseEnglishToggled || Locale.getDefault().language != "en") && !isTiramisuPlus()) + binding.settingsUseEnglish.isChecked = config.useEnglish + binding.settingsUseEnglishHolder.setOnClickListener { + binding.settingsUseEnglish.toggle() + config.useEnglish = binding.settingsUseEnglish.isChecked + exitProcess(0) + } + } + + private fun setupLanguage() { + binding.settingsLanguage.text = Locale.getDefault().displayLanguage + binding.settingsLanguageHolder.beVisibleIf(isTiramisuPlus()) + binding.settingsLanguageHolder.setOnClickListener { + launchChangeAppLanguageIntent() + } + } + + private fun setupAutosaveNotes() { + binding.settingsAutosaveNotes.isChecked = config.autosaveNotes + binding.settingsAutosaveNotesHolder.setOnClickListener { + binding.settingsAutosaveNotes.toggle() + config.autosaveNotes = binding.settingsAutosaveNotes.isChecked + } + } + + private fun setupDisplaySuccess() { + binding.settingsDisplaySuccess.isChecked = config.displaySuccess + binding.settingsDisplaySuccessHolder.setOnClickListener { + binding.settingsDisplaySuccess.toggle() + config.displaySuccess = binding.settingsDisplaySuccess.isChecked + } + } + + private fun setupClickableLinks() { + binding.settingsClickableLinks.isChecked = config.clickableLinks + binding.settingsClickableLinksHolder.setOnClickListener { + binding.settingsClickableLinks.toggle() + config.clickableLinks = binding.settingsClickableLinks.isChecked + } + } + + private fun setupMonospacedFont() { + binding.settingsMonospacedFont.isChecked = config.monospacedFont + binding.settingsMonospacedFontHolder.setOnClickListener { + binding.settingsMonospacedFont.toggle() + config.monospacedFont = binding.settingsMonospacedFont.isChecked + updateWidgets() + } + } + + private fun setupShowKeyboard() { + binding.settingsShowKeyboard.isChecked = config.showKeyboard + binding.settingsShowKeyboardHolder.setOnClickListener { + binding.settingsShowKeyboard.toggle() + config.showKeyboard = binding.settingsShowKeyboard.isChecked + } + } + + private fun setupShowNotePicker() { + NotesHelper(this).getNotes { + binding.settingsShowNotePickerHolder.beVisibleIf(it.size > 1) + } + + binding.settingsShowNotePicker.isChecked = config.showNotePicker + binding.settingsShowNotePickerHolder.setOnClickListener { + binding.settingsShowNotePicker.toggle() + config.showNotePicker = binding.settingsShowNotePicker.isChecked + } + } + + private fun setupShowWordCount() { + binding.settingsShowWordCount.isChecked = config.showWordCount + binding.settingsShowWordCountHolder.setOnClickListener { + binding.settingsShowWordCount.toggle() + config.showWordCount = binding.settingsShowWordCount.isChecked + } + } + + private fun setupEnableLineWrap() { + binding.settingsEnableLineWrap.isChecked = config.enableLineWrap + binding.settingsEnableLineWrapHolder.setOnClickListener { + binding.settingsEnableLineWrap.toggle() + config.enableLineWrap = binding.settingsEnableLineWrap.isChecked + } + } + + private fun setupFontSize() { + binding.settingsFontSize.text = getFontSizePercentText(config.fontSizePercentage) + binding.settingsFontSizeHolder.setOnClickListener { + val items = arrayListOf( + RadioItem(FONT_SIZE_50_PERCENT, getFontSizePercentText(FONT_SIZE_50_PERCENT)), + RadioItem(FONT_SIZE_60_PERCENT, getFontSizePercentText(FONT_SIZE_60_PERCENT)), + RadioItem(FONT_SIZE_75_PERCENT, getFontSizePercentText(FONT_SIZE_75_PERCENT)), + RadioItem(FONT_SIZE_90_PERCENT, getFontSizePercentText(FONT_SIZE_90_PERCENT)), + RadioItem(FONT_SIZE_100_PERCENT, getFontSizePercentText(FONT_SIZE_100_PERCENT)), + RadioItem(FONT_SIZE_125_PERCENT, getFontSizePercentText(FONT_SIZE_125_PERCENT)), + RadioItem(FONT_SIZE_150_PERCENT, getFontSizePercentText(FONT_SIZE_150_PERCENT)), + RadioItem(FONT_SIZE_175_PERCENT, getFontSizePercentText(FONT_SIZE_175_PERCENT)), + RadioItem(FONT_SIZE_200_PERCENT, getFontSizePercentText(FONT_SIZE_200_PERCENT)), + RadioItem(FONT_SIZE_250_PERCENT, getFontSizePercentText(FONT_SIZE_250_PERCENT)), + RadioItem(FONT_SIZE_300_PERCENT, getFontSizePercentText(FONT_SIZE_300_PERCENT)) + ) + + RadioGroupDialog(this@SettingsActivity, items, config.fontSizePercentage) { + config.fontSizePercentage = it as Int + binding.settingsFontSize.text = getFontSizePercentText(config.fontSizePercentage) + updateWidgets() + } + } + } + + private fun getFontSizePercentText(fontSizePercentage: Int): String = "$fontSizePercentage%" + + private fun setupGravity() { + binding.settingsGravity.text = getGravityText() + binding.settingsGravityHolder.setOnClickListener { + val items = listOf(GRAVITY_START, GRAVITY_CENTER, GRAVITY_END).map { RadioItem(it, getGravityOptionLabel(it)) } + RadioGroupDialog(this@SettingsActivity, ArrayList(items), config.gravity) { + config.gravity = it as Int + binding.settingsGravity.text = getGravityText() + updateWidgets() + } + } + } + + private fun getGravityOptionLabel(gravity: Int): String { + val leftToRightDirection = TextUtilsCompat.getLayoutDirectionFromLocale(Locale.getDefault()) == ViewCompat.LAYOUT_DIRECTION_LTR + val leftRightLabels = listOf(R.string.left, R.string.right) + val startEndLabels = if (leftToRightDirection) { + leftRightLabels + } else { + leftRightLabels.reversed() + } + return getString( + when (gravity) { + GRAVITY_START -> startEndLabels.first() + GRAVITY_CENTER -> R.string.center + else -> startEndLabels.last() + } + ) + } + + private fun getGravityText() = getGravityOptionLabel(config.gravity) + + private fun setupCursorPlacement() { + binding.settingsCursorPlacement.isChecked = config.placeCursorToEnd + binding.settingsCursorPlacementHolder.setOnClickListener { + binding.settingsCursorPlacement.toggle() + config.placeCursorToEnd = binding.settingsCursorPlacement.isChecked + } + } + + private fun setupCustomizeWidgetColors() { + var widgetToCustomize: Widget? = null + + binding.settingsWidgetColorCustomizationHolder.setOnClickListener { + Intent(this, WidgetConfigureActivity::class.java).apply { + putExtra(IS_CUSTOMIZING_COLORS, true) + + widgetToCustomize?.apply { + putExtra(CUSTOMIZED_WIDGET_ID, widgetId) + putExtra(CUSTOMIZED_WIDGET_KEY_ID, id) + putExtra(CUSTOMIZED_WIDGET_NOTE_ID, noteId) + putExtra(CUSTOMIZED_WIDGET_BG_COLOR, widgetBgColor) + putExtra(CUSTOMIZED_WIDGET_TEXT_COLOR, widgetTextColor) + putExtra(CUSTOMIZED_WIDGET_SHOW_TITLE, widgetShowTitle) + } + + startActivity(this) + } + } + + ensureBackgroundThread { + val widgets = widgetsDB.getWidgets().filter { it.widgetId != 0 } + if (widgets.size == 1) { + widgetToCustomize = widgets.first() + } + } + } + + private fun setupIncognitoMode() { + binding.settingsUseIncognitoModeHolder.beVisibleIf(isOreoPlus()) + binding.settingsUseIncognitoMode.isChecked = config.useIncognitoMode + binding.settingsUseIncognitoModeHolder.setOnClickListener { + binding.settingsUseIncognitoMode.toggle() + config.useIncognitoMode = binding.settingsUseIncognitoMode.isChecked + } + } + + private fun setupNotesExport() { + binding.settingsExportNotesHolder.setOnClickListener { + ExportNotesDialog(this) { filename -> + saveDocument.launch(filename) + } + } + } + + private fun setupNotesImport() { + binding.settingsImportNotesHolder.setOnClickListener { + getContent.launch(notesFileType) + } + } + + private fun exportNotes(notes: List, uri: Uri) { + if (notes.isEmpty()) { + toast(com.simplemobiletools.commons.R.string.no_entries_for_exporting) + } else { + try { + val outputStream = contentResolver.openOutputStream(uri)!! + + val jsonString = Json.encodeToString(notes) + outputStream.use { + it.write(jsonString.toByteArray()) + } + toast(com.simplemobiletools.commons.R.string.exporting_successful) + } catch (e: Exception) { + showErrorToast(e) + } + } + } + + private fun importNotes(uri: Uri) { + try { + val jsonString = contentResolver.openInputStream(uri)!!.use { inputStream -> + inputStream.bufferedReader().readText() + } + val objects = Json.decodeFromString>(jsonString) + if (objects.isEmpty()) { + toast(com.simplemobiletools.commons.R.string.no_entries_for_importing) + return + } + NotesHelper(this).importNotes(this, objects) { importResult -> + when (importResult) { + NotesHelper.ImportResult.IMPORT_OK -> toast(com.simplemobiletools.commons.R.string.importing_successful) + NotesHelper.ImportResult.IMPORT_PARTIAL -> toast(com.simplemobiletools.commons.R.string.importing_some_entries_failed) + NotesHelper.ImportResult.IMPORT_NOTHING_NEW -> toast(com.simplemobiletools.commons.R.string.no_new_items) + else -> toast(com.simplemobiletools.commons.R.string.importing_failed) + } + } + } catch (_: SerializationException) { + toast(com.simplemobiletools.commons.R.string.invalid_file_format) + } catch (_: IllegalArgumentException) { + toast(com.simplemobiletools.commons.R.string.invalid_file_format) + } catch (e: Exception) { + showErrorToast(e) + } + } + + private fun setupEnableAutomaticBackups() { + binding.settingsBackupsLabel.beVisibleIf(isRPlus()) + binding.settingsEnableAutomaticBackupsHolder.beVisibleIf(isRPlus()) + binding.settingsEnableAutomaticBackups.isChecked = config.autoBackup + binding.settingsEnableAutomaticBackupsHolder.setOnClickListener { + val wasBackupDisabled = !config.autoBackup + if (wasBackupDisabled) { + ManageAutoBackupsDialog( + activity = this, + onSuccess = { + enableOrDisableAutomaticBackups(true) + scheduleNextAutomaticBackup() + } + ) + } else { + cancelScheduledAutomaticBackup() + enableOrDisableAutomaticBackups(false) + } + } + } + + private fun setupManageAutomaticBackups() { + binding.settingsManageAutomaticBackupsHolder.beVisibleIf(isRPlus() && config.autoBackup) + binding.settingsManageAutomaticBackupsHolder.setOnClickListener { + ManageAutoBackupsDialog( + activity = this, + onSuccess = { + scheduleNextAutomaticBackup() + } + ) + } + } + + private fun enableOrDisableAutomaticBackups(enable: Boolean) { + config.autoBackup = enable + binding.settingsEnableAutomaticBackups.isChecked = enable + binding.settingsManageAutomaticBackupsHolder.beVisibleIf(enable) + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/activities/SimpleActivity.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/activities/SimpleActivity.kt similarity index 91% rename from app/src/main/kotlin/com/simplemobiletools/notes/activities/SimpleActivity.kt rename to app/src/main/kotlin/com/simplemobiletools/notes/pro/activities/SimpleActivity.kt index a322e5da3..3c11eae24 100644 --- a/app/src/main/kotlin/com/simplemobiletools/notes/activities/SimpleActivity.kt +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/activities/SimpleActivity.kt @@ -1,7 +1,7 @@ -package com.simplemobiletools.notes.activities +package com.simplemobiletools.notes.pro.activities import com.simplemobiletools.commons.activities.BaseSimpleActivity -import com.simplemobiletools.notes.R +import com.simplemobiletools.notes.pro.R open class SimpleActivity : BaseSimpleActivity() { override fun getAppIconIDs() = arrayListOf( diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/activities/SplashActivity.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/activities/SplashActivity.kt similarity index 71% rename from app/src/main/kotlin/com/simplemobiletools/notes/activities/SplashActivity.kt rename to app/src/main/kotlin/com/simplemobiletools/notes/pro/activities/SplashActivity.kt index e0f06329c..45c8e25f2 100644 --- a/app/src/main/kotlin/com/simplemobiletools/notes/activities/SplashActivity.kt +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/activities/SplashActivity.kt @@ -1,14 +1,14 @@ -package com.simplemobiletools.notes.activities +package com.simplemobiletools.notes.pro.activities import android.content.Intent import com.simplemobiletools.commons.activities.BaseSplashActivity -import com.simplemobiletools.notes.helpers.OPEN_NOTE_ID +import com.simplemobiletools.notes.pro.helpers.OPEN_NOTE_ID class SplashActivity : BaseSplashActivity() { override fun initActivity() { if (intent.extras?.containsKey(OPEN_NOTE_ID) == true) { Intent(this, MainActivity::class.java).apply { - putExtra(OPEN_NOTE_ID, intent.getIntExtra(OPEN_NOTE_ID, -1)) + putExtra(OPEN_NOTE_ID, intent.getLongExtra(OPEN_NOTE_ID, -1L)) startActivity(this) } } else { diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/activities/WidgetConfigureActivity.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/activities/WidgetConfigureActivity.kt new file mode 100644 index 000000000..fe58a85db --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/activities/WidgetConfigureActivity.kt @@ -0,0 +1,273 @@ +package com.simplemobiletools.notes.pro.activities + +import android.app.Activity +import android.appwidget.AppWidgetManager +import android.content.Intent +import android.content.res.ColorStateList +import android.graphics.Color +import android.graphics.Typeface +import android.graphics.drawable.ColorDrawable +import android.os.Bundle +import android.util.TypedValue +import android.widget.RemoteViews +import com.google.gson.Gson +import com.google.gson.reflect.TypeToken +import com.simplemobiletools.commons.dialogs.ColorPickerDialog +import com.simplemobiletools.commons.dialogs.RadioGroupDialog +import com.simplemobiletools.commons.extensions.* +import com.simplemobiletools.commons.helpers.IS_CUSTOMIZING_COLORS +import com.simplemobiletools.commons.helpers.PROTECTION_NONE +import com.simplemobiletools.commons.helpers.ensureBackgroundThread +import com.simplemobiletools.commons.models.RadioItem +import com.simplemobiletools.notes.pro.R +import com.simplemobiletools.notes.pro.adapters.ChecklistAdapter +import com.simplemobiletools.notes.pro.databinding.WidgetConfigBinding +import com.simplemobiletools.notes.pro.extensions.config +import com.simplemobiletools.notes.pro.extensions.getPercentageFontSize +import com.simplemobiletools.notes.pro.extensions.widgetsDB +import com.simplemobiletools.notes.pro.helpers.* +import com.simplemobiletools.notes.pro.models.ChecklistItem +import com.simplemobiletools.notes.pro.models.Note +import com.simplemobiletools.notes.pro.models.NoteType +import com.simplemobiletools.notes.pro.models.Widget + +class WidgetConfigureActivity : SimpleActivity() { + private var mBgAlpha = 0f + private var mWidgetId = 0 + private var mBgColor = 0 + private var mBgColorWithoutTransparency = 0 + private var mTextColor = 0 + private var mCurrentNoteId = 0L + private var mIsCustomizingColors = false + private var mShowTitle = false + private var mNotes = listOf() + private val binding by viewBinding(WidgetConfigBinding::inflate) + + public override fun onCreate(savedInstanceState: Bundle?) { + useDynamicTheme = false + super.onCreate(savedInstanceState) + setResult(RESULT_CANCELED) + setContentView(binding.root) + initVariables() + + mWidgetId = intent.extras?.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID) ?: AppWidgetManager.INVALID_APPWIDGET_ID + + if (mWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID && !mIsCustomizingColors) { + finish() + } + + updateTextColors(binding.notesPickerHolder) + binding.configSave.setOnClickListener { saveConfig() } + binding.configBgColor.setOnClickListener { pickBackgroundColor() } + binding.configTextColor.setOnClickListener { pickTextColor() } + binding.notesPickerValue.setOnClickListener { showNoteSelector() } + + val primaryColor = getProperPrimaryColor() + binding.configBgSeekbar.setColors(mTextColor, primaryColor, primaryColor) + binding.notesPickerHolder.background = ColorDrawable(getProperBackgroundColor()) + + binding.showNoteTitleHolder.setOnClickListener { + binding.showNoteTitle.toggle() + handleNoteTitleDisplay() + } + } + + override fun onResume() { + super.onResume() + binding.textNoteView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getPercentageFontSize()) + } + + private fun initVariables() { + val extras = intent.extras + if (extras?.getInt(CUSTOMIZED_WIDGET_ID, 0) == 0) { + mBgColor = config.widgetBgColor + mTextColor = config.widgetTextColor + } else { + mBgColor = extras?.getInt(CUSTOMIZED_WIDGET_BG_COLOR) ?: config.widgetBgColor + mTextColor = extras?.getInt(CUSTOMIZED_WIDGET_TEXT_COLOR) ?: config.widgetTextColor + mShowTitle = extras?.getBoolean(CUSTOMIZED_WIDGET_SHOW_TITLE) ?: false + } + + if (mTextColor == resources.getColor(com.simplemobiletools.commons.R.color.default_widget_text_color) && config.isUsingSystemTheme) { + mTextColor = resources.getColor(com.simplemobiletools.commons.R.color.you_primary_color, theme) + } + + mBgAlpha = Color.alpha(mBgColor) / 255.toFloat() + + mBgColorWithoutTransparency = Color.rgb(Color.red(mBgColor), Color.green(mBgColor), Color.blue(mBgColor)) + binding.configBgSeekbar.apply { + progress = (mBgAlpha * 100).toInt() + + onSeekBarChangeListener { + mBgAlpha = it / 100f + updateBackgroundColor() + } + } + updateBackgroundColor() + + updateTextColor() + mIsCustomizingColors = extras?.getBoolean(IS_CUSTOMIZING_COLORS) ?: false + binding.notesPickerHolder.beVisibleIf(!mIsCustomizingColors) + binding.textNoteViewTitle.beGoneIf(!mShowTitle) + + NotesHelper(this).getNotes { + mNotes = it + binding.notesPickerHolder.beVisibleIf(mNotes.size > 1 && !mIsCustomizingColors) + var note = mNotes.firstOrNull { !it.isLocked() } + + if (mNotes.size == 1 && note == null) { + note = mNotes.first() + if (note.shouldBeUnlocked(this)) { + updateCurrentNote(note) + } else { + performSecurityCheck( + protectionType = note.protectionType, + requiredHash = note.protectionHash, + successCallback = { _, _ -> updateCurrentNote(note) }, + failureCallback = { finish() } + ) + } + } else if (note != null) { + updateCurrentNote(note) + } + } + } + + private fun showNoteSelector() { + val items = ArrayList() + mNotes.forEach { + items.add(RadioItem(it.id!!.toInt(), it.title)) + } + + RadioGroupDialog(this, items, mCurrentNoteId.toInt()) { + val selectedId = it as Int + val note = mNotes.firstOrNull { it.id!!.toInt() == selectedId } ?: return@RadioGroupDialog + if (note.protectionType == PROTECTION_NONE || note.shouldBeUnlocked(this)) { + updateCurrentNote(note) + } else { + performSecurityCheck( + protectionType = note.protectionType, + requiredHash = note.protectionHash, + successCallback = { _, _ -> updateCurrentNote(note) } + ) + } + } + } + + private fun updateCurrentNote(note: Note) { + mCurrentNoteId = note.id!! + binding.notesPickerValue.text = note.title + binding.textNoteViewTitle.text = note.title + if (note.type == NoteType.TYPE_CHECKLIST) { + val checklistItemType = object : TypeToken>() {}.type + val items = Gson().fromJson>(note.value, checklistItemType) ?: ArrayList(1) + items.apply { + if (isEmpty()) { + add(ChecklistItem(0, System.currentTimeMillis(), "Milk", true)) + add(ChecklistItem(1, System.currentTimeMillis(), "Butter", true)) + add(ChecklistItem(2, System.currentTimeMillis(), "Salt", false)) + add(ChecklistItem(3, System.currentTimeMillis(), "Water", false)) + add(ChecklistItem(4, System.currentTimeMillis(), "Meat", true)) + } + } + + ChecklistAdapter(this, items, null, binding.checklistNoteView, false) {}.apply { + updateTextColor(mTextColor) + binding.checklistNoteView.adapter = this + } + binding.textNoteView.beGone() + binding.checklistNoteView.beVisible() + } else { + val sampleValue = if (note.value.isEmpty() || mIsCustomizingColors) getString(R.string.widget_config) else note.value + binding.textNoteView.text = sampleValue + binding.textNoteView.typeface = if (config.monospacedFont) Typeface.MONOSPACE else Typeface.DEFAULT + binding.textNoteView.beVisible() + binding.checklistNoteView.beGone() + } + } + + private fun saveConfig() { + if (mCurrentNoteId == 0L) { + finish() + return + } + + val views = RemoteViews(packageName, R.layout.activity_main) + views.setBackgroundColor(R.id.text_note_view, mBgColor) + views.setBackgroundColor(R.id.checklist_note_view, mBgColor) + AppWidgetManager.getInstance(this)?.updateAppWidget(mWidgetId, views) ?: return + + val extras = intent.extras + val id = if (extras?.containsKey(CUSTOMIZED_WIDGET_KEY_ID) == true) extras.getLong(CUSTOMIZED_WIDGET_KEY_ID) else null + mWidgetId = extras?.getInt(CUSTOMIZED_WIDGET_ID, mWidgetId) ?: mWidgetId + mCurrentNoteId = extras?.getLong(CUSTOMIZED_WIDGET_NOTE_ID, mCurrentNoteId) ?: mCurrentNoteId + val widget = Widget(id, mWidgetId, mCurrentNoteId, mBgColor, mTextColor, mShowTitle) + ensureBackgroundThread { + widgetsDB.insertOrUpdate(widget) + } + + storeWidgetBackground() + requestWidgetUpdate() + + Intent().apply { + putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mWidgetId) + setResult(Activity.RESULT_OK, this) + } + finish() + } + + private fun storeWidgetBackground() { + config.apply { + widgetBgColor = mBgColor + widgetTextColor = mTextColor + } + } + + private fun requestWidgetUpdate() { + Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE, null, this, MyWidgetProvider::class.java).apply { + putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, intArrayOf(mWidgetId)) + sendBroadcast(this) + } + } + + private fun updateBackgroundColor() { + mBgColor = mBgColorWithoutTransparency.adjustAlpha(mBgAlpha) + binding.textNoteView.setBackgroundColor(mBgColor) + binding.checklistNoteView.setBackgroundColor(mBgColor) + binding.textNoteViewTitle.setBackgroundColor(mBgColor) + binding.configBgColor.setFillWithStroke(mBgColor, mBgColor) + binding.configSave.backgroundTintList = ColorStateList.valueOf(getProperPrimaryColor()) + } + + private fun updateTextColor() { + binding.textNoteView.setTextColor(mTextColor) + binding.textNoteViewTitle.setTextColor(mTextColor) + (binding.checklistNoteView.adapter as? ChecklistAdapter)?.updateTextColor(mTextColor) + binding.configTextColor.setFillWithStroke(mTextColor, mTextColor) + binding.configSave.setTextColor(getProperPrimaryColor().getContrastColor()) + } + + private fun pickBackgroundColor() { + ColorPickerDialog(this, mBgColorWithoutTransparency) { wasPositivePressed, color -> + if (wasPositivePressed) { + mBgColorWithoutTransparency = color + updateBackgroundColor() + } + } + } + + private fun pickTextColor() { + ColorPickerDialog(this, mTextColor) { wasPositivePressed, color -> + if (wasPositivePressed) { + mTextColor = color + updateTextColor() + } + } + } + + private fun handleNoteTitleDisplay() { + val showTitle = binding.showNoteTitle.isChecked + binding.textNoteViewTitle.beGoneIf(!showTitle) + mShowTitle = showTitle + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/adapters/ChecklistAdapter.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/adapters/ChecklistAdapter.kt new file mode 100644 index 000000000..0c7193a33 --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/adapters/ChecklistAdapter.kt @@ -0,0 +1,249 @@ +package com.simplemobiletools.notes.pro.adapters + +import android.graphics.Paint +import android.graphics.drawable.Drawable +import android.util.TypedValue +import android.view.Menu +import android.view.MotionEvent +import android.view.View +import android.view.ViewGroup +import androidx.recyclerview.widget.ItemTouchHelper +import androidx.recyclerview.widget.RecyclerView +import com.simplemobiletools.commons.activities.BaseSimpleActivity +import com.simplemobiletools.commons.adapters.MyRecyclerViewAdapter +import com.simplemobiletools.commons.extensions.applyColorFilter +import com.simplemobiletools.commons.extensions.beVisibleIf +import com.simplemobiletools.commons.extensions.getColoredDrawableWithColor +import com.simplemobiletools.commons.extensions.removeBit +import com.simplemobiletools.commons.helpers.SORT_BY_CUSTOM +import com.simplemobiletools.commons.interfaces.ItemMoveCallback +import com.simplemobiletools.commons.interfaces.ItemTouchHelperContract +import com.simplemobiletools.commons.interfaces.StartReorderDragListener +import com.simplemobiletools.commons.views.MyRecyclerView +import com.simplemobiletools.notes.pro.R +import com.simplemobiletools.notes.pro.databinding.ItemChecklistBinding +import com.simplemobiletools.notes.pro.dialogs.RenameChecklistItemDialog +import com.simplemobiletools.notes.pro.extensions.config +import com.simplemobiletools.notes.pro.extensions.getPercentageFontSize +import com.simplemobiletools.notes.pro.helpers.DONE_CHECKLIST_ITEM_ALPHA +import com.simplemobiletools.notes.pro.interfaces.ChecklistItemsListener +import com.simplemobiletools.notes.pro.models.ChecklistItem +import java.util.Collections + +class ChecklistAdapter( + activity: BaseSimpleActivity, var items: MutableList, val listener: ChecklistItemsListener?, + recyclerView: MyRecyclerView, val showIcons: Boolean, itemClick: (Any) -> Unit +) : + MyRecyclerViewAdapter(activity, recyclerView, itemClick), ItemTouchHelperContract { + + private lateinit var crossDrawable: Drawable + private lateinit var checkDrawable: Drawable + private var touchHelper: ItemTouchHelper? = null + private var startReorderDragListener: StartReorderDragListener + + init { + setupDragListener(true) + initDrawables() + + touchHelper = ItemTouchHelper(ItemMoveCallback(this)) + touchHelper!!.attachToRecyclerView(recyclerView) + + startReorderDragListener = object : StartReorderDragListener { + override fun requestDrag(viewHolder: RecyclerView.ViewHolder) { + touchHelper?.startDrag(viewHolder) + } + } + } + + override fun getActionMenuId() = R.menu.cab_checklist + + override fun actionItemPressed(id: Int) { + if (selectedKeys.isEmpty()) { + return + } + + when (id) { + R.id.cab_move_to_top -> moveSelectedItemsToTop() + R.id.cab_move_to_bottom -> moveSelectedItemsToBottom() + R.id.cab_rename -> renameChecklistItem() + R.id.cab_delete -> deleteSelection() + } + } + + override fun getSelectableItemCount() = items.size + + override fun getIsItemSelectable(position: Int) = true + + override fun getItemSelectionKey(position: Int) = items.getOrNull(position)?.id + + override fun getItemKeyPosition(key: Int) = items.indexOfFirst { it.id == key } + + override fun onActionModeCreated() {} + + override fun onActionModeDestroyed() {} + + override fun prepareActionMode(menu: Menu) { + val selectedItems = getSelectedItems() + if (selectedItems.isEmpty()) { + return + } + + menu.findItem(R.id.cab_rename).isVisible = isOneItemSelected() + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { + return createViewHolder(ItemChecklistBinding.inflate(layoutInflater, parent, false).root) + } + + override fun onBindViewHolder(holder: ViewHolder, position: Int) { + val item = items[position] + holder.bindView(item, true, true) { itemView, layoutPosition -> + setupView(itemView, item, holder) + } + bindViewHolder(holder) + } + + override fun getItemCount() = items.size + + private fun initDrawables() { + val res = activity.resources + crossDrawable = res.getColoredDrawableWithColor( + com.simplemobiletools.commons.R.drawable.ic_cross_vector, + res.getColor(com.simplemobiletools.commons.R.color.md_red_700) + ) + checkDrawable = res.getColoredDrawableWithColor( + com.simplemobiletools.commons.R.drawable.ic_check_vector, + res.getColor(com.simplemobiletools.commons.R.color.md_green_700) + ) + } + + private fun renameChecklistItem() { + val item = getSelectedItems().first() + RenameChecklistItemDialog(activity, item.title) { + val position = getSelectedItemPositions().first() + item.title = it + listener?.saveChecklist() + notifyItemChanged(position) + finishActMode() + } + } + + private fun deleteSelection() { + val removeItems = ArrayList(selectedKeys.size) + val positions = ArrayList() + selectedKeys.forEach { + val key = it + val position = items.indexOfFirst { it.id == key } + if (position != -1) { + positions.add(position) + + val favorite = getItemWithKey(key) + if (favorite != null) { + removeItems.add(favorite) + } + } + } + + items.removeAll(removeItems.toSet()) + positions.sortDescending() + removeSelectedItems(positions) + + listener?.saveChecklist { + if (items.isEmpty()) { + listener.refreshItems() + } + } + } + + private fun moveSelectedItemsToTop() { + activity.config.sorting = SORT_BY_CUSTOM + val movedPositions = mutableListOf() + selectedKeys.reversed().forEach { checklistId -> + val position = items.indexOfFirst { it.id == checklistId } + val tempItem = items[position] + items.removeAt(position) + movedPositions.add(position) + items.add(0, tempItem) + } + + movedPositions.forEach { + notifyItemMoved(it, 0) + } + listener?.saveChecklist() + } + + private fun moveSelectedItemsToBottom() { + activity.config.sorting = SORT_BY_CUSTOM + val movedPositions = mutableListOf() + selectedKeys.forEach { checklistId -> + val position = items.indexOfFirst { it.id == checklistId } + val tempItem = items[position] + items.removeAt(position) + movedPositions.add(position) + items.add(items.size, tempItem) + } + + movedPositions.forEach { + notifyItemMoved(it, items.size - 1) + } + listener?.saveChecklist() + } + + private fun getItemWithKey(key: Int): ChecklistItem? = items.firstOrNull { it.id == key } + + private fun getSelectedItems() = items.filter { selectedKeys.contains(it.id) } as ArrayList + + private fun setupView(view: View, checklistItem: ChecklistItem, holder: ViewHolder) { + val isSelected = selectedKeys.contains(checklistItem.id) + ItemChecklistBinding.bind(view).apply { + checklistTitle.apply { + text = checklistItem.title + setTextColor(textColor) + setTextSize(TypedValue.COMPLEX_UNIT_PX, context.getPercentageFontSize()) + gravity = context.config.getTextGravity() + + if (checklistItem.isDone) { + paintFlags = paintFlags or Paint.STRIKE_THRU_TEXT_FLAG + alpha = DONE_CHECKLIST_ITEM_ALPHA + } else { + paintFlags = paintFlags.removeBit(Paint.STRIKE_THRU_TEXT_FLAG) + alpha = 1f + } + } + + checklistImage.setImageDrawable(if (checklistItem.isDone) checkDrawable else crossDrawable) + checklistImage.beVisibleIf(showIcons && selectedKeys.isEmpty()) + checklistHolder.isSelected = isSelected + + checklistDragHandle.beVisibleIf(selectedKeys.isNotEmpty()) + checklistDragHandle.applyColorFilter(textColor) + checklistDragHandle.setOnTouchListener { v, event -> + if (event.action == MotionEvent.ACTION_DOWN) { + startReorderDragListener.requestDrag(holder) + } + false + } + } + } + + override fun onRowMoved(fromPosition: Int, toPosition: Int) { + activity.config.sorting = SORT_BY_CUSTOM + if (fromPosition < toPosition) { + for (i in fromPosition until toPosition) { + Collections.swap(items, i, i + 1) + } + } else { + for (i in fromPosition downTo toPosition + 1) { + Collections.swap(items, i, i - 1) + } + } + notifyItemMoved(fromPosition, toPosition) + } + + override fun onRowSelected(myViewHolder: ViewHolder?) { + } + + override fun onRowClear(myViewHolder: ViewHolder?) { + listener?.saveChecklist() + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/adapters/NotesPagerAdapter.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/adapters/NotesPagerAdapter.kt new file mode 100644 index 000000000..909659f16 --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/adapters/NotesPagerAdapter.kt @@ -0,0 +1,100 @@ +package com.simplemobiletools.notes.pro.adapters + +import android.app.Activity +import android.os.Bundle +import android.view.ViewGroup +import androidx.fragment.app.FragmentManager +import androidx.fragment.app.FragmentStatePagerAdapter +import com.simplemobiletools.commons.extensions.showErrorToast +import com.simplemobiletools.notes.pro.fragments.ChecklistFragment +import com.simplemobiletools.notes.pro.fragments.NoteFragment +import com.simplemobiletools.notes.pro.fragments.TextFragment +import com.simplemobiletools.notes.pro.helpers.NOTE_ID +import com.simplemobiletools.notes.pro.models.Note +import com.simplemobiletools.notes.pro.models.NoteType + +class NotesPagerAdapter(fm: FragmentManager, val notes: List, val activity: Activity) : FragmentStatePagerAdapter(fm) { + private var fragments: HashMap = LinkedHashMap() + + override fun getCount() = notes.size + + override fun getItem(position: Int): NoteFragment { + val bundle = Bundle() + val note = notes[position] + val id = note.id + if (id != null) { + bundle.putLong(NOTE_ID, id) + } + + if (fragments.containsKey(position)) { + return fragments[position]!! + } + + val fragment = if (note.type == NoteType.TYPE_TEXT) TextFragment() else ChecklistFragment() + fragment.arguments = bundle + fragments[position] = fragment + return fragment + } + + override fun getPageTitle(position: Int) = notes[position].title + + fun updateCurrentNoteData(position: Int, path: String, value: String) { + (fragments[position])?.apply { + updateNotePath(path) + updateNoteValue(value) + } + } + + fun getFragment(position: Int) = fragments[position] + + fun textFragment(position: Int): TextFragment? = (fragments[position] as? TextFragment) + + fun getCurrentNotesView(position: Int) = (fragments[position] as? TextFragment)?.getNotesView() + + fun getCurrentNoteViewText(position: Int) = (fragments[position] as? TextFragment)?.getCurrentNoteViewText() + + fun appendText(position: Int, text: String) = (fragments[position] as? TextFragment)?.getNotesView()?.append(text) + + fun saveCurrentNote(position: Int, force: Boolean) = (fragments[position] as? TextFragment)?.saveText(force) + + fun focusEditText(position: Int) = (fragments[position] as? TextFragment)?.focusEditText() + + fun anyHasUnsavedChanges() = fragments.values.any { (it as? TextFragment)?.hasUnsavedChanges() == true } + + fun saveAllFragmentTexts() = fragments.values.forEach { (it as? TextFragment)?.saveText(false) } + + fun getNoteChecklistRawItems(position: Int) = (fragments[position] as? ChecklistFragment)?.items + + fun getNoteChecklistItems(position: Int) = (fragments[position] as? ChecklistFragment)?.getChecklistItems() + + fun undo(position: Int) = (fragments[position] as? TextFragment)?.undo() + + fun redo(position: Int) = (fragments[position] as? TextFragment)?.redo() + + override fun finishUpdate(container: ViewGroup) { + try { + super.finishUpdate(container) + } catch (e: Exception) { + activity.showErrorToast(e) + } + } + + override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) { + super.destroyItem(container, position, `object`) + fragments.remove(position) + } + + override fun instantiateItem(container: ViewGroup, position: Int): Any { + val fragment = super.instantiateItem(container, position) as NoteFragment + fragments[position] = fragment + return fragment + } + + fun removeDoneCheckListItems(position: Int) { + (fragments[position] as? ChecklistFragment)?.removeDoneItems() + } + + fun refreshChecklist(position: Int) { + (fragments[position] as? ChecklistFragment)?.refreshItems() + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/adapters/OpenNoteAdapter.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/adapters/OpenNoteAdapter.kt new file mode 100644 index 000000000..904222d24 --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/adapters/OpenNoteAdapter.kt @@ -0,0 +1,140 @@ +package com.simplemobiletools.notes.pro.adapters + +import android.content.Context +import android.graphics.Color +import android.text.SpannableString +import android.text.style.StrikethroughSpan +import android.view.Menu +import android.view.View +import android.view.ViewGroup +import com.google.gson.Gson +import com.google.gson.reflect.TypeToken +import com.simplemobiletools.commons.activities.BaseSimpleActivity +import com.simplemobiletools.commons.adapters.MyRecyclerViewAdapter +import com.simplemobiletools.commons.extensions.beGoneIf +import com.simplemobiletools.commons.extensions.beVisibleIf +import com.simplemobiletools.commons.extensions.getColoredDrawableWithColor +import com.simplemobiletools.commons.extensions.isBlackAndWhiteTheme +import com.simplemobiletools.commons.helpers.LOWER_ALPHA_INT +import com.simplemobiletools.commons.helpers.SORT_BY_CUSTOM +import com.simplemobiletools.commons.views.MyRecyclerView +import com.simplemobiletools.notes.pro.databinding.OpenNoteItemBinding +import com.simplemobiletools.notes.pro.extensions.config +import com.simplemobiletools.notes.pro.models.ChecklistItem +import com.simplemobiletools.notes.pro.models.Note +import com.simplemobiletools.notes.pro.models.NoteType + +class OpenNoteAdapter( + activity: BaseSimpleActivity, var items: List, + recyclerView: MyRecyclerView, itemClick: (Any) -> Unit +) : MyRecyclerViewAdapter(activity, recyclerView, itemClick) { + override fun getActionMenuId() = 0 + + override fun actionItemPressed(id: Int) {} + + override fun getSelectableItemCount() = itemCount + + override fun getIsItemSelectable(position: Int) = false + + override fun getItemSelectionKey(position: Int) = items.getOrNull(position)?.id?.toInt() + + override fun getItemKeyPosition(key: Int) = items.indexOfFirst { it.id?.toInt() == key } + + override fun onActionModeCreated() {} + + override fun onActionModeDestroyed() {} + + override fun prepareActionMode(menu: Menu) {} + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { + return createViewHolder(OpenNoteItemBinding.inflate(layoutInflater, parent, false).root) + } + + override fun onBindViewHolder(holder: ViewHolder, position: Int) { + val item = items[position] + holder.bindView(item, true, false) { itemView, layoutPosition -> + setupView(itemView, item) + } + bindViewHolder(holder) + } + + override fun getItemCount() = items.size + + private fun setupView(view: View, note: Note) { + OpenNoteItemBinding.bind(view).apply { + root.setupCard() + openNoteItemTitle.apply { + text = note.title + setTextColor(properPrimaryColor) + } + val formattedText = note.getFormattedValue(root.context) + openNoteItemText.beGoneIf(formattedText.isNullOrBlank() || note.isLocked()) + iconLock.beVisibleIf(note.isLocked()) + iconLock.setImageDrawable(activity.resources.getColoredDrawableWithColor(com.simplemobiletools.commons.R.drawable.ic_lock_vector, properPrimaryColor)) + openNoteItemText.apply { + text = formattedText + setTextColor(textColor) + } + } + } + + private fun View.setupCard() { + if (context.isBlackAndWhiteTheme()) { + setBackgroundResource(com.simplemobiletools.commons.R.drawable.black_dialog_background) + } else { + val cardBackgroundColor = if (backgroundColor == Color.BLACK) { + Color.WHITE + } else { + Color.BLACK + } + val cardBackground = if (context.config.isUsingSystemTheme) { + com.simplemobiletools.commons.R.drawable.dialog_you_background + } else { + com.simplemobiletools.commons.R.drawable.dialog_bg + } + background = + activity.resources.getColoredDrawableWithColor(cardBackground, cardBackgroundColor, LOWER_ALPHA_INT) + } + } + + private fun Note.getFormattedValue(context: Context): CharSequence? { + return when (type) { + NoteType.TYPE_TEXT -> getNoteStoredValue(context) + NoteType.TYPE_CHECKLIST -> { + val checklistItemType = object : TypeToken>() {}.type + var items = Gson().fromJson>(getNoteStoredValue(context), checklistItemType) ?: listOf() + items = items.filter { it.title != null }.let { + val sorting = context.config.sorting + ChecklistItem.sorting = sorting + if (ChecklistItem.sorting and SORT_BY_CUSTOM == 0) { + it.sorted().let { + if (context.config.moveDoneChecklistItems) { + it.sortedBy { it.isDone } + } else { + it + } + } + } else { + it + } + } + val linePrefix = "• " + val stringifiedItems = items.joinToString(separator = System.lineSeparator()) { + "${linePrefix}${it.title}" + } + + val formattedText = SpannableString(stringifiedItems) + var currentPos = 0 + items.forEach { item -> + currentPos += linePrefix.length + if (item.isDone) { + formattedText.setSpan(StrikethroughSpan(), currentPos, currentPos + item.title.length, 0) + } + currentPos += item.title.length + currentPos += System.lineSeparator().length + } + formattedText + } + } + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/adapters/WidgetAdapter.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/adapters/WidgetAdapter.kt new file mode 100644 index 000000000..8aaf006ff --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/adapters/WidgetAdapter.kt @@ -0,0 +1,156 @@ +package com.simplemobiletools.notes.pro.adapters + +import android.content.Context +import android.content.Intent +import android.graphics.Paint +import android.view.View +import android.widget.RemoteViews +import android.widget.RemoteViewsService +import com.simplemobiletools.commons.extensions.adjustAlpha +import com.simplemobiletools.commons.extensions.setText +import com.simplemobiletools.commons.extensions.setTextSize +import com.simplemobiletools.commons.helpers.SORT_BY_CUSTOM +import com.simplemobiletools.commons.helpers.WIDGET_TEXT_COLOR +import com.simplemobiletools.notes.pro.R +import com.simplemobiletools.notes.pro.R.id.widget_text_holder +import com.simplemobiletools.notes.pro.extensions.config +import com.simplemobiletools.notes.pro.extensions.getPercentageFontSize +import com.simplemobiletools.notes.pro.extensions.notesDB +import com.simplemobiletools.notes.pro.helpers.* +import com.simplemobiletools.notes.pro.models.ChecklistItem +import com.simplemobiletools.notes.pro.models.Note +import com.simplemobiletools.notes.pro.models.NoteType +import kotlinx.serialization.decodeFromString +import kotlinx.serialization.json.Json + +class WidgetAdapter(val context: Context, val intent: Intent) : RemoteViewsService.RemoteViewsFactory { + private val textIds = arrayOf( + R.id.widget_text_left, R.id.widget_text_center, R.id.widget_text_right, + R.id.widget_text_left_monospace, R.id.widget_text_center_monospace, R.id.widget_text_right_monospace + ) + private val checklistIds = arrayOf( + R.id.checklist_text_left, R.id.checklist_text_center, R.id.checklist_text_right, + R.id.checklist_text_left_monospace, R.id.checklist_text_center_monospace, R.id.checklist_text_right_monospace + ) + private var widgetTextColor = DEFAULT_WIDGET_TEXT_COLOR + private var note: Note? = null + private var checklistItems = mutableListOf() + + override fun getViewAt(position: Int): RemoteViews { + val noteId = intent.getLongExtra(NOTE_ID, 0L) + val remoteView: RemoteViews + + if (note == null) { + return RemoteViews(context.packageName, R.layout.widget_text_layout) + } + + val textSize = context.getPercentageFontSize() / context.resources.displayMetrics.density + if (note!!.type == NoteType.TYPE_CHECKLIST) { + remoteView = RemoteViews(context.packageName, R.layout.item_checklist_widget).apply { + val checklistItem = checklistItems.getOrNull(position) ?: return@apply + val widgetNewTextColor = if (checklistItem.isDone) widgetTextColor.adjustAlpha(DONE_CHECKLIST_ITEM_ALPHA) else widgetTextColor + val paintFlags = if (checklistItem.isDone) Paint.STRIKE_THRU_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG else Paint.ANTI_ALIAS_FLAG + + for (id in checklistIds) { + setText(id, checklistItem.title) + setTextColor(id, widgetNewTextColor) + setTextSize(id, textSize) + setInt(id, "setPaintFlags", paintFlags) + setViewVisibility(id, View.GONE) + } + + setViewVisibility(getProperChecklistTextView(context), View.VISIBLE) + + Intent().apply { + putExtra(OPEN_NOTE_ID, noteId) + setOnClickFillInIntent(R.id.checklist_text_holder, this) + } + } + } else { + remoteView = RemoteViews(context.packageName, R.layout.widget_text_layout).apply { + val noteText = note!!.getNoteStoredValue(context) ?: "" + for (id in textIds) { + setText(id, noteText) + setTextColor(id, widgetTextColor) + setTextSize(id, textSize) + setViewVisibility(id, View.GONE) + } + setViewVisibility(getProperTextView(context), View.VISIBLE) + + Intent().apply { + putExtra(OPEN_NOTE_ID, noteId) + setOnClickFillInIntent(widget_text_holder, this) + } + } + } + + return remoteView + } + + private fun getProperTextView(context: Context): Int { + val gravity = context.config.gravity + val isMonospaced = context.config.monospacedFont + + return when { + gravity == GRAVITY_CENTER && isMonospaced -> R.id.widget_text_center_monospace + gravity == GRAVITY_CENTER -> R.id.widget_text_center + gravity == GRAVITY_END && isMonospaced -> R.id.widget_text_right_monospace + gravity == GRAVITY_END -> R.id.widget_text_right + isMonospaced -> R.id.widget_text_left_monospace + else -> R.id.widget_text_left + } + } + + private fun getProperChecklistTextView(context: Context): Int { + val gravity = context.config.gravity + val isMonospaced = context.config.monospacedFont + + return when { + gravity == GRAVITY_CENTER && isMonospaced -> R.id.checklist_text_center_monospace + gravity == GRAVITY_CENTER -> R.id.checklist_text_center + gravity == GRAVITY_END && isMonospaced -> R.id.checklist_text_right_monospace + gravity == GRAVITY_END -> R.id.checklist_text_right + isMonospaced -> R.id.checklist_text_left_monospace + else -> R.id.checklist_text_left + } + } + + override fun onCreate() {} + + override fun getLoadingView() = null + + override fun getItemId(position: Int) = position.toLong() + + override fun onDataSetChanged() { + widgetTextColor = intent.getIntExtra(WIDGET_TEXT_COLOR, DEFAULT_WIDGET_TEXT_COLOR) + val noteId = intent.getLongExtra(NOTE_ID, 0L) + note = context.notesDB.getNoteWithId(noteId) + if (note?.type == NoteType.TYPE_CHECKLIST) { + checklistItems = note!!.getNoteStoredValue(context)?.ifEmpty { "[]" }?.let { Json.decodeFromString(it) } ?: mutableListOf() + + // checklist title can be null only because of the glitch in upgrade to 6.6.0, remove this check in the future + checklistItems = checklistItems.filter { it.title != null }.toMutableList() as ArrayList + val sorting = context.config?.sorting ?: 0 + if (sorting and SORT_BY_CUSTOM == 0) { + checklistItems.sort() + if (context?.config?.moveDoneChecklistItems == true) { + checklistItems.sortBy { it.isDone } + } + } + } + } + + override fun hasStableIds() = true + + override fun getCount(): Int { + return if (note?.type == NoteType.TYPE_CHECKLIST) { + checklistItems.size + } else { + 1 + } + } + + override fun getViewTypeCount() = 2 + + override fun onDestroy() {} +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/databases/NotesDatabase.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/databases/NotesDatabase.kt new file mode 100644 index 000000000..f26818b5c --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/databases/NotesDatabase.kt @@ -0,0 +1,89 @@ +package com.simplemobiletools.notes.pro.databases + +import android.content.Context +import androidx.room.Database +import androidx.room.Room +import androidx.room.RoomDatabase +import androidx.room.migration.Migration +import androidx.sqlite.db.SupportSQLiteDatabase +import com.simplemobiletools.commons.helpers.PROTECTION_NONE +import com.simplemobiletools.notes.pro.R +import com.simplemobiletools.notes.pro.helpers.DEFAULT_WIDGET_TEXT_COLOR +import com.simplemobiletools.notes.pro.interfaces.NotesDao +import com.simplemobiletools.notes.pro.interfaces.WidgetsDao +import com.simplemobiletools.notes.pro.models.Note +import com.simplemobiletools.notes.pro.models.NoteType +import com.simplemobiletools.notes.pro.models.Widget +import java.util.concurrent.Executors + +@Database(entities = [Note::class, Widget::class], version = 4) +abstract class NotesDatabase : RoomDatabase() { + + abstract fun NotesDao(): NotesDao + + abstract fun WidgetsDao(): WidgetsDao + + companion object { + private var db: NotesDatabase? = null + private var defaultWidgetBgColor = 0 + + fun getInstance(context: Context): NotesDatabase { + defaultWidgetBgColor = context.resources.getColor(com.simplemobiletools.commons.R.color.default_widget_bg_color) + if (db == null) { + synchronized(NotesDatabase::class) { + if (db == null) { + db = Room.databaseBuilder(context.applicationContext, NotesDatabase::class.java, "notes.db") + .addCallback(object : Callback() { + override fun onCreate(db: SupportSQLiteDatabase) { + super.onCreate(db) + insertFirstNote(context) + } + }) + .addMigrations(MIGRATION_1_2) + .addMigrations(MIGRATION_2_3) + .addMigrations(MIGRATION_3_4) + .build() + db!!.openHelper.setWriteAheadLoggingEnabled(true) + } + } + } + return db!! + } + + fun destroyInstance() { + db = null + } + + private fun insertFirstNote(context: Context) { + Executors.newSingleThreadScheduledExecutor().execute { + val generalNote = context.resources.getString(R.string.general_note) + val note = Note(null, generalNote, "", NoteType.TYPE_TEXT, "", PROTECTION_NONE, "") + db!!.NotesDao().insertOrUpdate(note) + } + } + + private val MIGRATION_1_2 = object : Migration(1, 2) { + override fun migrate(database: SupportSQLiteDatabase) { + database.apply { + execSQL("ALTER TABLE widgets ADD COLUMN widget_bg_color INTEGER NOT NULL DEFAULT $defaultWidgetBgColor") + execSQL("ALTER TABLE widgets ADD COLUMN widget_text_color INTEGER NOT NULL DEFAULT $DEFAULT_WIDGET_TEXT_COLOR") + } + } + } + + private val MIGRATION_2_3 = object : Migration(2, 3) { + override fun migrate(database: SupportSQLiteDatabase) { + database.apply { + execSQL("ALTER TABLE notes ADD COLUMN protection_type INTEGER DEFAULT $PROTECTION_NONE NOT NULL") + execSQL("ALTER TABLE notes ADD COLUMN protection_hash TEXT DEFAULT '' NOT NULL") + } + } + } + + private val MIGRATION_3_4 = object : Migration(3, 4) { + override fun migrate(database: SupportSQLiteDatabase) { + database.execSQL("ALTER TABLE widgets ADD COLUMN widget_show_title INTEGER NOT NULL DEFAULT 0") + } + } + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/DateTimePatternInfoDialog.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/DateTimePatternInfoDialog.kt new file mode 100644 index 000000000..f7a865387 --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/DateTimePatternInfoDialog.kt @@ -0,0 +1,18 @@ +package com.simplemobiletools.notes.pro.dialogs + +import com.simplemobiletools.commons.activities.BaseSimpleActivity +import com.simplemobiletools.commons.extensions.getAlertDialogBuilder +import com.simplemobiletools.commons.extensions.setupDialogStuff +import com.simplemobiletools.notes.pro.R + +class DateTimePatternInfoDialog(activity: BaseSimpleActivity) { + + init { + val view = activity.layoutInflater.inflate(R.layout.datetime_pattern_info_layout, null) + activity.getAlertDialogBuilder() + .setPositiveButton(com.simplemobiletools.commons.R.string.ok) { _, _ -> { } } + .apply { + activity.setupDialogStuff(view, this) + } + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/DeleteNoteDialog.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/DeleteNoteDialog.kt new file mode 100644 index 000000000..23f096be3 --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/DeleteNoteDialog.kt @@ -0,0 +1,40 @@ +package com.simplemobiletools.notes.pro.dialogs + +import androidx.appcompat.app.AlertDialog +import com.simplemobiletools.commons.extensions.beVisible +import com.simplemobiletools.commons.extensions.getAlertDialogBuilder +import com.simplemobiletools.commons.extensions.setupDialogStuff +import com.simplemobiletools.notes.pro.R +import com.simplemobiletools.notes.pro.activities.SimpleActivity +import com.simplemobiletools.notes.pro.databinding.DialogDeleteNoteBinding +import com.simplemobiletools.notes.pro.models.Note + +class DeleteNoteDialog(val activity: SimpleActivity, val note: Note, val callback: (deleteFile: Boolean) -> Unit) { + var dialog: AlertDialog? = null + + init { + val message = String.format(activity.getString(R.string.delete_note_prompt_message), note.title) + val binding = DialogDeleteNoteBinding.inflate(activity.layoutInflater).apply{ + if (note.path.isNotEmpty()) { + deleteNoteCheckbox.text = String.format(activity.getString(R.string.delete_file_itself), note.path) + deleteNoteCheckboxHolder.beVisible() + deleteNoteCheckboxHolder.setOnClickListener { + deleteNoteCheckbox.toggle() + } + } + deleteNoteDescription.text = message + } + + activity.getAlertDialogBuilder() + .setPositiveButton(com.simplemobiletools.commons.R.string.delete) { dialog, which -> dialogConfirmed(binding.deleteNoteCheckbox.isChecked) } + .setNegativeButton(com.simplemobiletools.commons.R.string.cancel, null) + .apply { + activity.setupDialogStuff(binding.root, this) + } + } + + private fun dialogConfirmed(deleteFile: Boolean) { + callback(deleteFile && note.path.isNotEmpty()) + dialog?.dismiss() + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/ExportFileDialog.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/ExportFileDialog.kt new file mode 100644 index 000000000..bd393d01b --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/ExportFileDialog.kt @@ -0,0 +1,59 @@ +package com.simplemobiletools.notes.pro.dialogs + +import androidx.appcompat.app.AlertDialog +import com.simplemobiletools.commons.dialogs.FilePickerDialog +import com.simplemobiletools.commons.extensions.* +import com.simplemobiletools.notes.pro.R +import com.simplemobiletools.notes.pro.activities.SimpleActivity +import com.simplemobiletools.notes.pro.databinding.DialogExportFileBinding +import com.simplemobiletools.notes.pro.extensions.config +import com.simplemobiletools.notes.pro.models.Note +import java.io.File + +class ExportFileDialog(val activity: SimpleActivity, val note: Note, val callback: (exportPath: String) -> Unit) { + + init { + var realPath = File(note.path).parent ?: activity.config.lastUsedSavePath + val binding = DialogExportFileBinding.inflate(activity.layoutInflater).apply { + filePath.setText(activity.humanizePath(realPath)) + + fileName.setText(note.title) + extension.setText(activity.config.lastUsedExtension) + filePath.setOnClickListener { + FilePickerDialog(activity, realPath, false, false, true, true) { + filePath.setText(activity.humanizePath(it)) + realPath = it + } + } + } + + activity.getAlertDialogBuilder() + .setPositiveButton(com.simplemobiletools.commons.R.string.ok, null) + .setNegativeButton(com.simplemobiletools.commons.R.string.cancel, null) + .apply { + activity.setupDialogStuff(binding.root, this, R.string.export_as_file) { alertDialog -> + alertDialog.showKeyboard(binding.fileName) + alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { + val filename = binding.fileName.value + val extension = binding.extension.value + + if (filename.isEmpty()) { + activity.toast(com.simplemobiletools.commons.R.string.filename_cannot_be_empty) + return@setOnClickListener + } + + val fullFilename = if (extension.isEmpty()) filename else "$filename.$extension" + if (!fullFilename.isAValidFilename()) { + activity.toast(String.format(activity.getString(com.simplemobiletools.commons.R.string.filename_invalid_characters_placeholder, fullFilename))) + return@setOnClickListener + } + + activity.config.lastUsedExtension = extension + activity.config.lastUsedSavePath = realPath + callback("$realPath/$fullFilename") + alertDialog.dismiss() + } + } + } + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/ExportFilesDialog.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/ExportFilesDialog.kt new file mode 100644 index 000000000..553b1817b --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/ExportFilesDialog.kt @@ -0,0 +1,45 @@ +package com.simplemobiletools.notes.pro.dialogs + +import androidx.appcompat.app.AlertDialog +import com.simplemobiletools.commons.dialogs.FilePickerDialog +import com.simplemobiletools.commons.extensions.* +import com.simplemobiletools.notes.pro.R +import com.simplemobiletools.notes.pro.activities.SimpleActivity +import com.simplemobiletools.notes.pro.databinding.DialogExportFilesBinding +import com.simplemobiletools.notes.pro.extensions.config +import com.simplemobiletools.notes.pro.models.Note + +class ExportFilesDialog(val activity: SimpleActivity, val notes: ArrayList, val callback: (parent: String, extension: String) -> Unit) { + init { + var realPath = activity.config.lastUsedSavePath + val binding = DialogExportFilesBinding.inflate(activity.layoutInflater).apply { + folderPath.setText(activity.humanizePath(realPath)) + + extension.setText(activity.config.lastUsedExtension) + folderPath.setOnClickListener { + FilePickerDialog(activity, realPath, false, false, true, true) { + folderPath.setText(activity.humanizePath(it)) + realPath = it + } + } + } + + activity.getAlertDialogBuilder() + .setPositiveButton(com.simplemobiletools.commons.R.string.ok, null) + .setNegativeButton(com.simplemobiletools.commons.R.string.cancel, null) + .apply { + activity.setupDialogStuff(binding.root, this, R.string.export_as_file) { alertDialog -> + alertDialog.showKeyboard(binding.extension) + alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { + activity.handleSAFDialog(realPath) { + val extension = binding.extension.value + activity.config.lastUsedExtension = extension + activity.config.lastUsedSavePath = realPath + callback(realPath, extension) + alertDialog.dismiss() + } + } + } + } + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/ExportNotesDialog.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/ExportNotesDialog.kt new file mode 100644 index 000000000..a99096963 --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/ExportNotesDialog.kt @@ -0,0 +1,41 @@ +package com.simplemobiletools.notes.pro.dialogs + +import androidx.appcompat.app.AlertDialog +import com.simplemobiletools.commons.extensions.* +import com.simplemobiletools.notes.pro.R +import com.simplemobiletools.notes.pro.activities.SimpleActivity +import com.simplemobiletools.notes.pro.databinding.DialogExportNotesBinding + +class ExportNotesDialog(val activity: SimpleActivity, callback: (filename: String) -> Unit) { + + init { + val binding = DialogExportNotesBinding.inflate(activity.layoutInflater).apply { + exportNotesFilename.setText( + buildString { + append(root.context.getString(com.simplemobiletools.commons.R.string.notes)) + append("_") + append(root.context.getCurrentFormattedDateTime()) + } + ) + } + + activity.getAlertDialogBuilder().setPositiveButton(com.simplemobiletools.commons.R.string.ok, null).setNegativeButton(com.simplemobiletools.commons.R.string.cancel, null).apply { + activity.setupDialogStuff(binding.root, this, R.string.export_notes) { alertDialog -> + alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { + + val filename = binding.exportNotesFilename.value + when { + filename.isEmpty() -> activity.toast(com.simplemobiletools.commons.R.string.empty_name) + filename.isAValidFilename() -> { + callback(filename) + alertDialog.dismiss() + } + + else -> activity.toast(com.simplemobiletools.commons.R.string.invalid_name) + } + } + } + } + } +} + diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/ImportFolderDialog.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/ImportFolderDialog.kt new file mode 100644 index 000000000..a007e8788 --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/ImportFolderDialog.kt @@ -0,0 +1,81 @@ +package com.simplemobiletools.notes.pro.dialogs + +import androidx.appcompat.app.AlertDialog +import com.simplemobiletools.commons.extensions.* +import com.simplemobiletools.commons.helpers.PROTECTION_NONE +import com.simplemobiletools.commons.helpers.ensureBackgroundThread +import com.simplemobiletools.notes.pro.R +import com.simplemobiletools.notes.pro.activities.SimpleActivity +import com.simplemobiletools.notes.pro.databinding.DialogImportFolderBinding +import com.simplemobiletools.notes.pro.extensions.notesDB +import com.simplemobiletools.notes.pro.extensions.parseChecklistItems +import com.simplemobiletools.notes.pro.helpers.NotesHelper +import com.simplemobiletools.notes.pro.models.Note +import com.simplemobiletools.notes.pro.models.NoteType +import java.io.File + +class ImportFolderDialog(val activity: SimpleActivity, val path: String, val callback: () -> Unit) : AlertDialog.Builder(activity) { + private var dialog: AlertDialog? = null + + init { + val binding = DialogImportFolderBinding.inflate(activity.layoutInflater).apply { + openFileFilename.setText(activity.humanizePath(path)) + } + + activity.getAlertDialogBuilder() + .setPositiveButton(com.simplemobiletools.commons.R.string.ok, null) + .setNegativeButton(com.simplemobiletools.commons.R.string.cancel, null) + .apply { + activity.setupDialogStuff(binding.root, this, R.string.import_folder) { alertDialog -> + dialog = alertDialog + alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { + val updateFilesOnEdit = binding.openFileType.checkedRadioButtonId == R.id.open_file_update_file + ensureBackgroundThread { + saveFolder(updateFilesOnEdit) + } + } + } + } + } + + private fun saveFolder(updateFilesOnEdit: Boolean) { + val folder = File(path) + folder.listFiles { file -> + val filename = file.path.getFilenameFromPath() + when { + file.isDirectory -> false + filename.isMediaFile() -> false + file.length() > 1000 * 1000 -> false + activity.notesDB.getNoteIdWithTitle(filename) != null -> false + else -> true + } + }?.forEach { + val storePath = if (updateFilesOnEdit) it.absolutePath else "" + val title = it.absolutePath.getFilenameFromPath() + val value = if (updateFilesOnEdit) "" else it.readText() + val fileText = it.readText().trim() + val checklistItems = fileText.parseChecklistItems() + if (checklistItems != null) { + saveNote(title.substringBeforeLast('.'), fileText, NoteType.TYPE_CHECKLIST, "") + } else { + if (updateFilesOnEdit) { + activity.handleSAFDialog(path) { + saveNote(title, value, NoteType.TYPE_TEXT, storePath) + } + } else { + saveNote(title, value, NoteType.TYPE_TEXT, storePath) + } + } + } + + activity.runOnUiThread { + callback() + dialog?.dismiss() + } + } + + private fun saveNote(title: String, value: String, type: NoteType, path: String) { + val note = Note(null, title, value, type, path, PROTECTION_NONE, "") + NotesHelper(activity).insertOrUpdateNote(note) + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/ManageAutoBackupsDialog.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/ManageAutoBackupsDialog.kt new file mode 100644 index 000000000..c88a0d4a9 --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/ManageAutoBackupsDialog.kt @@ -0,0 +1,96 @@ +package com.simplemobiletools.notes.pro.dialogs + +import androidx.appcompat.app.AlertDialog +import com.simplemobiletools.commons.dialogs.FilePickerDialog +import com.simplemobiletools.commons.extensions.* +import com.simplemobiletools.commons.helpers.ensureBackgroundThread +import com.simplemobiletools.notes.pro.activities.SimpleActivity +import com.simplemobiletools.notes.pro.databinding.DialogManageAutomaticBackupsBinding +import com.simplemobiletools.notes.pro.extensions.config +import java.io.File + +class ManageAutoBackupsDialog(private val activity: SimpleActivity, onSuccess: () -> Unit) { + private val binding = DialogManageAutomaticBackupsBinding.inflate(activity.layoutInflater) + private val view = binding.root + private val config = activity.config + private var backupFolder = config.autoBackupFolder + + init { + binding.apply { + backupNotesFolder.setText(activity.humanizePath(backupFolder)) + val filename = config.autoBackupFilename.ifEmpty { + "${activity.getString(com.simplemobiletools.commons.R.string.notes)}_%Y%M%D_%h%m%s" + } + + backupNotesFilename.setText(filename) + backupNotesFilenameHint.setEndIconOnClickListener { + DateTimePatternInfoDialog(activity) + } + + backupNotesFilenameHint.setEndIconOnLongClickListener { + DateTimePatternInfoDialog(activity) + true + } + + backupNotesFolder.setOnClickListener { + selectBackupFolder() + } + } + + activity.getAlertDialogBuilder() + .setPositiveButton(com.simplemobiletools.commons.R.string.ok, null) + .setNegativeButton(com.simplemobiletools.commons.R.string.cancel, null) + .apply { + activity.setupDialogStuff(view, this, com.simplemobiletools.commons.R.string.manage_automatic_backups) { dialog -> + dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { + val filename = binding.backupNotesFilename.value + when { + filename.isEmpty() -> activity.toast(com.simplemobiletools.commons.R.string.empty_name) + filename.isAValidFilename() -> { + val file = File(backupFolder, "$filename.json") + if (file.exists() && !file.canWrite()) { + activity.toast(com.simplemobiletools.commons.R.string.name_taken) + return@setOnClickListener + } + + ensureBackgroundThread { + config.apply { + autoBackupFolder = backupFolder + autoBackupFilename = filename + } + + activity.runOnUiThread { + onSuccess() + } + + dialog.dismiss() + } + } + + else -> activity.toast(com.simplemobiletools.commons.R.string.invalid_name) + } + } + } + } + } + + private fun selectBackupFolder() { + activity.hideKeyboard(binding.backupNotesFilename) + FilePickerDialog(activity, backupFolder, false, showFAB = true) { path -> + activity.handleSAFDialog(path) { grantedSAF -> + if (!grantedSAF) { + return@handleSAFDialog + } + + activity.handleSAFDialogSdk30(path) { grantedSAF30 -> + if (!grantedSAF30) { + return@handleSAFDialogSdk30 + } + + backupFolder = path + binding.backupNotesFolder.setText(activity.humanizePath(path)) + } + } + } + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/NewChecklistItemDialog.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/NewChecklistItemDialog.kt new file mode 100644 index 000000000..8244d7aa1 --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/NewChecklistItemDialog.kt @@ -0,0 +1,79 @@ +package com.simplemobiletools.notes.pro.dialogs + +import android.app.Activity +import android.content.DialogInterface.BUTTON_POSITIVE +import android.view.KeyEvent +import android.view.View +import android.view.inputmethod.EditorInfo +import androidx.appcompat.widget.AppCompatEditText +import com.simplemobiletools.commons.extensions.* +import com.simplemobiletools.commons.helpers.DARK_GREY +import com.simplemobiletools.commons.helpers.SORT_BY_CUSTOM +import com.simplemobiletools.notes.pro.R +import com.simplemobiletools.notes.pro.databinding.DialogNewChecklistItemBinding +import com.simplemobiletools.notes.pro.databinding.ItemAddChecklistBinding +import com.simplemobiletools.notes.pro.extensions.config + +class NewChecklistItemDialog(val activity: Activity, callback: (titles: ArrayList) -> Unit) { + private val titles = mutableListOf() + private val binding = DialogNewChecklistItemBinding.inflate(activity.layoutInflater) + private val view = binding.root + + init { + addNewEditText() + val plusTextColor = if (activity.isWhiteTheme()) { + DARK_GREY + } else { + activity.getProperPrimaryColor().getContrastColor() + } + + binding.apply { + addItem.applyColorFilter(plusTextColor) + addItem.setOnClickListener { + addNewEditText() + } + settingsAddChecklistTop.beVisibleIf(activity.config.sorting == SORT_BY_CUSTOM) + settingsAddChecklistTop.isChecked = activity.config.addNewChecklistItemsTop + } + + activity.getAlertDialogBuilder() + .setPositiveButton(com.simplemobiletools.commons.R.string.ok, null) + .setNegativeButton(com.simplemobiletools.commons.R.string.cancel, null) + .apply { + activity.setupDialogStuff(view, this, R.string.add_new_checklist_items) { alertDialog -> + alertDialog.showKeyboard(titles.first()) + alertDialog.getButton(BUTTON_POSITIVE).setOnClickListener { + activity.config.addNewChecklistItemsTop = binding.settingsAddChecklistTop.isChecked + when { + titles.all { it.text!!.isEmpty() } -> activity.toast(com.simplemobiletools.commons.R.string.empty_name) + else -> { + val titles = titles.map { it.text.toString() }.filter { it.isNotEmpty() }.toMutableList() as ArrayList + callback(titles) + alertDialog.dismiss() + } + } + } + } + } + } + + private fun addNewEditText() { + ItemAddChecklistBinding.inflate(activity.layoutInflater).apply { + titleEditText.setOnEditorActionListener { _, actionId, _ -> + if (actionId == EditorInfo.IME_ACTION_NEXT || actionId == EditorInfo.IME_ACTION_DONE || actionId == KeyEvent.KEYCODE_ENTER) { + addNewEditText() + true + } else { + false + } + } + titles.add(titleEditText) + binding.checklistHolder.addView(this.root) + activity.updateTextColors(binding.checklistHolder) + binding.dialogHolder.post { + binding.dialogHolder.fullScroll(View.FOCUS_DOWN) + activity.showKeyboard(titleEditText) + } + } + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/NewNoteDialog.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/NewNoteDialog.kt new file mode 100644 index 000000000..502abca6f --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/NewNoteDialog.kt @@ -0,0 +1,59 @@ +package com.simplemobiletools.notes.pro.dialogs + +import android.app.Activity +import android.content.DialogInterface.BUTTON_POSITIVE +import com.simplemobiletools.commons.extensions.* +import com.simplemobiletools.commons.helpers.PROTECTION_NONE +import com.simplemobiletools.commons.helpers.ensureBackgroundThread +import com.simplemobiletools.notes.pro.R +import com.simplemobiletools.notes.pro.databinding.DialogNewNoteBinding +import com.simplemobiletools.notes.pro.extensions.config +import com.simplemobiletools.notes.pro.extensions.notesDB +import com.simplemobiletools.notes.pro.models.Note +import com.simplemobiletools.notes.pro.models.NoteType + +class NewNoteDialog(val activity: Activity, title: String? = null, val setChecklistAsDefault: Boolean, callback: (note: Note) -> Unit) { + init { + val binding = DialogNewNoteBinding.inflate(activity.layoutInflater).apply { + val defaultType = when { + setChecklistAsDefault -> typeChecklist.id + activity.config.lastCreatedNoteType == NoteType.TYPE_TEXT.value -> typeTextNote.id + else -> typeChecklist.id + } + + newNoteType.check(defaultType) + } + + binding.lockedNoteTitle.setText(title) + + activity.getAlertDialogBuilder() + .setPositiveButton(com.simplemobiletools.commons.R.string.ok, null) + .setNegativeButton(com.simplemobiletools.commons.R.string.cancel, null) + .apply { + activity.setupDialogStuff(binding.root, this, R.string.new_note) { alertDialog -> + alertDialog.showKeyboard(binding.lockedNoteTitle) + alertDialog.getButton(BUTTON_POSITIVE).setOnClickListener { + val newTitle = binding.lockedNoteTitle.value + ensureBackgroundThread { + when { + newTitle.isEmpty() -> activity.toast(R.string.no_title) + activity.notesDB.getNoteIdWithTitle(newTitle) != null -> activity.toast(R.string.title_taken) + else -> { + val type = if (binding.newNoteType.checkedRadioButtonId == binding.typeChecklist.id) { + NoteType.TYPE_CHECKLIST + } else { + NoteType.TYPE_TEXT + } + + activity.config.lastCreatedNoteType = type.value + val newNote = Note(null, newTitle, "", type, "", PROTECTION_NONE, "") + callback(newNote) + alertDialog.dismiss() + } + } + } + } + } + } + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/OpenFileDialog.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/OpenFileDialog.kt new file mode 100644 index 000000000..f1ce77219 --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/OpenFileDialog.kt @@ -0,0 +1,53 @@ +package com.simplemobiletools.notes.pro.dialogs + +import androidx.appcompat.app.AlertDialog +import com.simplemobiletools.commons.extensions.getAlertDialogBuilder +import com.simplemobiletools.commons.extensions.getFilenameFromPath +import com.simplemobiletools.commons.extensions.humanizePath +import com.simplemobiletools.commons.extensions.setupDialogStuff +import com.simplemobiletools.commons.helpers.PROTECTION_NONE +import com.simplemobiletools.notes.pro.R +import com.simplemobiletools.notes.pro.activities.SimpleActivity +import com.simplemobiletools.notes.pro.databinding.DialogOpenFileBinding +import com.simplemobiletools.notes.pro.models.Note +import com.simplemobiletools.notes.pro.models.NoteType +import java.io.File + +class OpenFileDialog(val activity: SimpleActivity, val path: String, val callback: (note: Note) -> Unit) : AlertDialog.Builder(activity) { + private var dialog: AlertDialog? = null + + init { + val binding = DialogOpenFileBinding.inflate(activity.layoutInflater).apply { + openFileFilename.setText(activity.humanizePath(path)) + } + + activity.getAlertDialogBuilder() + .setPositiveButton(com.simplemobiletools.commons.R.string.ok, null) + .setNegativeButton(com.simplemobiletools.commons.R.string.cancel, null) + .apply { + activity.setupDialogStuff(binding.root, this, R.string.open_file) { alertDialog -> + dialog = alertDialog + alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { + val updateFileOnEdit = binding.openFileType.checkedRadioButtonId == binding.openFileUpdateFile.id + val storePath = if (updateFileOnEdit) path else "" + val storeContent = if (updateFileOnEdit) "" else File(path).readText() + + if (updateFileOnEdit) { + activity.handleSAFDialog(path) { + saveNote(storeContent, storePath) + } + } else { + saveNote(storeContent, storePath) + } + } + } + } + } + + private fun saveNote(storeContent: String, storePath: String) { + val filename = path.getFilenameFromPath() + val note = Note(null, filename, storeContent, NoteType.TYPE_TEXT, storePath, PROTECTION_NONE, "") + callback(note) + dialog?.dismiss() + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/OpenNoteDialog.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/OpenNoteDialog.kt new file mode 100644 index 000000000..7a7b4fbc2 --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/OpenNoteDialog.kt @@ -0,0 +1,51 @@ +package com.simplemobiletools.notes.pro.dialogs + +import androidx.appcompat.app.AlertDialog +import androidx.recyclerview.widget.StaggeredGridLayoutManager +import com.simplemobiletools.commons.activities.BaseSimpleActivity +import com.simplemobiletools.commons.extensions.getAlertDialogBuilder +import com.simplemobiletools.commons.extensions.setupDialogStuff +import com.simplemobiletools.commons.views.AutoStaggeredGridLayoutManager +import com.simplemobiletools.notes.pro.R +import com.simplemobiletools.notes.pro.adapters.OpenNoteAdapter +import com.simplemobiletools.notes.pro.databinding.DialogOpenNoteBinding +import com.simplemobiletools.notes.pro.helpers.NotesHelper +import com.simplemobiletools.notes.pro.models.Note + +class OpenNoteDialog(val activity: BaseSimpleActivity, val callback: (checkedId: Long, newNote: Note?) -> Unit) { + private var dialog: AlertDialog? = null + + init { + val binding = DialogOpenNoteBinding.inflate(activity.layoutInflater) + + val noteItemWidth = activity.resources.getDimensionPixelSize(R.dimen.grid_note_item_width) + binding.dialogOpenNoteList.layoutManager = AutoStaggeredGridLayoutManager(noteItemWidth, StaggeredGridLayoutManager.VERTICAL) + + NotesHelper(activity).getNotes { + initDialog(it, binding) + } + } + + private fun initDialog(notes: List, binding: DialogOpenNoteBinding) { + binding.dialogOpenNoteList.adapter = OpenNoteAdapter(activity, notes, binding.dialogOpenNoteList) { + it as Note + callback(it.id!!, null) + dialog?.dismiss() + } + + binding.newNoteFab.setOnClickListener { + NewNoteDialog(activity, setChecklistAsDefault = false) { + callback(0, it) + dialog?.dismiss() + } + } + + activity.getAlertDialogBuilder() + .setNegativeButton(com.simplemobiletools.commons.R.string.cancel, null) + .apply { + activity.setupDialogStuff(binding.root, this, R.string.open_note) { alertDialog -> + dialog = alertDialog + } + } + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/RenameChecklistItemDialog.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/RenameChecklistItemDialog.kt new file mode 100644 index 000000000..dc1804afe --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/RenameChecklistItemDialog.kt @@ -0,0 +1,33 @@ +package com.simplemobiletools.notes.pro.dialogs + +import android.app.Activity +import android.content.DialogInterface.BUTTON_POSITIVE +import com.simplemobiletools.commons.extensions.* +import com.simplemobiletools.notes.pro.databinding.DialogRenameChecklistItemBinding + +class RenameChecklistItemDialog(val activity: Activity, val oldTitle: String, callback: (newTitle: String) -> Unit) { + init { + val binding = DialogRenameChecklistItemBinding.inflate(activity.layoutInflater).apply { + checklistItemTitle.setText(oldTitle) + } + + activity.getAlertDialogBuilder() + .setPositiveButton(com.simplemobiletools.commons.R.string.ok, null) + .setNegativeButton(com.simplemobiletools.commons.R.string.cancel, null) + .apply { + activity.setupDialogStuff(binding.root, this) { alertDialog -> + alertDialog.showKeyboard(binding.checklistItemTitle) + alertDialog.getButton(BUTTON_POSITIVE).setOnClickListener { + val newTitle = binding.checklistItemTitle.value + when { + newTitle.isEmpty() -> activity.toast(com.simplemobiletools.commons.R.string.empty_name) + else -> { + callback(newTitle) + alertDialog.dismiss() + } + } + } + } + } + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/RenameNoteDialog.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/RenameNoteDialog.kt new file mode 100644 index 000000000..65833769c --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/RenameNoteDialog.kt @@ -0,0 +1,88 @@ +package com.simplemobiletools.notes.pro.dialogs + +import android.content.DialogInterface.BUTTON_POSITIVE +import androidx.appcompat.app.AlertDialog +import com.simplemobiletools.commons.extensions.* +import com.simplemobiletools.commons.helpers.ensureBackgroundThread +import com.simplemobiletools.notes.pro.R +import com.simplemobiletools.notes.pro.activities.SimpleActivity +import com.simplemobiletools.notes.pro.databinding.DialogRenameNoteBinding +import com.simplemobiletools.notes.pro.extensions.config +import com.simplemobiletools.notes.pro.extensions.notesDB +import com.simplemobiletools.notes.pro.extensions.updateWidgets +import com.simplemobiletools.notes.pro.helpers.NotesHelper +import com.simplemobiletools.notes.pro.models.Note +import java.io.File + +class RenameNoteDialog(val activity: SimpleActivity, val note: Note, val currentNoteText: String?, val callback: (note: Note) -> Unit) { + + init { + val binding = DialogRenameNoteBinding.inflate(activity.layoutInflater) + val view = binding.root + binding.lockedNoteTitle.setText(note.title) + + activity.getAlertDialogBuilder() + .setPositiveButton(com.simplemobiletools.commons.R.string.ok, null) + .setNegativeButton(com.simplemobiletools.commons.R.string.cancel, null) + .apply { + activity.setupDialogStuff(view, this, R.string.rename_note) { alertDialog -> + alertDialog.showKeyboard(binding.lockedNoteTitle) + alertDialog.getButton(BUTTON_POSITIVE).setOnClickListener { + val title = binding.lockedNoteTitle.value + ensureBackgroundThread { + newTitleConfirmed(title, alertDialog) + } + } + } + } + } + + private fun newTitleConfirmed(title: String, dialog: AlertDialog) { + when { + title.isEmpty() -> activity.toast(R.string.no_title) + activity.notesDB.getNoteIdWithTitleCaseSensitive(title) != null -> activity.toast(R.string.title_taken) + else -> { + note.title = title + if (activity.config.autosaveNotes && currentNoteText != null) { + note.value = currentNoteText + } + + val path = note.path + if (path.isEmpty()) { + activity.notesDB.insertOrUpdate(note) + activity.runOnUiThread { + dialog.dismiss() + callback(note) + } + } else { + if (title.isEmpty()) { + activity.toast(com.simplemobiletools.commons.R.string.filename_cannot_be_empty) + return + } + + val file = File(path) + val newFile = File(file.parent, title) + if (!newFile.name.isAValidFilename()) { + activity.toast(com.simplemobiletools.commons.R.string.invalid_name) + return + } + + activity.renameFile(file.absolutePath, newFile.absolutePath, false) { success, useAndroid30Way -> + if (success) { + note.path = newFile.absolutePath + NotesHelper(activity).insertOrUpdateNote(note) { + dialog.dismiss() + callback(note) + } + } else { + activity.toast(com.simplemobiletools.commons.R.string.rename_file_error) + return@renameFile + } + } + } + + activity.baseContext.updateWidgets() + } + } + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/SortChecklistDialog.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/SortChecklistDialog.kt new file mode 100644 index 000000000..87ab6a9de --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/SortChecklistDialog.kt @@ -0,0 +1,95 @@ +package com.simplemobiletools.notes.pro.dialogs + +import com.simplemobiletools.commons.extensions.beGoneIf +import com.simplemobiletools.commons.extensions.getAlertDialogBuilder +import com.simplemobiletools.commons.extensions.setupDialogStuff +import com.simplemobiletools.commons.helpers.SORT_BY_CUSTOM +import com.simplemobiletools.commons.helpers.SORT_BY_DATE_CREATED +import com.simplemobiletools.commons.helpers.SORT_BY_TITLE +import com.simplemobiletools.commons.helpers.SORT_DESCENDING +import com.simplemobiletools.notes.pro.R +import com.simplemobiletools.notes.pro.activities.SimpleActivity +import com.simplemobiletools.notes.pro.databinding.DialogSortChecklistBinding +import com.simplemobiletools.notes.pro.extensions.config + +class SortChecklistDialog(private val activity: SimpleActivity, private val callback: () -> Unit) { + private val binding = DialogSortChecklistBinding.inflate(activity.layoutInflater) + private val view = binding.root + private val config = activity.config + private var currSorting = config.sorting + + init { + setupSortRadio() + setupOrderRadio() + setupMoveUndoneChecklistItems() + + activity.getAlertDialogBuilder() + .setPositiveButton(com.simplemobiletools.commons.R.string.ok) { _, _ -> dialogConfirmed() } + .setNegativeButton(com.simplemobiletools.commons.R.string.cancel, null) + .apply { + activity.setupDialogStuff(view, this, com.simplemobiletools.commons.R.string.sort_by) + } + } + + private fun setupSortRadio() { + val fieldRadio = binding.sortingDialogRadioSorting + fieldRadio.setOnCheckedChangeListener { group, checkedId -> + val isCustomSorting = checkedId == binding.sortingDialogRadioCustom.id + binding.sortingDialogRadioOrder.beGoneIf(isCustomSorting) + binding.sortingDialogOrderDivider.beGoneIf(isCustomSorting) + binding.moveUndoneChecklistItemsDivider.beGoneIf(isCustomSorting) + binding.settingsMoveUndoneChecklistItemsHolder.beGoneIf(isCustomSorting) + } + + var fieldBtn = binding.sortingDialogRadioTitle + + if (currSorting and SORT_BY_DATE_CREATED != 0) { + fieldBtn = binding.sortingDialogRadioDateCreated + } + + if (currSorting and SORT_BY_CUSTOM != 0) { + fieldBtn = binding.sortingDialogRadioCustom + } + + fieldBtn.isChecked = true + } + + private fun setupOrderRadio() { + var orderBtn = binding.sortingDialogRadioAscending + + if (currSorting and SORT_DESCENDING != 0) { + orderBtn = binding.sortingDialogRadioDescending + } + + orderBtn.isChecked = true + } + + private fun setupMoveUndoneChecklistItems() { + binding.settingsMoveUndoneChecklistItems.isChecked = config.moveDoneChecklistItems + binding.settingsMoveUndoneChecklistItemsHolder.setOnClickListener { + binding.settingsMoveUndoneChecklistItems.toggle() + } + } + + private fun dialogConfirmed() { + val sortingRadio = binding.sortingDialogRadioSorting + var sorting = when (sortingRadio.checkedRadioButtonId) { + R.id.sorting_dialog_radio_date_created -> SORT_BY_DATE_CREATED + R.id.sorting_dialog_radio_custom -> SORT_BY_CUSTOM + else -> SORT_BY_TITLE + } + + if (sortingRadio.checkedRadioButtonId != R.id.sorting_dialog_radio_custom + && binding.sortingDialogRadioOrder.checkedRadioButtonId == R.id.sorting_dialog_radio_descending + ) { + sorting = sorting or SORT_DESCENDING + } + + if (currSorting != sorting) { + config.sorting = sorting + } + + config.moveDoneChecklistItems = binding.settingsMoveUndoneChecklistItems.isChecked + callback() + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/UnlockNotesDialog.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/UnlockNotesDialog.kt new file mode 100644 index 000000000..a8f3f11b9 --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/UnlockNotesDialog.kt @@ -0,0 +1,78 @@ +package com.simplemobiletools.notes.pro.dialogs + +import android.content.DialogInterface +import androidx.appcompat.app.AlertDialog +import com.simplemobiletools.commons.activities.BaseSimpleActivity +import com.simplemobiletools.commons.extensions.* +import com.simplemobiletools.notes.pro.R +import com.simplemobiletools.notes.pro.databinding.DialogUnlockNotesBinding +import com.simplemobiletools.notes.pro.databinding.ItemLockedNoteBinding +import com.simplemobiletools.notes.pro.models.Note + +class UnlockNotesDialog(val activity: BaseSimpleActivity, val notes: List, callback: (unlockedNotes: List) -> Unit) { + private var dialog: AlertDialog? = null + private val binding = DialogUnlockNotesBinding.inflate(activity.layoutInflater) + private val view = binding.root + private val redColor = activity.getColor(com.simplemobiletools.commons.R.color.md_red) + private val greenColor = activity.getColor(com.simplemobiletools.commons.R.color.md_green) + private val unlockedNoteIds = mutableListOf() + + init { + for (note in notes) { + addLockedNoteView(note) + } + + activity.getAlertDialogBuilder() + .setPositiveButton(com.simplemobiletools.commons.R.string.skip, null) + .setNegativeButton(com.simplemobiletools.commons.R.string.cancel, null) + .apply { + activity.setupDialogStuff(view, this, R.string.unlock_notes, cancelOnTouchOutside = false) { alertDialog -> + dialog = alertDialog + alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener { + callback(unlockedNoteIds.mapNotNull { id -> notes.firstOrNull { it.id == id } }) + alertDialog.dismiss() + } + } + } + } + + private fun addLockedNoteView(note: Note) { + ItemLockedNoteBinding.inflate(activity.layoutInflater).apply { + binding.notesHolder.addView(this.root) + activity.updateTextColors(binding.notesHolder) + lockedNoteTitle.text = note.title + lockedUnlockedImage.applyColorFilter(redColor) + lockedNoteHolder.setOnClickListener { + if (note.id !in unlockedNoteIds) { + activity.performSecurityCheck( + protectionType = note.protectionType, + requiredHash = note.protectionHash, + successCallback = { _, _ -> + unlockedNoteIds.add(note.id!!) + lockedUnlockedImage.apply { + setImageResource(R.drawable.ic_lock_open_vector) + applyColorFilter(greenColor) + } + updatePositiveButton() + } + ) + } else { + unlockedNoteIds.remove(note.id) + lockedUnlockedImage.apply { + setImageResource(com.simplemobiletools.commons.R.drawable.ic_lock_vector) + applyColorFilter(redColor) + } + updatePositiveButton() + } + } + } + } + + private fun updatePositiveButton() { + dialog?.getButton(DialogInterface.BUTTON_POSITIVE)?.text = if (unlockedNoteIds.isNotEmpty()) { + activity.getString(com.simplemobiletools.commons.R.string.ok) + } else { + activity.getString(com.simplemobiletools.commons.R.string.skip) + } + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/extensions/Context.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/extensions/Context.kt new file mode 100644 index 000000000..b958e11fc --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/extensions/Context.kt @@ -0,0 +1,163 @@ +package com.simplemobiletools.notes.pro.extensions + +import android.app.AlarmManager +import android.app.PendingIntent +import android.appwidget.AppWidgetManager +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import androidx.core.app.AlarmManagerCompat +import com.simplemobiletools.commons.activities.BaseSimpleActivity +import com.simplemobiletools.commons.extensions.* +import com.simplemobiletools.commons.helpers.ExportResult +import com.simplemobiletools.commons.helpers.ensureBackgroundThread +import com.simplemobiletools.commons.helpers.isRPlus +import com.simplemobiletools.notes.pro.R +import com.simplemobiletools.notes.pro.databases.NotesDatabase +import com.simplemobiletools.notes.pro.dialogs.UnlockNotesDialog +import com.simplemobiletools.notes.pro.helpers.* +import com.simplemobiletools.notes.pro.interfaces.NotesDao +import com.simplemobiletools.notes.pro.interfaces.WidgetsDao +import com.simplemobiletools.notes.pro.models.Note +import com.simplemobiletools.notes.pro.receivers.AutomaticBackupReceiver +import org.joda.time.DateTime +import java.io.File +import java.io.FileOutputStream + +val Context.config: Config get() = Config.newInstance(applicationContext) + +val Context.notesDB: NotesDao get() = NotesDatabase.getInstance(applicationContext).NotesDao() + +val Context.widgetsDB: WidgetsDao get() = NotesDatabase.getInstance(applicationContext).WidgetsDao() + +fun Context.updateWidgets() { + val widgetIDs = AppWidgetManager.getInstance(applicationContext)?.getAppWidgetIds(ComponentName(applicationContext, MyWidgetProvider::class.java)) ?: return + if (widgetIDs.isNotEmpty()) { + Intent(applicationContext, MyWidgetProvider::class.java).apply { + action = AppWidgetManager.ACTION_APPWIDGET_UPDATE + putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, widgetIDs) + sendBroadcast(this) + } + } +} + +fun Context.getPercentageFontSize() = resources.getDimension(com.simplemobiletools.commons.R.dimen.middle_text_size) * (config.fontSizePercentage / 100f) + +fun BaseSimpleActivity.requestUnlockNotes(notes: List, callback: (unlockedNotes: List) -> Unit) { + val lockedNotes = notes.filter { it.isLocked() } + if (lockedNotes.isNotEmpty()) { + runOnUiThread { + UnlockNotesDialog(this, lockedNotes, callback) + } + } else { + callback(emptyList()) + } +} + +fun Context.getAutomaticBackupIntent(): PendingIntent { + val intent = Intent(this, AutomaticBackupReceiver::class.java) + return PendingIntent.getBroadcast(this, AUTOMATIC_BACKUP_REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE) +} + +fun Context.scheduleNextAutomaticBackup() { + if (config.autoBackup) { + val backupAtMillis = getNextAutoBackupTime().millis + val pendingIntent = getAutomaticBackupIntent() + val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager + try { + AlarmManagerCompat.setExactAndAllowWhileIdle(alarmManager, AlarmManager.RTC_WAKEUP, backupAtMillis, pendingIntent) + } catch (e: Exception) { + showErrorToast(e) + } + } +} + +fun Context.cancelScheduledAutomaticBackup() { + val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager + alarmManager.cancel(getAutomaticBackupIntent()) +} + +fun Context.checkAndBackupNotesOnBoot() { + if (config.autoBackup) { + val previousRealBackupTime = config.lastAutoBackupTime + val previousScheduledBackupTime = getPreviousAutoBackupTime().millis + val missedPreviousBackup = previousRealBackupTime < previousScheduledBackupTime + if (missedPreviousBackup) { + // device was probably off at the scheduled time so backup now + backupNotes() + } + } +} + +fun Context.backupNotes() { + require(isRPlus()) + ensureBackgroundThread { + val config = config + NotesHelper(this).getNotes { notesToBackup -> + if (notesToBackup.isEmpty()) { + toast(com.simplemobiletools.commons.R.string.no_entries_for_exporting) + config.lastAutoBackupTime = DateTime.now().millis + scheduleNextAutomaticBackup() + return@getNotes + } + + + val now = DateTime.now() + val year = now.year.toString() + val month = now.monthOfYear.ensureTwoDigits() + val day = now.dayOfMonth.ensureTwoDigits() + val hours = now.hourOfDay.ensureTwoDigits() + val minutes = now.minuteOfHour.ensureTwoDigits() + val seconds = now.secondOfMinute.ensureTwoDigits() + + val filename = config.autoBackupFilename + .replace("%Y", year, false) + .replace("%M", month, false) + .replace("%D", day, false) + .replace("%h", hours, false) + .replace("%m", minutes, false) + .replace("%s", seconds, false) + + val outputFolder = File(config.autoBackupFolder).apply { + mkdirs() + } + + var exportFile = File(outputFolder, "$filename.json") + var exportFilePath = exportFile.absolutePath + val outputStream = try { + if (hasProperStoredFirstParentUri(exportFilePath)) { + val exportFileUri = createDocumentUriUsingFirstParentTreeUri(exportFilePath) + if (!getDoesFilePathExist(exportFilePath)) { + createSAFFileSdk30(exportFilePath) + } + applicationContext.contentResolver.openOutputStream(exportFileUri, "wt") ?: FileOutputStream(exportFile) + } else { + var num = 0 + while (getDoesFilePathExist(exportFilePath) && !exportFile.canWrite()) { + num++ + exportFile = File(outputFolder, "${filename}_${num}.json") + exportFilePath = exportFile.absolutePath + } + FileOutputStream(exportFile) + } + } catch (e: Exception) { + showErrorToast(e) + scheduleNextAutomaticBackup() + return@getNotes + } + + val exportResult = try { + NotesHelper(this).exportNotes(notesToBackup, outputStream) + } catch (e: Exception) { + showErrorToast(e) + } + + if (exportResult == ExportResult.EXPORT_FAIL) { + toast(com.simplemobiletools.commons.R.string.exporting_failed) + } + + config.lastAutoBackupTime = DateTime.now().millis + scheduleNextAutomaticBackup() + } + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/extensions/Fragment.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/extensions/Fragment.kt new file mode 100644 index 000000000..4a1bc2ee8 --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/extensions/Fragment.kt @@ -0,0 +1,6 @@ +package com.simplemobiletools.notes.pro.extensions + +import androidx.fragment.app.Fragment +import com.simplemobiletools.notes.pro.helpers.Config + +val Fragment.config: Config? get() = if (context != null) Config.newInstance(context!!) else null diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/extensions/String.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/extensions/String.kt new file mode 100644 index 000000000..5ecf3bf25 --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/extensions/String.kt @@ -0,0 +1,16 @@ +package com.simplemobiletools.notes.pro.extensions + +import com.google.gson.Gson +import com.google.gson.reflect.TypeToken +import com.simplemobiletools.notes.pro.models.ChecklistItem + +fun String.parseChecklistItems(): ArrayList? { + if (startsWith("[{") && endsWith("}]")) { + try { + val checklistItemType = object : TypeToken>() {}.type + return Gson().fromJson>(this, checklistItemType) ?: null + } catch (e: Exception) { + } + } + return null +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/fragments/ChecklistFragment.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/fragments/ChecklistFragment.kt new file mode 100644 index 000000000..04003ed7b --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/fragments/ChecklistFragment.kt @@ -0,0 +1,257 @@ +package com.simplemobiletools.notes.pro.fragments + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.ImageView +import android.widget.TextView +import com.google.gson.Gson +import com.google.gson.reflect.TypeToken +import com.simplemobiletools.commons.extensions.* +import com.simplemobiletools.commons.helpers.SORT_BY_CUSTOM +import com.simplemobiletools.commons.helpers.ensureBackgroundThread +import com.simplemobiletools.notes.pro.activities.SimpleActivity +import com.simplemobiletools.notes.pro.adapters.ChecklistAdapter +import com.simplemobiletools.notes.pro.databinding.FragmentChecklistBinding +import com.simplemobiletools.notes.pro.dialogs.NewChecklistItemDialog +import com.simplemobiletools.notes.pro.extensions.config +import com.simplemobiletools.notes.pro.extensions.updateWidgets +import com.simplemobiletools.notes.pro.helpers.NOTE_ID +import com.simplemobiletools.notes.pro.helpers.NotesHelper +import com.simplemobiletools.notes.pro.interfaces.ChecklistItemsListener +import com.simplemobiletools.notes.pro.models.ChecklistItem +import com.simplemobiletools.notes.pro.models.Note +import java.io.File + +class ChecklistFragment : NoteFragment(), ChecklistItemsListener { + + private var noteId = 0L + + private lateinit var binding: FragmentChecklistBinding + + var items = mutableListOf() + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { + binding = FragmentChecklistBinding.inflate(inflater, container, false) + noteId = requireArguments().getLong(NOTE_ID, 0L) + setupFragmentColors() + return binding.root + } + + override fun onResume() { + super.onResume() + loadNoteById(noteId) + } + + override fun setMenuVisibility(menuVisible: Boolean) { + super.setMenuVisibility(menuVisible) + + if (menuVisible) { + activity?.hideKeyboard() + } else if (::binding.isInitialized) { + (binding.checklistList.adapter as? ChecklistAdapter)?.finishActMode() + } + } + + private fun loadNoteById(noteId: Long) { + NotesHelper(requireActivity()).getNoteWithId(noteId) { storedNote -> + if (storedNote != null && activity?.isDestroyed == false) { + note = storedNote + + try { + val checklistItemType = object : TypeToken>() {}.type + items = Gson().fromJson>(storedNote.getNoteStoredValue(requireActivity()), checklistItemType) ?: ArrayList(1) + + // checklist title can be null only because of the glitch in upgrade to 6.6.0, remove this check in the future + items = items.filter { it.title != null }.toMutableList() as ArrayList + val sorting = config?.sorting ?: 0 + if (sorting and SORT_BY_CUSTOM == 0 && config?.moveDoneChecklistItems == true) { + items.sortBy { it.isDone } + } + + setupFragment() + } catch (e: Exception) { + migrateCheckListOnFailure(storedNote) + } + } + } + } + + private fun migrateCheckListOnFailure(note: Note) { + items.clear() + + note.getNoteStoredValue(requireActivity())?.split("\n")?.map { it.trim() }?.filter { it.isNotBlank() }?.forEachIndexed { index, value -> + items.add( + ChecklistItem( + id = index, + title = value, + isDone = false + ) + ) + } + + saveChecklist() + } + + private fun setupFragment() { + if (activity == null || requireActivity().isFinishing) { + return + } + + setupFragmentColors() + checkLockState() + setupAdapter() + } + + private fun setupFragmentColors() { + val adjustedPrimaryColor = requireActivity().getProperPrimaryColor() + binding.checklistFab.apply { + setColors( + requireActivity().getProperTextColor(), + adjustedPrimaryColor, + adjustedPrimaryColor.getContrastColor() + ) + + setOnClickListener { + showNewItemDialog() + (binding.checklistList.adapter as? ChecklistAdapter)?.finishActMode() + } + } + + binding.fragmentPlaceholder.setTextColor(requireActivity().getProperTextColor()) + binding.fragmentPlaceholder2.apply { + setTextColor(adjustedPrimaryColor) + underlineText() + setOnClickListener { + showNewItemDialog() + } + } + } + + override fun checkLockState() { + if (note == null) { + return + } + + binding.apply { + checklistContentHolder.beVisibleIf(!note!!.isLocked() || shouldShowLockedContent) + checklistFab.beVisibleIf(!note!!.isLocked() || shouldShowLockedContent) + setupLockedViews(this.toCommonBinding(), note!!) + } + } + + private fun showNewItemDialog() { + NewChecklistItemDialog(activity as SimpleActivity) { titles -> + var currentMaxId = items.maxByOrNull { item -> item.id }?.id ?: 0 + val newItems = ArrayList() + + titles.forEach { title -> + title.split("\n").map { it.trim() }.filter { it.isNotBlank() }.forEach { row -> + newItems.add(ChecklistItem(currentMaxId + 1, System.currentTimeMillis(), row, false)) + currentMaxId++ + } + } + + if (config?.addNewChecklistItemsTop == true) { + items.addAll(0, newItems) + } else { + items.addAll(newItems) + } + + saveNote() + setupAdapter() + } + } + + private fun setupAdapter() { + updateUIVisibility() + ChecklistItem.sorting = requireContext().config.sorting + if (ChecklistItem.sorting and SORT_BY_CUSTOM == 0) { + items.sort() + if (context?.config?.moveDoneChecklistItems == true) { + items.sortBy { it.isDone } + } + } + ChecklistAdapter( + activity = activity as SimpleActivity, + items = items, + listener = this, + recyclerView = binding.checklistList, + showIcons = true + ) { item -> + val clickedNote = item as ChecklistItem + clickedNote.isDone = !clickedNote.isDone + + saveNote(items.indexOfFirst { it.id == clickedNote.id }) + context?.updateWidgets() + }.apply { + binding.checklistList.adapter = this + } + } + + private fun saveNote(refreshIndex: Int = -1, callback: () -> Unit = {}) { + if (note == null) { + return + } + + if (note!!.path.isNotEmpty() && !note!!.path.startsWith("content://") && !File(note!!.path).exists()) { + return + } + + if (context == null || activity == null) { + return + } + + if (note != null) { + if (refreshIndex != -1) { + binding.checklistList.post { + binding.checklistList.adapter?.notifyItemChanged(refreshIndex) + } + } + + note!!.value = getChecklistItems() + + ensureBackgroundThread { + saveNoteValue(note!!, note!!.value) + context?.updateWidgets() + activity?.runOnUiThread(callback) + } + } + } + + fun removeDoneItems() { + items = items.filter { !it.isDone }.toMutableList() as ArrayList + saveNote() + setupAdapter() + } + + private fun updateUIVisibility() { + binding.apply { + fragmentPlaceholder.beVisibleIf(items.isEmpty()) + fragmentPlaceholder2.beVisibleIf(items.isEmpty()) + checklistList.beVisibleIf(items.isNotEmpty()) + } + } + + fun getChecklistItems() = Gson().toJson(items) + + override fun saveChecklist(callback: () -> Unit) { + saveNote(callback = callback) + } + + override fun refreshItems() { + loadNoteById(noteId) + setupAdapter() + } + + private fun FragmentChecklistBinding.toCommonBinding(): CommonNoteBinding = this.let { + object : CommonNoteBinding { + override val root: View = it.root + override val noteLockedLayout: View = it.noteLockedLayout + override val noteLockedImage: ImageView = it.noteLockedImage + override val noteLockedLabel: TextView = it.noteLockedLabel + override val noteLockedShow: TextView = it.noteLockedShow + } + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/fragments/NoteFragment.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/fragments/NoteFragment.kt new file mode 100644 index 000000000..132e80d0e --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/fragments/NoteFragment.kt @@ -0,0 +1,84 @@ +package com.simplemobiletools.notes.pro.fragments + +import android.util.TypedValue +import android.view.View +import android.widget.ImageView +import android.widget.TextView +import androidx.fragment.app.Fragment +import com.simplemobiletools.commons.extensions.* +import com.simplemobiletools.commons.helpers.PROTECTION_NONE +import com.simplemobiletools.notes.pro.activities.MainActivity +import com.simplemobiletools.notes.pro.extensions.config +import com.simplemobiletools.notes.pro.extensions.getPercentageFontSize +import com.simplemobiletools.notes.pro.helpers.NotesHelper +import com.simplemobiletools.notes.pro.models.Note + +abstract class NoteFragment : Fragment() { + protected var note: Note? = null + var shouldShowLockedContent = false + + protected fun setupLockedViews(binding: CommonNoteBinding, note: Note) { + binding.apply { + noteLockedLayout.beVisibleIf(note.isLocked() && !shouldShowLockedContent) + noteLockedImage.applyColorFilter(requireContext().getProperTextColor()) + + noteLockedLabel.setTextColor(requireContext().getProperTextColor()) + noteLockedLabel.setTextSize(TypedValue.COMPLEX_UNIT_PX, binding.root.context.getPercentageFontSize()) + + noteLockedShow.underlineText() + noteLockedShow.setTextColor(requireContext().getProperPrimaryColor()) + noteLockedShow.setTextSize(TypedValue.COMPLEX_UNIT_PX, binding.root.context.getPercentageFontSize()) + noteLockedShow.setOnClickListener { + handleUnlocking() + } + } + } + + protected fun saveNoteValue(note: Note, content: String?) { + if (note.path.isEmpty()) { + NotesHelper(requireActivity()).insertOrUpdateNote(note) { + (activity as? MainActivity)?.noteSavedSuccessfully(note.title) + } + } else { + if (content != null) { + val displaySuccess = activity?.config?.displaySuccess ?: false + (activity as? MainActivity)?.tryExportNoteValueToFile(note.path, note.title, content, displaySuccess) + } + } + } + + fun handleUnlocking(callback: (() -> Unit)? = null) { + if (callback != null && (note!!.protectionType == PROTECTION_NONE || shouldShowLockedContent)) { + callback() + return + } + + activity?.performSecurityCheck( + protectionType = note!!.protectionType, + requiredHash = note!!.protectionHash, + successCallback = { _, _ -> + shouldShowLockedContent = true + checkLockState() + callback?.invoke() + } + ) + } + + fun updateNoteValue(value: String) { + note?.value = value + } + + fun updateNotePath(path: String) { + note?.path = path + } + + abstract fun checkLockState() + + interface CommonNoteBinding { + val root: View + val noteLockedLayout: View + val noteLockedImage: ImageView + val noteLockedLabel: TextView + val noteLockedShow: TextView + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/fragments/TextFragment.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/fragments/TextFragment.kt new file mode 100644 index 000000000..ff142fbb1 --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/fragments/TextFragment.kt @@ -0,0 +1,354 @@ +package com.simplemobiletools.notes.pro.fragments + +import android.annotation.SuppressLint +import android.content.Context +import android.graphics.Typeface +import android.os.Bundle +import android.text.Editable +import android.text.Selection +import android.text.TextWatcher +import android.text.style.UnderlineSpan +import android.text.util.Linkify +import android.util.TypedValue +import android.view.LayoutInflater +import android.view.MotionEvent +import android.view.View +import android.view.ViewGroup +import android.view.inputmethod.EditorInfo +import android.view.inputmethod.InputMethodManager +import android.widget.ImageView +import android.widget.TextView +import androidx.viewbinding.ViewBinding +import com.simplemobiletools.commons.extensions.* +import com.simplemobiletools.commons.views.MyEditText +import com.simplemobiletools.commons.views.MyTextView +import com.simplemobiletools.notes.pro.R +import com.simplemobiletools.notes.pro.activities.MainActivity +import com.simplemobiletools.notes.pro.databinding.FragmentTextBinding +import com.simplemobiletools.notes.pro.databinding.NoteViewHorizScrollableBinding +import com.simplemobiletools.notes.pro.databinding.NoteViewStaticBinding +import com.simplemobiletools.notes.pro.extensions.config +import com.simplemobiletools.notes.pro.extensions.getPercentageFontSize +import com.simplemobiletools.notes.pro.extensions.updateWidgets +import com.simplemobiletools.notes.pro.helpers.MyMovementMethod +import com.simplemobiletools.notes.pro.helpers.NOTE_ID +import com.simplemobiletools.notes.pro.helpers.NotesHelper +import com.simplemobiletools.notes.pro.models.TextHistory +import com.simplemobiletools.notes.pro.models.TextHistoryItem +import java.io.File + +// text history handling taken from https://gist.github.com/zeleven/0cfa738c1e8b65b23ff7df1fc30c9f7e +class TextFragment : NoteFragment() { + private val TEXT = "text" + + private var textHistory = TextHistory() + private var isUndoOrRedo = false + private var skipTextUpdating = false + private var noteId = 0L + private var touchDownX = 0f + private var moveXThreshold = 0 // make sure swiping across notes works well, do not swallow the gestures + + private lateinit var binding: FragmentTextBinding + private lateinit var innerBinding: ViewBinding + private lateinit var noteEditText: MyEditText + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { + binding = FragmentTextBinding.inflate(inflater, container, false) + noteId = requireArguments().getLong(NOTE_ID, 0L) + moveXThreshold = resources.getDimension(com.simplemobiletools.commons.R.dimen.activity_margin).toInt() + retainInstance = true + + innerBinding = if (config!!.enableLineWrap) { + NoteViewStaticBinding.inflate(inflater, binding.notesRelativeLayout, true).apply { + noteEditText = textNoteView + } + } else { + NoteViewHorizScrollableBinding.inflate(inflater, binding.notesRelativeLayout, true).apply { + noteEditText = textNoteView + } + } + if (config!!.clickableLinks) { + noteEditText.apply { + linksClickable = true + autoLinkMask = Linkify.WEB_URLS or Linkify.EMAIL_ADDRESSES + movementMethod = MyMovementMethod.getInstance() + } + } + + if (innerBinding is NoteViewHorizScrollableBinding) { + val casted = innerBinding as NoteViewHorizScrollableBinding + casted.notesHorizontalScrollview.onGlobalLayout { + casted.textNoteView.minWidth = casted.notesHorizontalScrollview.width + } + } + + return binding.root + } + + override fun onResume() { + super.onResume() + + NotesHelper(requireActivity()).getNoteWithId(noteId) { + if (it != null) { + note = it + setupFragment() + } + } + } + + override fun onPause() { + super.onPause() + if (config!!.autosaveNotes) { + saveText(false) + } + + removeTextWatcher() + } + + override fun setMenuVisibility(menuVisible: Boolean) { + super.setMenuVisibility(menuVisible) + if (!menuVisible && noteId != 0L && config?.autosaveNotes == true) { + saveText(false) + } + + if (menuVisible && noteId != 0L) { + val currentText = getCurrentNoteViewText() + if (currentText != null) { + (activity as MainActivity).currentNoteTextChanged(currentText, isUndoAvailable(), isRedoAvailable()) + } + } + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + if (note != null) { + outState.putString(TEXT, getCurrentNoteViewText()) + } + } + + override fun onViewStateRestored(savedInstanceState: Bundle?) { + super.onViewStateRestored(savedInstanceState) + if (savedInstanceState != null && note != null && savedInstanceState.containsKey(TEXT)) { + skipTextUpdating = true + val newText = savedInstanceState.getString(TEXT) ?: "" + innerBinding.root.findViewById(R.id.text_note_view).text = newText + } + } + + @SuppressLint("ClickableViewAccessibility") + private fun setupFragment() { + val config = config ?: return + noteEditText.apply { + typeface = if (config.monospacedFont) Typeface.MONOSPACE else Typeface.DEFAULT + + val fileContents = note!!.getNoteStoredValue(context) + if (fileContents == null) { + (activity as MainActivity).deleteNote(false, note!!) + return + } + + val adjustedPrimaryColor = context.getProperPrimaryColor() + setColors(context.getProperTextColor(), adjustedPrimaryColor, context.getProperBackgroundColor()) + setTextSize(TypedValue.COMPLEX_UNIT_PX, context.getPercentageFontSize()) + highlightColor = adjustedPrimaryColor.adjustAlpha(.4f) + + gravity = config.getTextGravity() + if (text.toString() != fileContents) { + if (!skipTextUpdating) { + removeTextWatcher() + setText(fileContents) + setTextWatcher() + } + skipTextUpdating = false + setSelection(if (config.placeCursorToEnd) text!!.length else 0) + } + + if (config.showKeyboard && isMenuVisible && (!note!!.isLocked() || shouldShowLockedContent)) { + onGlobalLayout { + if (activity?.isDestroyed == false) { + requestFocus() + val inputManager = requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager + inputManager.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT) + } + } + } + + imeOptions = if (config.useIncognitoMode) { + imeOptions or EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING + } else { + imeOptions.removeBit(EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING) + } + } + + noteEditText.setOnTouchListener { v, event -> + when (event.action) { + MotionEvent.ACTION_DOWN -> touchDownX = event.x + MotionEvent.ACTION_MOVE -> { + val diffX = Math.abs(event.x - touchDownX) + if (diffX > moveXThreshold) { + binding.root.requestDisallowInterceptTouchEvent(false) + } + } + } + false + } + + if (config.showWordCount) { + binding.notesCounter.setTextColor(requireContext().getProperTextColor()) + setWordCounter(noteEditText.text.toString()) + } + + checkLockState() + setTextWatcher() + } + + fun setTextWatcher() { + noteEditText.apply { + removeTextChangedListener(textWatcher) + addTextChangedListener(textWatcher) + } + } + + fun removeTextWatcher() = noteEditText.removeTextChangedListener(textWatcher) + + override fun checkLockState() { + if (note == null) { + return + } + + binding.apply { + notesCounter.beVisibleIf((!note!!.isLocked() || shouldShowLockedContent) && config!!.showWordCount) + notesScrollview.beVisibleIf(!note!!.isLocked() || shouldShowLockedContent) + setupLockedViews(this.toCommonBinding(), note!!) + } + } + + fun getNotesView() = noteEditText + + fun saveText(force: Boolean) { + if (note == null) { + return + } + + if (note!!.path.isNotEmpty() && !note!!.path.startsWith("content://") && !File(note!!.path).exists()) { + return + } + + if (context == null || activity == null) { + return + } + + val newText = getCurrentNoteViewText() + val oldText = note!!.getNoteStoredValue(requireContext()) + if (newText != null && (newText != oldText || force)) { + note!!.value = newText + saveNoteValue(note!!, newText) + requireContext().updateWidgets() + } + } + + fun hasUnsavedChanges() = note != null && getCurrentNoteViewText() != note!!.getNoteStoredValue(requireContext()) + + fun focusEditText() { + noteEditText.requestFocus() + } + + fun getCurrentNoteViewText() = noteEditText.text?.toString() + + private fun setWordCounter(text: String) { + val words = text.replace("\n", " ").split(" ") + binding.notesCounter.text = words.count { it.isNotEmpty() }.toString() + } + + fun undo() { + val edit = textHistory.getPrevious() ?: return + + val text = noteEditText.editableText + val start = edit.start + val end = start + if (edit.after != null) edit.after.length else 0 + + isUndoOrRedo = true + try { + text.replace(start, end, edit.before) + } catch (e: Exception) { + activity?.showErrorToast(e) + return + } + + isUndoOrRedo = false + + for (span in text.getSpans(0, text.length, UnderlineSpan::class.java)) { + text.removeSpan(span) + } + + Selection.setSelection( + text, if (edit.before == null) { + start + } else { + start + edit.before.length + } + ) + } + + fun redo() { + val edit = textHistory.getNext() ?: return + + val text = noteEditText.editableText + val start = edit.start + val end = start + if (edit.before != null) edit.before.length else 0 + + isUndoOrRedo = true + text.replace(start, end, edit.after) + isUndoOrRedo = false + + for (o in text.getSpans(0, text.length, UnderlineSpan::class.java)) { + text.removeSpan(o) + } + + Selection.setSelection( + text, if (edit.after == null) { + start + } else { + start + edit.after.length + } + ) + } + + fun isUndoAvailable() = textHistory.position > 0 + + fun isRedoAvailable() = textHistory.position < textHistory.history.size + + private var textWatcher: TextWatcher = object : TextWatcher { + private var beforeChange: CharSequence? = null + private var afterChange: CharSequence? = null + + override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { + if (!isUndoOrRedo) { + beforeChange = s.subSequence(start, start + count) + } + } + + override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { + if (!isUndoOrRedo) { + afterChange = s.subSequence(start, start + count) + textHistory.add(TextHistoryItem(start, beforeChange!!, afterChange!!)) + } + } + + override fun afterTextChanged(editable: Editable) { + val text = editable.toString() + setWordCounter(text) + (activity as MainActivity).currentNoteTextChanged(text, isUndoAvailable(), isRedoAvailable()) + } + } + + private fun FragmentTextBinding.toCommonBinding(): CommonNoteBinding = this.let { + object : CommonNoteBinding { + override val root: View = it.root + override val noteLockedLayout: View = it.noteLockedLayout + override val noteLockedImage: ImageView = it.noteLockedImage + override val noteLockedLabel: TextView = it.noteLockedLabel + override val noteLockedShow: TextView = it.noteLockedShow + } + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/helpers/CollatorBasedComparator.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/helpers/CollatorBasedComparator.kt new file mode 100644 index 000000000..3ac26f173 --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/helpers/CollatorBasedComparator.kt @@ -0,0 +1,81 @@ +package com.simplemobiletools.notes.pro.helpers + +import java.text.Collator + +/** + * Collator-based string comparator + * + * Adapted from AlphanumericComparator to support numerical collation. It sorts accents properly too. + */ +class CollatorBasedComparator : Comparator { + override fun compare(string1: String, string2: String): Int { + val collator = getCollator() + + var thisMarker = 0 + var thatMarker = 0 + + while (thisMarker < string1.length && thatMarker < string2.length) { + val thisChunk = getChunk(string1, string1.length, thisMarker) + thisMarker += thisChunk.length + + val thatChunk = getChunk(string2, string2.length, thatMarker) + thatMarker += thatChunk.length + + val result = if (isDigit(thisChunk[0]) && isDigit(thatChunk[0])) { + collateNumerically(thisChunk, thatChunk) + } else { + collator.compare(thisChunk, thatChunk) + } + + if (result != 0) { + return coerceResult(result) + } + } + + return coerceResult(string1.length - string2.length) + } + + private fun collateNumerically(string1: String, string2: String): Int { + var result: Int + result = string1.length - string2.length + if (result == 0) { + // equal length, the first different number counts + for (i in string1.indices) { + result = string1[i] - string2[i] + if (result != 0) { + break + } + } + } + return result + } + + private fun getChunk(string: String, length: Int, marker: Int): String { + var current = marker + var c = string[current] + val chunk = StringBuilder(c.toString()) + current++ + val chunkOfDigits = isDigit(c) + while (current < length) { + c = string[current] + if (isDigit(c) != chunkOfDigits) { + break + } + chunk.append(c) + current++ + } + + return chunk.toString() + } + + private fun isDigit(ch: Char) = ch in '0'..'9' + + private fun coerceResult(compareToResult: Int) = compareToResult.coerceIn(-1, 1) + + private fun getCollator(): Collator { + val collator = Collator.getInstance() + collator.strength = Collator.PRIMARY + collator.decomposition = Collator.CANONICAL_DECOMPOSITION + return collator + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/helpers/Config.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/helpers/Config.kt similarity index 56% rename from app/src/main/kotlin/com/simplemobiletools/notes/helpers/Config.kt rename to app/src/main/kotlin/com/simplemobiletools/notes/pro/helpers/Config.kt index bb5be80df..99efa9300 100644 --- a/app/src/main/kotlin/com/simplemobiletools/notes/helpers/Config.kt +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/helpers/Config.kt @@ -1,8 +1,10 @@ -package com.simplemobiletools.notes.helpers +package com.simplemobiletools.notes.pro.helpers import android.content.Context import android.os.Environment +import android.view.Gravity import com.simplemobiletools.commons.helpers.BaseConfig +import com.simplemobiletools.notes.pro.models.NoteType class Config(context: Context) : BaseConfig(context) { companion object { @@ -37,21 +39,17 @@ class Config(context: Context) : BaseConfig(context) { get() = prefs.getBoolean(SHOW_WORD_COUNT, false) set(showWordCount) = prefs.edit().putBoolean(SHOW_WORD_COUNT, showWordCount).apply() - var fontSize: Int - get() = prefs.getInt(FONT_SIZE, FONT_SIZE_MEDIUM) - set(size) = prefs.edit().putInt(FONT_SIZE, size).apply() - var gravity: Int - get() = prefs.getInt(GRAVITY, GRAVITY_LEFT) + get() = prefs.getInt(GRAVITY, GRAVITY_START) set(size) = prefs.edit().putInt(GRAVITY, size).apply() - var currentNoteId: Int - get() = prefs.getInt(CURRENT_NOTE_ID, 1) - set(id) = prefs.edit().putInt(CURRENT_NOTE_ID, id).apply() + var currentNoteId: Long + get() = prefs.getLong(CURRENT_NOTE_ID, 1L) + set(id) = prefs.edit().putLong(CURRENT_NOTE_ID, id).apply() - var widgetNoteId: Int - get() = prefs.getInt(WIDGET_NOTE_ID, 1) - set(id) = prefs.edit().putInt(WIDGET_NOTE_ID, id).apply() + var widgetNoteId: Long + get() = prefs.getLong(WIDGET_NOTE_ID, 1L) + set(id) = prefs.edit().putLong(WIDGET_NOTE_ID, id).apply() var placeCursorToEnd: Boolean get() = prefs.getBoolean(CURSOR_PLACEMENT, true) @@ -62,10 +60,36 @@ class Config(context: Context) : BaseConfig(context) { set(enableLineWrap) = prefs.edit().putBoolean(ENABLE_LINE_WRAP, enableLineWrap).apply() var lastUsedExtension: String - get() = prefs.getString(LAST_USED_EXTENSION, "txt") + get() = prefs.getString(LAST_USED_EXTENSION, "txt")!! set(lastUsedExtension) = prefs.edit().putString(LAST_USED_EXTENSION, lastUsedExtension).apply() var lastUsedSavePath: String - get() = prefs.getString(LAST_USED_SAVE_PATH, Environment.getExternalStorageDirectory().toString()) + get() = prefs.getString(LAST_USED_SAVE_PATH, Environment.getExternalStorageDirectory().toString())!! set(lastUsedSavePath) = prefs.edit().putString(LAST_USED_SAVE_PATH, lastUsedSavePath).apply() + + var useIncognitoMode: Boolean + get() = prefs.getBoolean(USE_INCOGNITO_MODE, false) + set(useIncognitoMode) = prefs.edit().putBoolean(USE_INCOGNITO_MODE, useIncognitoMode).apply() + + var lastCreatedNoteType: Int + get() = prefs.getInt(LAST_CREATED_NOTE_TYPE, NoteType.TYPE_TEXT.value) + set(lastCreatedNoteType) = prefs.edit().putInt(LAST_CREATED_NOTE_TYPE, lastCreatedNoteType).apply() + + var moveDoneChecklistItems: Boolean + get() = prefs.getBoolean(MOVE_DONE_CHECKLIST_ITEMS, false) + set(moveDoneChecklistItems) = prefs.edit().putBoolean(MOVE_DONE_CHECKLIST_ITEMS, moveDoneChecklistItems).apply() + + fun getTextGravity() = when (gravity) { + GRAVITY_CENTER -> Gravity.CENTER_HORIZONTAL + GRAVITY_END -> Gravity.END + else -> Gravity.START + } + + var fontSizePercentage: Int + get() = prefs.getInt(FONT_SIZE_PERCENTAGE, 100) + set(fontSizePercentage) = prefs.edit().putInt(FONT_SIZE_PERCENTAGE, fontSizePercentage).apply() + + var addNewChecklistItemsTop: Boolean + get() = prefs.getBoolean(ADD_NEW_CHECKLIST_ITEMS_TOP, false) + set(addNewCheckListItemsTop) = prefs.edit().putBoolean(ADD_NEW_CHECKLIST_ITEMS_TOP, addNewCheckListItemsTop).apply() } diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/helpers/Constants.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/helpers/Constants.kt new file mode 100644 index 000000000..a61b28d59 --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/helpers/Constants.kt @@ -0,0 +1,82 @@ +package com.simplemobiletools.notes.pro.helpers + +import android.graphics.Color +import org.joda.time.DateTime + +const val NOTE_ID = "note_id" +const val OPEN_NOTE_ID = "open_note_id" +const val DONE_CHECKLIST_ITEM_ALPHA = 0.4f +const val CUSTOMIZED_WIDGET_ID = "customized_widget_id" +const val CUSTOMIZED_WIDGET_KEY_ID = "customized_widget_key_id" +const val CUSTOMIZED_WIDGET_NOTE_ID = "customized_widget_note_id" +const val CUSTOMIZED_WIDGET_BG_COLOR = "customized_widget_bg_color" +const val CUSTOMIZED_WIDGET_TEXT_COLOR = "customized_widget_text_color" +const val CUSTOMIZED_WIDGET_SHOW_TITLE = "customized_widget_show_title" +const val SHORTCUT_NEW_TEXT_NOTE = "shortcut_new_text_note" +const val SHORTCUT_NEW_CHECKLIST = "shortcut_new_checklist" +const val NEW_TEXT_NOTE = "new_text_note" +const val NEW_CHECKLIST = "new_checklist" +val DEFAULT_WIDGET_TEXT_COLOR = Color.parseColor("#FFF57C00") + +// shared preferences +const val CURRENT_NOTE_ID = "current_note_id" +const val AUTOSAVE_NOTES = "autosave_notes" +const val DISPLAY_SUCCESS = "display_success" +const val CLICKABLE_LINKS = "clickable_links" +const val WIDGET_NOTE_ID = "widget_note_id" +const val MONOSPACED_FONT = "monospaced_font" +const val SHOW_KEYBOARD = "show_keyboard" +const val SHOW_NOTE_PICKER = "show_note_picker" +const val SHOW_WORD_COUNT = "show_word_count" +const val GRAVITY = "gravity" +const val CURSOR_PLACEMENT = "cursor_placement" +const val LAST_USED_EXTENSION = "last_used_extension" +const val LAST_USED_SAVE_PATH = "last_used_save_path" +const val ENABLE_LINE_WRAP = "enable_line_wrap" +const val USE_INCOGNITO_MODE = "use_incognito_mode" +const val LAST_CREATED_NOTE_TYPE = "last_created_note_type" +const val MOVE_DONE_CHECKLIST_ITEMS = "move_undone_checklist_items" // it has been replaced from moving undone items at the top to moving done to bottom +const val FONT_SIZE_PERCENTAGE = "font_size_percentage" +const val EXPORT_MIME_TYPE = "text/plain" +const val ADD_NEW_CHECKLIST_ITEMS_TOP = "add_new_checklist_items_top" + +// auto backups +const val AUTOMATIC_BACKUP_REQUEST_CODE = 10001 +const val AUTO_BACKUP_INTERVAL_IN_DAYS = 1 + +// 6 am is the hardcoded automatic backup time, intervals shorter than 1 day are not yet supported. +fun getNextAutoBackupTime(): DateTime { + val now = DateTime.now() + val sixHour = now.withHourOfDay(6) + return if (now.millis < sixHour.millis) { + sixHour + } else { + sixHour.plusDays(AUTO_BACKUP_INTERVAL_IN_DAYS) + } +} + +fun getPreviousAutoBackupTime(): DateTime { + val nextBackupTime = getNextAutoBackupTime() + return nextBackupTime.minusDays(AUTO_BACKUP_INTERVAL_IN_DAYS) +} + +// gravity +const val GRAVITY_START = 0 +const val GRAVITY_CENTER = 1 +const val GRAVITY_END = 2 + +// mime types +const val MIME_TEXT_PLAIN = "text/plain" + +// font size percentage options +const val FONT_SIZE_50_PERCENT = 50 +const val FONT_SIZE_60_PERCENT = 60 +const val FONT_SIZE_75_PERCENT = 75 +const val FONT_SIZE_90_PERCENT = 90 +const val FONT_SIZE_100_PERCENT = 100 +const val FONT_SIZE_125_PERCENT = 125 +const val FONT_SIZE_150_PERCENT = 150 +const val FONT_SIZE_175_PERCENT = 175 +const val FONT_SIZE_200_PERCENT = 200 +const val FONT_SIZE_250_PERCENT = 250 +const val FONT_SIZE_300_PERCENT = 300 diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/helpers/MyMovementMethod.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/helpers/MyMovementMethod.kt similarity index 97% rename from app/src/main/kotlin/com/simplemobiletools/notes/helpers/MyMovementMethod.kt rename to app/src/main/kotlin/com/simplemobiletools/notes/pro/helpers/MyMovementMethod.kt index 4e76d1791..90a5fed4d 100644 --- a/app/src/main/kotlin/com/simplemobiletools/notes/helpers/MyMovementMethod.kt +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/helpers/MyMovementMethod.kt @@ -1,4 +1,4 @@ -package com.simplemobiletools.notes.helpers +package com.simplemobiletools.notes.pro.helpers import android.text.Selection import android.text.Spannable diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/helpers/MyWidgetProvider.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/helpers/MyWidgetProvider.kt new file mode 100644 index 000000000..8beda98e5 --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/helpers/MyWidgetProvider.kt @@ -0,0 +1,71 @@ +package com.simplemobiletools.notes.pro.helpers + +import android.app.PendingIntent +import android.appwidget.AppWidgetManager +import android.appwidget.AppWidgetProvider +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.widget.RemoteViews +import com.simplemobiletools.commons.extensions.applyColorFilter +import com.simplemobiletools.commons.extensions.getLaunchIntent +import com.simplemobiletools.commons.extensions.setText +import com.simplemobiletools.commons.extensions.setVisibleIf +import com.simplemobiletools.commons.helpers.WIDGET_TEXT_COLOR +import com.simplemobiletools.commons.helpers.ensureBackgroundThread +import com.simplemobiletools.notes.pro.R +import com.simplemobiletools.notes.pro.activities.SplashActivity +import com.simplemobiletools.notes.pro.extensions.notesDB +import com.simplemobiletools.notes.pro.extensions.widgetsDB +import com.simplemobiletools.notes.pro.models.Widget +import com.simplemobiletools.notes.pro.services.WidgetService + +class MyWidgetProvider : AppWidgetProvider() { + private fun setupAppOpenIntent(context: Context, views: RemoteViews, id: Int, widget: Widget) { + val intent = context.getLaunchIntent() ?: Intent(context, SplashActivity::class.java) + intent.putExtra(OPEN_NOTE_ID, widget.noteId) + val pendingIntent = PendingIntent.getActivity(context, widget.widgetId, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE) + views.setOnClickPendingIntent(id, pendingIntent) + } + + override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) { + super.onUpdate(context, appWidgetManager, appWidgetIds) + ensureBackgroundThread { + for (widgetId in appWidgetIds) { + val widget = context.widgetsDB.getWidgetWithWidgetId(widgetId) ?: continue + val views = RemoteViews(context.packageName, R.layout.widget) + val note = context.notesDB.getNoteWithId(widget.noteId) + views.applyColorFilter(R.id.notes_widget_background, widget.widgetBgColor) + views.setTextColor(R.id.widget_note_title, widget.widgetTextColor) + views.setText(R.id.widget_note_title, note?.title ?: "") + views.setVisibleIf(R.id.widget_note_title, widget.widgetShowTitle) + setupAppOpenIntent(context, views, R.id.notes_widget_holder, widget) + + Intent(context, WidgetService::class.java).apply { + putExtra(NOTE_ID, widget.noteId) + putExtra(WIDGET_TEXT_COLOR, widget.widgetTextColor) + data = Uri.parse(this.toUri(Intent.URI_INTENT_SCHEME)) + views.setRemoteAdapter(R.id.notes_widget_listview, this) + } + + val startActivityIntent = context.getLaunchIntent() ?: Intent(context, SplashActivity::class.java) + startActivityIntent.putExtra(OPEN_NOTE_ID, widget.noteId) + val startActivityPendingIntent = + PendingIntent.getActivity(context, widgetId, startActivityIntent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE) + views.setPendingIntentTemplate(R.id.notes_widget_listview, startActivityPendingIntent) + + appWidgetManager.updateAppWidget(widgetId, views) + appWidgetManager.notifyAppWidgetViewDataChanged(widgetId, R.id.notes_widget_listview) + } + } + } + + override fun onDeleted(context: Context, appWidgetIds: IntArray) { + super.onDeleted(context, appWidgetIds) + ensureBackgroundThread { + appWidgetIds.forEach { + context.widgetsDB.deleteWidgetId(it) + } + } + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/helpers/NotesHelper.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/helpers/NotesHelper.kt new file mode 100644 index 000000000..53fb7227c --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/helpers/NotesHelper.kt @@ -0,0 +1,146 @@ +package com.simplemobiletools.notes.pro.helpers + +import android.content.Context +import android.os.Handler +import android.os.Looper +import com.simplemobiletools.commons.activities.BaseSimpleActivity +import com.simplemobiletools.commons.helpers.ExportResult +import com.simplemobiletools.commons.helpers.PROTECTION_NONE +import com.simplemobiletools.commons.helpers.ensureBackgroundThread +import com.simplemobiletools.notes.pro.R +import com.simplemobiletools.notes.pro.extensions.config +import com.simplemobiletools.notes.pro.extensions.notesDB +import com.simplemobiletools.notes.pro.models.Note +import com.simplemobiletools.notes.pro.models.NoteType +import kotlinx.serialization.encodeToString +import kotlinx.serialization.json.Json +import java.io.File +import java.io.OutputStream + +class NotesHelper(val context: Context) { + fun getNotes(callback: (notes: List) -> Unit) { + ensureBackgroundThread { + // make sure the initial note has enough time to be precreated + if (context.config.appRunCount <= 1) { + context.notesDB.getNotes() + Thread.sleep(200) + } + + val notes = context.notesDB.getNotes().toMutableList() + val notesToDelete = mutableListOf() + notes.forEach { + if (it.path.isNotEmpty()) { + if (!it.path.startsWith("content://") && !File(it.path).exists()) { + context.notesDB.deleteNote(it) + notesToDelete.add(it) + } + } + } + + notes.removeAll(notesToDelete) + + if (notes.isEmpty()) { + val generalNote = context.resources.getString(R.string.general_note) + val note = Note(null, generalNote, "", NoteType.TYPE_TEXT, "", PROTECTION_NONE, "") + context.notesDB.insertOrUpdate(note) + notes.add(note) + } + + Handler(Looper.getMainLooper()).post { + callback(notes) + } + } + } + + fun getNoteWithId(id: Long, callback: (note: Note?) -> Unit) { + ensureBackgroundThread { + val note = context.notesDB.getNoteWithId(id) + Handler(Looper.getMainLooper()).post { + callback(note) + } + } + } + + fun getNoteIdWithPath(path: String, callback: (id: Long?) -> Unit) { + ensureBackgroundThread { + val id = context.notesDB.getNoteIdWithPath(path) + Handler(Looper.getMainLooper()).post { + callback(id) + } + } + } + + fun insertOrUpdateNote(note: Note, callback: ((newNoteId: Long) -> Unit)? = null) { + ensureBackgroundThread { + val noteId = context.notesDB.insertOrUpdate(note) + Handler(Looper.getMainLooper()).post { + callback?.invoke(noteId) + } + } + } + + fun insertOrUpdateNotes(notes: List, callback: ((newNoteIds: List) -> Unit)? = null) { + ensureBackgroundThread { + val noteIds = context.notesDB.insertOrUpdate(notes) + Handler(Looper.getMainLooper()).post { + callback?.invoke(noteIds) + } + } + } + + fun importNotes(activity: BaseSimpleActivity, notes: List, callback: (ImportResult) -> Unit) { + ensureBackgroundThread { + val currentNotes = activity.notesDB.getNotes() + if (currentNotes.isEmpty()) { + insertOrUpdateNotes(notes) { savedNotes -> + + val newCurrentNotes = activity.notesDB.getNotes() + + val result = when { + currentNotes.size == newCurrentNotes.size -> ImportResult.IMPORT_NOTHING_NEW + notes.size == savedNotes.size -> ImportResult.IMPORT_OK + savedNotes.isEmpty() -> ImportResult.IMPORT_FAIL + else -> ImportResult.IMPORT_PARTIAL + } + callback(result) + } + } else { + var imported = 0 + var skipped = 0 + + notes.forEach { note -> + val exists = context.notesDB.getNoteIdWithTitle(note.title) != null + if (!exists) { + context.notesDB.insertOrUpdate(note) + imported++ + } else { + skipped++ + } + } + + val result = when { + skipped == notes.size || imported == 0 -> ImportResult.IMPORT_NOTHING_NEW + imported == notes.size -> ImportResult.IMPORT_OK + else -> ImportResult.IMPORT_PARTIAL + } + callback(result) + } + } + } + + fun exportNotes(notesToBackup: List, outputStream: OutputStream): ExportResult { + return try { + val jsonString = Json.encodeToString(notesToBackup) + outputStream.use { + it.write(jsonString.toByteArray()) + } + ExportResult.EXPORT_OK + } catch (_: Error) { + ExportResult.EXPORT_FAIL + } + } + + enum class ImportResult { + IMPORT_FAIL, IMPORT_OK, IMPORT_PARTIAL, IMPORT_NOTHING_NEW + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/interfaces/ChecklistItemsListener.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/interfaces/ChecklistItemsListener.kt new file mode 100644 index 000000000..017662225 --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/interfaces/ChecklistItemsListener.kt @@ -0,0 +1,7 @@ +package com.simplemobiletools.notes.pro.interfaces + +interface ChecklistItemsListener { + fun refreshItems() + + fun saveChecklist(callback: () -> Unit = {}) +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/interfaces/NotesDao.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/interfaces/NotesDao.kt new file mode 100644 index 000000000..f86864349 --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/interfaces/NotesDao.kt @@ -0,0 +1,31 @@ +package com.simplemobiletools.notes.pro.interfaces + +import androidx.room.* +import com.simplemobiletools.notes.pro.models.Note + +@Dao +interface NotesDao { + @Query("SELECT * FROM notes ORDER BY title COLLATE UNICODE ASC ") + fun getNotes(): List + + @Query("SELECT * FROM notes WHERE id = :id") + fun getNoteWithId(id: Long): Note? + + @Query("SELECT id FROM notes WHERE path = :path") + fun getNoteIdWithPath(path: String): Long? + + @Query("SELECT id FROM notes WHERE title = :title COLLATE NOCASE") + fun getNoteIdWithTitle(title: String): Long? + + @Query("SELECT id FROM notes WHERE title = :title") + fun getNoteIdWithTitleCaseSensitive(title: String): Long? + + @Insert(onConflict = OnConflictStrategy.REPLACE) + fun insertOrUpdate(note: Note): Long + + @Insert(onConflict = OnConflictStrategy.REPLACE) + fun insertOrUpdate(notes: List): List + + @Delete + fun deleteNote(note: Note) +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/interfaces/WidgetsDao.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/interfaces/WidgetsDao.kt new file mode 100644 index 000000000..8b7dbd304 --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/interfaces/WidgetsDao.kt @@ -0,0 +1,25 @@ +package com.simplemobiletools.notes.pro.interfaces + +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.OnConflictStrategy +import androidx.room.Query +import com.simplemobiletools.notes.pro.models.Widget + +@Dao +interface WidgetsDao { + @Query("SELECT * FROM widgets") + fun getWidgets(): List + + @Query("SELECT * FROM widgets WHERE widget_id = :widgetId") + fun getWidgetWithWidgetId(widgetId: Int): Widget? + + @Insert(onConflict = OnConflictStrategy.REPLACE) + fun insertOrUpdate(widget: Widget): Long + + @Query("DELETE FROM widgets WHERE note_id = :noteId") + fun deleteNoteWidgets(noteId: Long) + + @Query("DELETE FROM widgets WHERE widget_id = :widgetId") + fun deleteWidgetId(widgetId: Int) +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/models/ChecklistItem.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/models/ChecklistItem.kt new file mode 100644 index 000000000..fb2437ceb --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/models/ChecklistItem.kt @@ -0,0 +1,32 @@ +package com.simplemobiletools.notes.pro.models + +import com.simplemobiletools.commons.helpers.SORT_BY_TITLE +import com.simplemobiletools.commons.helpers.SORT_DESCENDING +import com.simplemobiletools.notes.pro.helpers.CollatorBasedComparator +import kotlinx.serialization.Serializable + +@Serializable +data class ChecklistItem( + val id: Int, + val dateCreated: Long = 0L, + var title: String, + var isDone: Boolean +) : Comparable { + + companion object { + var sorting = 0 + } + + override fun compareTo(other: ChecklistItem): Int { + var result = when { + sorting and SORT_BY_TITLE != 0 -> CollatorBasedComparator().compare(title, other.title) + else -> dateCreated.compareTo(other.dateCreated) + } + + if (sorting and SORT_DESCENDING != 0) { + result *= -1 + } + + return result + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/models/Note.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/models/Note.kt new file mode 100644 index 000000000..0b010063b --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/models/Note.kt @@ -0,0 +1,53 @@ +package com.simplemobiletools.notes.pro.models + +import android.content.Context +import android.net.Uri +import androidx.room.* +import com.simplemobiletools.commons.extensions.isBiometricIdAvailable +import com.simplemobiletools.commons.helpers.PROTECTION_FINGERPRINT +import com.simplemobiletools.commons.helpers.PROTECTION_NONE +import kotlinx.serialization.Serializable +import java.io.File + +/** + * Represents a note. + * + * @property value The content of the note. Could be plain text or [ChecklistItem] + * @property type The type of the note. Should be one of the [NoteType] enum entries. + */ +@Serializable +@Entity(tableName = "notes", indices = [(Index(value = ["id"], unique = true))]) +@TypeConverters(NoteTypeConverter::class) +data class Note( + @PrimaryKey(autoGenerate = true) var id: Long?, + @ColumnInfo(name = "title") var title: String, + @ColumnInfo(name = "value") var value: String, + @ColumnInfo(name = "type") var type: NoteType, + @ColumnInfo(name = "path") var path: String, + @ColumnInfo(name = "protection_type") var protectionType: Int, + @ColumnInfo(name = "protection_hash") var protectionHash: String +) { + + fun getNoteStoredValue(context: Context): String? { + return if (path.isNotEmpty()) { + try { + if (path.startsWith("content://")) { + val inputStream = context.contentResolver.openInputStream(Uri.parse(path)) + inputStream?.bufferedReader().use { it!!.readText() } + } else { + File(path).readText() + } + } catch (e: Exception) { + null + } + } else { + value + } + } + + fun isLocked() = protectionType != PROTECTION_NONE + + fun shouldBeUnlocked(context: Context): Boolean { + return protectionType == PROTECTION_FINGERPRINT && !context.isBiometricIdAvailable() + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/models/NoteType.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/models/NoteType.kt new file mode 100644 index 000000000..d81d693a1 --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/models/NoteType.kt @@ -0,0 +1,15 @@ +package com.simplemobiletools.notes.pro.models + +import kotlinx.serialization.Serializable + +@Serializable +enum class NoteType(val value: Int) { + TYPE_TEXT(0), + TYPE_CHECKLIST(1); + + companion object { + fun fromValue(value: Int): NoteType { + return values().find { it.value == value } ?: TYPE_TEXT + } + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/models/NoteTypeConverter.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/models/NoteTypeConverter.kt new file mode 100644 index 000000000..a2e5b2bb0 --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/models/NoteTypeConverter.kt @@ -0,0 +1,15 @@ +package com.simplemobiletools.notes.pro.models + +import androidx.room.TypeConverter + +class NoteTypeConverter { + @TypeConverter + fun fromNoteType(noteType: NoteType): Int { + return noteType.value + } + + @TypeConverter + fun toNoteType(value: Int): NoteType { + return NoteType.fromValue(value) + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/models/TextHistory.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/models/TextHistory.kt similarity index 93% rename from app/src/main/kotlin/com/simplemobiletools/notes/models/TextHistory.kt rename to app/src/main/kotlin/com/simplemobiletools/notes/pro/models/TextHistory.kt index e3d76165f..3de176e6e 100644 --- a/app/src/main/kotlin/com/simplemobiletools/notes/models/TextHistory.kt +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/models/TextHistory.kt @@ -1,4 +1,4 @@ -package com.simplemobiletools.notes.models +package com.simplemobiletools.notes.pro.models import java.util.* diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/models/TextHistoryItem.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/models/TextHistoryItem.kt similarity index 67% rename from app/src/main/kotlin/com/simplemobiletools/notes/models/TextHistoryItem.kt rename to app/src/main/kotlin/com/simplemobiletools/notes/pro/models/TextHistoryItem.kt index e96c3cb13..72d7d720e 100644 --- a/app/src/main/kotlin/com/simplemobiletools/notes/models/TextHistoryItem.kt +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/models/TextHistoryItem.kt @@ -1,3 +1,3 @@ -package com.simplemobiletools.notes.models +package com.simplemobiletools.notes.pro.models data class TextHistoryItem(val start: Int, val before: CharSequence?, val after: CharSequence?) diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/models/Widget.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/models/Widget.kt new file mode 100644 index 000000000..996d8414d --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/models/Widget.kt @@ -0,0 +1,16 @@ +package com.simplemobiletools.notes.pro.models + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.Index +import androidx.room.PrimaryKey + +@Entity(tableName = "widgets", indices = [(Index(value = ["widget_id"], unique = true))]) +data class Widget( + @PrimaryKey(autoGenerate = true) var id: Long?, + @ColumnInfo(name = "widget_id") var widgetId: Int, + @ColumnInfo(name = "note_id") var noteId: Long, + @ColumnInfo(name = "widget_bg_color") var widgetBgColor: Int, + @ColumnInfo(name = "widget_text_color") var widgetTextColor: Int, + @ColumnInfo(name = "widget_show_title") var widgetShowTitle: Boolean +) diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/receivers/AutomaticBackupReceiver.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/receivers/AutomaticBackupReceiver.kt new file mode 100644 index 000000000..7d4949be5 --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/receivers/AutomaticBackupReceiver.kt @@ -0,0 +1,17 @@ +package com.simplemobiletools.notes.pro.receivers + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.os.PowerManager +import com.simplemobiletools.notes.pro.extensions.backupNotes + +class AutomaticBackupReceiver : BroadcastReceiver() { + + override fun onReceive(context: Context, intent: Intent) { + val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager + val wakelock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "simplenotes:automaticbackupreceiver") + wakelock.acquire(3000) + context.backupNotes() + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/pro/receivers/BootCompletedReceiver.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/receivers/BootCompletedReceiver.kt new file mode 100644 index 000000000..8cc032508 --- /dev/null +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/receivers/BootCompletedReceiver.kt @@ -0,0 +1,18 @@ +package com.simplemobiletools.notes.pro.receivers + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import com.simplemobiletools.commons.helpers.ensureBackgroundThread +import com.simplemobiletools.notes.pro.extensions.checkAndBackupNotesOnBoot + +class BootCompletedReceiver : BroadcastReceiver() { + + override fun onReceive(context: Context, intent: Intent) { + ensureBackgroundThread { + context.apply { + checkAndBackupNotesOnBoot() + } + } + } +} diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/services/WidgetService.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/services/WidgetService.kt similarity index 56% rename from app/src/main/kotlin/com/simplemobiletools/notes/services/WidgetService.kt rename to app/src/main/kotlin/com/simplemobiletools/notes/pro/services/WidgetService.kt index f0670a3bd..f313220a9 100644 --- a/app/src/main/kotlin/com/simplemobiletools/notes/services/WidgetService.kt +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/services/WidgetService.kt @@ -1,9 +1,9 @@ -package com.simplemobiletools.notes.services +package com.simplemobiletools.notes.pro.services import android.content.Intent import android.widget.RemoteViewsService -import com.simplemobiletools.notes.adapters.WidgetAdapter +import com.simplemobiletools.notes.pro.adapters.WidgetAdapter class WidgetService : RemoteViewsService() { - override fun onGetViewFactory(intent: Intent) = WidgetAdapter(applicationContext) + override fun onGetViewFactory(intent: Intent) = WidgetAdapter(applicationContext, intent) } diff --git a/app/src/main/kotlin/com/simplemobiletools/notes/views/MyHorizontalScrollView.kt b/app/src/main/kotlin/com/simplemobiletools/notes/pro/views/MyHorizontalScrollView.kt similarity index 91% rename from app/src/main/kotlin/com/simplemobiletools/notes/views/MyHorizontalScrollView.kt rename to app/src/main/kotlin/com/simplemobiletools/notes/pro/views/MyHorizontalScrollView.kt index 30b8fbe9a..51383591b 100644 --- a/app/src/main/kotlin/com/simplemobiletools/notes/views/MyHorizontalScrollView.kt +++ b/app/src/main/kotlin/com/simplemobiletools/notes/pro/views/MyHorizontalScrollView.kt @@ -1,4 +1,4 @@ -package com.simplemobiletools.notes.views +package com.simplemobiletools.notes.pro.views import android.content.Context import android.util.AttributeSet diff --git a/app/src/main/res/drawable-hdpi/img_widget_preview.png b/app/src/main/res/drawable-hdpi/img_widget_preview.png deleted file mode 100644 index 0738e7d2d..000000000 Binary files a/app/src/main/res/drawable-hdpi/img_widget_preview.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/img_widget_preview.png b/app/src/main/res/drawable-nodpi/img_widget_preview.png similarity index 100% rename from app/src/main/res/drawable-xxxhdpi/img_widget_preview.png rename to app/src/main/res/drawable-nodpi/img_widget_preview.png diff --git a/app/src/main/res/drawable-xhdpi/img_widget_preview.png b/app/src/main/res/drawable-xhdpi/img_widget_preview.png deleted file mode 100644 index 448ed7930..000000000 Binary files a/app/src/main/res/drawable-xhdpi/img_widget_preview.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/img_widget_preview.png b/app/src/main/res/drawable-xxhdpi/img_widget_preview.png deleted file mode 100644 index 98f7ff59d..000000000 Binary files a/app/src/main/res/drawable-xxhdpi/img_widget_preview.png and /dev/null differ diff --git a/app/src/main/res/drawable/ic_launcher_monochrome.xml b/app/src/main/res/drawable/ic_launcher_monochrome.xml new file mode 100644 index 000000000..f48f20c4d --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_monochrome.xml @@ -0,0 +1,3 @@ + + + diff --git a/app/src/main/res/drawable/ic_lock_open_vector.xml b/app/src/main/res/drawable/ic_lock_open_vector.xml new file mode 100644 index 000000000..542b90379 --- /dev/null +++ b/app/src/main/res/drawable/ic_lock_open_vector.xml @@ -0,0 +1,3 @@ + + + diff --git a/app/src/main/res/drawable/ic_shortcut_icon.xml b/app/src/main/res/drawable/ic_shortcut_icon.xml new file mode 100644 index 000000000..32f964227 --- /dev/null +++ b/app/src/main/res/drawable/ic_shortcut_icon.xml @@ -0,0 +1,3 @@ + + + diff --git a/app/src/main/res/drawable/shortcut_check.xml b/app/src/main/res/drawable/shortcut_check.xml new file mode 100644 index 000000000..6767562c6 --- /dev/null +++ b/app/src/main/res/drawable/shortcut_check.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/app/src/main/res/drawable/shortcut_note.xml b/app/src/main/res/drawable/shortcut_note.xml new file mode 100644 index 000000000..257754e24 --- /dev/null +++ b/app/src/main/res/drawable/shortcut_note.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml index be9a3c51a..3828eef23 100644 --- a/app/src/main/res/layout/activity_main.xml +++ b/app/src/main/res/layout/activity_main.xml @@ -1,16 +1,41 @@ - - + android:layout_height="?attr/actionBarSize" + android:background="@color/color_primary" + app:menu="@menu/menu" + app:titleTextAppearance="@style/AppTheme.ActionBar.TitleTextStyle" /> - + + + + + + + + + + + diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xml index d5b32170c..6ee073d17 100644 --- a/app/src/main/res/layout/activity_settings.xml +++ b/app/src/main/res/layout/activity_settings.xml @@ -1,522 +1,432 @@ - + android:layout_height="match_parent"> - + android:layout_height="?attr/actionBarSize" + android:background="@color/color_primary" + app:title="@string/settings" + app:titleTextAppearance="@style/AppTheme.ActionBar.TitleTextStyle" /> - + + + android:orientation="vertical"> - + android:text="@string/color_customization" /> - + + + + + + + + + + + + + + + - + - + - + - - - + + + + + + + + + + + + + + + + + + + android:text="@string/text" /> + + - + - + - - - - - + android:layout_height="wrap_content"> - + - - - + + + android:layout_height="wrap_content"> - + - - - + + + android:layout_height="wrap_content"> - + - - - + + + android:layout_height="wrap_content"> - + - + - + + + + + + + + + + + android:text="@string/startup" /> - + - + - + - + android:layout_height="wrap_content"> - - - + - + - - - - - + android:layout_height="wrap_content"> - + - - - + - + - - - - - + android:text="@string/saving_label" /> - - - + android:layout_height="wrap_content"> - + - + - - - - - + android:layout_height="wrap_content"> - + - - - + + + + + android:text="@string/migrating" /> - + + + + + + - + + - - - + - + android:text="@string/backups" /> - + - + - + + + android:layout_height="wrap_content"> - - - - - + + + + + + + diff --git a/app/src/main/res/layout/datetime_pattern_info_layout.xml b/app/src/main/res/layout/datetime_pattern_info_layout.xml new file mode 100644 index 000000000..36ee34d1f --- /dev/null +++ b/app/src/main/res/layout/datetime_pattern_info_layout.xml @@ -0,0 +1,9 @@ + + diff --git a/app/src/main/res/layout/dialog_delete_note.xml b/app/src/main/res/layout/dialog_delete_note.xml index 114651e76..f669a63f5 100644 --- a/app/src/main/res/layout/dialog_delete_note.xml +++ b/app/src/main/res/layout/dialog_delete_note.xml @@ -1,6 +1,6 @@ - + android:textSize="@dimen/bigger_text_size" + tools:text="@string/delete_note_prompt_message" /> - + android:background="?attr/selectableItemBackground" + android:padding="@dimen/activity_margin" + android:visibility="gone"> + + + diff --git a/app/src/main/res/layout/dialog_export_file.xml b/app/src/main/res/layout/dialog_export_file.xml index c2571b768..c3fd9b9dd 100644 --- a/app/src/main/res/layout/dialog_export_file.xml +++ b/app/src/main/res/layout/dialog_export_file.xml @@ -1,62 +1,57 @@ - - - - - - + android:layout_marginBottom="@dimen/activity_margin" + android:hint="@string/path"> + + + + - - - + android:hint="@string/filename"> + + + + - + android:hint="@string/extension"> + + + diff --git a/app/src/main/res/layout/dialog_export_files.xml b/app/src/main/res/layout/dialog_export_files.xml index aa6e23c40..fe95dd238 100644 --- a/app/src/main/res/layout/dialog_export_files.xml +++ b/app/src/main/res/layout/dialog_export_files.xml @@ -1,44 +1,39 @@ - - - - + android:layout_marginBottom="@dimen/activity_margin" + android:hint="@string/path"> - + - + + + android:hint="@string/extension"> + + + diff --git a/app/src/main/res/layout/dialog_export_notes.xml b/app/src/main/res/layout/dialog_export_notes.xml new file mode 100644 index 000000000..7e354d387 --- /dev/null +++ b/app/src/main/res/layout/dialog_export_notes.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/dialog_import_folder.xml b/app/src/main/res/layout/dialog_import_folder.xml index cbd2d5ae5..8475f95f6 100644 --- a/app/src/main/res/layout/dialog_import_folder.xml +++ b/app/src/main/res/layout/dialog_import_folder.xml @@ -1,29 +1,27 @@ - + android:paddingStart="@dimen/activity_margin" + android:paddingTop="@dimen/activity_margin" + android:paddingEnd="@dimen/activity_margin"> - - - + android:hint="@string/folder"> + + + + + android:paddingBottom="@dimen/activity_margin" + android:text="@string/update_file_at_note" /> + android:paddingBottom="@dimen/activity_margin" + android:text="@string/only_import_file_content" /> diff --git a/app/src/main/res/layout/dialog_manage_automatic_backups.xml b/app/src/main/res/layout/dialog_manage_automatic_backups.xml new file mode 100644 index 000000000..9aef64b47 --- /dev/null +++ b/app/src/main/res/layout/dialog_manage_automatic_backups.xml @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/dialog_new_checklist_item.xml b/app/src/main/res/layout/dialog_new_checklist_item.xml new file mode 100644 index 000000000..8a97d2541 --- /dev/null +++ b/app/src/main/res/layout/dialog_new_checklist_item.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/dialog_new_note.xml b/app/src/main/res/layout/dialog_new_note.xml index b5757f330..dad5583a0 100644 --- a/app/src/main/res/layout/dialog_new_note.xml +++ b/app/src/main/res/layout/dialog_new_note.xml @@ -1,20 +1,60 @@ - + android:paddingStart="@dimen/activity_margin" + android:paddingTop="@dimen/small_margin" + android:paddingEnd="@dimen/activity_margin"> - + android:hint="@string/label"> + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/dialog_open_file.xml b/app/src/main/res/layout/dialog_open_file.xml index be44a9b5b..df42f3fc8 100644 --- a/app/src/main/res/layout/dialog_open_file.xml +++ b/app/src/main/res/layout/dialog_open_file.xml @@ -1,29 +1,27 @@ - + android:paddingStart="@dimen/activity_margin" + android:paddingTop="@dimen/activity_margin" + android:paddingEnd="@dimen/activity_margin"> - - - + android:hint="@string/path"> + + + + + android:paddingTop="@dimen/normal_margin" + android:paddingBottom="@dimen/normal_margin" + android:text="@string/update_file_at_note" /> + android:paddingTop="@dimen/normal_margin" + android:paddingBottom="@dimen/normal_margin" + android:text="@string/only_import_file_content" /> diff --git a/app/src/main/res/layout/dialog_open_note.xml b/app/src/main/res/layout/dialog_open_note.xml index 30eed432d..6abdb1015 100644 --- a/app/src/main/res/layout/dialog_open_note.xml +++ b/app/src/main/res/layout/dialog_open_note.xml @@ -1,14 +1,36 @@ - - + android:layout_height="match_parent" + android:layout_marginStart="@dimen/small_margin" + android:layout_marginTop="@dimen/medium_margin" + android:layout_marginEnd="@dimen/small_margin" + android:minHeight="@dimen/min_open_note_popup_height" + app:layout_constraintHeight_max="@dimen/max_open_note_popup_height"> - + + + + + + + diff --git a/app/src/main/res/layout/dialog_rename_checklist_item.xml b/app/src/main/res/layout/dialog_rename_checklist_item.xml new file mode 100644 index 000000000..4bc1ae03e --- /dev/null +++ b/app/src/main/res/layout/dialog_rename_checklist_item.xml @@ -0,0 +1,28 @@ + + + + + + + + + diff --git a/app/src/main/res/layout/dialog_rename_note.xml b/app/src/main/res/layout/dialog_rename_note.xml index 38dd658d1..7e9bb395a 100644 --- a/app/src/main/res/layout/dialog_rename_note.xml +++ b/app/src/main/res/layout/dialog_rename_note.xml @@ -1,19 +1,26 @@ - - + android:hint="@string/title"> + + + + diff --git a/app/src/main/res/layout/dialog_sort_checklist.xml b/app/src/main/res/layout/dialog_sort_checklist.xml new file mode 100644 index 000000000..62733ba7a --- /dev/null +++ b/app/src/main/res/layout/dialog_sort_checklist.xml @@ -0,0 +1,96 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/dialog_unlock_notes.xml b/app/src/main/res/layout/dialog_unlock_notes.xml new file mode 100644 index 000000000..c0ac82de6 --- /dev/null +++ b/app/src/main/res/layout/dialog_unlock_notes.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + diff --git a/app/src/main/res/layout/fragment_checklist.xml b/app/src/main/res/layout/fragment_checklist.xml new file mode 100644 index 000000000..3922343c1 --- /dev/null +++ b/app/src/main/res/layout/fragment_checklist.xml @@ -0,0 +1,105 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/fragment_note.xml b/app/src/main/res/layout/fragment_note.xml deleted file mode 100644 index ef39270e5..000000000 --- a/app/src/main/res/layout/fragment_note.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - diff --git a/app/src/main/res/layout/fragment_text.xml b/app/src/main/res/layout/fragment_text.xml new file mode 100644 index 000000000..208f84640 --- /dev/null +++ b/app/src/main/res/layout/fragment_text.xml @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/item_add_checklist.xml b/app/src/main/res/layout/item_add_checklist.xml new file mode 100644 index 000000000..4dfd72db5 --- /dev/null +++ b/app/src/main/res/layout/item_add_checklist.xml @@ -0,0 +1,9 @@ + + diff --git a/app/src/main/res/layout/item_checklist.xml b/app/src/main/res/layout/item_checklist.xml new file mode 100644 index 000000000..25f1bc992 --- /dev/null +++ b/app/src/main/res/layout/item_checklist.xml @@ -0,0 +1,49 @@ + + + + + + + + + + diff --git a/app/src/main/res/layout/item_checklist_widget.xml b/app/src/main/res/layout/item_checklist_widget.xml new file mode 100644 index 000000000..e270c68fd --- /dev/null +++ b/app/src/main/res/layout/item_checklist_widget.xml @@ -0,0 +1,83 @@ + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/item_locked_note.xml b/app/src/main/res/layout/item_locked_note.xml new file mode 100644 index 000000000..e77ae12b0 --- /dev/null +++ b/app/src/main/res/layout/item_locked_note.xml @@ -0,0 +1,35 @@ + + + + + + + + diff --git a/app/src/main/res/layout/note_view_horiz_scrollable.xml b/app/src/main/res/layout/note_view_horiz_scrollable.xml index 514c6a5db..9a7ca54ec 100644 --- a/app/src/main/res/layout/note_view_horiz_scrollable.xml +++ b/app/src/main/res/layout/note_view_horiz_scrollable.xml @@ -1,6 +1,5 @@ - + android:textCursorDrawable="@null" /> - + diff --git a/app/src/main/res/layout/note_view_static.xml b/app/src/main/res/layout/note_view_static.xml index 2c562a4a1..dc24e716a 100644 --- a/app/src/main/res/layout/note_view_static.xml +++ b/app/src/main/res/layout/note_view_static.xml @@ -1,13 +1,13 @@ - + android:textCursorDrawable="@null" /> diff --git a/app/src/main/res/layout/open_note_item.xml b/app/src/main/res/layout/open_note_item.xml index 792640924..0e22322ae 100644 --- a/app/src/main/res/layout/open_note_item.xml +++ b/app/src/main/res/layout/open_note_item.xml @@ -1,26 +1,45 @@ - - + + + android:layout_alignParentStart="true" + android:layout_alignParentTop="true" + android:ellipsize="end" + android:lines="1" + android:textSize="@dimen/big_text_size" + android:textStyle="bold" + tools:text="Title" /> - + android:layout_below="@+id/open_note_item_title" + android:layout_alignParentStart="true" + android:layout_marginTop="@dimen/medium_margin" + android:ellipsize="end" + android:maxHeight="@dimen/grid_note_item_max_height" + tools:text="text" /> diff --git a/app/src/main/res/layout/widget.xml b/app/src/main/res/layout/widget.xml index ea3e025fc..49648cffb 100644 --- a/app/src/main/res/layout/widget.xml +++ b/app/src/main/res/layout/widget.xml @@ -1,14 +1,35 @@ - + + + + + android:layout_below="@id/widget_note_title" + android:divider="@null" /> diff --git a/app/src/main/res/layout/widget_config.xml b/app/src/main/res/layout/widget_config.xml index 5054d5dda..e5f3b8f0b 100644 --- a/app/src/main/res/layout/widget_config.xml +++ b/app/src/main/res/layout/widget_config.xml @@ -1,67 +1,144 @@ - - - - - + android:layout_height="match_parent"> - - + + - + android:paddingBottom="@dimen/activity_margin"> + + + + + + + + + + + + + + - - -