commit 53820a6811ce671eb3cfdfd5e0d2464dc3f3aac5 Author: harvey186 Date: Sun Dec 10 12:28:26 2023 +0100 creation diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..12c6da8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,18 @@ +*.iml +.gradle +/local.properties +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/misc.xml +/.idea/vcs.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +/.idea/deploymentTargetDropDown.xml +.DS_Store +/build +/captures +.externalNativeBuild +.cxx +local.properties diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..0806720 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,16 @@ +# Contributing to My Brain + +### To contribute : + +- Report bugs/glitches. +- Create new issues to give us ideas and feedback. +- Ask questions or suggest ideas in the comments section of any issue. +- You can also help us clean up the [issue section](https://github.com/mhss1/MyBrain/issues) by identifying duplicate issues. + +### Or if you are a developer: + +- Pick an issue or create a new one. +- Fork the repo. +- Create a feature branch in your fork and make your changes. +- Keep it simple and make sure the app runs on an actual Android device and everything works as expected +- Submit a pull request to the `dev` branch of the official [My Brain repo](https://github.com/mhss1/MyBrain/pulls) (PR to master will be rejected). diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + 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 new file mode 100644 index 0000000..007b7f7 --- /dev/null +++ b/README.md @@ -0,0 +1,62 @@ +![Stars](https://img.shields.io/github/stars/mhss1/mybrain?style=social) +[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0) + +app icon + +# My Brain + + +### Open-source, All-in-one productivity app for Tasks, Notes, Calendar, Diary and Bookmarks. + +
+ + + + + +
+ +[screenshots made by previewed](https://previewed.app/template/00CBF3F6) + +[Get it on F-Droid](https://f-droid.org/packages/com.mhss.app.mybrain) +[Get it on GitHub](https://github.com/mhss1/MyBrain/releases/latest) + +## Features +- Private with no data collection and no internet permission at all. +- Create tasks with priority, sub-tasks, description and due date and reminders. +- Create Notes that supports markdown which enables you to use Headers, lists, links etc.. +- Record your mood daily and view your mood summary with beautiful graphs. +- Save bookmarks for later by using the share menu from any other app. +- View your calendar events in a modern view and also with a beautiful home screen widget. +- Dashboard screen to see your tasks, calendar events, and more to see your day at a glance. + +## Technologies +- 100% Kotlin. +- Made Using Jetpack Compose. +- Widgets made with Compose Glance. +- Following Clean Architecture approach. +- Following MVVM Architectural Design Pattern. +### Used in the app : + - Room DB + - Hilt + - Preferences DataStore + - Kotlin coroutines + - Kotlin Flows + - Alarm Manager + - Jetpack Compose + - Compose Glance + +## Contributing +To get started, take a look at [CONTRIBUTING.md](CONTRIBUTING.md). + +--- +Icons Attribution +Paper icons created by Freepik - Flaticon +List icons created by Freepik - Flaticon +Calendar icons created by Freepik - Flaticon +Bookmark icons created by Freepik - Flaticon +Book icons created by Freepik - Flaticon diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/app/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/app/build.gradle.kts b/app/build.gradle.kts new file mode 100644 index 0000000..dd4f6d3 --- /dev/null +++ b/app/build.gradle.kts @@ -0,0 +1,136 @@ + +plugins { + id("com.android.application") + id("org.jetbrains.kotlin.android") + id ("com.google.dagger.hilt.android") + id ("com.google.devtools.ksp") +} + +android { + namespace = "com.mhss.app.mybrain" + compileSdk = 34 + + defaultConfig { + applicationId = "com.mhss.app.mybrain" + minSdk = 26 + targetSdk = 34 + versionCode = 7 + versionName = "1.0.6" + + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + vectorDrawables { + useSupportLibrary = true + } + } + + buildTypes { + release { + isMinifyEnabled = true + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro" + ) + } + debug { + isMinifyEnabled = false + applicationIdSuffix = ".debug" + resValue("string", "app_name", "MyBrain Debug") + } + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + kotlinOptions { + jvmTarget = "17" + + } + buildFeatures { + compose = true + buildConfig = true + } + composeOptions { + kotlinCompilerExtensionVersion = "1.5.2" + } + packaging { + resources { + excludes += "/META-INF/{AL2.0,LGPL2.1}" + } + } + androidResources { + generateLocaleConfig = true + } +} + +dependencies { + val roomVersion = "2.6.0" + val coroutinesVersion = "1.7.3" + val lifecycleVersion = "2.6.2" + val workVersion = "2.8.1" + implementation(platform("androidx.compose:compose-bom:2023.09.01")) + + implementation("androidx.core:core-ktx:1.12.0") + implementation("androidx.compose.ui:ui") + implementation("androidx.compose.material:material") + implementation("androidx.compose.ui:ui-tooling-preview") + implementation("androidx.lifecycle:lifecycle-runtime-ktx:$lifecycleVersion") + implementation("androidx.activity:activity-compose:1.8.0") + testImplementation("junit:junit:4.13.2") + androidTestImplementation("androidx.test.ext:junit:1.1.5") + androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1") + androidTestImplementation("androidx.compose.ui:ui-test-junit4") + debugImplementation("androidx.compose.ui:ui-tooling") + + // Compose navigation + implementation("androidx.navigation:navigation-compose:2.7.4") + implementation("androidx.hilt:hilt-navigation-compose:1.0.0") + + // Room + implementation("androidx.room:room-runtime:$roomVersion") + ksp("androidx.room:room-compiler:$roomVersion") + implementation("androidx.room:room-ktx:$roomVersion") + + //Dagger - Hilt + implementation("com.google.dagger:hilt-android:2.48") + ksp("com.google.dagger:hilt-android-compiler:2.48") + ksp("androidx.hilt:hilt-compiler:1.0.0") + implementation("androidx.hilt:hilt-work:1.0.0") + + // Coroutines + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutinesVersion") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutinesVersion") + + // Gson + implementation("com.google.code.gson:gson:2.10") + + // Preferences DataStore + implementation("androidx.datastore:datastore-preferences:1.0.0") + + // Accompanist libraries + implementation("com.google.accompanist:accompanist-flowlayout:0.23.1") + implementation("com.google.accompanist:accompanist-systemuicontroller:0.23.1") + implementation("com.google.accompanist:accompanist-permissions:0.23.1") + + // Compose MarkDown + implementation("com.github.jeziellago:compose-markdown:0.3.4") + + // Compose Glance (Widgets) + implementation("androidx.glance:glance-appwidget:1.0.0") + implementation("androidx.glance:glance-material:1.0.0") + + //Moshi + implementation("com.squareup.moshi:moshi-kotlin:1.14.0") + + // WorkManager + implementation("androidx.work:work-runtime-ktx:$workVersion") + + // Compose live data + implementation("androidx.compose.runtime:runtime-livedata") + + // DocumentFile + implementation("androidx.documentfile:documentfile:1.0.1") +} + +ksp { + arg("room.schemaLocation", "$projectDir/schemas") +} diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..22ffed6 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,32 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle.kts. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile +-dontobfuscate + +-dontwarn org.bouncycastle.jsse.BCSSLParameters +-dontwarn org.bouncycastle.jsse.BCSSLSocket +-dontwarn org.bouncycastle.jsse.provider.BouncyCastleJsseProvider +-dontwarn org.conscrypt.Conscrypt$Version +-dontwarn org.conscrypt.Conscrypt +-dontwarn org.conscrypt.ConscryptHostnameVerifier +-dontwarn org.openjsse.javax.net.ssl.SSLParameters +-dontwarn org.openjsse.javax.net.ssl.SSLSocket +-dontwarn org.openjsse.net.ssl.OpenJSSE \ No newline at end of file diff --git a/app/schemas/com.mhss.app.mybrain.data.local.MyBrainDatabase/1.json b/app/schemas/com.mhss.app.mybrain.data.local.MyBrainDatabase/1.json new file mode 100644 index 0000000..b9ef51a --- /dev/null +++ b/app/schemas/com.mhss.app.mybrain.data.local.MyBrainDatabase/1.json @@ -0,0 +1,258 @@ +{ + "formatVersion": 1, + "database": { + "version": 1, + "identityHash": "1e2bd9b0955419648a3c83b7027f8433", + "entities": [ + { + "tableName": "notes", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`title` TEXT NOT NULL, `content` TEXT NOT NULL, `created_date` INTEGER NOT NULL, `updated_date` INTEGER NOT NULL, `pinned` INTEGER NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)", + "fields": [ + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdDate", + "columnName": "created_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedDate", + "columnName": "updated_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "pinned", + "columnName": "pinned", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "tasks", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`title` TEXT NOT NULL, `description` TEXT NOT NULL, `is_completed` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `created_date` INTEGER NOT NULL, `updated_date` INTEGER NOT NULL, `sub_tasks` TEXT NOT NULL, `dueDate` INTEGER NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)", + "fields": [ + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "description", + "columnName": "description", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isCompleted", + "columnName": "is_completed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "priority", + "columnName": "priority", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdDate", + "columnName": "created_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedDate", + "columnName": "updated_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "subTasks", + "columnName": "sub_tasks", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dueDate", + "columnName": "dueDate", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "diary", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`title` TEXT NOT NULL, `content` TEXT NOT NULL, `created_date` INTEGER NOT NULL, `updated_date` INTEGER NOT NULL, `mood` INTEGER NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)", + "fields": [ + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdDate", + "columnName": "created_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedDate", + "columnName": "updated_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "mood", + "columnName": "mood", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "bookmarks", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`url` TEXT NOT NULL, `title` TEXT NOT NULL, `description` TEXT NOT NULL, `created_date` INTEGER NOT NULL, `updated_date` INTEGER NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)", + "fields": [ + { + "fieldPath": "url", + "columnName": "url", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "description", + "columnName": "description", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdDate", + "columnName": "created_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedDate", + "columnName": "updated_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "alarms", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `time` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "time", + "columnName": "time", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "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, '1e2bd9b0955419648a3c83b7027f8433')" + ] + } +} \ No newline at end of file diff --git a/app/schemas/com.mhss.app.mybrain.data.local.MyBrainDatabase/2.json b/app/schemas/com.mhss.app.mybrain.data.local.MyBrainDatabase/2.json new file mode 100644 index 0000000..d420068 --- /dev/null +++ b/app/schemas/com.mhss.app.mybrain.data.local.MyBrainDatabase/2.json @@ -0,0 +1,302 @@ +{ + "formatVersion": 1, + "database": { + "version": 2, + "identityHash": "fad6f140a4272bf79b901ad86cd27d66", + "entities": [ + { + "tableName": "notes", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`title` TEXT NOT NULL, `content` TEXT NOT NULL, `created_date` INTEGER NOT NULL, `updated_date` INTEGER NOT NULL, `pinned` INTEGER NOT NULL, `folder_id` INTEGER, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, FOREIGN KEY(`folder_id`) REFERENCES `note_folders`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdDate", + "columnName": "created_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedDate", + "columnName": "updated_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "pinned", + "columnName": "pinned", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "folderId", + "columnName": "folder_id", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [], + "foreignKeys": [ + { + "table": "note_folders", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "folder_id" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "tasks", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`title` TEXT NOT NULL, `description` TEXT NOT NULL, `is_completed` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `created_date` INTEGER NOT NULL, `updated_date` INTEGER NOT NULL, `sub_tasks` TEXT NOT NULL, `dueDate` INTEGER NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)", + "fields": [ + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "description", + "columnName": "description", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isCompleted", + "columnName": "is_completed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "priority", + "columnName": "priority", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdDate", + "columnName": "created_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedDate", + "columnName": "updated_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "subTasks", + "columnName": "sub_tasks", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dueDate", + "columnName": "dueDate", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "diary", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`title` TEXT NOT NULL, `content` TEXT NOT NULL, `created_date` INTEGER NOT NULL, `updated_date` INTEGER NOT NULL, `mood` INTEGER NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)", + "fields": [ + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdDate", + "columnName": "created_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedDate", + "columnName": "updated_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "mood", + "columnName": "mood", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "bookmarks", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`url` TEXT NOT NULL, `title` TEXT NOT NULL, `description` TEXT NOT NULL, `created_date` INTEGER NOT NULL, `updated_date` INTEGER NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)", + "fields": [ + { + "fieldPath": "url", + "columnName": "url", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "description", + "columnName": "description", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdDate", + "columnName": "created_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedDate", + "columnName": "updated_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "alarms", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `time` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "time", + "columnName": "time", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "note_folders", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`name` TEXT NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)", + "fields": [ + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [], + "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, 'fad6f140a4272bf79b901ad86cd27d66')" + ] + } +} \ No newline at end of file diff --git a/app/schemas/com.mhss.app.mybrain.data.local.MyBrainDatabase/3.json b/app/schemas/com.mhss.app.mybrain.data.local.MyBrainDatabase/3.json new file mode 100644 index 0000000..f9433f0 --- /dev/null +++ b/app/schemas/com.mhss.app.mybrain.data.local.MyBrainDatabase/3.json @@ -0,0 +1,314 @@ +{ + "formatVersion": 1, + "database": { + "version": 3, + "identityHash": "4cddc67715bf274c83c6f671b9ec8e5c", + "entities": [ + { + "tableName": "notes", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`title` TEXT NOT NULL, `content` TEXT NOT NULL, `created_date` INTEGER NOT NULL, `updated_date` INTEGER NOT NULL, `pinned` INTEGER NOT NULL, `folder_id` INTEGER, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, FOREIGN KEY(`folder_id`) REFERENCES `note_folders`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdDate", + "columnName": "created_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedDate", + "columnName": "updated_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "pinned", + "columnName": "pinned", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "folderId", + "columnName": "folder_id", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [], + "foreignKeys": [ + { + "table": "note_folders", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "folder_id" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "tasks", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`title` TEXT NOT NULL, `description` TEXT NOT NULL, `is_completed` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `created_date` INTEGER NOT NULL, `updated_date` INTEGER NOT NULL, `sub_tasks` TEXT NOT NULL, `dueDate` INTEGER NOT NULL, `recurring` INTEGER NOT NULL, `frequency` INTEGER NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)", + "fields": [ + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "description", + "columnName": "description", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isCompleted", + "columnName": "is_completed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "priority", + "columnName": "priority", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdDate", + "columnName": "created_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedDate", + "columnName": "updated_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "subTasks", + "columnName": "sub_tasks", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dueDate", + "columnName": "dueDate", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recurring", + "columnName": "recurring", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "frequency", + "columnName": "frequency", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "diary", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`title` TEXT NOT NULL, `content` TEXT NOT NULL, `created_date` INTEGER NOT NULL, `updated_date` INTEGER NOT NULL, `mood` INTEGER NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)", + "fields": [ + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdDate", + "columnName": "created_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedDate", + "columnName": "updated_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "mood", + "columnName": "mood", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "bookmarks", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`url` TEXT NOT NULL, `title` TEXT NOT NULL, `description` TEXT NOT NULL, `created_date` INTEGER NOT NULL, `updated_date` INTEGER NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)", + "fields": [ + { + "fieldPath": "url", + "columnName": "url", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "description", + "columnName": "description", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdDate", + "columnName": "created_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedDate", + "columnName": "updated_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "alarms", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `time` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "time", + "columnName": "time", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "note_folders", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`name` TEXT NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)", + "fields": [ + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [], + "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, '4cddc67715bf274c83c6f671b9ec8e5c')" + ] + } +} \ No newline at end of file diff --git a/app/schemas/com.mhss.app.mybrain.data.local.MyBrainDatabase/4.json b/app/schemas/com.mhss.app.mybrain.data.local.MyBrainDatabase/4.json new file mode 100644 index 0000000..a4c26aa --- /dev/null +++ b/app/schemas/com.mhss.app.mybrain.data.local.MyBrainDatabase/4.json @@ -0,0 +1,320 @@ +{ + "formatVersion": 1, + "database": { + "version": 4, + "identityHash": "0bf1c1b48ba41e376dcea76097a3724c", + "entities": [ + { + "tableName": "notes", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`title` TEXT NOT NULL, `content` TEXT NOT NULL, `created_date` INTEGER NOT NULL, `updated_date` INTEGER NOT NULL, `pinned` INTEGER NOT NULL, `folder_id` INTEGER, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, FOREIGN KEY(`folder_id`) REFERENCES `note_folders`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdDate", + "columnName": "created_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedDate", + "columnName": "updated_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "pinned", + "columnName": "pinned", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "folderId", + "columnName": "folder_id", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [], + "foreignKeys": [ + { + "table": "note_folders", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "folder_id" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "tasks", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`title` TEXT NOT NULL, `description` TEXT NOT NULL, `is_completed` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `created_date` INTEGER NOT NULL, `updated_date` INTEGER NOT NULL, `sub_tasks` TEXT NOT NULL, `dueDate` INTEGER NOT NULL, `recurring` INTEGER NOT NULL, `frequency` INTEGER NOT NULL, `frequency_amount` INTEGER NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)", + "fields": [ + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "description", + "columnName": "description", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isCompleted", + "columnName": "is_completed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "priority", + "columnName": "priority", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdDate", + "columnName": "created_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedDate", + "columnName": "updated_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "subTasks", + "columnName": "sub_tasks", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dueDate", + "columnName": "dueDate", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recurring", + "columnName": "recurring", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "frequency", + "columnName": "frequency", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "frequencyAmount", + "columnName": "frequency_amount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "diary", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`title` TEXT NOT NULL, `content` TEXT NOT NULL, `created_date` INTEGER NOT NULL, `updated_date` INTEGER NOT NULL, `mood` INTEGER NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)", + "fields": [ + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdDate", + "columnName": "created_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedDate", + "columnName": "updated_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "mood", + "columnName": "mood", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "bookmarks", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`url` TEXT NOT NULL, `title` TEXT NOT NULL, `description` TEXT NOT NULL, `created_date` INTEGER NOT NULL, `updated_date` INTEGER NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)", + "fields": [ + { + "fieldPath": "url", + "columnName": "url", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "description", + "columnName": "description", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdDate", + "columnName": "created_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedDate", + "columnName": "updated_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "alarms", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `time` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "time", + "columnName": "time", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "note_folders", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`name` TEXT NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)", + "fields": [ + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [], + "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, '0bf1c1b48ba41e376dcea76097a3724c')" + ] + } +} \ No newline at end of file diff --git a/app/src/androidTest/java/com/mhss/app/mybrain/ExampleInstrumentedTest.kt b/app/src/androidTest/java/com/mhss/app/mybrain/ExampleInstrumentedTest.kt new file mode 100644 index 0000000..6898cbc --- /dev/null +++ b/app/src/androidTest/java/com/mhss/app/mybrain/ExampleInstrumentedTest.kt @@ -0,0 +1,24 @@ +package com.mhss.app.mybrain + +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.ext.junit.runners.AndroidJUnit4 + +import org.junit.Test +import org.junit.runner.RunWith + +import org.junit.Assert.* + +/** + * Instrumented test, which will execute on an Android device. + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +@RunWith(AndroidJUnit4::class) +class ExampleInstrumentedTest { + @Test + fun useAppContext() { + // Context of the app under test. + val appContext = InstrumentationRegistry.getInstrumentation().targetContext + assertEquals("com.mhss.app.mybrain", appContext.packageName) + } +} \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..122c2c5 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,146 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/app/MyBrainApplication.kt b/app/src/main/java/com/mhss/app/mybrain/app/MyBrainApplication.kt new file mode 100644 index 0000000..4ef8e4e --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/app/MyBrainApplication.kt @@ -0,0 +1,59 @@ +package com.mhss.app.mybrain.app + +import android.app.Application +import android.app.NotificationChannel +import android.app.NotificationManager +import android.content.Context +import androidx.annotation.StringRes +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.preferencesDataStore +import androidx.hilt.work.HiltWorkerFactory +import androidx.work.Configuration +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.util.Constants +import dagger.hilt.android.HiltAndroidApp +import javax.inject.Inject + +val Context.dataStore: DataStore by preferencesDataStore(name = Constants.SETTINGS_PREFERENCES) + +@HiltAndroidApp +class MyBrainApplication : Application(), Configuration.Provider { + + companion object { + lateinit var appContext: Context + } + + @Inject + lateinit var workerFactory: HiltWorkerFactory + + override fun getWorkManagerConfiguration() = + Configuration.Builder() + .setWorkerFactory(workerFactory) + .build() + + override fun onCreate() { + super.onCreate() + appContext = this + createRemindersNotificationChannel() + } + + private fun createRemindersNotificationChannel() { + val channel = NotificationChannel( + Constants.REMINDERS_CHANNEL_ID, + getString(R.string.reminders_channel_name), + NotificationManager.IMPORTANCE_DEFAULT + ) + channel.description = getString(R.string.reminders_channel_description) + val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager + notificationManager.createNotificationChannel(channel) + + } +} + +// for string resources where context is not available +fun getString( + @StringRes + resId: Int, + vararg args: String +) = MyBrainApplication.appContext.getString(resId, *args) diff --git a/app/src/main/java/com/mhss/app/mybrain/data/backup/RoomBackupRepositoryImpl.kt b/app/src/main/java/com/mhss/app/mybrain/data/backup/RoomBackupRepositoryImpl.kt new file mode 100644 index 0000000..05ba8e5 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/data/backup/RoomBackupRepositoryImpl.kt @@ -0,0 +1,64 @@ +package com.mhss.app.mybrain.data.backup + +import android.content.Context +import android.net.Uri +import androidx.documentfile.provider.DocumentFile +import com.mhss.app.mybrain.data.local.MyBrainDatabase +import com.mhss.app.mybrain.domain.repository.RoomBackupRepository +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.io.File +import javax.inject.Inject + +class RoomBackupRepositoryImpl @Inject constructor( + private val database: MyBrainDatabase, + private val context: Context, +) : RoomBackupRepository { + + private val dbPath = File(context.getDatabasePath(database.openHelper.databaseName).toURI()) + + override suspend fun exportDatabase( + directoryUri: Uri, + encrypted: Boolean, // To be added in a future version + password: String // To be added in a future version + ): Boolean { + return withContext(Dispatchers.IO) { + try { + val fileName = "MyBrain_Backup_${System.currentTimeMillis()}.sqlite3" + val pickedDir = DocumentFile.fromTreeUri(context, directoryUri) + val destination = pickedDir!!.createFile("application/sqlite3", fileName) + + + val outputStream = + destination?.let { context.contentResolver.openOutputStream(it.uri) } + ?: return@withContext false + + dbPath.inputStream().copyTo(outputStream) + + true + } catch (e: Exception) { + e.printStackTrace() + false + } + } + } + + override suspend fun importDatabase( + fileUri: Uri, + encrypted: Boolean, // To be added in a future version + password: String // To be added in a future version + ): Boolean { + return withContext(Dispatchers.IO) { + try { + database.close() + context.contentResolver.openInputStream(fileUri)?.use { + it.copyTo(dbPath.outputStream()) + } ?: return@withContext false + true + } catch (e: Exception) { + e.printStackTrace() + false + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/data/local/MyBrainDatabase.kt b/app/src/main/java/com/mhss/app/mybrain/data/local/MyBrainDatabase.kt new file mode 100644 index 0000000..47d23f6 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/data/local/MyBrainDatabase.kt @@ -0,0 +1,26 @@ +package com.mhss.app.mybrain.data.local + +import androidx.room.Database +import androidx.room.RoomDatabase +import androidx.room.TypeConverters +import com.mhss.app.mybrain.data.local.converters.DBConverters +import com.mhss.app.mybrain.data.local.dao.* +import com.mhss.app.mybrain.domain.model.* + +@Database( + entities = [Note::class, Task::class, DiaryEntry::class, Bookmark::class, Alarm::class, NoteFolder::class], + version = 4 +) +@TypeConverters(DBConverters::class) +abstract class MyBrainDatabase: RoomDatabase() { + + abstract fun noteDao(): NoteDao + abstract fun taskDao(): TaskDao + abstract fun diaryDao(): DiaryDao + abstract fun bookmarkDao(): BookmarkDao + abstract fun alarmDao(): AlarmDao + + companion object { + const val DATABASE_NAME = "by_brain_db" + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/data/local/converters/DBConverters.kt b/app/src/main/java/com/mhss/app/mybrain/data/local/converters/DBConverters.kt new file mode 100644 index 0000000..63f0b16 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/data/local/converters/DBConverters.kt @@ -0,0 +1,30 @@ +package com.mhss.app.mybrain.data.local.converters + +import androidx.room.TypeConverter +import com.google.gson.Gson +import com.google.gson.reflect.TypeToken +import com.mhss.app.mybrain.domain.model.SubTask +import com.mhss.app.mybrain.util.diary.Mood + +class DBConverters { + + @TypeConverter + fun fromSubTasksList(value: List): String { + val gson = Gson() + val type = TypeToken.getParameterized(List::class.java, SubTask::class.java).type + return gson.toJson(value, type) + } + + @TypeConverter + fun toSubTasksList(value: String): List { + val gson = Gson() + val type = TypeToken.getParameterized(List::class.java, SubTask::class.java).type + return gson.fromJson(value, type) + } + + @TypeConverter + fun toMood(value: Int) = enumValues()[value] + + @TypeConverter + fun fromMood(value: Mood) = value.ordinal +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/data/local/dao/AlarmDao.kt b/app/src/main/java/com/mhss/app/mybrain/data/local/dao/AlarmDao.kt new file mode 100644 index 0000000..76f5196 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/data/local/dao/AlarmDao.kt @@ -0,0 +1,21 @@ +package com.mhss.app.mybrain.data.local.dao + +import androidx.room.* +import com.mhss.app.mybrain.domain.model.Alarm + +@Dao +interface AlarmDao { + + @Query("SELECT * FROM alarms") + suspend fun getAll(): List + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun insert(alarm: Alarm) + + @Delete + suspend fun delete(alarm: Alarm) + + @Query("DELETE FROM alarms WHERE id = :id") + suspend fun delete(id: Int) + +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/data/local/dao/BookmarkDao.kt b/app/src/main/java/com/mhss/app/mybrain/data/local/dao/BookmarkDao.kt new file mode 100644 index 0000000..98d2aa4 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/data/local/dao/BookmarkDao.kt @@ -0,0 +1,31 @@ +package com.mhss.app.mybrain.data.local.dao + +import androidx.room.* +import com.mhss.app.mybrain.domain.model.Bookmark +import kotlinx.coroutines.flow.Flow + +@Dao +interface BookmarkDao { + + @Query("SELECT * FROM bookmarks") + fun getAllBookmarks(): Flow> + + @Query("SELECT * FROM bookmarks WHERE id = :id") + suspend fun getBookmark(id: Int): Bookmark + + @Query("SELECT * FROM bookmarks WHERE title LIKE '%' || :query || '%' OR description LIKE '%' || :query || '%' OR url LIKE '%' || :query || '%'") + suspend fun getBookmark(query: String): List + + @Insert + suspend fun insertBookmark(bookmark: Bookmark) + + @Update + suspend fun updateBookmark(bookmark: Bookmark) + + @Delete + suspend fun deleteBookmark(bookmark: Bookmark) + + @Insert + suspend fun insertBookmarks(bookmarks: List) + +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/data/local/dao/DiaryDao.kt b/app/src/main/java/com/mhss/app/mybrain/data/local/dao/DiaryDao.kt new file mode 100644 index 0000000..2978049 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/data/local/dao/DiaryDao.kt @@ -0,0 +1,31 @@ +package com.mhss.app.mybrain.data.local.dao + +import androidx.room.* +import com.mhss.app.mybrain.domain.model.DiaryEntry +import kotlinx.coroutines.flow.Flow + +@Dao +interface DiaryDao { + + @Query("SELECT * FROM diary") + fun getAllEntries(): Flow> + + @Query("SELECT * FROM diary WHERE id = :id") + suspend fun getEntry(id: Int): DiaryEntry + + @Query("SELECT * FROM diary WHERE title LIKE '%' || :query || '%' OR content LIKE '%' || :query || '%'") + suspend fun getEntriesByTitle(query: String): List + + @Insert + suspend fun insertEntry(diary: DiaryEntry) + + @Insert + suspend fun insertEntries(diary: List) + + @Update + suspend fun updateEntry(diary: DiaryEntry) + + @Delete + suspend fun deleteEntry(diary: DiaryEntry) + +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/data/local/dao/NoteDao.kt b/app/src/main/java/com/mhss/app/mybrain/data/local/dao/NoteDao.kt new file mode 100644 index 0000000..2343221 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/data/local/dao/NoteDao.kt @@ -0,0 +1,49 @@ +package com.mhss.app.mybrain.data.local.dao + +import androidx.room.* +import com.mhss.app.mybrain.domain.model.Note +import com.mhss.app.mybrain.domain.model.NoteFolder +import kotlinx.coroutines.flow.Flow + +@Dao +interface NoteDao { + + @Query("SELECT * FROM notes") + fun getAllNotes(): Flow> + + @Query("SELECT * FROM notes WHERE id = :id") + suspend fun getNote(id: Int): Note + + @Query("SELECT * FROM notes WHERE title LIKE '%' || :query || '%' OR content LIKE '%' || :query || '%'") + suspend fun getNotesByTitle(query: String): List + + @Query("SELECT * FROM notes WHERE folder_id = :folderId") + fun getNotesByFolder(folderId: Int): Flow> + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun insertNote(note: Note) + + @Insert(onConflict = OnConflictStrategy.IGNORE) + suspend fun insertNotes(notes: List) + + @Update + suspend fun updateNote(note: Note) + + @Delete + suspend fun deleteNote(note: Note) + + @Insert(onConflict = OnConflictStrategy.IGNORE) + suspend fun insertNoteFolder(folder: NoteFolder) + + @Insert(onConflict = OnConflictStrategy.IGNORE) + suspend fun insertNoteFolders(folders: List) + + @Update + suspend fun updateNoteFolder(folder: NoteFolder) + + @Delete + suspend fun deleteNoteFolder(folder: NoteFolder) + + @Query("SELECT * FROM note_folders") + fun getAllNoteFolders(): Flow> +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/data/local/dao/TaskDao.kt b/app/src/main/java/com/mhss/app/mybrain/data/local/dao/TaskDao.kt new file mode 100644 index 0000000..6323731 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/data/local/dao/TaskDao.kt @@ -0,0 +1,34 @@ +package com.mhss.app.mybrain.data.local.dao + +import androidx.room.* +import com.mhss.app.mybrain.domain.model.Task +import kotlinx.coroutines.flow.Flow + +@Dao +interface TaskDao { + + @Query("SELECT * FROM tasks") + fun getAllTasks(): Flow> + + @Query("SELECT * FROM tasks WHERE id = :id") + suspend fun getTask(id: Int): Task + + @Query("SELECT * FROM tasks WHERE title LIKE '%' || :title || '%'") + fun getTasksByTitle(title: String): Flow> + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun insertTask(task: Task): Long + + @Insert(onConflict = OnConflictStrategy.IGNORE) + suspend fun insertTasks(tasks: List) + + @Update + suspend fun updateTask(task: Task) + + @Delete + suspend fun deleteTask(task: Task) + + @Query("UPDATE tasks SET is_completed = :completed WHERE id = :id") + suspend fun updateCompleted(id: Int, completed: Boolean) + +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/data/local/migrations/RoomMigrations.kt b/app/src/main/java/com/mhss/app/mybrain/data/local/migrations/RoomMigrations.kt new file mode 100644 index 0000000..e4cad58 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/data/local/migrations/RoomMigrations.kt @@ -0,0 +1,29 @@ +package com.mhss.app.mybrain.data.local.migrations + +import androidx.room.migration.Migration +import androidx.sqlite.db.SupportSQLiteDatabase + +// Added note folders +val MIGRATION_1_2 = object : Migration(1, 2) { + override fun migrate(database: SupportSQLiteDatabase) { + database.execSQL("CREATE TABLE note_folders (name TEXT NOT NULL, id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)") + + database.execSQL("CREATE TABLE IF NOT EXISTS `notes_new` (`title` TEXT NOT NULL, `content` TEXT NOT NULL, `created_date` INTEGER NOT NULL, `updated_date` INTEGER NOT NULL, `pinned` INTEGER NOT NULL, `folder_id` INTEGER, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, FOREIGN KEY (folder_id) REFERENCES note_folders (id) ON UPDATE NO ACTION ON DELETE CASCADE)") + database.execSQL("INSERT INTO notes_new (title, content, created_date, updated_date, pinned, id) SELECT title, content, created_date, updated_date, pinned, id FROM notes") + database.execSQL("DROP TABLE notes") + database.execSQL("ALTER TABLE notes_new RENAME TO notes") + } +} + +val MIGRATION_2_3 = object : Migration(2, 3) { + override fun migrate(database: SupportSQLiteDatabase) { + database.execSQL("ALTER TABLE tasks ADD COLUMN recurring INTEGER NOT NULL DEFAULT 0") + database.execSQL("ALTER TABLE tasks ADD COLUMN frequency INTEGER NOT NULL DEFAULT 0") + } +} + +val MIGRATION_3_4 = object : Migration(3, 4) { + override fun migrate(database: SupportSQLiteDatabase) { + database.execSQL("ALTER TABLE tasks ADD COLUMN frequency_amount INTEGER NOT NULL DEFAULT 1") + } +} diff --git a/app/src/main/java/com/mhss/app/mybrain/data/repository/AlarmRepositoryImpl.kt b/app/src/main/java/com/mhss/app/mybrain/data/repository/AlarmRepositoryImpl.kt new file mode 100644 index 0000000..cad3a0e --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/data/repository/AlarmRepositoryImpl.kt @@ -0,0 +1,39 @@ +package com.mhss.app.mybrain.data.repository + +import com.mhss.app.mybrain.data.local.dao.AlarmDao +import com.mhss.app.mybrain.domain.model.Alarm +import com.mhss.app.mybrain.domain.repository.AlarmRepository +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import javax.inject.Inject + +class AlarmRepositoryImpl @Inject constructor( + private val alarmDao: AlarmDao, + private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO +) : AlarmRepository { + + override suspend fun getAlarms(): List { + return withContext(ioDispatcher) { + alarmDao.getAll() + } + } + + override suspend fun insertAlarm(alarm: Alarm) { + withContext(ioDispatcher) { + alarmDao.insert(alarm) + } + } + + override suspend fun deleteAlarm(alarm: Alarm) { + withContext(ioDispatcher) { + alarmDao.delete(alarm) + } + } + + override suspend fun deleteAlarm(id: Int) { + withContext(ioDispatcher) { + alarmDao.delete(id) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/data/repository/BookmarkRepositoryImpl.kt b/app/src/main/java/com/mhss/app/mybrain/data/repository/BookmarkRepositoryImpl.kt new file mode 100644 index 0000000..d8b390a --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/data/repository/BookmarkRepositoryImpl.kt @@ -0,0 +1,49 @@ +package com.mhss.app.mybrain.data.repository + +import com.mhss.app.mybrain.data.local.dao.BookmarkDao +import com.mhss.app.mybrain.domain.model.Bookmark +import com.mhss.app.mybrain.domain.repository.BookmarkRepository +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.withContext + +class BookmarkRepositoryImpl( + private val bookmarkDao: BookmarkDao, + private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO +) : BookmarkRepository { + + override fun getAllBookmarks(): Flow> { + return bookmarkDao.getAllBookmarks() + } + + override suspend fun getBookmark(id: Int): Bookmark { + return withContext(ioDispatcher) { + bookmarkDao.getBookmark(id) + } + } + + override suspend fun searchBookmarks(query: String): List { + return withContext(ioDispatcher) { + bookmarkDao.getBookmark(query) + } + } + + override suspend fun addBookmark(bookmark: Bookmark) { + withContext(ioDispatcher) { + bookmarkDao.insertBookmark(bookmark) + } + } + + override suspend fun deleteBookmark(bookmark: Bookmark) { + withContext(ioDispatcher) { + bookmarkDao.deleteBookmark(bookmark) + } + } + + override suspend fun updateBookmark(bookmark: Bookmark) { + withContext(ioDispatcher) { + bookmarkDao.updateBookmark(bookmark) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/data/repository/CalendarRepositoryImpl.kt b/app/src/main/java/com/mhss/app/mybrain/data/repository/CalendarRepositoryImpl.kt new file mode 100644 index 0000000..a16d193 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/data/repository/CalendarRepositoryImpl.kt @@ -0,0 +1,285 @@ +package com.mhss.app.mybrain.data.repository + +import android.content.ContentUris +import android.content.ContentValues +import android.content.Context +import android.database.Cursor +import android.net.Uri +import android.provider.CalendarContract +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.domain.model.Calendar +import com.mhss.app.mybrain.domain.model.CalendarEvent +import com.mhss.app.mybrain.domain.repository.CalendarRepository +import com.mhss.app.mybrain.util.calendar.* +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.util.* + +class CalendarRepositoryImpl(private val context: Context) : CalendarRepository { + + override suspend fun getEvents(): List { + return withContext(Dispatchers.IO) { + val projection: Array = arrayOf( + CalendarContract.Events._ID, + CalendarContract.Events.TITLE, + CalendarContract.Events.DESCRIPTION, + CalendarContract.Events.DTSTART, + CalendarContract.Events.DTEND, + CalendarContract.Events.EVENT_LOCATION, + CalendarContract.Events.ALL_DAY, + CalendarContract.Events.EVENT_COLOR, + CalendarContract.Events.CALENDAR_ID, + CalendarContract.Events.RRULE, + CalendarContract.Events.DURATION, + CalendarContract.Events.CALENDAR_COLOR + ) + val instancesProjection = arrayOf( + CalendarContract.Instances.EVENT_ID, + CalendarContract.Instances.TITLE, + CalendarContract.Instances.DESCRIPTION, + CalendarContract.Instances.BEGIN, + CalendarContract.Instances.END, + CalendarContract.Instances.EVENT_LOCATION, + CalendarContract.Instances.ALL_DAY, + CalendarContract.Instances.EVENT_COLOR, + CalendarContract.Instances.CALENDAR_ID, + CalendarContract.Instances.RRULE, + CalendarContract.Instances.DURATION, + CalendarContract.Instances.CALENDAR_COLOR + ) + val contentResolver = context.contentResolver + val events = mutableListOf() + + val uri: Uri = CalendarContract.Events.CONTENT_URI + val cur: Cursor? = contentResolver.query( + uri, + projection, + "${CalendarContract.Events.DTSTART} > ? AND ${CalendarContract.Events.DELETED} = 0", + // events today or in the future only + arrayOf(System.currentTimeMillis().toString()), + null + ) + + if (cur != null) { + while (cur.moveToNext()) { + val eventId: Long = cur.getLong(ID_INDEX) + val title: String = cur.getString(TITLE_INDEX) ?: continue + val description: String? = cur.getString(DESC_INDEX) + val start: Long = cur.getLong(START_INDEX) + val duration: String = cur.getString(EVENT_DURATION_INDEX) ?: "" + val end: Long = if (duration.isNotBlank()) duration.extractEndFromDuration(start) else cur.getLong(END_INDEX) + val location: String? = cur.getString(LOCATION_INDEX) + val allDay: Boolean = cur.getInt(ALL_DAY_INDEX) == 1 + val color: Int = cur.getInt(COlOR_INDEX) + val calendarColor: Int = cur.getInt(CALENDAR_COLOR_INDEX) + val calendarId: Long = cur.getLong(EVENT_CALENDAR_ID_INDEX) + val rrule: String = cur.getString(EVENT_RRULE_INDEX) ?: "" + val recurring: Boolean = rrule.isNotBlank() +// val frequency: String = rrule.extractFrequency() + + if (!recurring) + events.add(CalendarEvent( + id = eventId , + title = title, + description = description, + start = start, + end = end, + location = location, + allDay = allDay, + color = if (color != 0) color else calendarColor, + calendarId = calendarId, + )) + } + cur.close() + } + + // get recurring events + val startM = java.util.Calendar.getInstance().timeInMillis + val endM = startM + 6 * 30 * 24 * 60 * 60 * 1000L + val builder = CalendarContract.Instances.CONTENT_URI.buildUpon() + ContentUris.appendId(builder, startM) + ContentUris.appendId(builder, endM) + val curI = contentResolver.query( + builder.build(), + instancesProjection, + null, null, null + ) + if (curI != null){ + while (curI.moveToNext()){ + val eventId: Long = curI.getLong(ID_INDEX) + val title: String = curI.getString(TITLE_INDEX) ?: continue + val description: String? = curI.getString(DESC_INDEX) + val start: Long = curI.getLong(START_INDEX) + val duration: String = curI.getString(EVENT_DURATION_INDEX) ?: "" + val end: Long = if (duration.isNotBlank()) duration.extractEndFromDuration(start) else curI.getLong(END_INDEX) + val location: String? = curI.getString(LOCATION_INDEX) + val allDay: Boolean = curI.getInt(ALL_DAY_INDEX) == 1 + val color: Int = curI.getInt(COlOR_INDEX) + val calendarColor: Int = curI.getInt(CALENDAR_COLOR_INDEX) + val calendarId: Long = curI.getLong(EVENT_CALENDAR_ID_INDEX) + val rrule: String = curI.getString(EVENT_RRULE_INDEX) ?: "" + val recurring: Boolean = rrule.isNotBlank() + val frequency: String = rrule.extractFrequency() + if (recurring) events.add(CalendarEvent( + id = eventId, + title = title, + description = description, + start = start, + end = end, + location = location, + allDay = allDay, + color = if (color != 0) color else calendarColor, + calendarId = calendarId, + frequency = frequency, + recurring = true, + )) + } + curI.close() + } + events.sortedBy { it.start } + } + } + + override suspend fun getCalendars() : List{ + return withContext(Dispatchers.IO){ + val projection = arrayOf( + CalendarContract.Calendars._ID, // 0 + CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, // 1 + CalendarContract.Calendars.ACCOUNT_NAME, // 2 + CalendarContract.Calendars.ACCOUNT_TYPE, // 3 + CalendarContract.Calendars.CALENDAR_COLOR// 4 + + ) + val uri = CalendarContract.Calendars.CONTENT_URI + val contentResolver = context.contentResolver + val cur = contentResolver.query( + uri, + projection, + null, + null, + null + ) + val calendars: MutableList = mutableListOf() + if (cur != null) { + while (cur.moveToNext()) { + + val calID: Long = cur.getLong(CALENDAR_ID_INDEX) + val calendarName: String = cur.getString(CALENDAR_NAME_INDEX) + val accountName: String = cur.getString(ACCOUNT_NAME_INDEX) + val color: Int = cur.getInt(CALENDAR_CALENDAR_COLOR_INDEX) + + calendars.add( + Calendar( + calID, + calendarName, + accountName, + color + ) + ) + } + cur.close() + calendars + }else + emptyList() + } + } + + override suspend fun addEvent(event: CalendarEvent) { + withContext(Dispatchers.IO){ + val values = ContentValues().apply { + put(CalendarContract.Events.CALENDAR_ID, event.calendarId) + put(CalendarContract.Events.TITLE, event.title) + put(CalendarContract.Events.DESCRIPTION, event.description) + put(CalendarContract.Events.DTSTART, event.start) + put(CalendarContract.Events.ALL_DAY, event.allDay) + put(CalendarContract.Events.EVENT_LOCATION, event.location) + if (event.recurring){ + put(CalendarContract.Events.RRULE, event.getEventRRule()) + put(CalendarContract.Events.DURATION, event.getEventDuration()) + } else { + put(CalendarContract.Events.DTEND, event.end) + } + put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().id) + } + context.contentResolver.insert(CalendarContract.Events.CONTENT_URI, values) + } + } + + override suspend fun updateEvent(event: CalendarEvent) { + withContext(Dispatchers.IO){ + val values = ContentValues().apply { + put(CalendarContract.Events.CALENDAR_ID, event.calendarId) + put(CalendarContract.Events.TITLE, event.title) + put(CalendarContract.Events.DESCRIPTION, event.description) + put(CalendarContract.Events.DTSTART, event.start) + if (event.recurring && event.frequency.isNotBlank()){ + val end: Long? = null + put(CalendarContract.Events.RRULE, event.getEventRRule()) + put(CalendarContract.Events.DURATION, event.getEventDuration()) + put(CalendarContract.Events.DTEND, end) + }else { + val rule: String? = null + put(CalendarContract.Events.RRULE, rule) + put(CalendarContract.Events.DURATION, rule) + put(CalendarContract.Events.DTEND, event.end) + } + put(CalendarContract.Events.ALL_DAY, event.allDay) + put(CalendarContract.Events.EVENT_LOCATION, event.location) + } + val updateUri: Uri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, event.id) + context.contentResolver.update(updateUri, values, null, null) + } + } + + override suspend fun createCalendar() { + withContext(Dispatchers.IO){ + val uri = CalendarContract.Calendars.CONTENT_URI.asSyncAdapter(context.getString(R.string.app_name), CalendarContract.ACCOUNT_TYPE_LOCAL) + val values = ContentValues().apply { + put(CalendarContract.Calendars.ACCOUNT_TYPE, CalendarContract.ACCOUNT_TYPE_LOCAL) + put(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, context.getString(R.string.app_name)) + put(CalendarContract.Calendars.NAME, context.getString(R.string.app_name)) + put(CalendarContract.Calendars.ACCOUNT_NAME, context.getString(R.string.app_name)) + put(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, CalendarContract.Calendars.CAL_ACCESS_OWNER) + put(CalendarContract.Calendars.CALENDAR_COLOR, 0x03DAC5) + put(CalendarContract.Calendars.VISIBLE, 1) + put(CalendarContract.Calendars.SYNC_EVENTS, 1) + } + context.contentResolver.insert(uri, values) + } + } + + fun Uri.asSyncAdapter(account: String, accountType: String): Uri { + return buildUpon() + .appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true") + .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, account) + .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, accountType).build() + } + + + override suspend fun deleteEvent(event: CalendarEvent) { + withContext(Dispatchers.IO){ + val updateUri: Uri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, event.id) + context.contentResolver.delete(updateUri, null, null) + } + } + + companion object { + private const val ID_INDEX = 0 + private const val TITLE_INDEX = 1 + private const val DESC_INDEX = 2 + private const val START_INDEX = 3 + private const val END_INDEX = 4 + private const val LOCATION_INDEX = 5 + private const val ALL_DAY_INDEX = 6 + private const val COlOR_INDEX = 7 + private const val EVENT_CALENDAR_ID_INDEX = 8 + private const val EVENT_RRULE_INDEX = 9 + private const val EVENT_DURATION_INDEX = 10 + private const val CALENDAR_COLOR_INDEX = 11 + + private const val CALENDAR_ID_INDEX: Int = 0 + private const val CALENDAR_NAME_INDEX: Int = 1 + private const val ACCOUNT_NAME_INDEX: Int = 2 + private const val CALENDAR_CALENDAR_COLOR_INDEX: Int = 4 + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/data/repository/DiaryRepositoryImpl.kt b/app/src/main/java/com/mhss/app/mybrain/data/repository/DiaryRepositoryImpl.kt new file mode 100644 index 0000000..5c0108e --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/data/repository/DiaryRepositoryImpl.kt @@ -0,0 +1,49 @@ +package com.mhss.app.mybrain.data.repository + +import com.mhss.app.mybrain.data.local.dao.DiaryDao +import com.mhss.app.mybrain.domain.model.DiaryEntry +import com.mhss.app.mybrain.domain.repository.DiaryRepository +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.withContext + +class DiaryRepositoryImpl( + private val diaryDao: DiaryDao, + private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO +) : DiaryRepository { + + override fun getAllEntries(): Flow> { + return diaryDao.getAllEntries() + } + + override suspend fun getEntry(id: Int): DiaryEntry { + return withContext(ioDispatcher) { + diaryDao.getEntry(id) + } + } + + override suspend fun searchEntries(title: String): List { + return withContext(ioDispatcher) { + diaryDao.getEntriesByTitle(title) + } + } + + override suspend fun addEntry(diary: DiaryEntry) { + withContext(ioDispatcher) { + diaryDao.insertEntry(diary) + } + } + + override suspend fun updateEntry(diary: DiaryEntry) { + withContext(ioDispatcher) { + diaryDao.updateEntry(diary) + } + } + + override suspend fun deleteEntry(diary: DiaryEntry) { + withContext(ioDispatcher) { + diaryDao.deleteEntry(diary) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/data/repository/NoteRepositoryImpl.kt b/app/src/main/java/com/mhss/app/mybrain/data/repository/NoteRepositoryImpl.kt new file mode 100644 index 0000000..acffe7e --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/data/repository/NoteRepositoryImpl.kt @@ -0,0 +1,76 @@ +package com.mhss.app.mybrain.data.repository + +import com.mhss.app.mybrain.data.local.dao.NoteDao +import com.mhss.app.mybrain.domain.model.Note +import com.mhss.app.mybrain.domain.model.NoteFolder +import com.mhss.app.mybrain.domain.repository.NoteRepository +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.withContext + +class NoteRepositoryImpl( + private val noteDao: NoteDao, + private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO +) : NoteRepository { + + override fun getAllNotes(): Flow> { + return noteDao.getAllNotes() + } + + override suspend fun getNote(id: Int): Note { + return withContext(ioDispatcher) { + noteDao.getNote(id) + } + } + + override suspend fun searchNotes(query: String): List { + return withContext(ioDispatcher) { + noteDao.getNotesByTitle(query) + } + } + + override fun getNotesByFolder(folderId: Int): Flow> { + return noteDao.getNotesByFolder(folderId) + } + + override suspend fun addNote(note: Note) { + withContext(ioDispatcher) { + noteDao.insertNote(note) + } + } + + override suspend fun updateNote(note: Note) { + withContext(ioDispatcher) { + noteDao.updateNote(note) + } + } + + override suspend fun deleteNote(note: Note) { + withContext(ioDispatcher) { + noteDao.deleteNote(note) + } + } + + override suspend fun insertNoteFolder(folder: NoteFolder) { + withContext(ioDispatcher) { + noteDao.insertNoteFolder(folder) + } + } + + override suspend fun updateNoteFolder(folder: NoteFolder) { + withContext(ioDispatcher) { + noteDao.updateNoteFolder(folder) + } + } + + override suspend fun deleteNoteFolder(folder: NoteFolder) { + withContext(ioDispatcher) { + noteDao.deleteNoteFolder(folder) + } + } + + override fun getAllNoteFolders(): Flow> { + return noteDao.getAllNoteFolders() + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/data/repository/SettingsRepositoryImpl.kt b/app/src/main/java/com/mhss/app/mybrain/data/repository/SettingsRepositoryImpl.kt new file mode 100644 index 0000000..ac4f1c2 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/data/repository/SettingsRepositoryImpl.kt @@ -0,0 +1,30 @@ +package com.mhss.app.mybrain.data.repository + +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.edit +import com.mhss.app.mybrain.domain.repository.SettingsRepository +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.withContext + +class SettingsRepositoryImpl( + private val preferences: DataStore, + private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO +) : SettingsRepository { + + override suspend fun saveSettings(key: Preferences.Key, value: T) { + withContext(ioDispatcher) { + preferences.edit { settings -> + if (settings[key] != value) + settings[key] = value + } + } + } + + override fun getSettings(key: Preferences.Key, defaultValue: T): Flow { + return preferences.data.map { preferences -> preferences[key] ?: defaultValue } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/data/repository/TaskRepositoryImpl.kt b/app/src/main/java/com/mhss/app/mybrain/data/repository/TaskRepositoryImpl.kt new file mode 100644 index 0000000..50df343 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/data/repository/TaskRepositoryImpl.kt @@ -0,0 +1,55 @@ +package com.mhss.app.mybrain.data.repository + +import com.mhss.app.mybrain.data.local.dao.TaskDao +import com.mhss.app.mybrain.domain.model.Task +import com.mhss.app.mybrain.domain.repository.TaskRepository +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.withContext +import javax.inject.Inject + +class TaskRepositoryImpl( + private val taskDao: TaskDao, + private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO +) : TaskRepository { + + override fun getAllTasks(): Flow> { + return taskDao.getAllTasks() + } + + override suspend fun getTaskById(id: Int): Task { + return withContext(ioDispatcher) { + taskDao.getTask(id) + } + } + + override fun searchTasks(title: String): Flow> { + return taskDao.getTasksByTitle(title) + } + + override suspend fun insertTask(task: Task): Long { + return withContext(ioDispatcher) { + taskDao.insertTask(task) + } + } + + override suspend fun updateTask(task: Task) { + withContext(ioDispatcher) { + taskDao.updateTask(task) + } + } + + override suspend fun completeTask(id: Int, completed: Boolean) { + withContext(ioDispatcher) { + taskDao.updateCompleted(id, completed) + } + } + + override suspend fun deleteTask(task: Task) { + withContext(ioDispatcher) { + taskDao.deleteTask(task) + } + } + +} diff --git a/app/src/main/java/com/mhss/app/mybrain/di/AppModule.kt b/app/src/main/java/com/mhss/app/mybrain/di/AppModule.kt new file mode 100644 index 0000000..b16c893 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/di/AppModule.kt @@ -0,0 +1,97 @@ +package com.mhss.app.mybrain.di + +import android.content.Context +import androidx.room.Room +import com.mhss.app.mybrain.app.dataStore +import com.mhss.app.mybrain.data.backup.RoomBackupRepositoryImpl +import com.mhss.app.mybrain.data.local.MyBrainDatabase +import com.mhss.app.mybrain.data.local.dao.* +import com.mhss.app.mybrain.data.local.migrations.MIGRATION_1_2 +import com.mhss.app.mybrain.data.local.migrations.MIGRATION_2_3 +import com.mhss.app.mybrain.data.local.migrations.MIGRATION_3_4 +import com.mhss.app.mybrain.data.repository.* +import com.mhss.app.mybrain.domain.repository.* +import dagger.Module +import dagger.Provides +import dagger.hilt.InstallIn +import dagger.hilt.android.qualifiers.ApplicationContext +import dagger.hilt.components.SingletonComponent +import javax.inject.Singleton + +@Module +@InstallIn(SingletonComponent::class) +object AppModule { + + @Singleton + @Provides + fun provideMyBrainDataBase( + @ApplicationContext context: Context + ) = Room.databaseBuilder( + context, + MyBrainDatabase::class.java, + MyBrainDatabase.DATABASE_NAME + ).addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4) + .build() + + @Singleton + @Provides + fun provideNoteDao(myBrainDatabase: MyBrainDatabase) = myBrainDatabase.noteDao() + + @Singleton + @Provides + fun provideNoteRepository(noteDao: NoteDao): NoteRepository = NoteRepositoryImpl(noteDao) + + @Singleton + @Provides + fun provideTaskDao(myBrainDatabase: MyBrainDatabase) = myBrainDatabase.taskDao() + + @Singleton + @Provides + fun provideTaskRepository(taskDao: TaskDao): TaskRepository = TaskRepositoryImpl(taskDao) + + @Singleton + @Provides + fun provideBookmarkDao(myBrainDatabase: MyBrainDatabase) = myBrainDatabase.bookmarkDao() + + @Singleton + @Provides + fun provideBookmarkRepository(bookmarkDao: BookmarkDao): BookmarkRepository = + BookmarkRepositoryImpl(bookmarkDao) + + @Singleton + @Provides + fun provideDiaryDao(myBrainDatabase: MyBrainDatabase) = myBrainDatabase.diaryDao() + + @Singleton + @Provides + fun provideDiaryRepository(diaryDao: DiaryDao): DiaryRepository = DiaryRepositoryImpl(diaryDao) + + @Singleton + @Provides + fun provideCalendarRepository(@ApplicationContext context: Context): CalendarRepository = + CalendarRepositoryImpl(context) + + @Singleton + @Provides + fun provideAlarmDao(myBrainDatabase: MyBrainDatabase) = myBrainDatabase.alarmDao() + + @Singleton + @Provides + fun provideAlarmRepository(alarmDao: AlarmDao): AlarmRepository = AlarmRepositoryImpl(alarmDao) + + @Singleton + @Provides + fun provideSettingsRepository(@ApplicationContext context: Context): SettingsRepository = + SettingsRepositoryImpl(context.dataStore) + + @Singleton + @Provides + fun provideAppContext(@ApplicationContext context: Context) = context + + @Singleton + @Provides + fun provideBackupRepository( + myBrainDatabase: MyBrainDatabase, + @ApplicationContext context: Context + ): RoomBackupRepository = RoomBackupRepositoryImpl(myBrainDatabase ,context) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/di/CalendarWidgetEntryPoint.kt b/app/src/main/java/com/mhss/app/mybrain/di/CalendarWidgetEntryPoint.kt new file mode 100644 index 0000000..b499ecb --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/di/CalendarWidgetEntryPoint.kt @@ -0,0 +1,17 @@ +package com.mhss.app.mybrain.di + +import com.mhss.app.mybrain.domain.use_case.calendar.GetAllEventsUseCase +import com.mhss.app.mybrain.domain.use_case.settings.GetSettingsUseCase +import dagger.hilt.EntryPoint +import dagger.hilt.InstallIn +import dagger.hilt.components.SingletonComponent + + +@EntryPoint +@InstallIn(SingletonComponent::class) +interface CalendarWidgetEntryPoint { + + fun getSettingsUseCase(): GetSettingsUseCase + + fun getAllEventsUseCase(): GetAllEventsUseCase +} diff --git a/app/src/main/java/com/mhss/app/mybrain/di/TasksWidgetEntryPoint.kt b/app/src/main/java/com/mhss/app/mybrain/di/TasksWidgetEntryPoint.kt new file mode 100644 index 0000000..c2c5456 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/di/TasksWidgetEntryPoint.kt @@ -0,0 +1,15 @@ +package com.mhss.app.mybrain.di + +import com.mhss.app.mybrain.domain.use_case.settings.GetSettingsUseCase +import com.mhss.app.mybrain.domain.use_case.tasks.GetAllTasksUseCase +import dagger.hilt.EntryPoint +import dagger.hilt.InstallIn +import dagger.hilt.components.SingletonComponent + +@EntryPoint +@InstallIn(SingletonComponent::class) +interface TasksWidgetEntryPoint { + fun getSettingsUseCase(): GetSettingsUseCase + + fun getAllTasksUseCase(): GetAllTasksUseCase +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/model/Alarm.kt b/app/src/main/java/com/mhss/app/mybrain/domain/model/Alarm.kt new file mode 100644 index 0000000..29d6190 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/model/Alarm.kt @@ -0,0 +1,11 @@ +package com.mhss.app.mybrain.domain.model + +import androidx.room.Entity +import androidx.room.PrimaryKey + +@Entity(tableName = "alarms") +data class Alarm( + @PrimaryKey(autoGenerate = false) + val id: Int, + val time: Long, +) diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/model/Bookmark.kt b/app/src/main/java/com/mhss/app/mybrain/domain/model/Bookmark.kt new file mode 100644 index 0000000..cf75db6 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/model/Bookmark.kt @@ -0,0 +1,18 @@ +package com.mhss.app.mybrain.domain.model + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.PrimaryKey + +@Entity(tableName = "bookmarks") +data class Bookmark( + val url: String, + val title: String = "", + val description: String = "", + @ColumnInfo(name = "created_date") + val createdDate: Long = 0L, + @ColumnInfo(name = "updated_date") + val updatedDate: Long = 0L, + @PrimaryKey(autoGenerate = true) + val id: Int = 0 +) diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/model/Calendar.kt b/app/src/main/java/com/mhss/app/mybrain/domain/model/Calendar.kt new file mode 100644 index 0000000..7fa9b15 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/model/Calendar.kt @@ -0,0 +1,9 @@ +package com.mhss.app.mybrain.domain.model + +data class Calendar( + val id: Long, + val name: String, + val account: String, + val color: Int, + val included: Boolean = true +) diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/model/CalendarEvent.kt b/app/src/main/java/com/mhss/app/mybrain/domain/model/CalendarEvent.kt new file mode 100644 index 0000000..4a33378 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/model/CalendarEvent.kt @@ -0,0 +1,15 @@ +package com.mhss.app.mybrain.domain.model + +data class CalendarEvent( + val id: Long, + val title: String, + val description: String?, + val start: Long, + val end: Long, + val location: String?, + val allDay: Boolean = false, + val color: Int = 0, + val calendarId: Long, + val recurring: Boolean = false, + val frequency: String = "", + ) diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/model/DiaryEntry.kt b/app/src/main/java/com/mhss/app/mybrain/domain/model/DiaryEntry.kt new file mode 100644 index 0000000..fb5794a --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/model/DiaryEntry.kt @@ -0,0 +1,19 @@ +package com.mhss.app.mybrain.domain.model + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.PrimaryKey +import com.mhss.app.mybrain.util.diary.Mood + +@Entity(tableName = "diary") +data class DiaryEntry( + val title: String = "", + val content: String = "", + @ColumnInfo(name = "created_date") + val createdDate: Long = 0L, + @ColumnInfo(name = "updated_date") + val updatedDate: Long = 0L, + val mood: Mood, + @PrimaryKey(autoGenerate = true) + val id: Int = 0 +) diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/model/Note.kt b/app/src/main/java/com/mhss/app/mybrain/domain/model/Note.kt new file mode 100644 index 0000000..ac65f8a --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/model/Note.kt @@ -0,0 +1,32 @@ +package com.mhss.app.mybrain.domain.model + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.ForeignKey +import androidx.room.PrimaryKey + +@Entity( + tableName = "notes", + foreignKeys = [ + ForeignKey( + entity = NoteFolder::class, + parentColumns = ["id"], + childColumns = ["folder_id"], + onDelete = ForeignKey.CASCADE, + onUpdate = ForeignKey.NO_ACTION + ) + ] +) +data class Note( + val title: String = "", + val content: String = "", + @ColumnInfo(name = "created_date") + val createdDate: Long = 0L, + @ColumnInfo(name = "updated_date") + val updatedDate: Long = 0L, + val pinned: Boolean = false, + @ColumnInfo(name = "folder_id") + val folderId: Int? = null, + @PrimaryKey(autoGenerate = true) + val id: Int = 0, +) diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/model/NoteFolder.kt b/app/src/main/java/com/mhss/app/mybrain/domain/model/NoteFolder.kt new file mode 100644 index 0000000..68fa48b --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/model/NoteFolder.kt @@ -0,0 +1,13 @@ +package com.mhss.app.mybrain.domain.model + +import androidx.room.Entity +import androidx.room.PrimaryKey + +@Entity( + tableName = "note_folders", +) +data class NoteFolder( + val name: String, + @PrimaryKey(autoGenerate = true) + val id: Int = 0 +) diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/model/NotesBackUp.kt b/app/src/main/java/com/mhss/app/mybrain/domain/model/NotesBackUp.kt new file mode 100644 index 0000000..49791e1 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/model/NotesBackUp.kt @@ -0,0 +1,6 @@ +package com.mhss.app.mybrain.domain.model + +data class NotesBackUp( + val notes: List, + val folders: List +) diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/model/SubTask.kt b/app/src/main/java/com/mhss/app/mybrain/domain/model/SubTask.kt new file mode 100644 index 0000000..434e38d --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/model/SubTask.kt @@ -0,0 +1,9 @@ +package com.mhss.app.mybrain.domain.model + +import java.util.* + +data class SubTask( + val title: String, + val isCompleted: Boolean, + val id: UUID = UUID.randomUUID() +) diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/model/Task.kt b/app/src/main/java/com/mhss/app/mybrain/domain/model/Task.kt new file mode 100644 index 0000000..deb7d30 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/model/Task.kt @@ -0,0 +1,27 @@ +package com.mhss.app.mybrain.domain.model + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.PrimaryKey + +@Entity(tableName = "tasks") +data class Task( + val title: String, + val description: String = "", + @ColumnInfo(name = "is_completed") + val isCompleted: Boolean = false, + val priority: Int = 0, + @ColumnInfo(name = "created_date") + val createdDate: Long = 0L, + @ColumnInfo(name = "updated_date") + val updatedDate: Long = 0L, + @ColumnInfo(name = "sub_tasks") + val subTasks: List = emptyList(), + val dueDate: Long = 0L, + val recurring: Boolean = false, + val frequency: Int = 0, + @ColumnInfo(name = "frequency_amount") + val frequencyAmount: Int = 1, + @PrimaryKey(autoGenerate = true) + val id: Int = 0 +) diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/repository/AlarmRepository.kt b/app/src/main/java/com/mhss/app/mybrain/domain/repository/AlarmRepository.kt new file mode 100644 index 0000000..b7aa4f2 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/repository/AlarmRepository.kt @@ -0,0 +1,14 @@ +package com.mhss.app.mybrain.domain.repository + +import com.mhss.app.mybrain.domain.model.Alarm + +interface AlarmRepository { + + suspend fun getAlarms(): List + + suspend fun insertAlarm(alarm: Alarm) + + suspend fun deleteAlarm(alarm: Alarm) + + suspend fun deleteAlarm(id: Int) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/repository/BookmarkRepository.kt b/app/src/main/java/com/mhss/app/mybrain/domain/repository/BookmarkRepository.kt new file mode 100644 index 0000000..0c5f0d7 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/repository/BookmarkRepository.kt @@ -0,0 +1,19 @@ +package com.mhss.app.mybrain.domain.repository + +import com.mhss.app.mybrain.domain.model.Bookmark +import kotlinx.coroutines.flow.Flow + +interface BookmarkRepository { + + fun getAllBookmarks(): Flow> + + suspend fun getBookmark(id: Int): Bookmark + + suspend fun searchBookmarks(query: String): List + + suspend fun addBookmark(bookmark: Bookmark) + + suspend fun deleteBookmark(bookmark: Bookmark) + + suspend fun updateBookmark(bookmark: Bookmark) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/repository/CalendarRepository.kt b/app/src/main/java/com/mhss/app/mybrain/domain/repository/CalendarRepository.kt new file mode 100644 index 0000000..ed9587c --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/repository/CalendarRepository.kt @@ -0,0 +1,19 @@ +package com.mhss.app.mybrain.domain.repository + +import com.mhss.app.mybrain.domain.model.Calendar +import com.mhss.app.mybrain.domain.model.CalendarEvent + +interface CalendarRepository { + + suspend fun getEvents(): List + + suspend fun getCalendars(): List + + suspend fun addEvent(event: CalendarEvent) + + suspend fun deleteEvent(event: CalendarEvent) + + suspend fun updateEvent(event: CalendarEvent) + + suspend fun createCalendar() +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/repository/DiaryRepository.kt b/app/src/main/java/com/mhss/app/mybrain/domain/repository/DiaryRepository.kt new file mode 100644 index 0000000..0202ac6 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/repository/DiaryRepository.kt @@ -0,0 +1,20 @@ +package com.mhss.app.mybrain.domain.repository + +import com.mhss.app.mybrain.domain.model.DiaryEntry +import kotlinx.coroutines.flow.Flow + +interface DiaryRepository { + + fun getAllEntries(): Flow> + + suspend fun getEntry(id: Int): DiaryEntry + + suspend fun searchEntries(title: String): List + + suspend fun addEntry(diary: DiaryEntry) + + suspend fun updateEntry(diary: DiaryEntry) + + suspend fun deleteEntry(diary: DiaryEntry) + +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/repository/NoteRepository.kt b/app/src/main/java/com/mhss/app/mybrain/domain/repository/NoteRepository.kt new file mode 100644 index 0000000..c8cbc7f --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/repository/NoteRepository.kt @@ -0,0 +1,31 @@ +package com.mhss.app.mybrain.domain.repository + +import com.mhss.app.mybrain.domain.model.Note +import com.mhss.app.mybrain.domain.model.NoteFolder +import kotlinx.coroutines.flow.Flow + +interface NoteRepository { + + fun getAllNotes(): Flow> + + suspend fun getNote(id: Int): Note + + suspend fun searchNotes(query: String): List + + fun getNotesByFolder(folderId: Int): Flow> + + suspend fun addNote(note: Note) + + suspend fun updateNote(note: Note) + + suspend fun deleteNote(note: Note) + + suspend fun insertNoteFolder(folder: NoteFolder) + + suspend fun updateNoteFolder(folder: NoteFolder) + + suspend fun deleteNoteFolder(folder: NoteFolder) + + fun getAllNoteFolders(): Flow> + +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/repository/RoomBackupRepository.kt b/app/src/main/java/com/mhss/app/mybrain/domain/repository/RoomBackupRepository.kt new file mode 100644 index 0000000..7d1386e --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/repository/RoomBackupRepository.kt @@ -0,0 +1,10 @@ +package com.mhss.app.mybrain.domain.repository + +import android.net.Uri + +interface RoomBackupRepository { + + suspend fun exportDatabase(directoryUri: Uri, encrypted: Boolean, password: String): Boolean + + suspend fun importDatabase(fileUri: Uri, encrypted: Boolean, password: String): Boolean +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/repository/SettingsRepository.kt b/app/src/main/java/com/mhss/app/mybrain/domain/repository/SettingsRepository.kt new file mode 100644 index 0000000..559768a --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/repository/SettingsRepository.kt @@ -0,0 +1,12 @@ +package com.mhss.app.mybrain.domain.repository + +import androidx.datastore.preferences.core.Preferences +import kotlinx.coroutines.flow.Flow + +interface SettingsRepository { + + suspend fun saveSettings(key: Preferences.Key, value: T) + + fun getSettings(key: Preferences.Key, defaultValue: T): Flow + +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/repository/TaskRepository.kt b/app/src/main/java/com/mhss/app/mybrain/domain/repository/TaskRepository.kt new file mode 100644 index 0000000..fd447b1 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/repository/TaskRepository.kt @@ -0,0 +1,22 @@ +package com.mhss.app.mybrain.domain.repository + +import com.mhss.app.mybrain.domain.model.Task +import kotlinx.coroutines.flow.Flow + +interface TaskRepository { + + fun getAllTasks(): Flow> + + suspend fun getTaskById(id: Int): Task + + fun searchTasks(title: String): Flow> + + suspend fun insertTask(task: Task): Long + + suspend fun updateTask(task: Task) + + suspend fun completeTask(id: Int, completed: Boolean) + + suspend fun deleteTask(task: Task) + +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/alarm/AddAlarmUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/alarm/AddAlarmUseCase.kt new file mode 100644 index 0000000..3fe4b61 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/alarm/AddAlarmUseCase.kt @@ -0,0 +1,19 @@ +package com.mhss.app.mybrain.domain.use_case.alarm + +import android.app.AlarmManager +import android.content.Context +import com.mhss.app.mybrain.domain.model.Alarm +import com.mhss.app.mybrain.domain.repository.AlarmRepository +import com.mhss.app.mybrain.util.alarms.scheduleAlarm +import javax.inject.Inject + +class AddAlarmUseCase @Inject constructor( + private val alarmRepository: AlarmRepository, + private val context: Context +) { + suspend operator fun invoke(alarm: Alarm) { + val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager + alarmManager.scheduleAlarm(alarm, context) + alarmRepository.insertAlarm(alarm) + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/alarm/DeleteAlarmUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/alarm/DeleteAlarmUseCase.kt new file mode 100644 index 0000000..56c95d2 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/alarm/DeleteAlarmUseCase.kt @@ -0,0 +1,18 @@ +package com.mhss.app.mybrain.domain.use_case.alarm + +import android.app.AlarmManager +import android.content.Context +import com.mhss.app.mybrain.domain.repository.AlarmRepository +import com.mhss.app.mybrain.util.alarms.cancelAlarm +import javax.inject.Inject + +class DeleteAlarmUseCase @Inject constructor( + private val alarmRepository: AlarmRepository, + private val context: Context +) { + suspend operator fun invoke(alarmId: Int) { + val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager + alarmManager.cancelAlarm(alarmId, context) + alarmRepository.deleteAlarm(alarmId) + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/alarm/GetAllAlarmsUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/alarm/GetAllAlarmsUseCase.kt new file mode 100644 index 0000000..13d504a --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/alarm/GetAllAlarmsUseCase.kt @@ -0,0 +1,10 @@ +package com.mhss.app.mybrain.domain.use_case.alarm + +import com.mhss.app.mybrain.domain.repository.AlarmRepository +import javax.inject.Inject + +class GetAllAlarmsUseCase @Inject constructor( + private val alarmRepository: AlarmRepository +) { + suspend operator fun invoke() = alarmRepository.getAlarms() +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/bookmarks/AddBookmarkUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/bookmarks/AddBookmarkUseCase.kt new file mode 100644 index 0000000..c07584b --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/bookmarks/AddBookmarkUseCase.kt @@ -0,0 +1,11 @@ +package com.mhss.app.mybrain.domain.use_case.bookmarks + +import com.mhss.app.mybrain.domain.model.Bookmark +import com.mhss.app.mybrain.domain.repository.BookmarkRepository +import javax.inject.Inject + +class AddBookmarkUseCase @Inject constructor( + private val bookmarkRepository: BookmarkRepository +) { + suspend operator fun invoke(bookmark: Bookmark) = bookmarkRepository.addBookmark(bookmark) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/bookmarks/DeleteBookmarkUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/bookmarks/DeleteBookmarkUseCase.kt new file mode 100644 index 0000000..d845395 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/bookmarks/DeleteBookmarkUseCase.kt @@ -0,0 +1,11 @@ +package com.mhss.app.mybrain.domain.use_case.bookmarks + +import com.mhss.app.mybrain.domain.model.Bookmark +import com.mhss.app.mybrain.domain.repository.BookmarkRepository +import javax.inject.Inject + +class DeleteBookmarkUseCase @Inject constructor( + private val bookmarkRepository: BookmarkRepository +) { + suspend operator fun invoke(bookmark: Bookmark) = bookmarkRepository.deleteBookmark(bookmark) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/bookmarks/GetAllBookmarksUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/bookmarks/GetAllBookmarksUseCase.kt new file mode 100644 index 0000000..e4b2d57 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/bookmarks/GetAllBookmarksUseCase.kt @@ -0,0 +1,36 @@ +package com.mhss.app.mybrain.domain.use_case.bookmarks + +import com.mhss.app.mybrain.domain.model.Bookmark +import com.mhss.app.mybrain.domain.repository.BookmarkRepository +import com.mhss.app.mybrain.util.settings.Order +import com.mhss.app.mybrain.util.settings.OrderType +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.map +import javax.inject.Inject + +class GetAllBookmarksUseCase @Inject constructor( + private val bookmarksRepository: BookmarkRepository +) { + operator fun invoke(order: Order) : Flow>{ + return bookmarksRepository.getAllBookmarks().map { bookmarks -> + when (order.orderType) { + is OrderType.ASC -> { + when (order) { + is Order.Alphabetical -> bookmarks.sortedBy { it.title } + is Order.DateCreated -> bookmarks.sortedBy { it.createdDate } + is Order.DateModified -> bookmarks.sortedBy { it.updatedDate } + else -> bookmarks.sortedBy { it.updatedDate } + } + } + is OrderType.DESC -> { + when (order) { + is Order.Alphabetical -> bookmarks.sortedByDescending { it.title } + is Order.DateCreated -> bookmarks.sortedByDescending { it.createdDate } + is Order.DateModified -> bookmarks.sortedByDescending { it.updatedDate } + else -> bookmarks.sortedByDescending { it.updatedDate } + } + } + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/bookmarks/GetBookmarkUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/bookmarks/GetBookmarkUseCase.kt new file mode 100644 index 0000000..f3f460f --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/bookmarks/GetBookmarkUseCase.kt @@ -0,0 +1,10 @@ +package com.mhss.app.mybrain.domain.use_case.bookmarks + +import com.mhss.app.mybrain.domain.repository.BookmarkRepository +import javax.inject.Inject + +class GetBookmarkUseCase @Inject constructor( + private val bookmarkRepository: BookmarkRepository +) { + suspend operator fun invoke(id: Int) = bookmarkRepository.getBookmark(id) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/bookmarks/SearchBookmarksUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/bookmarks/SearchBookmarksUseCase.kt new file mode 100644 index 0000000..d811fae --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/bookmarks/SearchBookmarksUseCase.kt @@ -0,0 +1,10 @@ +package com.mhss.app.mybrain.domain.use_case.bookmarks + +import com.mhss.app.mybrain.domain.repository.BookmarkRepository +import javax.inject.Inject + +class SearchBookmarksUseCase @Inject constructor( + private val bookmarksRepository: BookmarkRepository +) { + suspend operator fun invoke(query: String) = bookmarksRepository.searchBookmarks(query) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/bookmarks/UpdateBookmarkUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/bookmarks/UpdateBookmarkUseCase.kt new file mode 100644 index 0000000..9f269f0 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/bookmarks/UpdateBookmarkUseCase.kt @@ -0,0 +1,11 @@ +package com.mhss.app.mybrain.domain.use_case.bookmarks + +import com.mhss.app.mybrain.domain.model.Bookmark +import com.mhss.app.mybrain.domain.repository.BookmarkRepository +import javax.inject.Inject + +class UpdateBookmarkUseCase @Inject constructor( + private val bookmarkRepository: BookmarkRepository +) { + suspend operator fun invoke(bookmark: Bookmark) = bookmarkRepository.updateBookmark(bookmark) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/calendar/AddCalendarEventUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/calendar/AddCalendarEventUseCase.kt new file mode 100644 index 0000000..0e3b1cb --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/calendar/AddCalendarEventUseCase.kt @@ -0,0 +1,26 @@ +package com.mhss.app.mybrain.domain.use_case.calendar + +import android.content.Context +import androidx.glance.appwidget.updateAll +import com.mhss.app.mybrain.domain.model.CalendarEvent +import com.mhss.app.mybrain.domain.repository.CalendarRepository +import com.mhss.app.mybrain.presentation.glance_widgets.CalendarHomeWidget +import javax.inject.Inject + +class AddCalendarEventUseCase @Inject constructor( + private val calendarEventRepository: CalendarRepository, + private val context: Context +) { + suspend operator fun invoke(calendarEvent: CalendarEvent) { + val calendars = calendarEventRepository.getCalendars() + if (calendars.isNotEmpty()) { + calendarEventRepository.addEvent(calendarEvent) + } else { + calendarEventRepository.createCalendar() + val calendar = calendarEventRepository.getCalendars().first() + calendarEventRepository.addEvent(calendarEvent.copy(calendarId = calendar.id)) + } + CalendarHomeWidget().updateAll(context) + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/calendar/DeleteCalendarEventUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/calendar/DeleteCalendarEventUseCase.kt new file mode 100644 index 0000000..5c43816 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/calendar/DeleteCalendarEventUseCase.kt @@ -0,0 +1,18 @@ +package com.mhss.app.mybrain.domain.use_case.calendar + +import android.content.Context +import androidx.glance.appwidget.updateAll +import com.mhss.app.mybrain.domain.model.CalendarEvent +import com.mhss.app.mybrain.domain.repository.CalendarRepository +import com.mhss.app.mybrain.presentation.glance_widgets.CalendarHomeWidget +import javax.inject.Inject + +class DeleteCalendarEventUseCase @Inject constructor( + private val calendarRepository: CalendarRepository, + private val context: Context +) { + suspend operator fun invoke(event: CalendarEvent) { + calendarRepository.deleteEvent(event) + CalendarHomeWidget().updateAll(context) + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/calendar/GetAllCalendarsUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/calendar/GetAllCalendarsUseCase.kt new file mode 100644 index 0000000..f6caad7 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/calendar/GetAllCalendarsUseCase.kt @@ -0,0 +1,13 @@ +package com.mhss.app.mybrain.domain.use_case.calendar + +import com.mhss.app.mybrain.domain.model.Calendar +import com.mhss.app.mybrain.domain.repository.CalendarRepository +import javax.inject.Inject + +class GetAllCalendarsUseCase @Inject constructor( + private val calendarRepository: CalendarRepository +) { + suspend operator fun invoke(excluded: List): Map> { + return calendarRepository.getCalendars().map { it.copy(included = (it.id.toInt() !in excluded)) }.groupBy { it.account } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/calendar/GetAllEventsUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/calendar/GetAllEventsUseCase.kt new file mode 100644 index 0000000..2627d16 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/calendar/GetAllEventsUseCase.kt @@ -0,0 +1,28 @@ +package com.mhss.app.mybrain.domain.use_case.calendar + +import com.mhss.app.mybrain.domain.model.CalendarEvent +import com.mhss.app.mybrain.domain.repository.CalendarRepository +import com.mhss.app.mybrain.util.date.formatDateForMapping +import javax.inject.Inject + +class GetAllEventsUseCase @Inject constructor( + private val calendarRepository: CalendarRepository +) { + suspend operator fun invoke(excluded: List, fromWidget: Boolean = false): Map> { + val events = try { + calendarRepository.getEvents() + .filter { it.calendarId.toInt() !in excluded } + } catch (e: Exception) { + return emptyMap() + } + return if (fromWidget) + events.take(30).groupBy { event -> + event.start.formatDateForMapping() + } + else + events.groupBy { event -> + event.start.formatDateForMapping() + } + + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/calendar/UpdateCalendarEventUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/calendar/UpdateCalendarEventUseCase.kt new file mode 100644 index 0000000..b289654 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/calendar/UpdateCalendarEventUseCase.kt @@ -0,0 +1,18 @@ +package com.mhss.app.mybrain.domain.use_case.calendar + +import android.content.Context +import androidx.glance.appwidget.updateAll +import com.mhss.app.mybrain.domain.model.CalendarEvent +import com.mhss.app.mybrain.domain.repository.CalendarRepository +import com.mhss.app.mybrain.presentation.glance_widgets.CalendarHomeWidget +import javax.inject.Inject + +class UpdateCalendarEventUseCase @Inject constructor( + private val calendarRepository: CalendarRepository, + private val context: Context +) { + suspend operator fun invoke(event: CalendarEvent) { + calendarRepository.updateEvent(event) + CalendarHomeWidget().updateAll(context) + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/diary/AddDiaryEntryUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/diary/AddDiaryEntryUseCase.kt new file mode 100644 index 0000000..1d7675e --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/diary/AddDiaryEntryUseCase.kt @@ -0,0 +1,11 @@ +package com.mhss.app.mybrain.domain.use_case.diary + +import com.mhss.app.mybrain.domain.model.DiaryEntry +import com.mhss.app.mybrain.domain.repository.DiaryRepository +import javax.inject.Inject + +class AddDiaryEntryUseCase @Inject constructor( + private val diaryRepository: DiaryRepository +) { + suspend operator fun invoke(entry: DiaryEntry) = diaryRepository.addEntry(entry) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/diary/DeleteDiaryEntryUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/diary/DeleteDiaryEntryUseCase.kt new file mode 100644 index 0000000..03c1384 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/diary/DeleteDiaryEntryUseCase.kt @@ -0,0 +1,11 @@ +package com.mhss.app.mybrain.domain.use_case.diary + +import com.mhss.app.mybrain.domain.model.DiaryEntry +import com.mhss.app.mybrain.domain.repository.DiaryRepository +import javax.inject.Inject + +class DeleteDiaryEntryUseCase @Inject constructor( + private val diaryRepository: DiaryRepository +) { + suspend operator fun invoke(entry: DiaryEntry) = diaryRepository.deleteEntry(entry) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/diary/GetAllEntriesUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/diary/GetAllEntriesUseCase.kt new file mode 100644 index 0000000..9b86730 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/diary/GetAllEntriesUseCase.kt @@ -0,0 +1,36 @@ +package com.mhss.app.mybrain.domain.use_case.diary + +import com.mhss.app.mybrain.domain.model.DiaryEntry +import com.mhss.app.mybrain.domain.repository.DiaryRepository +import com.mhss.app.mybrain.util.settings.Order +import com.mhss.app.mybrain.util.settings.OrderType +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.map +import javax.inject.Inject + +class GetAllEntriesUseCase @Inject constructor( + private val diaryRepository: DiaryRepository +) { + operator fun invoke(order: Order) : Flow> { + return diaryRepository.getAllEntries().map { entries -> + when (order.orderType) { + is OrderType.ASC -> { + when (order) { + is Order.Alphabetical -> entries.sortedBy { it.title } + is Order.DateCreated -> entries.sortedBy { it.createdDate } + is Order.DateModified -> entries.sortedBy { it.updatedDate } + else -> entries.sortedBy { it.updatedDate } + } + } + is OrderType.DESC -> { + when (order) { + is Order.Alphabetical -> entries.sortedByDescending { it.title } + is Order.DateCreated -> entries.sortedByDescending { it.createdDate } + is Order.DateModified -> entries.sortedByDescending { it.updatedDate } + else -> entries.sortedByDescending { it.updatedDate } + } + } + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/diary/GetDiaryEntryUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/diary/GetDiaryEntryUseCase.kt new file mode 100644 index 0000000..fe1df30 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/diary/GetDiaryEntryUseCase.kt @@ -0,0 +1,10 @@ +package com.mhss.app.mybrain.domain.use_case.diary + +import com.mhss.app.mybrain.domain.repository.DiaryRepository +import javax.inject.Inject + +class GetDiaryEntryUseCase @Inject constructor( + private val diaryRepository: DiaryRepository +) { + suspend operator fun invoke(id: Int) = diaryRepository.getEntry(id) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/diary/GetDiaryForChartUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/diary/GetDiaryForChartUseCase.kt new file mode 100644 index 0000000..3ceb5e7 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/diary/GetDiaryForChartUseCase.kt @@ -0,0 +1,23 @@ +package com.mhss.app.mybrain.domain.use_case.diary + +import com.mhss.app.mybrain.domain.model.DiaryEntry +import com.mhss.app.mybrain.domain.repository.DiaryRepository +import com.mhss.app.mybrain.util.date.inTheLast30Days +import com.mhss.app.mybrain.util.date.inTheLastYear +import kotlinx.coroutines.flow.first +import javax.inject.Inject + +class GetDiaryForChartUseCase @Inject constructor( + private val diaryRepository: DiaryRepository +) { + suspend operator fun invoke(monthly: Boolean) : List{ + return diaryRepository + .getAllEntries() + .first() + .filter { + if (monthly) it.createdDate.inTheLast30Days() + else it.createdDate.inTheLastYear() + } + .sortedBy { it.createdDate } + } +} diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/diary/SearchEntriesUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/diary/SearchEntriesUseCase.kt new file mode 100644 index 0000000..915abc9 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/diary/SearchEntriesUseCase.kt @@ -0,0 +1,10 @@ +package com.mhss.app.mybrain.domain.use_case.diary + +import com.mhss.app.mybrain.domain.repository.DiaryRepository +import javax.inject.Inject + +class SearchEntriesUseCase @Inject constructor( + private val repository: DiaryRepository +) { + suspend operator fun invoke(query: String) = repository.searchEntries(query) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/diary/UpdateDiaryEntryUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/diary/UpdateDiaryEntryUseCase.kt new file mode 100644 index 0000000..32c870a --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/diary/UpdateDiaryEntryUseCase.kt @@ -0,0 +1,11 @@ +package com.mhss.app.mybrain.domain.use_case.diary + +import com.mhss.app.mybrain.domain.model.DiaryEntry +import com.mhss.app.mybrain.domain.repository.DiaryRepository +import javax.inject.Inject + +class UpdateDiaryEntryUseCase @Inject constructor( + private val diaryRepository: DiaryRepository +) { + suspend operator fun invoke(entry: DiaryEntry) = diaryRepository.updateEntry(entry) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/AddNoteFolderUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/AddNoteFolderUseCase.kt new file mode 100644 index 0000000..1a55a90 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/AddNoteFolderUseCase.kt @@ -0,0 +1,11 @@ +package com.mhss.app.mybrain.domain.use_case.notes + +import com.mhss.app.mybrain.domain.model.NoteFolder +import com.mhss.app.mybrain.domain.repository.NoteRepository +import javax.inject.Inject + +class AddNoteFolderUseCass @Inject constructor( + private val noteRepository: NoteRepository +) { + suspend operator fun invoke(folder: NoteFolder) = noteRepository.insertNoteFolder(folder) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/AddNoteUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/AddNoteUseCase.kt new file mode 100644 index 0000000..a2d688b --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/AddNoteUseCase.kt @@ -0,0 +1,11 @@ +package com.mhss.app.mybrain.domain.use_case.notes + +import com.mhss.app.mybrain.domain.model.Note +import com.mhss.app.mybrain.domain.repository.NoteRepository +import javax.inject.Inject + +class AddNoteUseCase @Inject constructor( + private val notesRepository: NoteRepository +) { + suspend operator fun invoke(note: Note) = notesRepository.addNote(note) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/DeleteNoteFolderUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/DeleteNoteFolderUseCase.kt new file mode 100644 index 0000000..756b208 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/DeleteNoteFolderUseCase.kt @@ -0,0 +1,11 @@ +package com.mhss.app.mybrain.domain.use_case.notes + +import com.mhss.app.mybrain.domain.model.NoteFolder +import com.mhss.app.mybrain.domain.repository.NoteRepository +import javax.inject.Inject + +class DeleteNoteFolderUseCass @Inject constructor( + private val noteRepository: NoteRepository +) { + suspend operator fun invoke(folder: NoteFolder) = noteRepository.deleteNoteFolder(folder) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/DeleteNoteUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/DeleteNoteUseCase.kt new file mode 100644 index 0000000..e7ddc08 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/DeleteNoteUseCase.kt @@ -0,0 +1,11 @@ +package com.mhss.app.mybrain.domain.use_case.notes + +import com.mhss.app.mybrain.domain.model.Note +import com.mhss.app.mybrain.domain.repository.NoteRepository +import javax.inject.Inject + +class DeleteNoteUseCase @Inject constructor( + private val repository: NoteRepository +) { + suspend operator fun invoke(note: Note) = repository.deleteNote(note) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/GetAllNoteFoldersUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/GetAllNoteFoldersUseCase.kt new file mode 100644 index 0000000..0dda0f0 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/GetAllNoteFoldersUseCase.kt @@ -0,0 +1,10 @@ +package com.mhss.app.mybrain.domain.use_case.notes + +import com.mhss.app.mybrain.domain.repository.NoteRepository +import javax.inject.Inject + +class GetAllNoteFoldersUseCase @Inject constructor( + private val repository: NoteRepository +) { + suspend operator fun invoke() = repository.getAllNoteFolders() +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/GetAllNotesUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/GetAllNotesUseCase.kt new file mode 100644 index 0000000..7f47ee1 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/GetAllNotesUseCase.kt @@ -0,0 +1,37 @@ +package com.mhss.app.mybrain.domain.use_case.notes + +import com.mhss.app.mybrain.domain.model.Note +import com.mhss.app.mybrain.domain.repository.NoteRepository +import com.mhss.app.mybrain.util.settings.Order +import com.mhss.app.mybrain.util.settings.OrderType +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.map +import javax.inject.Inject + +class GetAllNotesUseCase @Inject constructor( + private val notesRepository: NoteRepository +) { + operator fun invoke(order: Order) : Flow> { + return notesRepository.getAllNotes().map { list -> + when (order.orderType) { + is OrderType.ASC -> { + when (order) { + is Order.Alphabetical -> list.sortedWith(compareBy({!it.pinned}, { it.title })) + is Order.DateCreated -> list.sortedWith(compareBy({!it.pinned}, { it.createdDate })) + is Order.DateModified -> list.sortedWith(compareBy({!it.pinned}, { it.updatedDate })) + else -> list.sortedWith(compareBy({!it.pinned}, { it.updatedDate })) + } + } + is OrderType.DESC -> { + when (order) { + is Order.Alphabetical -> list.sortedWith(compareBy({it.pinned}, { it.title })).reversed() + is Order.DateCreated -> list.sortedWith(compareBy({it.pinned}, { it.createdDate })).reversed() + is Order.DateModified -> list.sortedWith(compareBy({it.pinned}, { it.updatedDate })).reversed() + else -> list.sortedWith(compareBy({it.pinned}, { it.updatedDate })).reversed() + } + } + } + } + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/GetNoteUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/GetNoteUseCase.kt new file mode 100644 index 0000000..1159da7 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/GetNoteUseCase.kt @@ -0,0 +1,10 @@ +package com.mhss.app.mybrain.domain.use_case.notes + +import com.mhss.app.mybrain.domain.repository.NoteRepository +import javax.inject.Inject + +class GetNoteUseCase @Inject constructor( + private val notesRepository: NoteRepository +) { + suspend operator fun invoke(id: Int) = notesRepository.getNote(id) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/GetNotesByFolderUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/GetNotesByFolderUseCase.kt new file mode 100644 index 0000000..f8f6224 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/GetNotesByFolderUseCase.kt @@ -0,0 +1,32 @@ +package com.mhss.app.mybrain.domain.use_case.notes + +import com.mhss.app.mybrain.domain.repository.NoteRepository +import com.mhss.app.mybrain.util.settings.Order +import com.mhss.app.mybrain.util.settings.OrderType +import kotlinx.coroutines.flow.map +import javax.inject.Inject + +class GetNotesByFolderUseCase @Inject constructor( + private val notesRepository: NoteRepository +) { + operator fun invoke(folderId: Int, order: Order) = notesRepository.getNotesByFolder(folderId).map { list -> + when (order.orderType) { + is OrderType.ASC -> { + when (order) { + is Order.Alphabetical -> list.sortedWith(compareBy({!it.pinned}, { it.title })) + is Order.DateCreated -> list.sortedWith(compareBy({!it.pinned}, { it.createdDate })) + is Order.DateModified -> list.sortedWith(compareBy({!it.pinned}, { it.updatedDate })) + else -> list.sortedWith(compareBy({!it.pinned}, { it.updatedDate })) + } + } + is OrderType.DESC -> { + when (order) { + is Order.Alphabetical -> list.sortedWith(compareBy({it.pinned}, { it.title })).reversed() + is Order.DateCreated -> list.sortedWith(compareBy({it.pinned}, { it.createdDate })).reversed() + is Order.DateModified -> list.sortedWith(compareBy({it.pinned}, { it.updatedDate })).reversed() + else -> list.sortedWith(compareBy({it.pinned}, { it.updatedDate })).reversed() + } + } + } + } +} diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/NoteFolderDetailsScreen.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/NoteFolderDetailsScreen.kt new file mode 100644 index 0000000..d6f6587 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/NoteFolderDetailsScreen.kt @@ -0,0 +1,245 @@ +package com.mhss.app.mybrain.domain.use_case.notes + +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.grid.GridCells +import androidx.compose.foundation.lazy.grid.LazyVerticalGrid +import androidx.compose.foundation.lazy.grid.items +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.* +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Delete +import androidx.compose.material.icons.filled.Edit +import androidx.compose.runtime.* +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.hilt.navigation.compose.hiltViewModel +import androidx.navigation.NavHostController +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.presentation.notes.NoteEvent +import com.mhss.app.mybrain.presentation.notes.NoteItem +import com.mhss.app.mybrain.presentation.notes.NotesViewModel +import com.mhss.app.mybrain.presentation.util.Screen +import com.mhss.app.mybrain.util.Constants +import com.mhss.app.mybrain.util.settings.ItemView + +@OptIn(ExperimentalFoundationApi::class) +@Composable +fun NoteFolderDetailsScreen( + navController: NavHostController, + id: Int, + viewModel: NotesViewModel = hiltViewModel() +) { + val uiState = viewModel.notesUiState + val folder = uiState.folder + + var openDeleteDialog by remember { mutableStateOf(false) } + var openEditDialog by remember { mutableStateOf(false) } + + val scaffoldState = rememberScaffoldState() + LaunchedEffect(true) {viewModel.onEvent(NoteEvent.GetFolderNotes(id)) } + LaunchedEffect(uiState) { + if (viewModel.notesUiState.navigateUp) { + navController.popBackStack(route = Screen.NotesScreen.route, inclusive = false) + } + if (uiState.error != null) { + scaffoldState.snackbarHostState.showSnackbar( + uiState.error + ) + viewModel.onEvent(NoteEvent.ErrorDisplayed) + } + } + Scaffold( + scaffoldState = scaffoldState, + topBar = { + TopAppBar( + title = { + Text( + text = folder?.name ?: "", + style = MaterialTheme.typography.h5.copy(fontWeight = FontWeight.Bold) + ) + }, + backgroundColor = MaterialTheme.colors.background, + elevation = 0.dp, + actions = { + IconButton(onClick = { openDeleteDialog = true }) { + Icon(Icons.Default.Delete, stringResource(R.string.delete_folder)) + } + IconButton(onClick = { openEditDialog = true }) { + Icon(Icons.Default.Edit, stringResource(R.string.delete_folder)) + } + } + ) + }, + floatingActionButton = { + FloatingActionButton( + onClick = { + navController.navigate( + Screen.NoteDetailsScreen.route.replace( + "{${Constants.NOTE_ID_ARG}}", + "${-1}" + ).replace( + "{${Constants.FOLDER_ID}}", + "$id" + ) + ) + }, + backgroundColor = MaterialTheme.colors.primary, + ) { + Icon( + modifier = Modifier.size(25.dp), + painter = painterResource(R.drawable.ic_add), + contentDescription = stringResource(R.string.add_note), + tint = Color.White + ) + } + } + ) { _ -> + if (uiState.noteView == ItemView.LIST) { + LazyColumn( + verticalArrangement = Arrangement.spacedBy(8.dp), + contentPadding = PaddingValues( + top = 12.dp, + bottom = 24.dp, + start = 12.dp, + end = 12.dp + ) + ) { + items(uiState.folderNotes, key = { it.id }) { note -> + NoteItem( + note = note, + onClick = { + navController.navigate( + Screen.NoteDetailsScreen.route.replace( + "{${Constants.NOTE_ID_ARG}}", + "${note.id}" + ).replace( + "{${Constants.FOLDER_ID}}", + "-1" + ) + ) + } + ) + } + } + } else { + LazyVerticalGrid( + columns = GridCells.Adaptive(150.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), + contentPadding = PaddingValues( + top = 12.dp, + bottom = 24.dp, + start = 12.dp, + end = 12.dp + ) + ) { + items(uiState.folderNotes) { note -> + key(note.id) { + NoteItem( + note = note, + onClick = { + navController.navigate( + Screen.NoteDetailsScreen.route.replace( + "{${Constants.NOTE_ID_ARG}}", + "${note.id}" + ).replace( + "{${Constants.FOLDER_ID}}", + "-1" + ) + ) + }, + modifier = Modifier.animateItemPlacement().height(220.dp) + ) + } + } + } + } + if (openDeleteDialog) + AlertDialog( + shape = RoundedCornerShape(25.dp), + onDismissRequest = { openDeleteDialog = false }, + title = { Text(stringResource(R.string.delete_note_confirmation_title)) }, + text = { + Text( + stringResource( + R.string.delete_folder_confirmation_message, + ) + ) + }, + confirmButton = { + Button( + colors = ButtonDefaults.buttonColors(backgroundColor = Color.Red), + shape = RoundedCornerShape(25.dp), + onClick = { + viewModel.onEvent(NoteEvent.DeleteFolder(folder!!)) + openDeleteDialog = false + }, + ) { + Text(stringResource(R.string.delete_folder), color = Color.White) + } + }, + dismissButton = { + Button( + shape = RoundedCornerShape(25.dp), + onClick = { + openDeleteDialog = false + }) { + Text(stringResource(R.string.cancel), color = Color.White) + } + } + ) + if (openEditDialog){ + var name by remember { mutableStateOf(folder?.name ?: "") } + AlertDialog( + onDismissRequest = { openEditDialog = false }, + title = { + Text( + text = stringResource(id = R.string.edit_folder), + style = MaterialTheme.typography.h6 + ) + }, + text = { + TextField( + value = name, + onValueChange = { name = it }, + label = { + Text( + text = stringResource(id = R.string.name), + style = MaterialTheme.typography.body1 + ) + }, + ) + }, + confirmButton = { + Button( + shape = RoundedCornerShape(25.dp), + onClick = { + viewModel.onEvent(NoteEvent.UpdateFolder(folder?.copy(name = name)!!)) + openEditDialog = false + }, + ) { + Text(stringResource(R.string.save), color = Color.White) + } + }, + dismissButton = { + TextButton( + shape = RoundedCornerShape(25.dp), + onClick = { openEditDialog = false }, + ) { + Text(stringResource(R.string.cancel), color = Color.White) + } + } + ) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/SearchNotesUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/SearchNotesUseCase.kt new file mode 100644 index 0000000..f3ced34 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/SearchNotesUseCase.kt @@ -0,0 +1,10 @@ +package com.mhss.app.mybrain.domain.use_case.notes + +import com.mhss.app.mybrain.domain.repository.NoteRepository +import javax.inject.Inject + +class SearchNotesUseCase @Inject constructor( + private val notesRepository: NoteRepository +) { + suspend operator fun invoke(query: String) = notesRepository.searchNotes(query) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/UpdateNoteFolderUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/UpdateNoteFolderUseCase.kt new file mode 100644 index 0000000..9e0fad6 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/UpdateNoteFolderUseCase.kt @@ -0,0 +1,11 @@ +package com.mhss.app.mybrain.domain.use_case.notes + +import com.mhss.app.mybrain.domain.model.NoteFolder +import com.mhss.app.mybrain.domain.repository.NoteRepository +import javax.inject.Inject + +class UpdateNoteFolderUseCass @Inject constructor( +private val noteRepository: NoteRepository +) { + suspend operator fun invoke(folder: NoteFolder) = noteRepository.updateNoteFolder(folder) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/UpdateNoteUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/UpdateNoteUseCase.kt new file mode 100644 index 0000000..1bc25c7 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/notes/UpdateNoteUseCase.kt @@ -0,0 +1,11 @@ +package com.mhss.app.mybrain.domain.use_case.notes + +import com.mhss.app.mybrain.domain.model.Note +import com.mhss.app.mybrain.domain.repository.NoteRepository +import javax.inject.Inject + +class UpdateNoteUseCase @Inject constructor( + private val notesRepository: NoteRepository +) { + suspend operator fun invoke(note: Note) = notesRepository.updateNote(note) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/settings/GetSettingsUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/settings/GetSettingsUseCase.kt new file mode 100644 index 0000000..a23196e --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/settings/GetSettingsUseCase.kt @@ -0,0 +1,11 @@ +package com.mhss.app.mybrain.domain.use_case.settings + +import androidx.datastore.preferences.core.Preferences +import com.mhss.app.mybrain.domain.repository.SettingsRepository +import javax.inject.Inject + +class GetSettingsUseCase @Inject constructor( + private val settingsRepository: SettingsRepository +) { + operator fun invoke(key: Preferences.Key, defaultValue: T) = settingsRepository.getSettings(key, defaultValue) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/settings/SaveSettingsUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/settings/SaveSettingsUseCase.kt new file mode 100644 index 0000000..bceb40a --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/settings/SaveSettingsUseCase.kt @@ -0,0 +1,11 @@ +package com.mhss.app.mybrain.domain.use_case.settings + +import androidx.datastore.preferences.core.Preferences +import com.mhss.app.mybrain.domain.repository.SettingsRepository +import javax.inject.Inject + +class SaveSettingsUseCase @Inject constructor( + private val settingsRepository: SettingsRepository +) { + suspend operator fun invoke(key: Preferences.Key, value: T) = settingsRepository.saveSettings(key, value) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/tasks/AddTaskFromShareActivity.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/tasks/AddTaskFromShareActivity.kt new file mode 100644 index 0000000..394f05f --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/tasks/AddTaskFromShareActivity.kt @@ -0,0 +1,43 @@ +package com.mhss.app.mybrain.domain.use_case.tasks + +import android.content.Intent +import android.os.Bundle +import android.widget.Toast +import androidx.activity.ComponentActivity +import androidx.activity.viewModels +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.domain.model.Task +import com.mhss.app.mybrain.presentation.tasks.TaskEvent +import com.mhss.app.mybrain.presentation.tasks.TasksViewModel +import dagger.hilt.android.AndroidEntryPoint + +@AndroidEntryPoint +class AddTaskFromShareActivity : ComponentActivity() { + + private val viewModel: TasksViewModel by viewModels() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + if (intent != null) { + if (intent.action == Intent.ACTION_SEND && intent.type == "text/plain") { + val title = intent.getStringExtra(Intent.EXTRA_TEXT) + if (!title.isNullOrBlank()) { + viewModel.onEvent( + TaskEvent.AddTask( + Task( + title = title, + createdDate = System.currentTimeMillis(), + updatedDate = System.currentTimeMillis() + ) + ) + ) + Toast.makeText(this, getString(R.string.added_task), Toast.LENGTH_SHORT) + .show() + } else + Toast.makeText(this, getString(R.string.error_empty_title), Toast.LENGTH_SHORT) + .show() + } + } + finish() + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/tasks/AddTaskUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/tasks/AddTaskUseCase.kt new file mode 100644 index 0000000..2a3bb13 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/tasks/AddTaskUseCase.kt @@ -0,0 +1,13 @@ +package com.mhss.app.mybrain.domain.use_case.tasks + +import com.mhss.app.mybrain.domain.model.Task +import com.mhss.app.mybrain.domain.repository.TaskRepository +import javax.inject.Inject + +class AddTaskUseCase @Inject constructor( + private val tasksRepository: TaskRepository, +) { + suspend operator fun invoke(task: Task): Long { + return tasksRepository.insertTask(task) + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/tasks/DeleteTaskUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/tasks/DeleteTaskUseCase.kt new file mode 100644 index 0000000..0650721 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/tasks/DeleteTaskUseCase.kt @@ -0,0 +1,13 @@ +package com.mhss.app.mybrain.domain.use_case.tasks + +import com.mhss.app.mybrain.domain.model.Task +import com.mhss.app.mybrain.domain.repository.TaskRepository +import javax.inject.Inject + +class DeleteTaskUseCase @Inject constructor( + private val taskRepository: TaskRepository +) { + suspend operator fun invoke(task: Task) { + taskRepository.deleteTask(task) + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/tasks/GetAllTasksUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/tasks/GetAllTasksUseCase.kt new file mode 100644 index 0000000..cbf28e1 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/tasks/GetAllTasksUseCase.kt @@ -0,0 +1,43 @@ +package com.mhss.app.mybrain.domain.use_case.tasks + +import com.mhss.app.mybrain.domain.model.Task +import com.mhss.app.mybrain.domain.repository.TaskRepository +import com.mhss.app.mybrain.util.settings.Order +import com.mhss.app.mybrain.util.settings.OrderType +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.map +import javax.inject.Inject + +class GetAllTasksUseCase @Inject constructor( + private val tasksRepository: TaskRepository +) { + operator fun invoke(order: Order, showCompleted: Boolean = true): Flow> { + return tasksRepository.getAllTasks().map { tasks -> + when (order.orderType) { + is OrderType.ASC -> { + when (order) { + is Order.Alphabetical -> tasks.sortedBy { it.title } + is Order.DateCreated -> tasks.sortedBy { it.createdDate } + is Order.DateModified -> tasks.sortedBy { it.updatedDate } + is Order.Priority -> tasks.sortedBy { it.priority } + is Order.DueDate -> tasks.sortedWith(compareBy({ it.dueDate == 0L }, { it.dueDate })) + } + } + is OrderType.DESC -> { + when (order) { + is Order.Alphabetical -> tasks.sortedByDescending { it.title } + is Order.DateCreated -> tasks.sortedByDescending { it.createdDate } + is Order.DateModified -> tasks.sortedByDescending { it.updatedDate } + is Order.Priority -> tasks.sortedByDescending { it.priority } + is Order.DueDate -> tasks.sortedWith(compareBy({ it.dueDate == 0L }, { it.dueDate })).reversed() + } + } + } + }.map { list -> + if (showCompleted) + list + else + list.filter { !it.isCompleted } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/tasks/GetTaskByIdUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/tasks/GetTaskByIdUseCase.kt new file mode 100644 index 0000000..8babcea --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/tasks/GetTaskByIdUseCase.kt @@ -0,0 +1,10 @@ +package com.mhss.app.mybrain.domain.use_case.tasks + +import com.mhss.app.mybrain.domain.repository.TaskRepository +import javax.inject.Inject + +class GetTaskByIdUseCase @Inject constructor( + private val tasksRepository: TaskRepository +) { + suspend operator fun invoke(id: Int) = tasksRepository.getTaskById(id) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/tasks/SearchTasksUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/tasks/SearchTasksUseCase.kt new file mode 100644 index 0000000..a7d9d12 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/tasks/SearchTasksUseCase.kt @@ -0,0 +1,14 @@ +package com.mhss.app.mybrain.domain.use_case.tasks + +import com.mhss.app.mybrain.domain.model.Task +import com.mhss.app.mybrain.domain.repository.TaskRepository +import kotlinx.coroutines.flow.Flow +import javax.inject.Inject + +class SearchTasksUseCase @Inject constructor( + private val tasksRepository: TaskRepository +) { + operator fun invoke(query: String): Flow> { + return tasksRepository.searchTasks(query) + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/tasks/UpdateTaskCompletedUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/tasks/UpdateTaskCompletedUseCase.kt new file mode 100644 index 0000000..c4aad11 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/tasks/UpdateTaskCompletedUseCase.kt @@ -0,0 +1,17 @@ +package com.mhss.app.mybrain.domain.use_case.tasks + +import com.mhss.app.mybrain.domain.repository.TaskRepository +import com.mhss.app.mybrain.domain.use_case.alarm.DeleteAlarmUseCase +import javax.inject.Inject + +class UpdateTaskCompletedUseCase @Inject constructor( + private val tasksRepository: TaskRepository, + private val deleteAlarm: DeleteAlarmUseCase, + ) { + suspend operator fun invoke(taskId: Int, completed: Boolean) { + tasksRepository.completeTask(taskId, completed) + if (completed) { + deleteAlarm(taskId) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/domain/use_case/tasks/UpdateTaskUseCase.kt b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/tasks/UpdateTaskUseCase.kt new file mode 100644 index 0000000..05ade13 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/domain/use_case/tasks/UpdateTaskUseCase.kt @@ -0,0 +1,13 @@ +package com.mhss.app.mybrain.domain.use_case.tasks + +import com.mhss.app.mybrain.domain.model.Task +import com.mhss.app.mybrain.domain.repository.TaskRepository +import javax.inject.Inject + +class UpdateTaskUseCase @Inject constructor( + private val tasksRepository: TaskRepository +) { + suspend operator fun invoke(task: Task) { + tasksRepository.updateTask(task) + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/bookmarks/BookmarkDetailsScreen.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/bookmarks/BookmarkDetailsScreen.kt new file mode 100644 index 0000000..2eafe73 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/bookmarks/BookmarkDetailsScreen.kt @@ -0,0 +1,239 @@ +package com.mhss.app.mybrain.presentation.bookmarks + +import android.content.Intent +import android.net.Uri +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.* +import androidx.compose.runtime.* +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.hilt.navigation.compose.hiltViewModel +import androidx.navigation.NavHostController +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.domain.model.Bookmark +import com.mhss.app.mybrain.presentation.util.Screen +import com.mhss.app.mybrain.util.bookmarks.isValidUrl + +@Composable +fun BookmarkDetailsScreen( + navController: NavHostController, + bookmarkId: Int, + viewModel: BookmarksViewModel = hiltViewModel() +) { + LaunchedEffect(true) { + if (bookmarkId != -1) { + viewModel.onEvent(BookmarkEvent.GetBookmark(bookmarkId)) + } + } + val state = viewModel.uiState + val scaffoldState = rememberScaffoldState() + var openDialog by rememberSaveable { mutableStateOf(false) } + val context = LocalContext.current + + var title by rememberSaveable { mutableStateOf(state.bookmark?.title ?: "") } + var description by rememberSaveable { mutableStateOf(state.bookmark?.description ?: "") } + var url by rememberSaveable { mutableStateOf(state.bookmark?.url ?: "") } + + LaunchedEffect(state.bookmark) { + if (state.bookmark != null) { + title = state.bookmark.title + description = state.bookmark.description + url = state.bookmark.url + } + } + LaunchedEffect(state) { + if (state.navigateUp) { + openDialog = false + navController.popBackStack(route = Screen.BookmarksScreen.route, inclusive = false) + } + if (state.error != null) { + scaffoldState.snackbarHostState.showSnackbar( + state.error + ) + viewModel.onEvent(BookmarkEvent.ErrorDisplayed) + } + } + BackHandler { + addOrUpdateBookmark( + Bookmark( + title = title, + description = description, + url = url + ), + state.bookmark, + onNotChanged = { + navController.popBackStack( + route = Screen.BookmarksScreen.route, + inclusive = false + ) + }, + onUpdate = { + if (state.bookmark != null) { + viewModel.onEvent( + BookmarkEvent.UpdateBookmark( + state.bookmark.copy( + title = title, + description = description, + url = url + ) + ) + ) + } else { + viewModel.onEvent( + BookmarkEvent.AddBookmark( + Bookmark( + title = title, + description = description, + url = url + ) + ) + ) + } + + } + ) + } + Scaffold( + scaffoldState = scaffoldState, + topBar = { + TopAppBar( + title = {}, + actions = { + if (state.bookmark != null) IconButton(onClick = { openDialog = true }) { + Icon( + painter = painterResource(id = R.drawable.ic_delete), + contentDescription = stringResource(R.string.delete_bookmark) + ) + } + if (url.isValidUrl()) + IconButton(onClick = { + val intent = Intent(Intent.ACTION_VIEW) + intent.data = Uri.parse(if (!url.startsWith("http://") && !url.startsWith("https://")) "http://$url" else url) + context.startActivity(intent) + }) { + Icon( + painter = painterResource(id = R.drawable.ic_open_link), + contentDescription = stringResource(R.string.open_link), + modifier = Modifier.size(24.dp), + ) + } + }, + backgroundColor = MaterialTheme.colors.background, + elevation = 0.dp, + ) + }, + ) { + Column( + Modifier + .fillMaxSize() + .padding(12.dp) + ) { + OutlinedTextField( + value = url, + onValueChange = { url = it }, + label = { Text(text = stringResource(R.string.url)) }, + shape = RoundedCornerShape(15.dp), + modifier = Modifier.fillMaxWidth(), + ) + Spacer(Modifier.height(8.dp)) + OutlinedTextField( + value = title, + onValueChange = { title = it }, + label = { Text(text = stringResource(R.string.title)) }, + shape = RoundedCornerShape(15.dp), + modifier = Modifier.fillMaxWidth(), + ) + Spacer(Modifier.height(8.dp)) + OutlinedTextField( + value = description, + onValueChange = { description = it }, + label = { Text(text = stringResource(R.string.description)) }, + shape = RoundedCornerShape(15.dp), + modifier = Modifier.fillMaxWidth(), + ) + Spacer(Modifier.height(8.dp)) + TextButton( + onClick = { + if (state.bookmark != null) + url = state.bookmark.url + else navController.popBackStack( + route = Screen.BookmarksScreen.route, + inclusive = false + ) + }, + modifier = Modifier.align(Alignment.End) + ) { + Text( + text = if (state.bookmark != null) stringResource(R.string.cancel_changes) + else stringResource(R.string.cancel) + ) + } + } + if (openDialog) + AlertDialog( + shape = RoundedCornerShape(25.dp), + onDismissRequest = { openDialog = false }, + title = { Text(stringResource(R.string.delete_bookmark_confirmation_title)) }, + text = { + Text( + stringResource( + R.string.delete_bookmark_confirmation_message + ) + ) + }, + confirmButton = { + Button( + colors = ButtonDefaults.buttonColors(backgroundColor = Color.Red), + shape = RoundedCornerShape(25.dp), + onClick = { + viewModel.onEvent(BookmarkEvent.DeleteBookmark(state.bookmark!!)) + }, + ) { + Text(stringResource(R.string.delete_bookmark), color = Color.White) + } + }, + dismissButton = { + Button( + shape = RoundedCornerShape(25.dp), + onClick = { + openDialog = false + }) { + Text(stringResource(R.string.cancel), color = Color.White) + } + } + ) + } +} + +private fun addOrUpdateBookmark( + newBookmark: Bookmark, + bookmark: Bookmark? = null, + onNotChanged: () -> Unit = {}, + onUpdate: (Bookmark) -> Unit, +) { + if (bookmark != null) { + if (bookmarkChanged(newBookmark, bookmark)) + onUpdate(bookmark) + else + onNotChanged() + } else { + onUpdate(newBookmark) + } +} + +private fun bookmarkChanged( + bookmark: Bookmark, + newBookmark: Bookmark +): Boolean { + return bookmark.title != newBookmark.title || + bookmark.description != newBookmark.description || + bookmark.url != newBookmark.url +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/bookmarks/BookmarkEvent.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/bookmarks/BookmarkEvent.kt new file mode 100644 index 0000000..de37603 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/bookmarks/BookmarkEvent.kt @@ -0,0 +1,16 @@ +package com.mhss.app.mybrain.presentation.bookmarks + +import com.mhss.app.mybrain.domain.model.Bookmark +import com.mhss.app.mybrain.util.settings.ItemView +import com.mhss.app.mybrain.util.settings.Order + +sealed class BookmarkEvent { + data class AddBookmark(val bookmark: Bookmark) : BookmarkEvent() + data class GetBookmark(val bookmarkId: Int) : BookmarkEvent() + data class SearchBookmarks(val query: String) : BookmarkEvent() + data class UpdateOrder(val order: Order) : BookmarkEvent() + data class UpdateView(val view: ItemView) : BookmarkEvent() + data class UpdateBookmark(val bookmark: Bookmark) : BookmarkEvent() + data class DeleteBookmark(val bookmark: Bookmark) : BookmarkEvent() + object ErrorDisplayed: BookmarkEvent() +} diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/bookmarks/BookmarkItem.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/bookmarks/BookmarkItem.kt new file mode 100644 index 0000000..430210c --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/bookmarks/BookmarkItem.kt @@ -0,0 +1,77 @@ +package com.mhss.app.mybrain.presentation.bookmarks + +import android.content.Intent +import android.net.Uri +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.* +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.domain.model.Bookmark +import com.mhss.app.mybrain.util.bookmarks.isValidUrl + +@Composable +fun BookmarkItem( + modifier: Modifier = Modifier, + bookmark: Bookmark, + onClick: (Bookmark) -> Unit, + onInvalidUrl: () -> Unit +) { + Card( + modifier = modifier, + shape = RoundedCornerShape(20.dp), + elevation = 8.dp + ) { + val context = LocalContext.current + Column( + modifier = Modifier + .clickable { onClick(bookmark) } + .padding(12.dp) + .fillMaxWidth() + ) { + if (bookmark.title.isNotBlank()){ + Text( + bookmark.title, + style = MaterialTheme.typography.body1.copy(fontWeight = FontWeight.Bold), + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + Spacer(Modifier.height(8.dp)) + } + Row { + + } + Text( + bookmark.url, + style = MaterialTheme.typography.body1.copy(fontWeight = FontWeight.Bold), + color = Color.Gray + ) + IconButton( + onClick = { + if (bookmark.url.isValidUrl()){ + val intent = Intent(Intent.ACTION_VIEW) + intent.data = Uri.parse(if (!bookmark.url.startsWith("http://") && !bookmark.url.startsWith("https://")) "http://${bookmark.url}" else bookmark.url) + context.startActivity(intent) + } else + onInvalidUrl() + }, + modifier = Modifier.align(Alignment.End) + ) { + Icon( + painterResource(id = R.drawable.ic_open_link), + stringResource(id = R.string.open_link) + ) + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/bookmarks/BookmarkSearchScreen.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/bookmarks/BookmarkSearchScreen.kt new file mode 100644 index 0000000..b2eb536 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/bookmarks/BookmarkSearchScreen.kt @@ -0,0 +1,120 @@ +package com.mhss.app.mybrain.presentation.bookmarks + +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.grid.GridCells +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.grid.LazyVerticalGrid +import androidx.compose.foundation.lazy.grid.items +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.OutlinedTextField +import androidx.compose.material.Scaffold +import androidx.compose.material.Text +import androidx.compose.material.rememberScaffoldState +import androidx.compose.runtime.* +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.hilt.navigation.compose.hiltViewModel +import androidx.navigation.NavHostController +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.app.getString +import com.mhss.app.mybrain.presentation.util.Screen +import com.mhss.app.mybrain.util.Constants +import com.mhss.app.mybrain.util.settings.ItemView +import kotlinx.coroutines.launch + +@OptIn(ExperimentalFoundationApi::class) +@Composable +fun BookmarkSearchScreen( + navController: NavHostController, + viewModel: BookmarksViewModel = hiltViewModel() +) { + val state = viewModel.uiState + val scope = rememberCoroutineScope() + val scaffoldState = rememberScaffoldState() + Scaffold(scaffoldState = scaffoldState) { paddingValues -> + Column( + modifier = Modifier.fillMaxSize().padding(paddingValues), + ) { + var query by rememberSaveable { + mutableStateOf("") + } + LaunchedEffect(query){viewModel.onEvent(BookmarkEvent.SearchBookmarks(query))} + val focusRequester = remember { FocusRequester() } + LaunchedEffect(true){focusRequester.requestFocus()} + OutlinedTextField( + value = query, + onValueChange = {query = it}, + label = { Text(stringResource(R.string.search_bookmarks)) }, + shape = RoundedCornerShape(15.dp), + modifier = Modifier + .fillMaxWidth() + .padding(16.dp) + .focusRequester(focusRequester) + ) + if (state.bookmarksView == ItemView.LIST){ + LazyColumn( + verticalArrangement = Arrangement.spacedBy(8.dp), + contentPadding = PaddingValues(12.dp) + ) { + items(state.searchBookmarks, key = {it.id}) { bookmark -> + BookmarkItem( + bookmark = bookmark, + onClick = { + navController.navigate( + Screen.BookmarkDetailScreen.route.replace( + "{${Constants.BOOKMARK_ID_ARG}}", + "${bookmark.id}" + ) + ) + }, + onInvalidUrl = { + scope.launch { + scaffoldState.snackbarHostState.showSnackbar( + getString(R.string.invalid_url) + ) + } + } + ) + } + } + } else { + LazyVerticalGrid( + columns = GridCells.Adaptive(150.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), + contentPadding = PaddingValues(12.dp) + ){ + items(state.searchBookmarks){ bookmark -> + key(bookmark.id) { + BookmarkItem( + bookmark = bookmark, + onClick = { + navController.navigate( + Screen.BookmarkDetailScreen.route.replace( + "{${Constants.BOOKMARK_ID_ARG}}", + "${bookmark.id}" + ) + ) + }, + onInvalidUrl = { + scope.launch { + scaffoldState.snackbarHostState.showSnackbar( + getString(R.string.invalid_url) + ) + } + }, + modifier = Modifier.animateItemPlacement() + ) + } + } + } + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/bookmarks/BookmarksScreen.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/bookmarks/BookmarksScreen.kt new file mode 100644 index 0000000..e576b2f --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/bookmarks/BookmarksScreen.kt @@ -0,0 +1,292 @@ +package com.mhss.app.mybrain.presentation.bookmarks + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.grid.GridCells +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.grid.LazyVerticalGrid +import androidx.compose.foundation.lazy.grid.items +import androidx.compose.foundation.lazy.items +import androidx.compose.material.* +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.hilt.navigation.compose.hiltViewModel +import androidx.navigation.NavHostController +import com.google.accompanist.flowlayout.FlowRow +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.presentation.util.Screen +import com.mhss.app.mybrain.util.Constants +import com.mhss.app.mybrain.util.settings.ItemView +import com.mhss.app.mybrain.util.settings.Order +import com.mhss.app.mybrain.util.settings.OrderType +import kotlinx.coroutines.launch +import com.mhss.app.mybrain.app.getString + +@OptIn(ExperimentalFoundationApi::class) +@Composable +fun BookmarksScreen( + navController: NavHostController, + viewModel: BookmarksViewModel = hiltViewModel() +) { + val uiState = viewModel.uiState + val scope = rememberCoroutineScope() + val scaffoldState = rememberScaffoldState() + var orderSettingsVisible by remember { mutableStateOf(false) } + Scaffold( + scaffoldState = scaffoldState, + topBar = { + TopAppBar( + title = { + Text( + text = stringResource(R.string.bookmarks), + style = MaterialTheme.typography.h5.copy(fontWeight = FontWeight.Bold) + ) + }, + backgroundColor = MaterialTheme.colors.background, + elevation = 0.dp, + ) + }, + floatingActionButton = { + FloatingActionButton( + onClick = { + navController.navigate( + Screen.BookmarkDetailScreen.route.replace( + "{${Constants.BOOKMARK_ID_ARG}}", + "${-1}" + ) + ) + }, + backgroundColor = MaterialTheme.colors.primary, + ) { + Icon( + modifier = Modifier.size(25.dp), + painter = painterResource(R.drawable.ic_add), + contentDescription = stringResource(R.string.add_bookmark), + tint = Color.White + ) + } + }, + ) { paddingValues -> + if (uiState.bookmarks.isEmpty()) + NoBookmarksMessage() + Column { + Row( + Modifier.fillMaxWidth().padding(paddingValues), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween + ) { + IconButton(onClick = { orderSettingsVisible = !orderSettingsVisible }) { + Icon( + modifier = Modifier.size(25.dp), + painter = painterResource(R.drawable.ic_settings_sliders), + contentDescription = stringResource(R.string.order_by) + ) + } + IconButton(onClick = { + navController.navigate(Screen.BookmarkSearchScreen.route) + }) { + Icon( + modifier = Modifier.size(25.dp), + painter = painterResource(id = R.drawable.ic_search), + contentDescription = stringResource(R.string.search) + ) + } + } + AnimatedVisibility(visible = orderSettingsVisible) { + BookmarksSettingsSection( + uiState.bookmarksOrder, + uiState.bookmarksView, + onOrderChange = { + viewModel.onEvent(BookmarkEvent.UpdateOrder(it)) + }, + onViewChange = { + viewModel.onEvent(BookmarkEvent.UpdateView(it)) + } + ) + } + if (uiState.bookmarksView == ItemView.LIST) { + LazyColumn( + verticalArrangement = Arrangement.spacedBy(8.dp), + contentPadding = PaddingValues(12.dp) + ) { + items(uiState.bookmarks, key = { it.id }) { bookmark -> + BookmarkItem( + bookmark = bookmark, + onClick = { + navController.navigate( + Screen.BookmarkDetailScreen.route.replace( + "{${Constants.BOOKMARK_ID_ARG}}", + "${bookmark.id}" + ) + ) + }, + onInvalidUrl = { + scope.launch { + scaffoldState.snackbarHostState.showSnackbar( + getString(R.string.invalid_url) + ) + } + }, + modifier = Modifier.animateItemPlacement() + ) + } + } + } else { + LazyVerticalGrid( + columns = GridCells.Adaptive(150.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), + contentPadding = PaddingValues(12.dp) + ) { + items(uiState.bookmarks) { bookmark -> + key(bookmark.id) { + BookmarkItem( + bookmark = bookmark, + onClick = { + navController.navigate( + Screen.BookmarkDetailScreen.route.replace( + "{${Constants.BOOKMARK_ID_ARG}}", + "${bookmark.id}" + ) + ) + }, + onInvalidUrl = { + scope.launch { + scaffoldState.snackbarHostState.showSnackbar( + getString(R.string.invalid_url) + ) + } + }, + modifier = Modifier.animateItemPlacement().height(220.dp) + ) + } + } + } + } + } + } +} + +@Composable +fun BookmarksSettingsSection( + order: Order, + view: ItemView, + onOrderChange: (Order) -> Unit, + onViewChange: (ItemView) -> Unit +) { + val orders = listOf( + Order.DateModified(), + Order.DateCreated(), + Order.Alphabetical() + ) + val orderTypes = listOf( + OrderType.ASC(), + OrderType.DESC() + ) + val views = listOf( + ItemView.LIST, + ItemView.GRID + ) + Column( + Modifier.background(color = MaterialTheme.colors.background) + ) { + Text( + text = stringResource(R.string.order_by), + style = MaterialTheme.typography.body1, + modifier = Modifier.padding(start = 8.dp) + ) + FlowRow( + modifier = Modifier.padding(end = 8.dp) + ) { + orders.forEach { + Row(verticalAlignment = Alignment.CenterVertically) { + RadioButton( + selected = order.orderTitle == it.orderTitle, + onClick = { + if (order.orderTitle != it.orderTitle) + onOrderChange( + it.copy(orderType = order.orderType) + ) + } + ) + Text(text = it.orderTitle, style = MaterialTheme.typography.body1) + } + } + } + Divider() + FlowRow { + orderTypes.forEach { + Row(verticalAlignment = Alignment.CenterVertically) { + RadioButton( + selected = order.orderType.orderTitle == it.orderTitle, + onClick = { + if (order.orderTitle != it.orderTitle) + onOrderChange( + order.copy(it) + ) + } + ) + Spacer(modifier = Modifier.width(4.dp)) + Text(text = it.orderTitle, style = MaterialTheme.typography.body1) + } + } + } + Divider() + Text( + text = stringResource(R.string.view_as), + style = MaterialTheme.typography.body1, + modifier = Modifier.padding(start = 8.dp, top = 8.dp) + ) + FlowRow { + views.forEach { + Row(verticalAlignment = Alignment.CenterVertically) { + RadioButton( + selected = view.title == it.title, + onClick = { + if (view.title != it.title) + onViewChange( + it + ) + } + ) + Spacer(modifier = Modifier.width(4.dp)) + Text(text = stringResource(it.title), style = MaterialTheme.typography.body1) + } + } + } + Spacer(Modifier.height(8.dp)) + } +} + +@Composable +fun NoBookmarksMessage() { + Column( + modifier = Modifier.fillMaxSize(), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center + ) { + Text( + text = stringResource(R.string.no_bookmarks_message), + style = MaterialTheme.typography.body1.copy(fontWeight = FontWeight.Bold), + color = Color.Gray, + textAlign = TextAlign.Center + ) + Spacer(modifier = Modifier.height(12.dp)) + Image( + modifier = Modifier.size(125.dp), + painter = painterResource(id = R.drawable.bookmarks_img), + contentDescription = stringResource(R.string.no_bookmarks_message), + alpha = 0.7f + ) + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/bookmarks/BookmarksViewModel.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/bookmarks/BookmarksViewModel.kt new file mode 100644 index 0000000..41e81ef --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/bookmarks/BookmarksViewModel.kt @@ -0,0 +1,139 @@ +package com.mhss.app.mybrain.presentation.bookmarks + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.datastore.preferences.core.intPreferencesKey +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.app.getString +import com.mhss.app.mybrain.domain.model.Bookmark +import com.mhss.app.mybrain.domain.use_case.bookmarks.* +import com.mhss.app.mybrain.domain.use_case.settings.GetSettingsUseCase +import com.mhss.app.mybrain.domain.use_case.settings.SaveSettingsUseCase +import com.mhss.app.mybrain.util.Constants +import com.mhss.app.mybrain.util.bookmarks.isValidUrl +import com.mhss.app.mybrain.util.settings.* +import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.collect +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.launch +import javax.inject.Inject + +@HiltViewModel +class BookmarksViewModel @Inject constructor( + private val addBookmark: AddBookmarkUseCase, + private val updateBookmark: UpdateBookmarkUseCase, + private val deleteBookmark: DeleteBookmarkUseCase, + private val getAlBookmarks: GetAllBookmarksUseCase, + private val searchBookmarks: SearchBookmarksUseCase, + private val getBookmark: GetBookmarkUseCase, + getSettings: GetSettingsUseCase, + private val saveSettings: SaveSettingsUseCase +) : ViewModel() { + + + var uiState by mutableStateOf(UiState()) + private set + + private var getBookmarksJob: Job? = null + + init { + viewModelScope.launch { + combine( + getSettings( + intPreferencesKey(Constants.BOOKMARK_ORDER_KEY), + Order.DateModified(OrderType.ASC()).toInt() + ), + getSettings( + intPreferencesKey(Constants.BOOKMARK_VIEW_KEY), + ItemView.LIST.value + ) + ) { order, view -> + uiState = uiState.copy(bookmarksOrder = order.toOrder()) + getBookmarks(order.toOrder()) + if (uiState.bookmarksView.value != view) { + uiState = uiState.copy(bookmarksView = view.toNotesView()) + } + }.collect() + } + } + + fun onEvent(event: BookmarkEvent) { + when (event) { + is BookmarkEvent.AddBookmark -> viewModelScope.launch { + uiState = if ( + event.bookmark.url.isBlank() + && event.bookmark.title.isBlank() + && event.bookmark.description.isBlank() + ) + uiState.copy(navigateUp = true) + else { + if (event.bookmark.url.isValidUrl()) { + addBookmark(event.bookmark) + uiState.copy(navigateUp = true) + } else + uiState.copy(error = getString(R.string.invalid_url)) + } + } + is BookmarkEvent.DeleteBookmark -> viewModelScope.launch { + deleteBookmark(event.bookmark) + uiState = uiState.copy(navigateUp = true) + } + is BookmarkEvent.GetBookmark -> viewModelScope.launch { + val bookmark = getBookmark(event.bookmarkId) + uiState = uiState.copy(bookmark = bookmark) + } + is BookmarkEvent.SearchBookmarks -> viewModelScope.launch { + val bookmarks = searchBookmarks(event.query) + uiState = uiState.copy(searchBookmarks = bookmarks) + } + is BookmarkEvent.UpdateBookmark -> viewModelScope.launch { + uiState = if (!event.bookmark.url.isValidUrl()) { + uiState.copy(error = getString(R.string.invalid_url)) + } else { + updateBookmark(event.bookmark.copy(updatedDate = System.currentTimeMillis())) + uiState.copy(navigateUp = true) + } + } + is BookmarkEvent.UpdateOrder -> viewModelScope.launch { + saveSettings( + intPreferencesKey(Constants.BOOKMARK_ORDER_KEY), + event.order.toInt() + ) + } + is BookmarkEvent.UpdateView -> viewModelScope.launch { + saveSettings( + intPreferencesKey(Constants.BOOKMARK_VIEW_KEY), + event.view.value + ) + } + BookmarkEvent.ErrorDisplayed -> uiState = uiState.copy(error = null) + } + } + + data class UiState( + val bookmarks: List = emptyList(), + val bookmarksOrder: Order = Order.DateModified(OrderType.ASC()), + val bookmarksView: ItemView = ItemView.LIST, + val bookmark: Bookmark? = null, + val error: String? = null, + val searchBookmarks: List = emptyList(), + val navigateUp: Boolean = false + ) + + private fun getBookmarks(order: Order) { + getBookmarksJob?.cancel() + getBookmarksJob = getAlBookmarks(order) + .onEach { bookmarks -> + uiState = uiState.copy( + bookmarks = bookmarks, + bookmarksOrder = order + ) + }.launchIn(viewModelScope) + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/bookmarks/SaveBookmarkActivity.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/bookmarks/SaveBookmarkActivity.kt new file mode 100644 index 0000000..503a197 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/bookmarks/SaveBookmarkActivity.kt @@ -0,0 +1,46 @@ +package com.mhss.app.mybrain.presentation.bookmarks + +import android.content.Intent +import android.os.Bundle +import android.widget.Toast +import androidx.activity.ComponentActivity +import androidx.activity.viewModels +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.domain.model.Bookmark +import com.mhss.app.mybrain.util.bookmarks.isValidUrl +import dagger.hilt.android.AndroidEntryPoint + +@AndroidEntryPoint +class SaveBookmarkActivity : ComponentActivity() { + + private val viewModel: BookmarksViewModel by viewModels() + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + if (intent != null) { + if (intent.action == Intent.ACTION_SEND && intent.type == "text/plain") { + val url = intent.getStringExtra(Intent.EXTRA_TEXT) + if (!url.isNullOrBlank()) { + if (url.isValidUrl()) { + viewModel.onEvent( + BookmarkEvent.AddBookmark( + Bookmark( + url = url.trim(), + createdDate = System.currentTimeMillis(), + updatedDate = System.currentTimeMillis() + ) + ) + ) + Toast.makeText(this, getString(R.string.bookmark_saved), Toast.LENGTH_SHORT) + .show() + } else { + Toast.makeText(this, getString(R.string.invalid_url), Toast.LENGTH_SHORT) + .show() + } + } + } else { + Toast.makeText(this, getString(R.string.invalid_url), Toast.LENGTH_SHORT).show() + } + } + finish() + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/calendar/CalendarDashboardWidget.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/calendar/CalendarDashboardWidget.kt new file mode 100644 index 0000000..6b11105 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/calendar/CalendarDashboardWidget.kt @@ -0,0 +1,123 @@ +package com.mhss.app.mybrain.presentation.calendar + +import android.Manifest +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.* +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import com.google.accompanist.permissions.ExperimentalPermissionsApi +import com.google.accompanist.permissions.rememberPermissionState +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.domain.model.CalendarEvent +import com.mhss.app.mybrain.ui.theme.LightGray + +@OptIn(ExperimentalPermissionsApi::class) +@Composable +fun CalendarDashboardWidget( + modifier: Modifier = Modifier, + events: Map>, + onPermission: (Boolean) -> Unit = {}, + onClick: () -> Unit = {}, + onAddEventClicked: () -> Unit = {}, + onEventClicked: (CalendarEvent) -> Unit = {} +) { + Card( + shape = RoundedCornerShape(24.dp), + elevation = 8.dp, + modifier = Modifier + .fillMaxWidth() + .padding(8.dp) + ) { + val context = LocalContext.current + val readCalendarPermissionState = rememberPermissionState( + Manifest.permission.READ_CALENDAR + ) + val isDark = !MaterialTheme.colors.isLight + Column( + modifier = modifier + .clickable { onClick() } + .padding(8.dp) + ) { + Row( + Modifier.fillMaxWidth().padding(4.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Text(stringResource(R.string.calendar), style = MaterialTheme.typography.body1) + Icon( + painterResource(R.drawable.ic_add), + stringResource(R.string.add_event), + modifier = Modifier + .size(18.dp) + .clickable { + onAddEventClicked() + } + ) + } + Spacer(Modifier.height(8.dp)) + LazyColumn( + modifier = Modifier + .fillMaxSize() + .clip(RoundedCornerShape(20.dp)) + .background(if (isDark) Color.DarkGray else LightGray), + contentPadding = PaddingValues(vertical = 10.dp, horizontal = 8.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + horizontalAlignment = Alignment.CenterHorizontally + ) { + if (readCalendarPermissionState.hasPermission) { + if (events.isEmpty()) { + item { + LaunchedEffect(true) { onPermission(true) } + Text( + text = stringResource(R.string.no_events), + modifier = Modifier.padding(16.dp), + style = MaterialTheme.typography.body1 + ) + } + } else { + events.forEach { (day, events) -> + item { + LaunchedEffect(true) { onPermission(true) } + Column( + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + Text( + text = day, + style = MaterialTheme.typography.body2 + ) + events.forEach { event -> + CalendarEventSmallItem(event = event, onClick = { + onEventClicked(event) + }) + } + } + } + } + } + } else { + item { + LaunchedEffect(true) { onPermission(false) } + NoReadCalendarPermissionMessage( + shouldShowRationale = readCalendarPermissionState.shouldShowRationale, + context + ) { + readCalendarPermissionState.launchPermissionRequest() + } + } + } + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/calendar/CalendarEventDetailsScreen.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/calendar/CalendarEventDetailsScreen.kt new file mode 100644 index 0000000..c75094f --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/calendar/CalendarEventDetailsScreen.kt @@ -0,0 +1,658 @@ +package com.mhss.app.mybrain.presentation.calendar + +import android.app.DatePickerDialog +import android.app.TimePickerDialog +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.provider.Settings +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.* +import androidx.compose.runtime.* +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.toArgb +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.hilt.navigation.compose.hiltViewModel +import androidx.navigation.NavHostController +import com.google.accompanist.permissions.ExperimentalPermissionsApi +import com.google.accompanist.permissions.rememberPermissionState +import com.google.gson.Gson +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.domain.model.Calendar +import com.mhss.app.mybrain.domain.model.CalendarEvent +import com.mhss.app.mybrain.util.calendar.* +import com.mhss.app.mybrain.util.date.HOUR_IN_MILLIS +import com.mhss.app.mybrain.util.date.formatDate +import com.mhss.app.mybrain.util.date.formatTime +import java.net.URLDecoder +import java.nio.charset.StandardCharsets + +@OptIn(ExperimentalPermissionsApi::class) +@Composable +fun CalendarEventDetailsScreen( + navController: NavHostController, + eventJson: String = "", + viewModel: CalendarViewModel = hiltViewModel() +) { + val state = viewModel.uiState + val writeCalendarPermissionState = rememberPermissionState( + permission = android.Manifest.permission.WRITE_CALENDAR + ) + var openDeleteDialog by rememberSaveable { mutableStateOf(false) } + val context = LocalContext.current + val event by remember { + mutableStateOf( + if (eventJson.isNotEmpty()) { + val decodedJson = URLDecoder.decode(eventJson, StandardCharsets.UTF_8.toString()) + Gson().fromJson(decodedJson, CalendarEvent::class.java) + } else + null + ) + } + var title by rememberSaveable { mutableStateOf(event?.title ?: "") } + var description by rememberSaveable { mutableStateOf(event?.description ?: "") } + var startDate by rememberSaveable { + mutableStateOf( + event?.start ?: (System.currentTimeMillis() + HOUR_IN_MILLIS) + ) + } + var endDate by rememberSaveable { + mutableStateOf( + event?.end ?: (System.currentTimeMillis() + 2 * HOUR_IN_MILLIS) + ) + } + var frequency by rememberSaveable { mutableStateOf(event?.frequency ?: CALENDAR_FREQ_NEVER) } + var calendar by remember { + mutableStateOf( + Calendar( + id = 1, + name = "", + color = Color.Black.toArgb(), + account = "" + ) + ) + } + LaunchedEffect(state.calendarsList) { + if (event != null) { + if (state.calendarsList.isNotEmpty()) { + calendar = state.calendarsList.first { it.id == event!!.calendarId } + } + } else { + if (state.calendarsList.isNotEmpty()) { + calendar = state.calendarsList.first() + } + } + } + + var allDay by rememberSaveable { mutableStateOf(event?.allDay ?: false) } + var location by rememberSaveable { mutableStateOf(event?.location ?: "") } + val scaffoldState = rememberScaffoldState() + if (writeCalendarPermissionState.hasPermission) { + LaunchedEffect(true) { viewModel.onEvent(CalendarViewModelEvent.ReadPermissionChanged(true)) } + LaunchedEffect(state) { + if (state.navigateUp) { + openDeleteDialog = false + navController.navigateUp() + } + if (state.error != null) { + scaffoldState.snackbarHostState.showSnackbar( + state.error + ) + viewModel.onEvent(CalendarViewModelEvent.ErrorDisplayed) + } + } + Scaffold( + scaffoldState = scaffoldState, + topBar = { + if (eventJson.isNotBlank()) TopAppBar( + title = {}, + backgroundColor = MaterialTheme.colors.background, + elevation = 0.dp, + actions = { + IconButton(onClick = { openDeleteDialog = true }) { + Icon( + painter = painterResource(id = R.drawable.ic_delete), + contentDescription = stringResource(R.string.delete_event) + ) + } + } + ) + }, + floatingActionButton = { + FloatingActionButton(onClick = { + val newEvent = CalendarEvent( + id = event?.id ?: 0, + title = title, + description = description, + start = startDate, + end = endDate, + allDay = allDay, + location = location, + calendarId = calendar.id, + recurring = frequency != CALENDAR_FREQ_NEVER, + frequency = frequency + ) + if (event != null) { + viewModel.onEvent(CalendarViewModelEvent.EditEvent(newEvent)) + } else { + viewModel.onEvent(CalendarViewModelEvent.AddEvent(newEvent)) + } + }) { + Icon( + painter = painterResource(id = R.drawable.ic_save), + contentDescription = stringResource(R.string.add_event) + ) + } + } + ) { + DeleteEventDialog( + openDeleteDialog, + onDelete = { viewModel.onEvent(CalendarViewModelEvent.DeleteEvent(event!!)) }, + onDismiss = {openDeleteDialog = false} + ) + Column( + modifier = Modifier + .fillMaxSize() + .padding(12.dp) + .verticalScroll(rememberScrollState()), + ) { + OutlinedTextField( + value = title, + onValueChange = { title = it }, + label = { Text(text = stringResource(R.string.title)) }, + shape = RoundedCornerShape(15.dp), + modifier = Modifier.fillMaxWidth(), + ) + Spacer(Modifier.height(8.dp)) + CalendarChoiceSection( + selectedCalendar = calendar, + calendars = state.calendarsList, + onCalendarSelected = { calendar = it } + ) + Spacer(Modifier.height(8.dp)) + EventTimeSection( + start = java.util.Calendar.getInstance().apply { timeInMillis = startDate }, + end = java.util.Calendar.getInstance().apply { timeInMillis = endDate }, + onStartDateSelected = { startDate = it.timeInMillis }, + onEndDateSelected = { endDate = it.timeInMillis }, + allDay = allDay, + onAllDayChange = { allDay = it }, + frequency = frequency, + onFrequencySelected = { frequency = it } + ) + Spacer(Modifier.height(8.dp)) + OutlinedTextField( + value = location, + onValueChange = { location = it }, + label = { Text(text = stringResource(R.string.location)) }, + shape = RoundedCornerShape(15.dp), + modifier = Modifier.fillMaxWidth(), + leadingIcon = { + Icon(painter = painterResource(id = R.drawable.ic_location), null) + } + ) + Spacer(Modifier.height(8.dp)) + OutlinedTextField( + value = description, + onValueChange = { description = it }, + label = { Text(text = stringResource(R.string.description)) }, + shape = RoundedCornerShape(15.dp), + modifier = Modifier.fillMaxWidth(), + leadingIcon = { + Icon(painter = painterResource(id = R.drawable.ic_description), null) + } + ) + Spacer(Modifier.height(8.dp)) + } + } + } else { + LaunchedEffect(true) { viewModel.onEvent(CalendarViewModelEvent.ReadPermissionChanged(false)) } + NoWriteCalendarPermissionMessage( + shouldShowRationale = writeCalendarPermissionState.shouldShowRationale, + context = context + ) { + writeCalendarPermissionState.launchPermissionRequest() + } + } +} + +@Composable +fun NoWriteCalendarPermissionMessage( + shouldShowRationale: Boolean, + context: Context, + onRequest: () -> Unit +) { + Column( + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center, + modifier = Modifier.fillMaxSize() + ) { + Text( + text = stringResource(R.string.no_write_calendar_permission_message), + style = MaterialTheme.typography.body1, + textAlign = TextAlign.Center + ) + Spacer(Modifier.height(12.dp)) + if (shouldShowRationale) { + TextButton(onClick = { + val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS) + intent.data = Uri.fromParts("package", context.packageName, null) + context.startActivity(intent) + }) { + Text(text = stringResource(R.string.go_to_settings)) + } + + } else { + TextButton(onClick = { onRequest() }) { + Text(text = stringResource(R.string.grant_permission)) + } + } + } +} + +@Composable +fun CalendarChoiceSection( + selectedCalendar: Calendar, + calendars: List, + onCalendarSelected: (Calendar) -> Unit +) { + var expanded by remember { mutableStateOf(false) } + Box( + Modifier + .fillMaxWidth() + .clickable { expanded = true } + .padding(vertical = 12.dp) + ) { + Row( + verticalAlignment = Alignment.CenterVertically + ) { + Box( + Modifier + .size(18.dp) + .clip(CircleShape) + .background(Color(selectedCalendar.color)) + ) + Spacer(Modifier.width(8.dp)) + Column { + Text( + text = selectedCalendar.name, + style = MaterialTheme.typography.body1 + ) + Spacer(Modifier.height(4.dp)) + Text( + text = selectedCalendar.account, + style = MaterialTheme.typography.body2 + ) + } + } + DropdownMenu( + expanded = expanded, + onDismissRequest = { expanded = false }, + ) { + calendars.forEach { calendar -> + DropdownMenuItem( + onClick = { + expanded = false + onCalendarSelected(calendar) + }, + modifier = Modifier + .fillMaxWidth() + .padding(8.dp) + ) { + Box( + Modifier + .size(20.dp) + .clip(CircleShape) + .background(Color(calendar.color)) + ) + Spacer(Modifier.width(8.dp)) + Column { + Text( + text = calendar.name, + style = MaterialTheme.typography.body1 + ) + Spacer(Modifier.height(4.dp)) + Text( + text = calendar.account, + style = MaterialTheme.typography.body2 + ) + } + } + Spacer(Modifier.height(4.dp)) + } + } + } +} + +@Composable +fun EventTimeSection( + start: java.util.Calendar, + end: java.util.Calendar, + onStartDateSelected: (java.util.Calendar) -> Unit, + onEndDateSelected: (java.util.Calendar) -> Unit, + allDay: Boolean, + onAllDayChange: (Boolean) -> Unit, + frequency: String, + onFrequencySelected: (String) -> Unit +) { + val context = LocalContext.current + Column { + Row( + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier + .fillMaxWidth() + .padding(end = 12.dp) + ) { + Row( + verticalAlignment = Alignment.CenterVertically + ) { + Icon(painter = painterResource(R.drawable.ic_time), null) + Spacer(Modifier.width(8.dp)) + Text( + text = stringResource(R.string.all_day), + style = MaterialTheme.typography.body1 + ) + } + Switch( + checked = allDay, + onCheckedChange = { onAllDayChange(it) } + ) + } + Row( + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth() + ) { + Text( + text = start.timeInMillis.formatDate(), + style = MaterialTheme.typography.body1, + modifier = Modifier + .clickable { + showDatePicker(start, context) { + val newEvent = java.util.Calendar + .getInstance() + .apply { + this[java.util.Calendar.YEAR] = it[java.util.Calendar.YEAR] + this[java.util.Calendar.MONTH] = + it[java.util.Calendar.MONTH] + this[java.util.Calendar.DAY_OF_MONTH] = + it[java.util.Calendar.DAY_OF_MONTH] + + this[java.util.Calendar.HOUR_OF_DAY] = + start[java.util.Calendar.HOUR_OF_DAY] + this[java.util.Calendar.MINUTE] = + start[java.util.Calendar.MINUTE] + } + onStartDateSelected( + newEvent + ) + if (newEvent.timeInMillis > end.timeInMillis) { + onEndDateSelected(newEvent.apply { timeInMillis += HOUR_IN_MILLIS }) + } + } + } + .padding(horizontal = 28.dp, vertical = 16.dp) + ) + Text( + text = start.timeInMillis.formatTime(), + style = MaterialTheme.typography.body1, + modifier = Modifier + .clickable { + showTimePicker(start, context) { + val newEvent = java.util.Calendar + .getInstance() + .apply { + this[java.util.Calendar.HOUR_OF_DAY] = + it[java.util.Calendar.HOUR_OF_DAY] + this[java.util.Calendar.MINUTE] = + it[java.util.Calendar.MINUTE] + + this[java.util.Calendar.YEAR] = + start[java.util.Calendar.YEAR] + this[java.util.Calendar.MONTH] = + start[java.util.Calendar.MONTH] + this[java.util.Calendar.DAY_OF_MONTH] = + start[java.util.Calendar.DAY_OF_MONTH] + } + onStartDateSelected( + newEvent + ) + if (newEvent.timeInMillis > end.timeInMillis) { + onEndDateSelected(newEvent.apply { timeInMillis += HOUR_IN_MILLIS }) + } + } + } + .padding(horizontal = 18.dp, vertical = 16.dp) + + ) + } + Row( + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth() + ) { + Text( + text = end.timeInMillis.formatDate(), + style = MaterialTheme.typography.body1, + modifier = Modifier + .clickable { + showDatePicker(end, context) { + val newEvent = java.util.Calendar + .getInstance() + .apply { + this[java.util.Calendar.YEAR] = it[java.util.Calendar.YEAR] + this[java.util.Calendar.MONTH] = + it[java.util.Calendar.MONTH] + this[java.util.Calendar.DAY_OF_MONTH] = + it[java.util.Calendar.DAY_OF_MONTH] + + this[java.util.Calendar.HOUR_OF_DAY] = + end[java.util.Calendar.HOUR_OF_DAY] + this[java.util.Calendar.MINUTE] = + end[java.util.Calendar.MINUTE] + } + onEndDateSelected( + newEvent + ) + if (newEvent.timeInMillis < start.timeInMillis) { + onStartDateSelected(newEvent.apply { timeInMillis -= HOUR_IN_MILLIS }) + } + } + } + .padding(horizontal = 28.dp, vertical = 16.dp) + ) + Text( + text = end.timeInMillis.formatTime(), + style = MaterialTheme.typography.body1, + modifier = Modifier + .clickable { + showTimePicker(end, context) { + val newEvent = java.util.Calendar + .getInstance() + .apply { + this[java.util.Calendar.HOUR_OF_DAY] = + it[java.util.Calendar.HOUR_OF_DAY] + this[java.util.Calendar.MINUTE] = + it[java.util.Calendar.MINUTE] + + this[java.util.Calendar.YEAR] = + end[java.util.Calendar.YEAR] + this[java.util.Calendar.MONTH] = + end[java.util.Calendar.MONTH] + this[java.util.Calendar.DAY_OF_MONTH] = + end[java.util.Calendar.DAY_OF_MONTH] + } + onEndDateSelected( + newEvent + ) + if (newEvent.timeInMillis < start.timeInMillis) { + onStartDateSelected(newEvent.apply { timeInMillis -= HOUR_IN_MILLIS }) + } + } + } + .padding(horizontal = 18.dp, vertical = 16.dp) + ) + } + var openDialog by remember { mutableStateOf(false) } + Row( + modifier = Modifier + .clickable { openDialog = true } + .fillMaxWidth() + .padding(top = 12.dp, bottom = 16.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon(painter = painterResource(id = R.drawable.ic_refresh), null) + Spacer(Modifier.width(8.dp)) + Text(frequency.toUIFrequency(), style = MaterialTheme.typography.body1) + FrequencyDialog( + selectedFrequency = frequency, + onFrequencySelected = { + onFrequencySelected(it) + openDialog = false + }, + open = openDialog, + onClose = { openDialog = false } + ) + } + } +} + +fun showDatePicker( + initialDate: java.util.Calendar, + context: Context, + onDateSelected: (java.util.Calendar) -> Unit +) { + val tempDate = java.util.Calendar.getInstance() + val datePicker = DatePickerDialog( + context, + { _, year, month, day -> + tempDate[java.util.Calendar.YEAR] = year + tempDate[java.util.Calendar.MONTH] = month + tempDate[java.util.Calendar.DAY_OF_MONTH] = day + onDateSelected(tempDate) + }, + initialDate[java.util.Calendar.YEAR], + initialDate[java.util.Calendar.MONTH], + initialDate[java.util.Calendar.DAY_OF_MONTH] + ) + datePicker.show() +} + +fun showTimePicker( + initialDate: java.util.Calendar, + context: Context, + onTimeSelected: (java.util.Calendar) -> Unit +) { + val tempDate = java.util.Calendar.getInstance() + val timePicker = TimePickerDialog( + context, + { _, hour, minute -> + tempDate[java.util.Calendar.HOUR_OF_DAY] = hour + tempDate[java.util.Calendar.MINUTE] = minute + onTimeSelected(tempDate) + }, + initialDate[java.util.Calendar.HOUR_OF_DAY], + initialDate[java.util.Calendar.MINUTE], + false + ) + timePicker.show() +} + +@Composable +fun FrequencyDialog( + selectedFrequency: String, + onFrequencySelected: (String) -> Unit, + open: Boolean, + onClose: () -> Unit, +) { + val frequencies = listOf( + CALENDAR_FREQ_NEVER, + CALENDAR_FREQ_DAILY, + CALENDAR_FREQ_WEEKLY, + CALENDAR_FREQ_MONTHLY, + CALENDAR_FREQ_YEARLY + ) + if (open) AlertDialog( + onDismissRequest = { onClose() }, + title = {}, + text = { + Column( + modifier = Modifier.padding(12.dp), + verticalArrangement = Arrangement.spacedBy(4.dp) + ) { + frequencies.forEach { frequency -> + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween + ) { + Text( + text = frequency.toUIFrequency(), + style = MaterialTheme.typography.body1 + ) + RadioButton( + selected = frequency == selectedFrequency, + onClick = { onFrequencySelected(frequency) } + ) + } + } + } + }, + buttons = {} + ) +} + +@Composable +fun DeleteEventDialog( + openDialog: Boolean, + onDelete: () -> Unit, + onDismiss: () -> Unit +) { + if (openDialog) AlertDialog( + shape = RoundedCornerShape(25.dp), + onDismissRequest = { onDismiss() }, + title = { Text(stringResource(R.string.delete_event_confirmation_title)) }, + text = { + Text( + stringResource( + R.string.delete_event_confirmation_message + ) + ) + }, + confirmButton = { + Button( + colors = ButtonDefaults.buttonColors(backgroundColor = Color.Red), + shape = RoundedCornerShape(25.dp), + onClick = { + onDelete() + }, + ) { + Text(stringResource(R.string.delete_event), color = Color.White) + } + }, + dismissButton = { + Button( + shape = RoundedCornerShape(25.dp), + onClick = { + onDismiss() + }) { + Text(stringResource(R.string.cancel), color = Color.White) + } + } + ) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/calendar/CalendarEventItem.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/calendar/CalendarEventItem.kt new file mode 100644 index 0000000..b1c8bff --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/calendar/CalendarEventItem.kt @@ -0,0 +1,74 @@ +package com.mhss.app.mybrain.presentation.calendar + +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyItemScope +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.Card +import androidx.compose.material.MaterialTheme +import androidx.compose.material.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import com.mhss.app.mybrain.domain.model.CalendarEvent +import com.mhss.app.mybrain.util.date.formatEventStartEnd + +@OptIn(ExperimentalFoundationApi::class) +@Composable +fun LazyItemScope.CalendarEventItem( + event: CalendarEvent, + modifier: Modifier = Modifier, + onClick: (CalendarEvent) -> Unit +) { + Card( + modifier = modifier + .animateItemPlacement(), + shape = RoundedCornerShape(20.dp), + elevation = 8.dp + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.padding(start = 12.dp) + ) { + Box( + modifier = Modifier + .width(8.dp) + .height(34.dp) + .clip(RoundedCornerShape(4.dp)) + .background(Color(event.color)), + ) + Spacer(Modifier.width(4.dp)) + Column( + modifier = Modifier + .clickable { onClick(event) } + .padding(12.dp) + .fillMaxWidth() + ) { + Text( + event.title, + style = MaterialTheme.typography.body1.copy(fontWeight = FontWeight.Bold), + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + Spacer(Modifier.height(8.dp)) + Text( + formatEventStartEnd( + start = event.start, + end = event.end, + location = event.location, + allDay = event.allDay, + ), + style = MaterialTheme.typography.body1, + ) + + } + } + } +} diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/calendar/CalendarEventSmallItem.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/calendar/CalendarEventSmallItem.kt new file mode 100644 index 0000000..86fadce --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/calendar/CalendarEventSmallItem.kt @@ -0,0 +1,68 @@ +package com.mhss.app.mybrain.presentation.calendar + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.Card +import androidx.compose.material.MaterialTheme +import androidx.compose.material.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import com.mhss.app.mybrain.domain.model.CalendarEvent +import com.mhss.app.mybrain.util.date.formatEventStartEnd + +@Composable +fun CalendarEventSmallItem( + event: CalendarEvent, + onClick: (CalendarEvent) -> Unit +) { + Card( + shape = RoundedCornerShape(16.dp), + elevation = 6.dp, + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.padding(start = 8.dp) + ) { + Box( + modifier = Modifier + .width(6.dp) + .height(26.dp) + .clip(RoundedCornerShape(3.dp)) + .background(Color(event.color)), + ) + Spacer(Modifier.width(4.dp)) + Column( + modifier = Modifier + .clickable { onClick(event) } + .padding(8.dp) + .fillMaxWidth() + ) { + Text( + event.title, + style = MaterialTheme.typography.body2.copy(fontWeight = FontWeight.Bold), + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + Spacer(Modifier.height(6.dp)) + Text( + formatEventStartEnd( + start = event.start, + end = event.end, + location = event.location, + allDay = event.allDay, + ), + style = MaterialTheme.typography.body2, + ) + + } + } + } +} diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/calendar/CalendarEventWidgetItem.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/calendar/CalendarEventWidgetItem.kt new file mode 100644 index 0000000..b9a0f71 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/calendar/CalendarEventWidgetItem.kt @@ -0,0 +1,86 @@ +package com.mhss.app.mybrain.presentation.calendar + +import androidx.compose.runtime.Composable +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.glance.GlanceModifier +import androidx.glance.ImageProvider +import androidx.glance.action.actionParametersOf +import androidx.glance.action.clickable +import androidx.glance.appwidget.action.actionRunCallback +import androidx.glance.appwidget.cornerRadius +import androidx.glance.background +import androidx.glance.layout.* +import androidx.glance.text.FontWeight +import androidx.glance.text.Text +import androidx.glance.text.TextStyle +import androidx.glance.unit.ColorProvider +import com.google.gson.Gson +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.domain.model.CalendarEvent +import com.mhss.app.mybrain.presentation.glance_widgets.CalendarWidgetItemClick +import com.mhss.app.mybrain.presentation.glance_widgets.eventJson +import com.mhss.app.mybrain.util.date.formatEventStartEnd + +@Composable +fun CalendarEventWidgetItem( + event: CalendarEvent, +) { + Box( + GlanceModifier + .padding(vertical = 4.dp) + ) { + Box( + modifier = GlanceModifier + .cornerRadius(16.dp) + .background(ImageProvider(R.drawable.small_item_rounded_corner_shape)) + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = GlanceModifier.padding(start = 8.dp) + ) { + Box( + modifier = GlanceModifier + .width(6.dp) + .height(26.dp) + .cornerRadius(6.dp) + .background(Color(event.color)), + ) {} + Spacer(GlanceModifier.width(4.dp)) + Column( + modifier = GlanceModifier + .padding(8.dp) + .fillMaxWidth() + ) { + Text( + event.title, + style = TextStyle( + color = ColorProvider(Color.White), + fontWeight = FontWeight.Bold, + fontSize = 14.sp + ), + maxLines = 2 + ) + Spacer(GlanceModifier.height(6.dp)) + Text( + formatEventStartEnd( + start = event.start, + end = event.end, + location = event.location, + allDay = event.allDay, + ), + style = TextStyle(color = ColorProvider(Color.LightGray)) + ) + } + } + Box(GlanceModifier.fillMaxSize().clickable( + actionRunCallback( + parameters = actionParametersOf( + eventJson to Gson().toJson(event, CalendarEvent::class.java) + ) + ) + )) {} + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/calendar/CalendarHomeScreenWidget.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/calendar/CalendarHomeScreenWidget.kt new file mode 100644 index 0000000..51fe700 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/calendar/CalendarHomeScreenWidget.kt @@ -0,0 +1,159 @@ +package com.mhss.app.mybrain.presentation.calendar + +import androidx.compose.runtime.Composable +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.glance.* +import androidx.glance.action.clickable +import androidx.glance.appwidget.action.actionRunCallback +import androidx.glance.appwidget.cornerRadius +import androidx.glance.appwidget.lazy.LazyColumn +import androidx.glance.layout.* +import androidx.glance.text.FontWeight +import androidx.glance.text.Text +import androidx.glance.text.TextAlign +import androidx.glance.text.TextStyle +import androidx.glance.unit.ColorProvider +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.app.getString +import com.mhss.app.mybrain.domain.model.CalendarEvent +import com.mhss.app.mybrain.presentation.glance_widgets.AddEventAction +import com.mhss.app.mybrain.presentation.glance_widgets.GoToSettingsAction +import com.mhss.app.mybrain.presentation.glance_widgets.NavigateToCalendarAction +import com.mhss.app.mybrain.presentation.glance_widgets.RefreshCalendarAction + +@Composable +fun CalendarHomeScreenWidget( + events: Map>, + hasPermission: Boolean +) { + Box( + modifier = GlanceModifier + .fillMaxWidth() + .background(ImageProvider(R.drawable.large_item_rounded_corner_shape)) + .cornerRadius(25.dp) + ) { + Column( + modifier = GlanceModifier + .padding(8.dp) + ) { + Row( + GlanceModifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalAlignment = Alignment.CenterHorizontally + ) { + Text( + getString(R.string.calendar), + style = TextStyle( + color = ColorProvider(Color.White), + fontWeight = FontWeight.Bold, + fontSize = 16.sp + ), + modifier = GlanceModifier + .padding(horizontal = 8.dp) + .clickable(onClick = actionRunCallback()) + ) + Row( + modifier = GlanceModifier + .clickable(onClick = actionRunCallback()) + .fillMaxWidth() + .padding(horizontal = 8.dp), + horizontalAlignment = Alignment.End + ) { + Image( + modifier = GlanceModifier + .size(22.dp) + .clickable(actionRunCallback()), + provider = ImageProvider(R.drawable.ic_refresh), + contentDescription = "refresh" + ) + Spacer(GlanceModifier.width(12.dp)) + Image( + modifier = GlanceModifier + .size(22.dp) + .clickable(actionRunCallback()) + , + provider = ImageProvider(R.drawable.ic_add), + contentDescription = "add event", + ) + } + } + Spacer(GlanceModifier.height(8.dp)) + if (hasPermission) { + LazyColumn( + modifier = GlanceModifier + .fillMaxSize() + .background(ImageProvider(R.drawable.large_inner_item_rounded_corner_shape)) + .cornerRadius(20.dp), + horizontalAlignment = Alignment.CenterHorizontally + ) { + if (events.isEmpty()) { + item { + Text( + text = getString(R.string.no_events), + modifier = GlanceModifier.fillMaxWidth().padding(16.dp), + style = TextStyle( + color = ColorProvider(Color.White), + fontWeight = FontWeight.Normal, + fontSize = 18.sp, + textAlign = TextAlign.Center + ), + ) + } + } + item { Spacer(GlanceModifier.height(6.dp)) } + events.forEach { (day, dayEvents) -> + item { + Column( + modifier = GlanceModifier + .fillMaxWidth() + .padding(start = 4.dp, end = 4.dp) + ) { + Text( + text = day.substring(0, day.indexOf(",")), + style = TextStyle( + color = ColorProvider(Color.White), + fontWeight = FontWeight.Normal, + fontSize = 14.sp + ), + modifier = GlanceModifier.padding(bottom = 3.dp) + ) + dayEvents.forEach { event -> + CalendarEventWidgetItem(event = event) + } + } + } + } + } + } else { + Column( + modifier = GlanceModifier.fillMaxSize(), + horizontalAlignment = Alignment.CenterHorizontally + ) { + Text( + text = getString(R.string.no_read_calendar_permission_message), + modifier = GlanceModifier.padding(16.dp), + style = TextStyle( + textAlign = TextAlign.Center, + color = ColorProvider(Color.White) + ) + ) + Spacer(GlanceModifier.height(4.dp)) + Button( + text = getString(R.string.go_to_settings), + onClick = actionRunCallback() + ) + Spacer(GlanceModifier.height(4.dp)) + Text( + text = getString(R.string.calendar_widget_refresh_message), + modifier = GlanceModifier.padding(12.dp), + style = TextStyle( + textAlign = TextAlign.Center + ) + ) + } + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/calendar/CalendarScreen.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/calendar/CalendarScreen.kt new file mode 100644 index 0000000..94bff01 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/calendar/CalendarScreen.kt @@ -0,0 +1,321 @@ +@file:OptIn(ExperimentalPermissionsApi::class, ExperimentalAnimationApi::class) + +package com.mhss.app.mybrain.presentation.calendar + +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.provider.Settings +import androidx.compose.animation.AnimatedContent +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.ExperimentalAnimationApi +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.material.* +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.ArrowDropDown +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.hilt.navigation.compose.hiltViewModel +import androidx.navigation.NavHostController +import com.google.accompanist.permissions.ExperimentalPermissionsApi +import com.google.accompanist.permissions.rememberPermissionState +import com.google.gson.Gson +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.domain.model.Calendar +import com.mhss.app.mybrain.domain.model.CalendarEvent +import com.mhss.app.mybrain.presentation.util.Screen +import com.mhss.app.mybrain.util.Constants +import com.mhss.app.mybrain.util.date.* +import kotlinx.coroutines.launch +import java.net.URLEncoder +import java.nio.charset.StandardCharsets + +@Composable +fun CalendarScreen( + navController: NavHostController, + viewModel: CalendarViewModel = hiltViewModel() +) { + val state = viewModel.uiState + val context = LocalContext.current + val lazyListState = rememberLazyListState() + var settingsVisible by remember { mutableStateOf(false) } + val readCalendarPermissionState = rememberPermissionState( + android.Manifest.permission.READ_CALENDAR + ) + val month by remember(state.events) { + derivedStateOf { + state.events.values.elementAt(lazyListState.firstVisibleItemIndex).first().start.monthName() + } + } + val scope = rememberCoroutineScope() + Scaffold( + topBar = { + TopAppBar( + title = { + Text( + text = stringResource(R.string.calendar), + style = MaterialTheme.typography.h5.copy(fontWeight = FontWeight.Bold) + ) + }, + actions = { + if (state.events.isNotEmpty()) MonthDropDownMenu( + selectedMonth = month, + months = state.months, + onMonthSelected = { selected -> + scope.launch { + lazyListState.scrollToItem( + state.events.values.indexOfFirst { + it.first().start.monthName() == selected + } + ) + } + } + ) + }, + backgroundColor = MaterialTheme.colors.background, + elevation = 0.dp, + ) + }, + floatingActionButton = { + if (readCalendarPermissionState.hasPermission) FloatingActionButton( + onClick = { + navController.navigate( + Screen.CalendarEventDetailsScreen.route.replace( + "{${Constants.CALENDAR_EVENT_ARG}}", + " " + ) + ) + }, + backgroundColor = MaterialTheme.colors.primary, + ) { + Icon( + modifier = Modifier.size(25.dp), + painter = painterResource(R.drawable.ic_add), + contentDescription = stringResource(R.string.add_event), + tint = Color.White + ) + } + }, + ) { + Column( + verticalArrangement = Arrangement.Center, + horizontalAlignment = Alignment.CenterHorizontally, + modifier = Modifier.fillMaxSize() + ) { + if (readCalendarPermissionState.hasPermission) { + LaunchedEffect(true) { + viewModel.onEvent( + CalendarViewModelEvent + .ReadPermissionChanged(readCalendarPermissionState.hasPermission) + ) + } + Row( + Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween + ) { + IconButton(onClick = { settingsVisible = !settingsVisible }) { + Icon( + modifier = Modifier.size(25.dp), + painter = painterResource(R.drawable.ic_settings_sliders), + contentDescription = stringResource(R.string.include_calendars) + ) + } + } + AnimatedVisibility(visible = settingsVisible) { + CalendarSettingsSection( + calendars = state.calendars, onCalendarClicked = { + viewModel.onEvent(CalendarViewModelEvent.IncludeCalendar(it)) + } + ) + } + LazyColumn( + state = lazyListState, + contentPadding = PaddingValues(12.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + modifier = Modifier.fillMaxSize() + ) { + state.events.forEach { (day, events) -> + item { + Column( + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + Text( + text = day.substring(0, day.indexOf(",")), + style = MaterialTheme.typography.h5 + ) + events.forEach { event -> + CalendarEventItem(event = event, onClick = { + val eventJson = Gson().toJson(event, CalendarEvent::class.java) + // encoding the string to avoid crashes when the event contains fields that equals a URL + val encodedJson = URLEncoder.encode(eventJson, StandardCharsets.UTF_8.toString()) + navController.navigate( + Screen.CalendarEventDetailsScreen.route.replace( + "{${Constants.CALENDAR_EVENT_ARG}}", + encodedJson + ) + ) + }) + } + } + } + } + } + } else { + NoReadCalendarPermissionMessage( + shouldShowRationale = readCalendarPermissionState.shouldShowRationale, + context + ) { + readCalendarPermissionState.launchPermissionRequest() + } + } + } + } + +} + +@Composable +fun NoReadCalendarPermissionMessage( + shouldShowRationale: Boolean, + context: Context, + onRequest: () -> Unit +) { + Column( + horizontalAlignment = Alignment.CenterHorizontally + ) { + Text( + text = stringResource(R.string.no_read_calendar_permission_message), + style = MaterialTheme.typography.body1, + textAlign = TextAlign.Center + ) + Spacer(Modifier.height(12.dp)) + if (shouldShowRationale) { + TextButton(onClick = { + val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS) + intent.data = Uri.fromParts("package", context.packageName, null) + context.startActivity(intent) + }) { + Text(text = stringResource(R.string.go_to_settings)) + } + + } else { + TextButton(onClick = { onRequest() }) { + Text(text = stringResource(R.string.grant_permission)) + } + } + } +} + +@Composable +fun MonthDropDownMenu( + selectedMonth: String, + months: List, + onMonthSelected: (String) -> Unit +) { + var expanded by remember { mutableStateOf(false) } + Box( + Modifier + .clickable { expanded = true } + .padding(12.dp) + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + ) { + AnimatedContent(targetState = selectedMonth) { month -> + Text( + text = month, + style = MaterialTheme.typography.h6.copy(fontWeight = FontWeight.Bold) + ) + } + Icon(imageVector = Icons.Default.ArrowDropDown, contentDescription = null) + } + DropdownMenu( + expanded = expanded, + onDismissRequest = { expanded = false }, + ) { + months.forEach { + DropdownMenuItem( + onClick = { + onMonthSelected(it) + expanded = false + } + ) { + Text(text = it) + } + } + } + } +} + +@Composable +fun CalendarSettingsSection( + calendars: Map>, + onCalendarClicked: (Calendar) -> Unit +) { + Column { + Divider() + Text( + text = stringResource(R.string.include_calendars), + style = MaterialTheme.typography.body1.copy(fontWeight = FontWeight.Bold), + modifier = Modifier.padding(8.dp) + ) + Divider() + calendars.keys.forEach { calendar -> + var expanded by remember { mutableStateOf(false) } + Box( + Modifier + .clickable { expanded = true } + .padding(12.dp) + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = calendar, + style = MaterialTheme.typography.body1 + ) + Icon(imageVector = Icons.Default.ArrowDropDown, contentDescription = null) + } + DropdownMenu( + expanded = expanded, + onDismissRequest = { expanded = false }, + ) { + calendars[calendar]?.forEach { subCalendar -> + DropdownMenuItem( + onClick = { + onCalendarClicked(subCalendar) + } + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + Checkbox( + checked = subCalendar.included, + onCheckedChange = { onCalendarClicked(subCalendar) }, + colors = CheckboxDefaults.colors( + uncheckedColor = Color(subCalendar.color), + checkedColor = Color(subCalendar.color) + ) + ) + Text( + text = subCalendar.name, + style = MaterialTheme.typography.body2 + ) + } + } + } + } + } + } + Spacer(Modifier.height(8.dp)) + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/calendar/CalendarViewModel.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/calendar/CalendarViewModel.kt new file mode 100644 index 0000000..5653313 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/calendar/CalendarViewModel.kt @@ -0,0 +1,127 @@ +package com.mhss.app.mybrain.presentation.calendar + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.datastore.preferences.core.stringSetPreferencesKey +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.app.getString +import com.mhss.app.mybrain.domain.model.Calendar +import com.mhss.app.mybrain.domain.model.CalendarEvent +import com.mhss.app.mybrain.domain.use_case.calendar.* +import com.mhss.app.mybrain.domain.use_case.settings.GetSettingsUseCase +import com.mhss.app.mybrain.domain.use_case.settings.SaveSettingsUseCase +import com.mhss.app.mybrain.util.Constants +import com.mhss.app.mybrain.util.date.monthName +import com.mhss.app.mybrain.util.settings.addAndToStringSet +import com.mhss.app.mybrain.util.settings.removeAndToStringSet +import com.mhss.app.mybrain.util.settings.toIntList +import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.launch +import javax.inject.Inject + +@HiltViewModel +class CalendarViewModel @Inject constructor( + private val getAllEventsUseCase: GetAllEventsUseCase, + private val getAllCalendarsUseCase: GetAllCalendarsUseCase, + private val addEvent: AddCalendarEventUseCase, + private val editEvent: UpdateCalendarEventUseCase, + private val deleteEvent: DeleteCalendarEventUseCase, + private val saveSettings: SaveSettingsUseCase, + private val getSettings: GetSettingsUseCase +) : ViewModel() { + + var uiState by mutableStateOf(UiState()) + private set + + private var updateEventsJob : Job? = null + + fun onEvent(event: CalendarViewModelEvent) { + when(event){ + is CalendarViewModelEvent.IncludeCalendar -> updateExcludedCalendars(event.calendar.id.toInt(), event.calendar.included) + is CalendarViewModelEvent.ReadPermissionChanged -> { + if (event.hasPermission) collectSettings() + else updateEventsJob?.cancel() + } + is CalendarViewModelEvent.AddEvent -> viewModelScope.launch { + uiState = if (event.event.title.isNotBlank()) { + if (event.event.start > System.currentTimeMillis()) { + addEvent(event.event) + uiState.copy(navigateUp = true) + } else { + uiState.copy(error = getString(R.string.error_future_event)) + } + } else { + uiState.copy(error = getString(R.string.error_empty_title)) + } + } + is CalendarViewModelEvent.DeleteEvent -> viewModelScope.launch { + if (event.event.title.isNotBlank()) { + deleteEvent(event.event) + uiState = uiState.copy(navigateUp = true) + } + } + is CalendarViewModelEvent.EditEvent -> viewModelScope.launch { + uiState = if (event.event.title.isNotBlank()) { + if (event.event.start > System.currentTimeMillis()) { + editEvent(event.event) + uiState.copy(navigateUp = true) + } else { + uiState.copy(error = getString(R.string.error_future_event)) + } + } else { + uiState.copy(error = getString(R.string.error_empty_title)) + } + } + CalendarViewModelEvent.ErrorDisplayed -> { + uiState = uiState.copy(error = null) + } + } + } + + private fun updateExcludedCalendars(id: Int, add: Boolean) { + viewModelScope.launch { + saveSettings( + stringSetPreferencesKey(Constants.EXCLUDED_CALENDARS_KEY), + if (add) uiState.excludedCalendars.addAndToStringSet(id) + else uiState.excludedCalendars.removeAndToStringSet(id) + ) + } + } + + private fun collectSettings() { + updateEventsJob = getSettings( + stringSetPreferencesKey(Constants.EXCLUDED_CALENDARS_KEY), + emptySet() + ).onEach { calendarsSet -> + val events = getAllEventsUseCase(calendarsSet.toIntList()) + val calendars = getAllCalendarsUseCase(calendarsSet.toIntList()) + val allCalendars = getAllCalendarsUseCase(emptyList()) + val months = events.map { + it.value.first().start.monthName() + }.distinct() + uiState = uiState.copy( + excludedCalendars = calendarsSet.map { it.toInt() }.toMutableList(), + events = events, + calendars = calendars, + months = months, + calendarsList = allCalendars.values.flatten() + ) + }.launchIn(viewModelScope) + } + + data class UiState( + val events: Map> = emptyMap(), + val calendars: Map> = emptyMap(), + val calendarsList: List = emptyList(), + val excludedCalendars: MutableList = mutableListOf(), + val months: List = emptyList(), + val navigateUp: Boolean = false, + val error: String? = null + ) +} diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/calendar/CalendarViewModelEvent.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/calendar/CalendarViewModelEvent.kt new file mode 100644 index 0000000..438bd83 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/calendar/CalendarViewModelEvent.kt @@ -0,0 +1,13 @@ +package com.mhss.app.mybrain.presentation.calendar + +import com.mhss.app.mybrain.domain.model.Calendar +import com.mhss.app.mybrain.domain.model.CalendarEvent + +sealed class CalendarViewModelEvent { + data class IncludeCalendar(val calendar: Calendar) : CalendarViewModelEvent() + data class ReadPermissionChanged(val hasPermission: Boolean) : CalendarViewModelEvent() + data class EditEvent(val event: CalendarEvent) : CalendarViewModelEvent() + data class DeleteEvent(val event: CalendarEvent) : CalendarViewModelEvent() + data class AddEvent(val event: CalendarEvent) : CalendarViewModelEvent() + object ErrorDisplayed : CalendarViewModelEvent() +} diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/diary/DiaryChartScreen.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/diary/DiaryChartScreen.kt new file mode 100644 index 0000000..055fc23 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/diary/DiaryChartScreen.kt @@ -0,0 +1,81 @@ +package com.mhss.app.mybrain.presentation.diary + +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.Tab +import androidx.compose.material.TabPosition +import androidx.compose.material.TabRow +import androidx.compose.material.TabRowDefaults.tabIndicatorOffset +import androidx.compose.material.Text +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.hilt.navigation.compose.hiltViewModel +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.app.getString +import com.mhss.app.mybrain.presentation.tasks.AnimatedTabIndicator + +@Composable +fun DiaryChartScreen( + viewModel: DiaryViewModel = hiltViewModel() +) { + Column( + Modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(12.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + horizontalAlignment = Alignment.CenterHorizontally + ) { + val state = viewModel.uiState + var monthly by remember { mutableStateOf(true) } + MonthlyOrYearlyTab { + viewModel.onEvent(DiaryEvent.ChangeChartEntriesRange(it)) + monthly = it + } + MoodCircularBar(entries = state.chartEntries) + MoodFlowChart(entries = state.chartEntries, monthly) + } +} + +@Composable +fun MonthlyOrYearlyTab( + onChange: (Boolean) -> Unit +) { + var selected by remember { + mutableStateOf(getString(R.string.last_30_days)) + } + val indicator = @Composable { tabPositions: List -> + AnimatedTabIndicator(Modifier.tabIndicatorOffset(tabPositions[if (selected == stringResource(R.string.last_30_days)) 0 else 1])) + } + LaunchedEffect(true){ + onChange(true) + } + TabRow( + selectedTabIndex = if (selected == stringResource(R.string.last_30_days)) 0 else 1, + indicator = indicator, + modifier = Modifier.clip(RoundedCornerShape(14.dp)) + ) { + Tab( + text = { Text(stringResource(R.string.last_30_days)) }, + selected = selected == stringResource(R.string.last_30_days), + onClick = { + selected = getString(R.string.last_30_days) + onChange(true) + }, + ) + Tab( + text = { Text(stringResource(R.string.last_year)) }, + selected = selected == stringResource(R.string.last_year), + onClick = { + selected = getString(R.string.last_year) + onChange(false) + } + ) + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/diary/DiaryEntryDetailsScreen.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/diary/DiaryEntryDetailsScreen.kt new file mode 100644 index 0000000..5589c74 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/diary/DiaryEntryDetailsScreen.kt @@ -0,0 +1,334 @@ +package com.mhss.app.mybrain.presentation.diary + +import android.app.DatePickerDialog +import android.app.TimePickerDialog +import android.content.Context +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.* +import androidx.compose.runtime.* +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.hilt.navigation.compose.hiltViewModel +import androidx.navigation.NavHostController +import com.mhss.app.mybrain.domain.model.DiaryEntry +import com.mhss.app.mybrain.presentation.util.Screen +import com.mhss.app.mybrain.util.diary.Mood +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.util.date.fullDate +import dev.jeziellago.compose.markdowntext.MarkdownText +import java.util.* + +@Composable +fun DiaryEntryDetailsScreen( + navController: NavHostController, + entryId: Int, + viewModel: DiaryViewModel = hiltViewModel() +) { + LaunchedEffect(true) { + if (entryId != -1) { + viewModel.onEvent(DiaryEvent.GetEntry(entryId)) + } + } + val state = viewModel.uiState + val scaffoldState = rememberScaffoldState() + var openDialog by rememberSaveable { mutableStateOf(false) } + val context = LocalContext.current + + var title by rememberSaveable { mutableStateOf(state.entry?.title ?: "") } + var content by rememberSaveable { mutableStateOf(state.entry?.content ?: "") } + var mood by rememberSaveable { mutableStateOf(state.entry?.mood ?: Mood.OKAY) } + var date by rememberSaveable { + mutableLongStateOf( + state.entry?.createdDate ?: System.currentTimeMillis() + ) + } + val readingMode = state.readingMode + + LaunchedEffect(state.entry) { + if (state.entry != null && title.isBlank() && content.isBlank()) { + title = state.entry.title + content = state.entry.content + date = state.entry.createdDate + mood = state.entry.mood + } + } + LaunchedEffect(state) { + if (state.navigateUp) { + openDialog = false + navController.popBackStack(route = Screen.DiaryScreen.route, inclusive = false) + } + if (state.error != null) { + scaffoldState.snackbarHostState.showSnackbar( + state.error + ) + viewModel.onEvent(DiaryEvent.ErrorDisplayed) + } + } + BackHandler { + if (state.entry != null) { + val entry = state.entry.copy( + title = title, + content = content, + mood = mood, + createdDate = date, + updatedDate = System.currentTimeMillis() + ) + if (entryChanged( + state.entry, + entry + ) + ) viewModel.onEvent(DiaryEvent.UpdateEntry(entry)) + else navController.popBackStack(route = Screen.DiaryScreen.route, inclusive = false) + } else + navController.popBackStack(route = Screen.DiaryScreen.route, inclusive = false) + } + Scaffold( + scaffoldState = scaffoldState, + topBar = { + TopAppBar( + title = {}, + actions = { + IconButton(onClick = { + viewModel.onEvent(DiaryEvent.ToggleReadingMode) + }) { + Icon( + painter = painterResource(id = R.drawable.ic_read_mode), + contentDescription = stringResource(R.string.reading_mode), + modifier = Modifier.size(24.dp), + tint = if (readingMode) Color.Green else Color.Gray + ) + } + if (state.entry != null) IconButton(onClick = { openDialog = true }) { + Icon( + painter = painterResource(id = R.drawable.ic_delete), + contentDescription = stringResource(R.string.delete_entry) + ) + } + TextButton(onClick = { + showDatePicker( + Calendar.getInstance().apply { timeInMillis = date }, + context, + onDateSelected = { + date = it + } + ) + }) { + Text( + text = date.fullDate(), + color = MaterialTheme.colors.onBackground, + fontWeight = FontWeight.Bold + ) + } + }, + backgroundColor = MaterialTheme.colors.background, + elevation = 0.dp, + ) + }, + floatingActionButton = { + if (state.entry == null) + FloatingActionButton( + onClick = { + val entry = DiaryEntry( + title = title, + content = content, + mood = mood, + createdDate = date, + updatedDate = System.currentTimeMillis() + ) + viewModel.onEvent(DiaryEvent.AddEntry(entry)) + + }, + backgroundColor = MaterialTheme.colors.primary, + ) { + Icon( + painter = painterResource(id = R.drawable.ic_save), + contentDescription = stringResource(R.string.save_entry), + modifier = Modifier.size(25.dp), + tint = Color.White + ) + } + } + ) { paddingValues -> + Column( + Modifier + .fillMaxSize() + .padding(12.dp) + .padding(paddingValues) + ) { + Text( + text = stringResource(R.string.mood), + style = MaterialTheme.typography.body1, + modifier = Modifier.padding(start = 10.dp) + ) + Spacer(Modifier.height(8.dp)) + EntryMoodSection( + currentMood = mood, + ) { mood = it } + Spacer(Modifier.height(8.dp)) + OutlinedTextField( + value = title, + onValueChange = { title = it }, + label = { Text(text = stringResource(R.string.title)) }, + shape = RoundedCornerShape(15.dp), + modifier = Modifier.fillMaxWidth(), + ) + Spacer(Modifier.height(8.dp)) + if (readingMode) { + MarkdownText( + markdown = content.ifBlank { stringResource(R.string.content) }, + modifier = Modifier + .fillMaxWidth() + .fillMaxHeight() + .padding(vertical = 6.dp) + .border(1.dp, Color.Gray, RoundedCornerShape(20.dp)) + .padding(10.dp) + ) + } else { + OutlinedTextField( + value = content, + onValueChange = { content = it }, + label = { Text(text = stringResource(R.string.content)) }, + shape = RoundedCornerShape(15.dp), + modifier = Modifier.fillMaxWidth(), + ) + } + } + if (openDialog) + AlertDialog( + shape = RoundedCornerShape(25.dp), + onDismissRequest = { openDialog = false }, + title = { Text(stringResource(R.string.delete_diary_entry_confirmation_title)) }, + text = { + Text( + stringResource( + R.string.delete_diary_entry_confirmation_message + ) + ) + }, + confirmButton = { + Button( + colors = ButtonDefaults.buttonColors(backgroundColor = Color.Red), + shape = RoundedCornerShape(25.dp), + onClick = { + viewModel.onEvent(DiaryEvent.DeleteEntry(state.entry!!)) + }, + ) { + Text( + stringResource(R.string.delete_entry), + color = Color.White + ) + } + }, + dismissButton = { + Button( + shape = RoundedCornerShape(25.dp), + onClick = { + openDialog = false + }) { + Text( + stringResource(R.string.cancel), + color = Color.White + ) + } + } + ) + } +} + +@Composable +fun EntryMoodSection( + currentMood: Mood, + onMoodChange: (Mood) -> Unit +) { + val moods = listOf(Mood.AWESOME, Mood.GOOD, Mood.OKAY, Mood.BAD, Mood.TERRIBLE) + Row( + Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + moods.forEach { mood -> + MoodItem( + mood = mood, + chosen = mood == currentMood, + onMoodChange = { onMoodChange(mood) } + ) + } + } +} + +@Composable +private fun MoodItem(mood: Mood, chosen: Boolean, onMoodChange: () -> Unit) { + Box(Modifier.clip(RoundedCornerShape(8.dp))) { + Column( + horizontalAlignment = Alignment.CenterHorizontally, + modifier = Modifier + .clickable { onMoodChange() } + .padding(6.dp) + ) { + Icon( + painter = painterResource(id = mood.icon), + contentDescription = stringResource(mood.title), + tint = if (chosen) mood.color else Color.Gray, + modifier = Modifier.size(48.dp) + ) + Spacer(Modifier.height(8.dp)) + Text( + text = stringResource(mood.title), + color = if (chosen) mood.color else Color.Gray, + style = MaterialTheme.typography.body2 + ) + } + } +} + +private fun entryChanged( + entry: DiaryEntry?, + newEntry: DiaryEntry +): Boolean { + return entry?.title != newEntry.title || + entry.content != newEntry.content || + entry.mood != newEntry.mood || + entry.createdDate != newEntry.createdDate +} + +private fun showDatePicker( + date: Calendar, + context: Context, + onDateSelected: (Long) -> Unit +) { + + val tempDate = Calendar.getInstance() + val timePicker = TimePickerDialog( + context, + { _, hour, minute -> + tempDate[Calendar.HOUR_OF_DAY] = hour + tempDate[Calendar.MINUTE] = minute + onDateSelected(tempDate.timeInMillis) + }, date[Calendar.HOUR_OF_DAY], date[Calendar.MINUTE], false + ) + val datePicker = DatePickerDialog( + context, + { _, year, month, day -> + tempDate[Calendar.YEAR] = year + tempDate[Calendar.MONTH] = month + tempDate[Calendar.DAY_OF_MONTH] = day + timePicker.show() + }, + date[Calendar.YEAR], + date[Calendar.MONTH], + date[Calendar.DAY_OF_MONTH] + ) + datePicker.show() +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/diary/DiaryEntryItem.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/diary/DiaryEntryItem.kt new file mode 100644 index 0000000..2796f7c --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/diary/DiaryEntryItem.kt @@ -0,0 +1,76 @@ +package com.mhss.app.mybrain.presentation.diary + +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyItemScope +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.Card +import androidx.compose.material.Icon +import androidx.compose.material.MaterialTheme +import androidx.compose.material.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.mhss.app.mybrain.domain.model.DiaryEntry +import com.mhss.app.mybrain.util.date.fullDate +import dev.jeziellago.compose.markdowntext.MarkdownText + +@OptIn(ExperimentalFoundationApi::class) +@Composable +fun LazyItemScope.DiaryEntryItem( + modifier: Modifier = Modifier, + entry: DiaryEntry, + onClick: (DiaryEntry) -> Unit +) { + Card( + modifier = modifier + .animateItemPlacement(), + shape = RoundedCornerShape(20.dp), + elevation = 8.dp + ) { + Column( + modifier = Modifier + .clickable { onClick(entry) } + .padding(12.dp) + .fillMaxWidth() + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + Icon( + painterResource(entry.mood.icon), + stringResource(entry.mood.title), + tint = entry.mood.color, + modifier = Modifier.size(30.dp) + ) + Spacer(Modifier.width(8.dp)) + Text( + entry.title, + style = MaterialTheme.typography.body1.copy(fontWeight = FontWeight.Bold), + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + if (entry.content.isNotBlank()){ + MarkdownText( + markdown = entry.content, + maxLines = 10, + onClick = {onClick(entry)}, + fontSize = 12.sp + ) + Spacer(Modifier.height(8.dp)) + } + Spacer(Modifier.height(8.dp)) + Text( + text = entry.createdDate.fullDate(), + style = MaterialTheme.typography.body2.copy(fontWeight = FontWeight.Bold), + modifier = Modifier.align(Alignment.End) + ) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/diary/DiaryEvent.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/diary/DiaryEvent.kt new file mode 100644 index 0000000..8098882 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/diary/DiaryEvent.kt @@ -0,0 +1,16 @@ +package com.mhss.app.mybrain.presentation.diary + +import com.mhss.app.mybrain.domain.model.DiaryEntry +import com.mhss.app.mybrain.util.settings.Order + +sealed class DiaryEvent { + data class AddEntry(val entry: DiaryEntry) : DiaryEvent() + data class GetEntry(val entryId: Int) : DiaryEvent() + data class SearchEntries(val query: String) : DiaryEvent() + data class UpdateOrder(val order: Order) : DiaryEvent() + data class UpdateEntry(val entry: DiaryEntry) : DiaryEvent() + data class DeleteEntry(val entry: DiaryEntry) : DiaryEvent() + data class ChangeChartEntriesRange(val monthly: Boolean) : DiaryEvent() + data object ErrorDisplayed: DiaryEvent() + data object ToggleReadingMode: DiaryEvent() +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/diary/DiaryScreen.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/diary/DiaryScreen.kt new file mode 100644 index 0000000..3fa71e8 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/diary/DiaryScreen.kt @@ -0,0 +1,215 @@ +package com.mhss.app.mybrain.presentation.diary + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material.* +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.hilt.navigation.compose.hiltViewModel +import androidx.navigation.NavHostController +import com.google.accompanist.flowlayout.FlowRow +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.presentation.util.Screen +import com.mhss.app.mybrain.util.Constants +import com.mhss.app.mybrain.util.settings.Order +import com.mhss.app.mybrain.util.settings.OrderType + +@Composable +fun DiaryScreen( + navController: NavHostController, + viewModel: DiaryViewModel = hiltViewModel() +) { + val uiState = viewModel.uiState + var orderSettingsVisible by remember { mutableStateOf(false) } + Scaffold( + topBar = { + TopAppBar( + title = { + Text( + text = stringResource(R.string.diary), + style = MaterialTheme.typography.h5.copy(fontWeight = FontWeight.Bold) + ) + }, + backgroundColor = MaterialTheme.colors.background, + elevation = 0.dp, + actions = { + IconButton(onClick = { + navController.navigate(Screen.DiaryChartScreen.route) + }) { + Icon( + painter = painterResource(id = R.drawable.ic_chart), + contentDescription = stringResource(R.string.diary_chart), + modifier = Modifier.size(34.dp) + ) + } + } + ) + }, + floatingActionButton = { + FloatingActionButton( + onClick = { + navController.navigate( + Screen.DiaryDetailScreen.route.replace( + "{${Constants.DIARY_ID_ARG}}", + "${-1}" + ) + ) + }, + backgroundColor = MaterialTheme.colors.primary, + ) { + Icon( + modifier = Modifier.size(25.dp), + painter = painterResource(R.drawable.ic_add), + contentDescription = stringResource(R.string.add_entry), + tint = Color.White + ) + } + } + ) { + if (uiState.entries.isEmpty()) + NoEntriesMessage() + Column { + Row( + Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween + ) { + IconButton(onClick = { orderSettingsVisible = !orderSettingsVisible }) { + Icon( + modifier = Modifier.size(25.dp), + painter = painterResource(R.drawable.ic_settings_sliders), + contentDescription = stringResource(R.string.order_by) + ) + } + IconButton(onClick = { + navController.navigate(Screen.DiarySearchScreen.route) + }) { + Icon( + modifier = Modifier.size(25.dp), + painter = painterResource(id = R.drawable.ic_search), + contentDescription = stringResource(R.string.search) + ) + } + } + AnimatedVisibility(visible = orderSettingsVisible) { + DiarySettingsSection( + uiState.entriesOrder, + onOrderChange = { + viewModel.onEvent(DiaryEvent.UpdateOrder(it)) + }, + ) + } + LazyColumn( + verticalArrangement = Arrangement.spacedBy(8.dp), + contentPadding = PaddingValues(12.dp) + ) { + items(uiState.entries, key = { it.id }) { entry -> + DiaryEntryItem( + entry = entry, + onClick = { + navController.navigate( + Screen.DiaryDetailScreen.route.replace( + "{${Constants.DIARY_ID_ARG}}", + "${entry.id}" + ) + ) + } + ) + } + } + } + } +} + +@Composable +fun DiarySettingsSection(order: Order, onOrderChange: (Order) -> Unit) { + val orders = listOf( + Order.DateModified(), + Order.DateCreated(), + Order.Alphabetical() + ) + val orderTypes = listOf( + OrderType.ASC(), + OrderType.DESC() + ) + Column( + Modifier.background(color = MaterialTheme.colors.background) + ) { + Text( + text = stringResource(R.string.order_by), + style = MaterialTheme.typography.body1, + modifier = Modifier.padding(start = 8.dp) + ) + FlowRow( + modifier = Modifier.padding(end = 8.dp) + ) { + orders.forEach { + Row(verticalAlignment = Alignment.CenterVertically) { + RadioButton( + selected = order.orderTitle == it.orderTitle, + onClick = { + if (order.orderTitle != it.orderTitle) + onOrderChange( + it.copy(orderType = order.orderType) + ) + } + ) + Text(text = it.orderTitle, style = MaterialTheme.typography.body1) + } + } + } + Divider() + FlowRow { + orderTypes.forEach { + Row(verticalAlignment = Alignment.CenterVertically) { + RadioButton( + selected = order.orderType.orderTitle == it.orderTitle, + onClick = { + if (order.orderTitle != it.orderTitle) + onOrderChange( + order.copy(it) + ) + } + ) + Spacer(modifier = Modifier.width(4.dp)) + Text(text = it.orderTitle, style = MaterialTheme.typography.body1) + } + } + } + Spacer(Modifier.height(8.dp)) + } +} + +@Composable +fun NoEntriesMessage() { + Column( + modifier = Modifier.fillMaxSize(), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center + ) { + Text( + text = stringResource(R.string.no_entries_message), + style = MaterialTheme.typography.body1.copy(fontWeight = FontWeight.Bold), + color = Color.Gray, + textAlign = TextAlign.Center + ) + Spacer(modifier = Modifier.height(12.dp)) + Image( + modifier = Modifier.size(125.dp), + painter = painterResource(id = R.drawable.diary_img), + contentDescription = stringResource(R.string.no_entries_message), + alpha = 0.7f + ) + } +} diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/diary/DiarySearchScreen.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/diary/DiarySearchScreen.kt new file mode 100644 index 0000000..2bf5628 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/diary/DiarySearchScreen.kt @@ -0,0 +1,66 @@ +package com.mhss.app.mybrain.presentation.diary + +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.OutlinedTextField +import androidx.compose.material.Text +import androidx.compose.runtime.* +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.hilt.navigation.compose.hiltViewModel +import androidx.navigation.NavHostController +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.presentation.util.Screen +import com.mhss.app.mybrain.util.Constants + +@Composable +fun DiarySearchScreen( + navController: NavHostController, + viewModel: DiaryViewModel = hiltViewModel() +) { + val state = viewModel.uiState + Column( + modifier = Modifier.fillMaxSize(), + ) { + var query by rememberSaveable { + mutableStateOf("") + } + LaunchedEffect(query){viewModel.onEvent(DiaryEvent.SearchEntries(query))} + val focusRequester = remember { FocusRequester() } + LaunchedEffect(true){focusRequester.requestFocus()} + OutlinedTextField( + value = query, + onValueChange = {query = it}, + label = { Text(stringResource(R.string.search_diary)) }, + shape = RoundedCornerShape(15.dp), + modifier = Modifier + .fillMaxWidth() + .padding(16.dp) + .focusRequester(focusRequester) + ) + LazyColumn( + verticalArrangement = Arrangement.spacedBy(8.dp), + contentPadding = PaddingValues(12.dp) + ) { + items(state.searchEntries, key = {it.id}){ entry -> + DiaryEntryItem( + entry = entry, + onClick = { + navController.navigate( + Screen.DiaryDetailScreen.route.replace( + "{${Constants.DIARY_ID_ARG}}", + "${entry.id}" + ) + ) + } + ) + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/diary/DiaryViewModel.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/diary/DiaryViewModel.kt new file mode 100644 index 0000000..b0ea62a --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/diary/DiaryViewModel.kt @@ -0,0 +1,119 @@ +package com.mhss.app.mybrain.presentation.diary + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.datastore.preferences.core.intPreferencesKey +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.mhss.app.mybrain.domain.model.DiaryEntry +import com.mhss.app.mybrain.domain.use_case.diary.* +import com.mhss.app.mybrain.domain.use_case.settings.GetSettingsUseCase +import com.mhss.app.mybrain.domain.use_case.settings.SaveSettingsUseCase +import com.mhss.app.mybrain.util.Constants +import com.mhss.app.mybrain.util.settings.* +import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.launch +import javax.inject.Inject + +@HiltViewModel +class DiaryViewModel @Inject constructor( + private val addEntry: AddDiaryEntryUseCase, + private val updateEntry: UpdateDiaryEntryUseCase, + private val deleteEntry: DeleteDiaryEntryUseCase, + private val getAlEntries: GetAllEntriesUseCase, + private val searchEntries: SearchEntriesUseCase, + private val getEntry: GetDiaryEntryUseCase, + private val getSettings: GetSettingsUseCase, + private val saveSettings: SaveSettingsUseCase, + private val getEntriesForChart: GetDiaryForChartUseCase +) : ViewModel() { + + var uiState by mutableStateOf(UiState()) + private set + + private var getEntriesJob: Job? = null + + init { + viewModelScope.launch { + getSettings( + intPreferencesKey(Constants.DIARY_ORDER_KEY), + Order.DateModified(OrderType.ASC()).toInt() + ).collect { + getEntries(it.toOrder()) + } + } + } + + fun onEvent(event: DiaryEvent) { + when (event) { + is DiaryEvent.AddEntry -> viewModelScope.launch { + addEntry(event.entry) + uiState = uiState.copy( + navigateUp = true + ) + } + is DiaryEvent.DeleteEntry -> viewModelScope.launch { + deleteEntry(event.entry) + uiState = uiState.copy( + navigateUp = true + ) + } + is DiaryEvent.GetEntry -> viewModelScope.launch { + val entry = getEntry(event.entryId) + uiState = uiState.copy( + entry = entry + ) + } + is DiaryEvent.SearchEntries -> viewModelScope.launch { + val entries = searchEntries(event.query) + uiState = uiState.copy( + searchEntries = entries + ) + } + is DiaryEvent.UpdateEntry -> viewModelScope.launch { + updateEntry(event.entry) + uiState = uiState.copy( + navigateUp = true + ) + } + is DiaryEvent.UpdateOrder -> viewModelScope.launch { + saveSettings( + intPreferencesKey(Constants.DIARY_ORDER_KEY), + event.order.toInt() + ) + } + DiaryEvent.ErrorDisplayed -> uiState = uiState.copy(error = null) + is DiaryEvent.ChangeChartEntriesRange -> viewModelScope.launch { + uiState = uiState.copy(chartEntries = getEntriesForChart(event.monthly)) + } + is DiaryEvent.ToggleReadingMode -> uiState = uiState.copy(readingMode = !uiState.readingMode) + } + } + + data class UiState( + val entries: List = emptyList(), + val entriesOrder: Order = Order.DateModified(OrderType.ASC()), + val entry: DiaryEntry? = null, + val error: String? = null, + val searchEntries: List = emptyList(), + val navigateUp: Boolean = false, + val chartEntries : List = emptyList(), + val readingMode: Boolean = true + ) + + private fun getEntries(order: Order) { + getEntriesJob?.cancel() + getEntriesJob = getAlEntries(order) + .onEach { entries -> + uiState = uiState.copy( + entries = entries, + entriesOrder = order + ) + }.launchIn(viewModelScope) + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/diary/MoodCircularBar.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/diary/MoodCircularBar.kt new file mode 100644 index 0000000..0380acb --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/diary/MoodCircularBar.kt @@ -0,0 +1,205 @@ +package com.mhss.app.mybrain.presentation.diary + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.Card +import androidx.compose.material.Icon +import androidx.compose.material.MaterialTheme +import androidx.compose.material.Text +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.withStyle +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.domain.model.DiaryEntry +import com.mhss.app.mybrain.util.diary.Mood + +@Composable +fun MoodCircularBar( + modifier: Modifier = Modifier, + entries: List, + strokeWidth: Float = 85f, + showPercentage: Boolean = true, + onClick: () -> Unit = {} +) { + Card( + shape = RoundedCornerShape(24.dp), + elevation = 8.dp, + modifier = modifier + .fillMaxWidth() + .padding(6.dp) + ) { + Column( + Modifier.clickable { + onClick() + } + ) { + val mostFrequentMood by remember(entries) { + derivedStateOf { + // if multiple ones with the same frequency, return the most positive one + val entriesGrouped = entries + .groupBy { it.mood } + val max = entriesGrouped.maxOf { it.value.size } + entriesGrouped + .filter { it.value.size == max } + .maxByOrNull { + it.key.value + }?.key ?: Mood.OKAY + } + } + val moods by remember(entries) { + derivedStateOf { + entries.toPercentages() + } + } + Text( + text = stringResource(R.string.mood_summary), + style = MaterialTheme.typography.h6.copy(fontWeight = FontWeight.Bold), + modifier = Modifier + .fillMaxWidth() + .padding(12.dp), + textAlign = TextAlign.Center + ) + if (entries.isNotEmpty()) { + Box( + modifier = Modifier + .fillMaxWidth() + .aspectRatio(1f), + contentAlignment = Alignment.Center + ) { + var currentAngle = remember { 90f } + Canvas( + modifier = Modifier + .fillMaxSize() + .padding(29.dp) + ) { + for ((mood, percentage) in moods) { + drawArc( + color = mood.color, + startAngle = currentAngle, + sweepAngle = percentage * 360f, + useCenter = false, + size = Size(size.width, size.width), + style = Stroke(strokeWidth) + ) + currentAngle += percentage * 360f + } + } + if (showPercentage) Column( + verticalArrangement = Arrangement.spacedBy(8.dp), + horizontalAlignment = Alignment.CenterHorizontally + ) { + for ((mood, percentage) in moods) { + Row( + verticalAlignment = Alignment.CenterVertically + ) { + Text( + stringResource( + R.string.percent, + (percentage * 100).toInt() + ) + ) + Spacer(Modifier.width(8.dp)) + Icon( + painter = painterResource(mood.icon), + contentDescription = stringResource(mood.title), + tint = mood.color, + modifier = Modifier.size(strokeWidth.dp / 3) + ) + } + } + } + } + Text( + text = buildAnnotatedString { + append(stringResource(R.string.your_mood_was)) + withStyle( + SpanStyle( + fontWeight = FontWeight.Bold, + color = mostFrequentMood.color + ) + ) { + append(stringResource(mostFrequentMood.title)) + } + append(stringResource(R.string.most_of_the_time)) + }, + style = MaterialTheme.typography.h6, + modifier = Modifier + .fillMaxWidth() + .padding(12.dp), + textAlign = TextAlign.Center + ) + } else { + Text( + text = stringResource(R.string.no_data_yet), + style = MaterialTheme.typography.body1, + modifier = Modifier + .fillMaxWidth() + .padding(12.dp), + textAlign = TextAlign.Center + ) + } + } + } +} + +fun List.toPercentages(): Map { + return this + .sortedBy { it.mood.value } + .groupingBy { it.mood } + .eachCount() + .mapValues { it.value / this.size.toFloat() } +} + +@Composable +@Preview +fun MoodCircularBarPreview() { + MoodCircularBar( + entries = listOf( + DiaryEntry( + id = 1, + mood = Mood.AWESOME + ), + DiaryEntry( + id = 1, + mood = Mood.AWESOME + ), + DiaryEntry( + id = 2, + mood = Mood.GOOD, + ), + DiaryEntry( + id = 3, + mood = Mood.OKAY, + ), + DiaryEntry( + id = 3, + mood = Mood.OKAY, + ), + DiaryEntry( + id = 4, + mood = Mood.BAD, + ), + DiaryEntry( + id = 5, + mood = Mood.TERRIBLE, + ), + DiaryEntry( + id = 5, + mood = Mood.TERRIBLE, + ) + ) + ) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/diary/MoodFlowChart.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/diary/MoodFlowChart.kt new file mode 100644 index 0000000..acc1bd2 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/diary/MoodFlowChart.kt @@ -0,0 +1,213 @@ +package com.mhss.app.mybrain.presentation.diary + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.Card +import androidx.compose.material.Icon +import androidx.compose.material.MaterialTheme +import androidx.compose.material.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.* +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import com.mhss.app.mybrain.domain.model.DiaryEntry +import com.mhss.app.mybrain.util.diary.Mood +import com.mhss.app.mybrain.R + +@Composable +fun MoodFlowChart( + entries: List, + monthly: Boolean = true +) { + Card( + shape = RoundedCornerShape(24.dp), + elevation = 8.dp, + modifier = Modifier + .fillMaxWidth() + .padding(8.dp) + ) { + Column( + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Text( + text = stringResource(R.string.mood_flow), + style = MaterialTheme.typography.h5, + modifier = Modifier + .fillMaxWidth() + .padding(12.dp), + textAlign = TextAlign.Center + ) + Row( + modifier = Modifier + .fillMaxWidth() + .aspectRatio(2f) + .padding(start = 8.dp), + verticalAlignment = Alignment.CenterVertically + ) { + val mostFrequentMood by remember(entries) { + derivedStateOf { + // if multiple ones with the same frequency, return the most positive one + val entriesGrouped = entries + .groupBy { it.mood } + val max = entriesGrouped.maxOf { it.value.size } + entriesGrouped + .filter { it.value.size == max } + .maxByOrNull { + it.key.value + }?.key ?: Mood.OKAY + } + } + val moods = listOf(Mood.AWESOME, Mood.GOOD, Mood.OKAY, Mood.BAD, Mood.TERRIBLE) + Column( + modifier = Modifier + .wrapContentWidth() + .fillMaxHeight(), + verticalArrangement = Arrangement.SpaceEvenly + ) { + moods.forEach { mood -> + Icon( + painter = painterResource(mood.icon), + tint = mood.color, + contentDescription = stringResource(mood.title), + modifier = Modifier.size(18.dp) + ) + } + } + if (entries.isNotEmpty()) + Canvas( + modifier = Modifier + .fillMaxSize() + .padding(8.dp) + ) { + val w = size.width + val h = size.height + + val max = Mood.AWESOME.value + val count = entries.size + + val offsets = entries.mapIndexed { index, entry -> + Offset( + w * ((if (index == 0) index.toFloat() else index + 1f) / count), + h * (1 - entry.mood.value.toFloat() / max.toFloat()) + ) + } + val path = Path().apply { + moveTo(offsets.first().x, offsets.first().y) + offsets.forEachIndexed { index, offset -> + if (index == 0) return@forEachIndexed + quadTo(offsets[index - 1], offset) + } + } + // workaround to copy compose path by using android path + val fillPath = android.graphics.Path(path.asAndroidPath()) + .asComposePath() + .apply { + lineTo( + if (offsets.size > 1) + (offsets[offsets.size - 2].x + offsets.last().x) / 2 + else offsets.last().x, h + ) + lineTo(0f, h) + close() + } + drawPath( + fillPath, + brush = Brush.verticalGradient( + listOf( + mostFrequentMood.color, + Color.Transparent + ), + endY = h + ) + ) + drawPath( + path, + color = mostFrequentMood.color, + style = Stroke(8f, cap = StrokeCap.Round) + ) + } else { + Text( + text = stringResource(R.string.no_data_yet), + modifier = Modifier.fillMaxSize(), + textAlign = TextAlign.Center + ) + } + } + Text( + text = if (monthly) stringResource(R.string.mood_during_month) + else stringResource(R.string.mood_during_year), + style = MaterialTheme.typography.body1, + modifier = Modifier.padding(bottom = 12.dp) + ) + } + } +} + +fun Path.quadTo(point1: Offset, point2: Offset) { + quadraticBezierTo( + point1.x, + point1.y, + (point1.x + point2.x) / 2f, + (point1.y + point2.y) / 2f, + ) +} + +@Preview +@Composable +fun MoodFlowChartPreview() { + MoodFlowChart( + entries = listOf( + DiaryEntry( + id = 1, + mood = Mood.AWESOME + ), + DiaryEntry( + id = 1, + mood = Mood.AWESOME + ), + DiaryEntry( + id = 2, + mood = Mood.GOOD, + ), + DiaryEntry( + id = 3, + mood = Mood.OKAY, + ), + DiaryEntry( + id = 4, + mood = Mood.GOOD, + ), + DiaryEntry( + id = 5, + mood = Mood.BAD, + ), + DiaryEntry( + id = 6, + mood = Mood.BAD, + ), + DiaryEntry( + id = 7, + mood = Mood.TERRIBLE, + ), + DiaryEntry( + id = 8, + mood = Mood.GOOD, + ), + DiaryEntry( + id = 8, + mood = Mood.BAD, + ) + ) + ) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/glance_widgets/CalendarHomeWidget.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/glance_widgets/CalendarHomeWidget.kt new file mode 100644 index 0000000..118fa6b --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/glance_widgets/CalendarHomeWidget.kt @@ -0,0 +1,53 @@ +package com.mhss.app.mybrain.presentation.glance_widgets + +import android.content.Context +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.core.content.ContextCompat +import androidx.datastore.preferences.core.stringSetPreferencesKey +import androidx.glance.GlanceId +import androidx.glance.appwidget.GlanceAppWidget +import androidx.glance.appwidget.GlanceAppWidgetReceiver +import androidx.glance.appwidget.provideContent +import com.mhss.app.mybrain.di.CalendarWidgetEntryPoint +import com.mhss.app.mybrain.presentation.calendar.CalendarHomeScreenWidget +import com.mhss.app.mybrain.util.Constants +import com.mhss.app.mybrain.util.settings.toIntList +import dagger.hilt.EntryPoints +import kotlinx.coroutines.flow.first + +class CalendarHomeWidget : GlanceAppWidget() { + + override suspend fun provideGlance(context: Context, id: GlanceId) { + + val entryPoint = EntryPoints.get(context, CalendarWidgetEntryPoint::class.java) + val includedCalendars = entryPoint.getSettingsUseCase().invoke( + stringSetPreferencesKey(Constants.EXCLUDED_CALENDARS_KEY), + emptySet() + ).first() + val events = entryPoint.getAllEventsUseCase().invoke(includedCalendars.toIntList(), true) + + provideContent { + val hasPermission by remember { + mutableStateOf( + ContextCompat.checkSelfPermission( + context, + android.Manifest.permission.READ_CALENDAR + ) == android.content.pm.PackageManager.PERMISSION_GRANTED + ) + } + + CalendarHomeScreenWidget( + events, + hasPermission + ) + } + } +} + +class CalendarWidgetReceiver : GlanceAppWidgetReceiver() { + override val glanceAppWidget: GlanceAppWidget = CalendarHomeWidget() + + +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/glance_widgets/CalendarWidgetActions.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/glance_widgets/CalendarWidgetActions.kt new file mode 100644 index 0000000..9de3986 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/glance_widgets/CalendarWidgetActions.kt @@ -0,0 +1,68 @@ +package com.mhss.app.mybrain.presentation.glance_widgets + +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.provider.Settings +import androidx.core.net.toUri +import androidx.glance.GlanceId +import androidx.glance.action.ActionParameters +import androidx.glance.appwidget.action.ActionCallback +import androidx.glance.appwidget.updateAll +import com.mhss.app.mybrain.presentation.main.MainActivity +import com.mhss.app.mybrain.util.Constants + +class AddEventAction : ActionCallback { + override suspend fun onAction(context: Context, glanceId: GlanceId, parameters: ActionParameters) { + val intent = Intent( + Intent.ACTION_VIEW, + "${Constants.CALENDAR_DETAILS_SCREEN_URI}/ ".toUri(), + context, + MainActivity::class.java + ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + context.startActivity(intent) + } +} + +class NavigateToCalendarAction : ActionCallback { + override suspend fun onAction(context: Context, glanceId: GlanceId, parameters: ActionParameters) { + val intent = Intent( + Intent.ACTION_VIEW, + Constants.CALENDAR_SCREEN_URI.toUri(), + context, + MainActivity::class.java + ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + context.startActivity(intent) + } +} + +class CalendarWidgetItemClick : ActionCallback { + override suspend fun onAction(context: Context, glanceId: GlanceId, parameters: ActionParameters) { + parameters[eventJson]?.let { + val intent = Intent( + Intent.ACTION_VIEW, + "${Constants.CALENDAR_DETAILS_SCREEN_URI}/$it".toUri(), + context, + MainActivity::class.java + ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + context.startActivity(intent) + } + } +} + +class GoToSettingsAction : ActionCallback { + override suspend fun onAction(context: Context, glanceId: GlanceId, parameters: ActionParameters) { + val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + intent.data = Uri.fromParts("package", context.packageName, null) + context.startActivity(intent) + } +} + +class RefreshCalendarAction : ActionCallback { + override suspend fun onAction(context: Context, glanceId: GlanceId, parameters: ActionParameters) { + CalendarHomeWidget().updateAll(context) + } +} + + +val eventJson = ActionParameters.Key("eventJson") \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/glance_widgets/CompleteTaskWidgetReceiver.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/glance_widgets/CompleteTaskWidgetReceiver.kt new file mode 100644 index 0000000..fa30594 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/glance_widgets/CompleteTaskWidgetReceiver.kt @@ -0,0 +1,26 @@ +package com.mhss.app.mybrain.presentation.glance_widgets + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import com.mhss.app.mybrain.domain.use_case.tasks.UpdateTaskCompletedUseCase +import dagger.hilt.android.AndroidEntryPoint +import kotlinx.coroutines.runBlocking +import javax.inject.Inject + +@AndroidEntryPoint +class CompleteTaskWidgetReceiver : BroadcastReceiver() { + + @Inject + lateinit var completeTask: UpdateTaskCompletedUseCase + + override fun onReceive(context: Context, intent: Intent) { + val id = intent.getIntExtra("taskId", -1) + val completed = intent.getBooleanExtra("completed", true) + if (id != -1) { + runBlocking { + completeTask(id, completed) + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/glance_widgets/RefreshCalendarWidgetReceiver.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/glance_widgets/RefreshCalendarWidgetReceiver.kt new file mode 100644 index 0000000..61bafcc --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/glance_widgets/RefreshCalendarWidgetReceiver.kt @@ -0,0 +1,17 @@ +package com.mhss.app.mybrain.presentation.glance_widgets + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import androidx.glance.appwidget.updateAll +import kotlinx.coroutines.runBlocking + + +class RefreshCalendarWidgetReceiver : BroadcastReceiver() { + + override fun onReceive(context: Context, intent: Intent) { + runBlocking { + CalendarHomeWidget().updateAll(context) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/glance_widgets/TasksHomeWidget.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/glance_widgets/TasksHomeWidget.kt new file mode 100644 index 0000000..0b36f48 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/glance_widgets/TasksHomeWidget.kt @@ -0,0 +1,44 @@ +package com.mhss.app.mybrain.presentation.glance_widgets + +import android.content.Context +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.datastore.preferences.core.* +import androidx.glance.GlanceId +import androidx.glance.appwidget.GlanceAppWidget +import androidx.glance.appwidget.GlanceAppWidgetReceiver +import androidx.glance.appwidget.provideContent +import com.mhss.app.mybrain.di.TasksWidgetEntryPoint +import com.mhss.app.mybrain.presentation.tasks.TasksHomeScreenWidget +import com.mhss.app.mybrain.util.Constants +import com.mhss.app.mybrain.util.settings.* +import dagger.hilt.EntryPoints + +class TasksHomeWidget : GlanceAppWidget() { + + override suspend fun provideGlance(context: Context, id: GlanceId) { + + val entryPoint = EntryPoints.get(context, TasksWidgetEntryPoint::class.java) + + provideContent { + + val order by entryPoint.getSettingsUseCase().invoke( + intPreferencesKey(Constants.TASKS_ORDER_KEY), + Order.DateModified(OrderType.ASC()).toInt() + ).collectAsState(Order.DateModified(OrderType.ASC()).toInt()) + val showCompletedTasks by entryPoint.getSettingsUseCase().invoke( + booleanPreferencesKey(Constants.SHOW_COMPLETED_TASKS_KEY), + false + ).collectAsState(false) + val tasks by entryPoint.getAllTasksUseCase().invoke(order.toOrder(), showCompletedTasks).collectAsState(emptyList()) + + TasksHomeScreenWidget( + tasks + ) + } + } +} + +class TasksWidgetReceiver : GlanceAppWidgetReceiver() { + override val glanceAppWidget: GlanceAppWidget = TasksHomeWidget() +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/glance_widgets/TasksWidgetActions.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/glance_widgets/TasksWidgetActions.kt new file mode 100644 index 0000000..421aa15 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/glance_widgets/TasksWidgetActions.kt @@ -0,0 +1,64 @@ +package com.mhss.app.mybrain.presentation.glance_widgets + +import android.content.Context +import android.content.Intent +import androidx.core.net.toUri +import androidx.glance.GlanceId +import androidx.glance.action.ActionParameters +import androidx.glance.appwidget.action.ActionCallback +import com.mhss.app.mybrain.presentation.main.MainActivity +import com.mhss.app.mybrain.util.Constants + +class AddTaskAction : ActionCallback { + override suspend fun onAction(context: Context, glanceId: GlanceId, parameters: ActionParameters) { + val intent = Intent( + Intent.ACTION_VIEW, + "${Constants.TASKS_SCREEN_URI}/true".toUri(), + context, + MainActivity::class.java + ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + context.startActivity(intent) + } +} + +class NavigateToTasksAction : ActionCallback { + override suspend fun onAction(context: Context, glanceId: GlanceId, parameters: ActionParameters) { + val intent = Intent( + Intent.ACTION_VIEW, + "${Constants.TASKS_SCREEN_URI}/false".toUri(), + context, + MainActivity::class.java + ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + context.startActivity(intent) + } +} + +class TaskWidgetItemClickAction : ActionCallback { + override suspend fun onAction(context: Context, glanceId: GlanceId, parameters: ActionParameters) { + parameters[taskId]?.let { + val intent = Intent( + Intent.ACTION_VIEW, + "${Constants.TASK_DETAILS_URI}/${it}".toUri(), + context, + MainActivity::class.java + ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + context.startActivity(intent) + } + } +} + +class CompleteTaskAction : ActionCallback { + override suspend fun onAction(context: Context, glanceId: GlanceId, parameters: ActionParameters) { + parameters[taskId]?.let { id -> + parameters[completed].let { completed -> + val intent = Intent(context, CompleteTaskWidgetReceiver::class.java) + intent.putExtra("taskId", id) + intent.putExtra("completed", completed) + context.sendBroadcast(intent) + } + } + } +} + +val taskId = ActionParameters.Key("taskId") +val completed = ActionParameters.Key("completed") \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/main/DashboardEvent.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/main/DashboardEvent.kt new file mode 100644 index 0000000..b4ef805 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/main/DashboardEvent.kt @@ -0,0 +1,10 @@ +package com.mhss.app.mybrain.presentation.main + +import com.mhss.app.mybrain.domain.model.Task + + +sealed class DashboardEvent { + data class ReadPermissionChanged(val hasPermission: Boolean) : DashboardEvent() + data class UpdateTask(val task: Task) : DashboardEvent() + object InitAll : DashboardEvent() +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/main/DashboardScreen.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/main/DashboardScreen.kt new file mode 100644 index 0000000..e7ac000 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/main/DashboardScreen.kt @@ -0,0 +1,137 @@ +package com.mhss.app.mybrain.presentation.main + +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.material.* +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.hilt.navigation.compose.hiltViewModel +import androidx.navigation.NavHostController +import com.google.gson.Gson +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.domain.model.CalendarEvent +import com.mhss.app.mybrain.presentation.calendar.CalendarDashboardWidget +import com.mhss.app.mybrain.presentation.diary.MoodCircularBar +import com.mhss.app.mybrain.presentation.tasks.TasksDashboardWidget +import com.mhss.app.mybrain.presentation.util.Screen +import com.mhss.app.mybrain.util.Constants +import java.net.URLEncoder +import java.nio.charset.StandardCharsets + +@Composable +fun DashboardScreen( + navController: NavHostController, + viewModel: MainViewModel = hiltViewModel() +) { + Scaffold( + topBar = { + TopAppBar( + title = { + Text( + text = stringResource(R.string.dashboard), + style = MaterialTheme.typography.h5.copy(fontWeight = FontWeight.Bold) + ) + }, + backgroundColor = MaterialTheme.colors.background, + elevation = 0.dp + ) + } + ) {paddingValues -> + LaunchedEffect(true) { viewModel.onDashboardEvent(DashboardEvent.InitAll) } + LazyColumn(contentPadding = paddingValues) { + item { + CalendarDashboardWidget( + modifier = Modifier + .fillMaxWidth() + .aspectRatio(1.5f), + events = viewModel.uiState.dashBoardEvents, + onClick = { + navController.navigate( + Screen.CalendarScreen.route + ) + }, + onPermission = { + viewModel.onDashboardEvent(DashboardEvent.ReadPermissionChanged(it)) + }, + onAddEventClicked = { + navController.navigate( + Screen.CalendarEventDetailsScreen.route.replace( + "{${Constants.CALENDAR_EVENT_ARG}}", + " " + ) + ) + }, + onEventClicked = { + val eventJson = Gson().toJson(it, CalendarEvent::class.java) + // encoding the string to avoid crashes when the event contains fields that equals a URL + val encodedJson = URLEncoder.encode(eventJson, StandardCharsets.UTF_8.toString()) + navController.navigate( + Screen.CalendarEventDetailsScreen.route.replace( + "{${Constants.CALENDAR_EVENT_ARG}}", + encodedJson + ) + ) + } + ) + } + item { + TasksDashboardWidget( + modifier = Modifier + .fillMaxWidth() + .aspectRatio(1.5f), + tasks = viewModel.uiState.dashBoardTasks, + onCheck = { + viewModel.onDashboardEvent(DashboardEvent.UpdateTask(it)) + }, + onTaskClick = { + navController.navigate( + Screen.TaskDetailScreen.route + .replace( + "{${Constants.TASK_ID_ARG}}", + it.id.toString() + ) + ) + }, + onAddClick = { + navController.navigate( + Screen.TasksScreen + .route + .replace( + "{${Constants.ADD_TASK_ARG}}", + "true" + ) + ) + }, + onClick = { + navController.navigate( + Screen.TasksScreen.route + ) + } + ) + } + item { + Row { + MoodCircularBar( + entries = viewModel.uiState.dashBoardEntries, + showPercentage = false, + modifier = Modifier.weight(1f, fill = true), + onClick = { + navController.navigate( + Screen.DiaryChartScreen.route + ) + } + ) + TasksSummaryCard( + modifier = Modifier.weight(1f, fill = true), + tasks = viewModel.uiState.summaryTasks + ) + } + } + item { Spacer(Modifier.height(65.dp)) } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/main/MainActivity.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/main/MainActivity.kt new file mode 100644 index 0000000..00532cb --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/main/MainActivity.kt @@ -0,0 +1,277 @@ +package com.mhss.app.mybrain.presentation.main + +import android.Manifest +import android.content.pm.PackageManager +import android.os.Build +import android.os.Bundle +import android.view.WindowManager.LayoutParams +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.activity.viewModels +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material.MaterialTheme +import androidx.compose.material.Surface +import androidx.compose.runtime.* +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.core.app.ActivityCompat +import androidx.core.content.ContextCompat +import androidx.navigation.NavType +import androidx.navigation.compose.NavHost +import androidx.navigation.compose.composable +import androidx.navigation.compose.rememberNavController +import androidx.navigation.navArgument +import androidx.navigation.navDeepLink +import com.google.accompanist.systemuicontroller.rememberSystemUiController +import com.mhss.app.mybrain.domain.use_case.notes.NoteFolderDetailsScreen +import com.mhss.app.mybrain.presentation.bookmarks.BookmarkDetailsScreen +import com.mhss.app.mybrain.presentation.bookmarks.BookmarkSearchScreen +import com.mhss.app.mybrain.presentation.bookmarks.BookmarksScreen +import com.mhss.app.mybrain.presentation.calendar.CalendarEventDetailsScreen +import com.mhss.app.mybrain.presentation.calendar.CalendarScreen +import com.mhss.app.mybrain.presentation.diary.DiaryChartScreen +import com.mhss.app.mybrain.presentation.diary.DiaryEntryDetailsScreen +import com.mhss.app.mybrain.presentation.diary.DiaryScreen +import com.mhss.app.mybrain.presentation.diary.DiarySearchScreen +import com.mhss.app.mybrain.presentation.notes.NoteDetailsScreen +import com.mhss.app.mybrain.presentation.notes.NotesScreen +import com.mhss.app.mybrain.presentation.notes.NotesSearchScreen +import com.mhss.app.mybrain.presentation.settings.ImportExportScreen +import com.mhss.app.mybrain.presentation.tasks.TaskDetailScreen +import com.mhss.app.mybrain.presentation.tasks.TasksScreen +import com.mhss.app.mybrain.presentation.tasks.TasksSearchScreen +import com.mhss.app.mybrain.presentation.util.Screen +import com.mhss.app.mybrain.ui.theme.MyBrainTheme +import com.mhss.app.mybrain.ui.theme.Rubik +import com.mhss.app.mybrain.util.Constants +import com.mhss.app.mybrain.util.settings.StartUpScreenSettings +import com.mhss.app.mybrain.util.settings.ThemeSettings +import com.mhss.app.mybrain.util.settings.toFontFamily +import com.mhss.app.mybrain.util.settings.toInt +import dagger.hilt.android.AndroidEntryPoint +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking + +@Suppress("BlockingMethodInNonBlockingContext") +@AndroidEntryPoint +class MainActivity : ComponentActivity() { + + private val viewModel: MainViewModel by viewModels() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + setContent { + val themeMode = viewModel.themeMode.collectAsState(initial = ThemeSettings.AUTO.value) + val font = viewModel.font.collectAsState(initial = Rubik.toInt()) + val blockScreenshots = viewModel.blockScreenshots.collectAsState(initial = false) + var startUpScreenSettings by remember { mutableStateOf(StartUpScreenSettings.SPACES.value) } + val systemUiController = rememberSystemUiController() + LaunchedEffect(true) { + runBlocking { + startUpScreenSettings = viewModel.defaultStartUpScreen.first() + } + if (!isNotificationPermissionGranted()) + ActivityCompat.requestPermissions( + this@MainActivity, + arrayOf(Manifest.permission.POST_NOTIFICATIONS), + 0 + ) + } + LaunchedEffect(blockScreenshots.value) { + if (blockScreenshots.value) { + window.setFlags( + LayoutParams.FLAG_SECURE, + LayoutParams.FLAG_SECURE + ) + } else + window.clearFlags(LayoutParams.FLAG_SECURE) + } + val startUpScreen = + if (startUpScreenSettings == StartUpScreenSettings.SPACES.value) + Screen.SpacesScreen.route else Screen.DashboardScreen.route + val isDarkMode = when (themeMode.value) { + ThemeSettings.DARK.value -> true + ThemeSettings.LIGHT.value -> false + else -> isSystemInDarkTheme() + } + SideEffect { + systemUiController.setSystemBarsColor( + if (isDarkMode) Color.Black else Color.White, + darkIcons = !isDarkMode + ) + } + MyBrainTheme(darkTheme = isDarkMode, fontFamily = font.value.toFontFamily()) { + val navController = rememberNavController() + Surface( + modifier = Modifier.fillMaxSize(), + color = MaterialTheme.colors.background + ) { + NavHost( + startDestination = Screen.Main.route, + navController = navController + ) { + composable(Screen.Main.route) { + MainScreen( + startUpScreen = startUpScreen, + mainNavController = navController + ) + } + composable( + Screen.TasksScreen.route, + arguments = listOf(navArgument(Constants.ADD_TASK_ARG) { + type = NavType.BoolType + defaultValue = false + }), + deepLinks = + listOf( + navDeepLink { + uriPattern = + "${Constants.TASKS_SCREEN_URI}/{${Constants.ADD_TASK_ARG}}" + } + ) + ) { + TasksScreen( + navController = navController, + addTask = it.arguments?.getBoolean(Constants.ADD_TASK_ARG) + ?: false + ) + } + composable( + Screen.TaskDetailScreen.route, + arguments = listOf(navArgument(Constants.TASK_ID_ARG) { + type = NavType.IntType + }), + deepLinks = + listOf( + navDeepLink { + uriPattern = + "${Constants.TASK_DETAILS_URI}/{${Constants.TASK_ID_ARG}}" + } + ) + ) { + TaskDetailScreen( + navController = navController, + it.arguments?.getInt(Constants.TASK_ID_ARG)!! + ) + } + composable(Screen.TaskSearchScreen.route) { + TasksSearchScreen(navController = navController) + } + composable( + Screen.NotesScreen.route + ) { + NotesScreen(navController = navController) + } + composable( + Screen.NoteDetailsScreen.route, + arguments = listOf(navArgument(Constants.NOTE_ID_ARG) { + type = NavType.IntType + }, + navArgument(Constants.FOLDER_ID) { + type = NavType.IntType + } + ), + ) { + NoteDetailsScreen( + navController, + it.arguments?.getInt(Constants.NOTE_ID_ARG) ?: -1, + it.arguments?.getInt(Constants.FOLDER_ID) ?: -1 + ) + } + composable(Screen.NoteSearchScreen.route) { + NotesSearchScreen(navController = navController) + } + composable(Screen.DiaryScreen.route) { + DiaryScreen(navController = navController) + } + composable(Screen.DiaryChartScreen.route) { + DiaryChartScreen() + } + composable(Screen.DiarySearchScreen.route) { + DiarySearchScreen(navController = navController) + } + composable( + Screen.DiaryDetailScreen.route, + arguments = listOf(navArgument(Constants.DIARY_ID_ARG) { + type = NavType.IntType + }) + ) { + DiaryEntryDetailsScreen( + navController = navController, + it.arguments?.getInt(Constants.DIARY_ID_ARG)!! + ) + } + composable(Screen.BookmarksScreen.route) { + BookmarksScreen(navController = navController) + } + composable( + Screen.BookmarkDetailScreen.route, + arguments = listOf(navArgument(Constants.BOOKMARK_ID_ARG) { + type = NavType.IntType + }) + ) { + BookmarkDetailsScreen( + navController = navController, + it.arguments?.getInt(Constants.BOOKMARK_ID_ARG)!! + ) + } + composable(Screen.BookmarkSearchScreen.route) { + BookmarkSearchScreen(navController = navController) + } + composable( + Screen.CalendarScreen.route, + deepLinks = listOf( + navDeepLink { + uriPattern = Constants.CALENDAR_SCREEN_URI + } + ) + ) { + CalendarScreen(navController = navController) + } + composable( + Screen.CalendarEventDetailsScreen.route, + arguments = listOf(navArgument(Constants.CALENDAR_EVENT_ARG) { + type = NavType.StringType + }), + deepLinks = listOf( + navDeepLink { + uriPattern = + "${Constants.CALENDAR_DETAILS_SCREEN_URI}/{${Constants.CALENDAR_EVENT_ARG}}" + } + ) + ) { + CalendarEventDetailsScreen( + navController = navController, + eventJson = it.arguments?.getString(Constants.CALENDAR_EVENT_ARG) + ?: "" + ) + } + composable( + Screen.NoteFolderDetailsScreen.route, + arguments = listOf(navArgument(Constants.FOLDER_ID) { + type = NavType.IntType + }) + ) { + NoteFolderDetailsScreen( + navController = navController, + it.arguments?.getInt(Constants.FOLDER_ID) ?: -1 + ) + } + composable(Screen.ImportExportScreen.route) { + ImportExportScreen() + } + } + } + } + } + } + + private fun isNotificationPermissionGranted(): Boolean { + return ContextCompat.checkSelfPermission( + this, + Manifest.permission.POST_NOTIFICATIONS + ) == PackageManager.PERMISSION_GRANTED || Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/main/MainScreen.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/main/MainScreen.kt new file mode 100644 index 0000000..4ccc1b7 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/main/MainScreen.kt @@ -0,0 +1,32 @@ +package com.mhss.app.mybrain.presentation.main + +import android.annotation.SuppressLint +import androidx.compose.material.* +import androidx.compose.runtime.* +import androidx.navigation.NavHostController +import androidx.navigation.compose.rememberNavController +import com.mhss.app.mybrain.presentation.main.components.MainBottomBar +import com.mhss.app.mybrain.presentation.main.components.NavigationGraph +import com.mhss.app.mybrain.presentation.util.BottomNavItem + +@SuppressLint("UnusedMaterialScaffoldPaddingParameter") +@Composable +fun MainScreen( + startUpScreen: String, + mainNavController: NavHostController +) { + val navController = rememberNavController() + val bottomNavItems = + listOf(BottomNavItem.Dashboard, BottomNavItem.Spaces, BottomNavItem.Settings) + Scaffold( + bottomBar = { + MainBottomBar(navController = navController, items = bottomNavItems) + } + ) { _ -> + NavigationGraph( + navController = navController, + mainNavController = mainNavController, + startUpScreen = startUpScreen + ) + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/main/MainViewModel.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/main/MainViewModel.kt new file mode 100644 index 0000000..86521f7 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/main/MainViewModel.kt @@ -0,0 +1,108 @@ +package com.mhss.app.mybrain.presentation.main + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.datastore.preferences.core.booleanPreferencesKey +import androidx.datastore.preferences.core.intPreferencesKey +import androidx.datastore.preferences.core.stringSetPreferencesKey +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.mhss.app.mybrain.domain.model.CalendarEvent +import com.mhss.app.mybrain.domain.model.DiaryEntry +import com.mhss.app.mybrain.domain.model.Task +import com.mhss.app.mybrain.domain.use_case.calendar.GetAllEventsUseCase +import com.mhss.app.mybrain.domain.use_case.diary.GetAllEntriesUseCase +import com.mhss.app.mybrain.domain.use_case.settings.GetSettingsUseCase +import com.mhss.app.mybrain.domain.use_case.tasks.GetAllTasksUseCase +import com.mhss.app.mybrain.domain.use_case.tasks.UpdateTaskUseCase +import com.mhss.app.mybrain.ui.theme.Rubik +import com.mhss.app.mybrain.util.Constants +import com.mhss.app.mybrain.util.date.inTheLastWeek +import com.mhss.app.mybrain.util.settings.* +import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.* +import kotlinx.coroutines.launch +import javax.inject.Inject + +@HiltViewModel +class MainViewModel @Inject constructor( + private val getSettings: GetSettingsUseCase, + private val getAllTasks: GetAllTasksUseCase, + private val getAllEntriesUseCase: GetAllEntriesUseCase, + private val updateTask: UpdateTaskUseCase, + private val getAllEventsUseCase: GetAllEventsUseCase +) : ViewModel() { + + var uiState by mutableStateOf(UiState()) + private set + + private var refreshTasksJob : Job? = null + + val themeMode = getSettings(intPreferencesKey(Constants.SETTINGS_THEME_KEY), ThemeSettings.AUTO.value) + val defaultStartUpScreen = getSettings(intPreferencesKey(Constants.DEFAULT_START_UP_SCREEN_KEY), StartUpScreenSettings.SPACES.value) + val font = getSettings(intPreferencesKey(Constants.APP_FONT_KEY), Rubik.toInt()) + val blockScreenshots = getSettings(booleanPreferencesKey(Constants.BLOCK_SCREENSHOTS_KEY), false) + + fun onDashboardEvent(event: DashboardEvent) { + when(event) { + is DashboardEvent.ReadPermissionChanged -> { + if (event.hasPermission) + getCalendarEvents() + } + is DashboardEvent.UpdateTask -> viewModelScope.launch { + updateTask(event.task) + } + DashboardEvent.InitAll -> collectDashboardData() + } + } + + data class UiState( + val dashBoardTasks: List = emptyList(), + val dashBoardEvents: Map> = emptyMap(), + val summaryTasks: List = emptyList(), + val dashBoardEntries: List = emptyList() + ) + + private fun getCalendarEvents() = viewModelScope.launch { + val excluded = getSettings( + stringSetPreferencesKey(Constants.EXCLUDED_CALENDARS_KEY), + emptySet() + ).first() + val events = getAllEventsUseCase(excluded.toIntList()) + uiState = uiState.copy( + dashBoardEvents = events + ) + } + + private fun collectDashboardData() = viewModelScope.launch { + combine( + getSettings( + intPreferencesKey(Constants.TASKS_ORDER_KEY), + Order.DateModified(OrderType.ASC()).toInt() + ), + getSettings( + booleanPreferencesKey(Constants.SHOW_COMPLETED_TASKS_KEY), + false + ), + getAllEntriesUseCase(Order.DateCreated(OrderType.ASC())) + ) { order, showCompleted, entries -> + uiState = uiState.copy( + dashBoardEntries = entries, + ) + refreshTasks(order.toOrder(), showCompleted) + }.collect() + } + + private fun refreshTasks(order: Order, showCompleted: Boolean) { + refreshTasksJob?.cancel() + refreshTasksJob = getAllTasks(order).onEach { tasks -> + uiState = uiState.copy( + dashBoardTasks = if (showCompleted) tasks else tasks.filter { !it.isCompleted }, + summaryTasks = tasks.filter { it.createdDate.inTheLastWeek() } + ) + }.launchIn(viewModelScope) + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/main/SettingsScreen.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/main/SettingsScreen.kt new file mode 100644 index 0000000..2fa9e1f --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/main/SettingsScreen.kt @@ -0,0 +1,385 @@ +package com.mhss.app.mybrain.presentation.main + +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.material.* +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.ArrowDropDown +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.datastore.preferences.core.booleanPreferencesKey +import androidx.datastore.preferences.core.intPreferencesKey +import androidx.hilt.navigation.compose.hiltViewModel +import androidx.navigation.NavHostController +import com.mhss.app.mybrain.BuildConfig +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.presentation.settings.SettingsBasicLinkItem +import com.mhss.app.mybrain.presentation.settings.SettingsItemCard +import com.mhss.app.mybrain.presentation.settings.SettingsViewModel +import com.mhss.app.mybrain.presentation.util.Screen +import com.mhss.app.mybrain.ui.theme.Rubik +import com.mhss.app.mybrain.util.Constants +import com.mhss.app.mybrain.util.settings.* + +@Composable +fun SettingsScreen( + navController: NavHostController, + viewModel: SettingsViewModel = hiltViewModel() +) { + Scaffold( + topBar = { + TopAppBar( + title = { + Text( + text = stringResource(R.string.settings), + style = MaterialTheme.typography.h5.copy(fontWeight = FontWeight.Bold) + ) + }, + backgroundColor = MaterialTheme.colors.background, + elevation = 0.dp, + ) + } + ) { paddingValues -> + LazyColumn(modifier = Modifier.fillMaxWidth(), contentPadding = paddingValues) { + item { + val theme = viewModel + .getSettings( + intPreferencesKey(Constants.SETTINGS_THEME_KEY), ThemeSettings.AUTO.value + ).collectAsState( + initial = ThemeSettings.AUTO.value + ) + ThemeSettingsItem(theme.value) { + when (theme.value) { + ThemeSettings.AUTO.value -> viewModel.saveSettings( + intPreferencesKey(Constants.SETTINGS_THEME_KEY), + ThemeSettings.LIGHT.value + ) + ThemeSettings.LIGHT.value -> viewModel.saveSettings( + intPreferencesKey(Constants.SETTINGS_THEME_KEY), + ThemeSettings.DARK.value + ) + ThemeSettings.DARK.value -> viewModel.saveSettings( + intPreferencesKey(Constants.SETTINGS_THEME_KEY), + ThemeSettings.AUTO.value + ) + } + } + } + item { + val screen = viewModel + .getSettings( + intPreferencesKey(Constants.DEFAULT_START_UP_SCREEN_KEY), + StartUpScreenSettings.SPACES.value + ).collectAsState( + initial = StartUpScreenSettings.SPACES.value + ) + StartUpScreenSettingsItem( + screen.value, + { + viewModel.saveSettings( + intPreferencesKey(Constants.DEFAULT_START_UP_SCREEN_KEY), + StartUpScreenSettings.SPACES.value + ) + }, + { + viewModel.saveSettings( + intPreferencesKey(Constants.DEFAULT_START_UP_SCREEN_KEY), + StartUpScreenSettings.DASHBOARD.value + ) + } + ) + } + item { + val screen = viewModel + .getSettings( + intPreferencesKey(Constants.APP_FONT_KEY), + Rubik.toInt() + ).collectAsState( + initial = Rubik.toInt() + ) + AppFontSettingsItem( + screen.value, + ) { font -> + viewModel.saveSettings( + intPreferencesKey(Constants.APP_FONT_KEY), + font + ) + } + } + item { + val block = viewModel + .getSettings( + booleanPreferencesKey(Constants.BLOCK_SCREENSHOTS_KEY), + false + ).collectAsState( + initial = false + ) + BlockScreenshotsSettingsItem( + block.value + ){ + viewModel.saveSettings( + booleanPreferencesKey(Constants.BLOCK_SCREENSHOTS_KEY), + it + ) + } + } + + item { + SettingsItemCard( + cornerRadius = 16.dp, + onClick = { + navController.navigate(Screen.ImportExportScreen.route) + } + ) { + Row { + Icon(painter = painterResource(id = R.drawable.ic_import_export), contentDescription = null) + Spacer(modifier = Modifier.width(8.dp)) + Text( + text = stringResource(R.string.export_import), + style = MaterialTheme.typography.h6 + ) + } + } + } + + item { + Text( + text = stringResource(R.string.about), + style = MaterialTheme.typography.h5, + modifier = Modifier + .padding(vertical = 16.dp, horizontal = 12.dp) + ) + } + + item { + SettingsBasicLinkItem( + title = R.string.app_version, + icon = R.drawable.ic_code, + subtitle = BuildConfig.VERSION_NAME, + link = Constants.GITHUB_RELEASES_LINK + ) + } + item { + SettingsBasicLinkItem( + title = R.string.project_on_github, + icon = R.drawable.ic_github, + link = Constants.PROJECT_GITHUB_LINK + ) + } + + item { + SettingsBasicLinkItem( + title = R.string.privacy_policy, + icon = R.drawable.ic_privacy, + link = Constants.PRIVACY_POLICY_LINK + ) + } + + item { + Text( + text = stringResource(R.string.product), + style = MaterialTheme.typography.h5, + modifier = Modifier + .padding(vertical = 16.dp, horizontal = 12.dp) + ) + } + + item { + SettingsBasicLinkItem( + title = R.string.request_feature_report_bug, + icon = R.drawable.ic_feature_issue, + link = Constants.GITHUB_ISSUES_LINK + ) + } + + item { + SettingsBasicLinkItem( + title = R.string.project_roadmap, + icon = R.drawable.ic_roadmap, + link = Constants.PROJECT_ROADMAP_LINK + ) + } + item { Spacer(Modifier.height(60.dp)) } + } + } +} + +@Composable +fun ThemeSettingsItem(theme: Int = 0, onClick: () -> Unit = {}) { + SettingsItemCard( + onClick = onClick, + cornerRadius = 18.dp + ) { + Text( + text = stringResource(R.string.app_theme), + style = MaterialTheme.typography.h6 + ) + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + text = when (theme) { + ThemeSettings.LIGHT.value -> stringResource(R.string.light_theme) + ThemeSettings.DARK.value -> stringResource(R.string.dark_theme) + else -> stringResource(R.string.auto_theme) + }, + style = MaterialTheme.typography.body1 + ) + Spacer(modifier = Modifier.width(4.dp)) + Icon( + painter = when (theme) { + ThemeSettings.LIGHT.value -> painterResource(id = R.drawable.ic_sun) + ThemeSettings.DARK.value -> painterResource(id = R.drawable.ic_dark) + else -> painterResource(id = R.drawable.ic_auto) + }, + contentDescription = theme.toString() + ) + } + } +} + +@Composable +fun StartUpScreenSettingsItem( + screen: Int, + onSpacesClick: () -> Unit = {}, + onDashboardClick: () -> Unit = {} +) { + var expanded by remember { mutableStateOf(false) } + SettingsItemCard( + cornerRadius = 16.dp, + onClick = { + expanded = true + }, + ) { + Text( + text = stringResource(R.string.start_up_screen), + style = MaterialTheme.typography.h6 + ) + Box( + modifier = Modifier + .fillMaxWidth(), + contentAlignment = Alignment.CenterEnd + ) { + Row( + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = when (screen) { + StartUpScreenSettings.SPACES.value -> stringResource(R.string.spaces) + StartUpScreenSettings.DASHBOARD.value -> stringResource(R.string.dashboard) + else -> stringResource(R.string.spaces) + }, + style = MaterialTheme.typography.body1 + ) + Spacer(modifier = Modifier.width(4.dp)) + Icon(imageVector = Icons.Default.ArrowDropDown, contentDescription = null) + } + DropdownMenu( + expanded = expanded, + onDismissRequest = { expanded = false }, + ) { + DropdownMenuItem(onClick = { + onSpacesClick() + expanded = false + }) { + Text( + text = stringResource(id = R.string.spaces), + style = MaterialTheme.typography.body1 + ) + } + DropdownMenuItem(onClick = { + onDashboardClick() + expanded = false + }) { + Text( + text = stringResource(id = R.string.dashboard), + style = MaterialTheme.typography.body1 + ) + } + } + } + } +} + +@Composable +fun AppFontSettingsItem( + selectedFont: Int, + onFontChange: (Int) -> Unit = {} +) { + var expanded by remember { mutableStateOf(false) } + val fonts = listOf( + FontFamily.Default, + Rubik, + FontFamily.Monospace, + FontFamily.SansSerif + ) + SettingsItemCard( + cornerRadius = 16.dp, + onClick = { + expanded = true + }, + ) { + Text( + text = stringResource(R.string.app_font), + style = MaterialTheme.typography.h6 + ) + Box( + modifier = Modifier + .fillMaxWidth(), + contentAlignment = Alignment.CenterEnd + ) { + Row( + verticalAlignment = Alignment.CenterVertically + ) { + Text( + selectedFont.toFontFamily().getName(), + style = MaterialTheme.typography.body1 + ) + Spacer(modifier = Modifier.width(4.dp)) + Icon(imageVector = Icons.Default.ArrowDropDown, contentDescription = null) + } + DropdownMenu( + expanded = expanded, + onDismissRequest = { expanded = false }, + ) { + fonts.forEach { + DropdownMenuItem(onClick = { + onFontChange(it.toInt()) + expanded = false + }) { + Text( + text = it.getName(), + style = MaterialTheme.typography.body1 + ) + } + } + } + } + } +} + +@Composable +fun BlockScreenshotsSettingsItem( + block: Boolean, + onBlockClick: (Boolean) -> Unit = {} +) { + SettingsItemCard( + cornerRadius = 16.dp, + onClick = { + onBlockClick(!block) + }, + vPadding = 10.dp + ) { + Text( + text = stringResource(R.string.block_screenshots), + style = MaterialTheme.typography.h6 + ) + Switch(checked = block, onCheckedChange = { + onBlockClick(it) + }) + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/main/SpacesScreen.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/main/SpacesScreen.kt new file mode 100644 index 0000000..1232c2c --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/main/SpacesScreen.kt @@ -0,0 +1,105 @@ + +package com.mhss.app.mybrain.presentation.main + +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.material.MaterialTheme +import androidx.compose.material.Scaffold +import androidx.compose.material.Text +import androidx.compose.material.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import androidx.navigation.NavHostController +import androidx.navigation.compose.rememberNavController +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.presentation.main.components.SpaceRegularCard +import com.mhss.app.mybrain.presentation.main.components.SpaceWideCard +import com.mhss.app.mybrain.presentation.util.Screen +import com.mhss.app.mybrain.ui.theme.* + +@Composable +fun SpacesScreen( + navController: NavHostController +) { + Scaffold( + topBar = { + TopAppBar( + title = { + Text( + text = stringResource(R.string.spaces), + style = MaterialTheme.typography.h5.copy(fontWeight = FontWeight.Bold) + ) + }, + backgroundColor = MaterialTheme.colors.background, + elevation = 0.dp + ) + } + ) { paddingValues -> + LazyColumn(contentPadding = paddingValues) { + item { + Row { + SpaceRegularCard( + modifier = Modifier.weight(1f, fill = true), + title = stringResource(R.string.notes), + image = R.drawable.notes_img, + backgroundColor = Blue + ){ + navController.navigate(Screen.NotesScreen.route) + } + SpaceRegularCard( + modifier = Modifier.weight(1f, fill = true), + title = stringResource(R.string.tasks), + image = R.drawable.tasks_img, + backgroundColor = Red + ){ + navController.navigate( + Screen.TasksScreen.route + ) + } + } + } + item { + Row { + SpaceRegularCard( + modifier = Modifier.weight(1f, fill = true), + title = stringResource(R.string.diary), + image = R.drawable.diary_img, + backgroundColor = Green + ){ + navController.navigate(Screen.DiaryScreen.route) + } + SpaceRegularCard( + modifier = Modifier.weight(1f, fill = true), + title = stringResource(R.string.bookmarks), + image = R.drawable.bookmarks_img, + backgroundColor = Orange + ){ + navController.navigate(Screen.BookmarksScreen.route) + } + } + } + item { + SpaceWideCard( + title = stringResource(R.string.calendar), + image = R.drawable.calendar_img, + backgroundColor = Purple + ){ + navController.navigate(Screen.CalendarScreen.route) + } + } + item { Spacer(Modifier.height(60.dp)) } + } + } +} + +@Preview +@Composable +fun SpacesScreenPreview() { + SpacesScreen( + navController = rememberNavController() + ) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/main/TasksSummaryCard.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/main/TasksSummaryCard.kt new file mode 100644 index 0000000..a9632ba --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/main/TasksSummaryCard.kt @@ -0,0 +1,115 @@ +package com.mhss.app.mybrain.presentation.main + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.Card +import androidx.compose.material.MaterialTheme +import androidx.compose.material.Text +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.StrokeCap +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.withStyle +import androidx.compose.ui.unit.dp +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.domain.model.Task +import com.mhss.app.mybrain.ui.theme.Blue + +@Composable +fun TasksSummaryCard( + tasks: List, + modifier: Modifier = Modifier, +) { + Card( + shape = RoundedCornerShape(24.dp), + elevation = 8.dp, + modifier = modifier + .fillMaxWidth() + .padding(6.dp) + ) { + val percentage by remember(tasks) { + derivedStateOf { + tasks.count { it.isCompleted }.toFloat() / tasks.size + } + } + Column { + Text( + text = stringResource(R.string.tasks_summary), + style = MaterialTheme.typography.h6.copy(fontWeight = FontWeight.Bold), + modifier = Modifier + .fillMaxWidth() + .padding(12.dp), + textAlign = TextAlign.Center + ) + if (tasks.isNotEmpty()) { + Box( + modifier = Modifier + .fillMaxWidth() + .aspectRatio(1f), + contentAlignment = Alignment.Center + ) { + Canvas( + modifier = Modifier + .fillMaxSize() + .padding(29.dp) + ) { + drawArc( + color = Color.Gray, + startAngle = 145f, + sweepAngle = 255f, + useCenter = false, + size = Size(size.width, size.width), + style = Stroke(65f, cap = StrokeCap.Round) + ) + drawArc( + color = Blue, + startAngle = 145f, + sweepAngle = percentage * 255f, + useCenter = false, + size = Size(size.width, size.width), + style = Stroke(65f, cap = StrokeCap.Round) + ) + } + } + Text( + text = buildAnnotatedString { + append(stringResource(R.string.you_completed)) + append(" ") + withStyle( + SpanStyle( + fontWeight = FontWeight.Bold, + ) + ) { + append(stringResource(R.string.percent, (percentage * 100).toInt())) + } + append(" ") + append(stringResource(R.string.of_last_week_tasks)) + }, + style = MaterialTheme.typography.h6, + modifier = Modifier + .fillMaxWidth() + .padding(12.dp), + textAlign = TextAlign.Center + ) + } else { + Text( + text = stringResource(R.string.no_tasks_yet), + style = MaterialTheme.typography.body1, + modifier = Modifier + .fillMaxWidth() + .padding(12.dp), + textAlign = TextAlign.Center + ) + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/main/components/MainBottomBar.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/main/components/MainBottomBar.kt new file mode 100644 index 0000000..74eb48d --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/main/components/MainBottomBar.kt @@ -0,0 +1,45 @@ +package com.mhss.app.mybrain.presentation.main.components + +import androidx.compose.material.* +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.navigation.NavGraph.Companion.findStartDestination +import androidx.navigation.NavHostController +import androidx.navigation.compose.currentBackStackEntryAsState +import com.mhss.app.mybrain.presentation.util.BottomNavItem + +@Composable +fun MainBottomBar( + navController: NavHostController, + items: List, +) { + BottomNavigation (backgroundColor = MaterialTheme.colors.background) { + val navBackStackEntry by navController.currentBackStackEntryAsState() + val currentDestination = navBackStackEntry?.destination + items.forEach { + BottomNavigationItem( + icon = { Icon( + if (currentDestination?.route == it.route) + painterResource(it.iconSelected) + else + painterResource(it.icon) + , + contentDescription = stringResource(it.title), + ) }, + selected = currentDestination?.route == it.route, + onClick = { + navController.navigate(it.route) { + popUpTo(navController.graph.findStartDestination().id) { + saveState = true + } + launchSingleTop = true + restoreState = true + } + }, + alwaysShowLabel = false + ) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/main/components/NavigationGraph.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/main/components/NavigationGraph.kt new file mode 100644 index 0000000..4e1500b --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/main/components/NavigationGraph.kt @@ -0,0 +1,30 @@ +package com.mhss.app.mybrain.presentation.main.components + +import androidx.compose.runtime.Composable +import androidx.navigation.NavHostController +import androidx.navigation.compose.NavHost +import androidx.navigation.compose.composable +import com.mhss.app.mybrain.presentation.main.DashboardScreen +import com.mhss.app.mybrain.presentation.main.SettingsScreen +import com.mhss.app.mybrain.presentation.main.SpacesScreen +import com.mhss.app.mybrain.presentation.util.Screen + +@Composable +fun NavigationGraph( + navController: NavHostController, + mainNavController: NavHostController, + startUpScreen: String +) { + NavHost(navController = navController, startDestination = startUpScreen){ + + composable(Screen.DashboardScreen.route){ + DashboardScreen(mainNavController) + } + composable(Screen.SpacesScreen.route){ + SpacesScreen(mainNavController) + } + composable(Screen.SettingsScreen.route){ + SettingsScreen(mainNavController) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/main/components/SpaceCards.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/main/components/SpaceCards.kt new file mode 100644 index 0000000..a31fb7f --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/main/components/SpaceCards.kt @@ -0,0 +1,96 @@ +package com.mhss.app.mybrain.presentation.main.components + +import androidx.compose.foundation.Image +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.Card +import androidx.compose.material.MaterialTheme +import androidx.compose.material.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.ui.theme.Blue + +@Composable +fun SpaceRegularCard( + title: String, + image: Int, + backgroundColor: Color, + modifier: Modifier = Modifier, + onClick: () -> Unit = {} +) { + Card( + modifier = modifier.padding(8.dp), + shape = RoundedCornerShape(25.dp), + backgroundColor = backgroundColor, + elevation = 12.dp + ) { + Column( + Modifier + .clickable { onClick() } + .aspectRatio(1.0f) + .padding(18.dp), + verticalArrangement = Arrangement.SpaceBetween + ) { + Text(text = title, style = MaterialTheme.typography.h5.copy(color = Color.White)) + Image( + modifier = Modifier + .size(70.dp) + .align(Alignment.End), + painter = painterResource(id = image), + contentDescription = title) + + } + } +} + +@Composable +fun SpaceWideCard( + title: String, + image: Int, + backgroundColor: Color = Color.White, + onClick: () -> Unit = {} +) { + Card( + modifier = Modifier.padding(8.dp), + shape = RoundedCornerShape(25.dp), + backgroundColor = backgroundColor, + elevation = 12.dp + ) { + Column( + Modifier + .fillMaxWidth() + .clickable { onClick() } + .padding(18.dp), + ) { + Text( + text = title, + style = MaterialTheme.typography.h4.copy(color = Color.White), + ) + Spacer(Modifier.height(12.dp)) + Image( + modifier = Modifier + .size(80.dp) + .align(Alignment.End), + painter = painterResource(id = image), + contentDescription = title) + + } + } +} + +@Preview +@Composable +fun SpaceRegularCardPreview() { + SpaceRegularCard( + "Notes", + R.drawable.notes_img, + Blue + ) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/notes/NoteDetailsScreen.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/notes/NoteDetailsScreen.kt new file mode 100644 index 0000000..a1c04ba --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/notes/NoteDetailsScreen.kt @@ -0,0 +1,372 @@ +package com.mhss.app.mybrain.presentation.notes + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.* +import androidx.compose.runtime.* +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.hilt.navigation.compose.hiltViewModel +import androidx.navigation.NavHostController +import com.google.accompanist.flowlayout.FlowRow +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.domain.model.Note +import com.mhss.app.mybrain.domain.model.NoteFolder +import com.mhss.app.mybrain.presentation.util.Screen +import com.mhss.app.mybrain.ui.theme.Orange +import com.mhss.app.mybrain.util.date.formatDateDependingOnDay +import dev.jeziellago.compose.markdowntext.MarkdownText + +@Composable +fun NoteDetailsScreen( + navController: NavHostController, + noteId: Int, + folderId: Int, + viewModel: NotesViewModel = hiltViewModel() +) { + LaunchedEffect(true) { + if (noteId != -1) viewModel.onEvent(NoteEvent.GetNote(noteId)) + if (folderId != -1) viewModel.onEvent(NoteEvent.GetFolder(folderId)) + } + val state = viewModel.notesUiState + val scaffoldState = rememberScaffoldState() + var openDeleteDialog by rememberSaveable { mutableStateOf(false) } + var openFolderDialog by rememberSaveable { mutableStateOf(false) } + + var title by rememberSaveable { mutableStateOf(state.note?.title ?: "") } + var content by rememberSaveable { mutableStateOf(state.note?.content ?: "") } + var pinned by rememberSaveable { mutableStateOf(state.note?.pinned ?: false) } + val readingMode = state.readingMode + var folder: NoteFolder? by remember { mutableStateOf(state.folder) } + val lastModified by remember(state.note) { + derivedStateOf { state.note?.updatedDate?.formatDateDependingOnDay() } + } + val wordCountString by remember { + derivedStateOf { content.split(" ").size.toString() } + } + + + LaunchedEffect(state.note) { + if (state.note != null) { + title = state.note.title + content = state.note.content + pinned = state.note.pinned + folder = state.folder + } + } + LaunchedEffect(state) { + if (state.navigateUp) { + openDeleteDialog = false + navController.popBackStack(route = Screen.NotesScreen.route, inclusive = false) + } + if (state.error != null) { + scaffoldState.snackbarHostState.showSnackbar( + state.error + ) + viewModel.onEvent(NoteEvent.ErrorDisplayed) + } + if (state.folder != folder) folder = state.folder + } + BackHandler { + addOrUpdateNote( + Note( + title = title, + content = content, + pinned = pinned, + folderId = folder?.id + ), + state.note, + onNotChanged = { + navController.popBackStack( + route = Screen.NotesScreen.route, + inclusive = false + ) + }, + onUpdate = { + if (state.note != null) { + viewModel.onEvent( + NoteEvent.UpdateNote( + state.note.copy( + title = title, + content = content, + folderId = folder?.id + ) + ) + ) + } else { + viewModel.onEvent( + NoteEvent.AddNote( + Note( + title = title, + content = content, + pinned = pinned, + folderId = folder?.id + ) + ) + ) + } + + } + ) + } + Scaffold( + scaffoldState = scaffoldState, + topBar = { + TopAppBar( + title = { + if (folder != null) { + Row( + modifier = Modifier + .clip(RoundedCornerShape(25.dp)) + .border(1.dp, Color.Gray, RoundedCornerShape(25.dp)) + .clickable { openFolderDialog = true }, + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + painterResource(R.drawable.ic_folder), + stringResource(R.string.folders), + modifier = Modifier.padding(start = 8.dp, top = 8.dp, bottom = 8.dp) + ) + Spacer(Modifier.width(8.dp)) + Text( + text = folder?.name!!, + modifier = Modifier.padding(end = 8.dp, top = 8.dp, bottom = 8.dp), + style = MaterialTheme.typography.body1 + ) + } + } else { + IconButton(onClick = { openFolderDialog = true }) { + Icon( + painterResource(R.drawable.ic_create_folder), + stringResource(R.string.folders), + modifier = Modifier.padding(12.dp) + ) + } + } + }, + actions = { + if (state.note != null) IconButton(onClick = { openDeleteDialog = true }) { + Icon( + painter = painterResource(id = R.drawable.ic_delete), + contentDescription = stringResource(R.string.delete_task) + ) + } + IconButton(onClick = { + pinned = !pinned + if (state.note != null) { + viewModel.onEvent(NoteEvent.PinNote) + } + }) { + Icon( + painter = if (pinned) painterResource(id = R.drawable.ic_pin_filled) + else painterResource(id = R.drawable.ic_pin), + contentDescription = stringResource(R.string.pin_note), + modifier = Modifier.size(24.dp), + tint = Orange + ) + } + IconButton(onClick = { + viewModel.onEvent(NoteEvent.ToggleReadingMode) + }) { + Icon( + painter = painterResource(id = R.drawable.ic_read_mode), + contentDescription = stringResource(R.string.reading_mode), + modifier = Modifier.size(24.dp), + tint = if (readingMode) Color.Green else Color.Gray + ) + } + }, + backgroundColor = MaterialTheme.colors.background, + elevation = 0.dp, + ) + }, + ) { paddingValues -> + Column( + Modifier + .fillMaxSize() + .padding(12.dp) + .padding(paddingValues) + ) { + OutlinedTextField( + value = title, + onValueChange = { title = it }, + label = { Text(text = stringResource(R.string.title)) }, + shape = RoundedCornerShape(15.dp), + modifier = Modifier.fillMaxWidth(), + ) + if (readingMode) + MarkdownText( + markdown = content.ifBlank { stringResource(R.string.note_content) }, + modifier = Modifier + .fillMaxWidth() + .weight(1f) + .padding(vertical = 6.dp) + .border(1.dp, Color.Gray, RoundedCornerShape(20.dp)) + .padding(10.dp) + ) + else + OutlinedTextField( + value = content, + onValueChange = { content = it }, + label = { + Text(text = stringResource(R.string.note_content)) + }, + shape = RoundedCornerShape(15.dp), + modifier = Modifier + .fillMaxWidth() + .weight(1f) + .padding(bottom = 8.dp), + ) + + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween + ) { + Text( + text = lastModified ?: "", + style = MaterialTheme.typography.caption.copy(color = Color.Gray) + ) + Text( + text = wordCountString, + style = MaterialTheme.typography.caption.copy(color = Color.Gray) + ) + } + } + if (openDeleteDialog) + AlertDialog( + shape = RoundedCornerShape(25.dp), + onDismissRequest = { openDeleteDialog = false }, + title = { Text(stringResource(R.string.delete_note_confirmation_title)) }, + text = { + Text( + stringResource( + R.string.delete_note_confirmation_message, + state.note?.title!! + ) + ) + }, + confirmButton = { + Button( + colors = ButtonDefaults.buttonColors(backgroundColor = Color.Red), + shape = RoundedCornerShape(25.dp), + onClick = { + viewModel.onEvent(NoteEvent.DeleteNote(state.note!!)) + }, + ) { + Text(stringResource(R.string.delete_note), color = Color.White) + } + }, + dismissButton = { + Button( + shape = RoundedCornerShape(25.dp), + onClick = { + openDeleteDialog = false + }) { + Text(stringResource(R.string.cancel), color = Color.White) + } + } + ) + if (openFolderDialog) + AlertDialog( + shape = RoundedCornerShape(25.dp), + onDismissRequest = { openFolderDialog = false }, + title = { Text(stringResource(R.string.change_folder)) }, + text = { + FlowRow { + Row( + modifier = Modifier + .padding(4.dp) + .clip(RoundedCornerShape(25.dp)) + .border(1.dp, Color.Gray, RoundedCornerShape(25.dp)) + .clickable { + folder = null + openFolderDialog = false + } + .background(if (folder == null) MaterialTheme.colors.onBackground else Color.Transparent), + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = stringResource(R.string.none), + modifier = Modifier.padding(8.dp), + style = MaterialTheme.typography.body1, + color = if (folder == null) MaterialTheme.colors.background else MaterialTheme.colors.onBackground + ) + } + state.folders.forEach { + Row( + modifier = Modifier + .padding(4.dp) + .clip(RoundedCornerShape(25.dp)) + .border(1.dp, Color.Gray, RoundedCornerShape(25.dp)) + .clickable { + folder = it + openFolderDialog = false + } + .background(if (folder?.id == it.id) MaterialTheme.colors.onBackground else Color.Transparent), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + painterResource(R.drawable.ic_folder), + stringResource(R.string.folders), + modifier = Modifier.padding( + start = 8.dp, + top = 8.dp, + bottom = 8.dp + ), + tint = if (folder?.id == it.id) MaterialTheme.colors.background else MaterialTheme.colors.onBackground + ) + Spacer(Modifier.width(8.dp)) + Text( + text = it.name, + modifier = Modifier.padding( + end = 8.dp, + top = 8.dp, + bottom = 8.dp + ), + style = MaterialTheme.typography.body1, + color = if (folder?.id == it.id) MaterialTheme.colors.background else MaterialTheme.colors.onBackground + ) + } + } + } + }, + buttons = {} + ) + } +} + +private fun addOrUpdateNote( + newNote: Note, + note: Note? = null, + onNotChanged: () -> Unit = {}, + onUpdate: (Note) -> Unit, +) { + if (note != null) { + if (noteChanged(newNote, note)) + onUpdate(note) + else + onNotChanged() + } else { + onUpdate(newNote) + } +} + +private fun noteChanged( + note: Note, + newNote: Note +): Boolean { + return note.title != newNote.title || + note.content != newNote.content || + note.folderId != newNote.folderId +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/notes/NoteEvent.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/notes/NoteEvent.kt new file mode 100644 index 0000000..869509b --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/notes/NoteEvent.kt @@ -0,0 +1,24 @@ +package com.mhss.app.mybrain.presentation.notes + +import com.mhss.app.mybrain.domain.model.Note +import com.mhss.app.mybrain.domain.model.NoteFolder +import com.mhss.app.mybrain.util.settings.ItemView +import com.mhss.app.mybrain.util.settings.Order + +sealed class NoteEvent { + data class GetNote(val noteId: Int) : NoteEvent() + data class AddNote(val note: Note) : NoteEvent() + data class SearchNotes(val query: String) : NoteEvent() + data class UpdateOrder(val order: Order) : NoteEvent() + data class UpdateView(val view: ItemView) : NoteEvent() + data class UpdateNote(val note: Note) : NoteEvent() + data class DeleteNote(val note: Note) : NoteEvent() + object PinNote : NoteEvent() + object ToggleReadingMode : NoteEvent() + object ErrorDisplayed: NoteEvent() + data class CreateFolder(val folder: NoteFolder): NoteEvent() + data class DeleteFolder(val folder: NoteFolder): NoteEvent() + data class UpdateFolder(val folder: NoteFolder): NoteEvent() + data class GetFolderNotes(val id: Int): NoteEvent() + data class GetFolder(val id: Int): NoteEvent() +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/notes/NoteItem.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/notes/NoteItem.kt new file mode 100644 index 0000000..a2feaeb --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/notes/NoteItem.kt @@ -0,0 +1,78 @@ +package com.mhss.app.mybrain.presentation.notes + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.Card +import androidx.compose.material.Icon +import androidx.compose.material.MaterialTheme +import androidx.compose.material.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.domain.model.Note +import com.mhss.app.mybrain.ui.theme.Orange +import com.mhss.app.mybrain.util.date.formatDateDependingOnDay +import dev.jeziellago.compose.markdowntext.MarkdownText + +@Composable +fun NoteItem( + modifier: Modifier = Modifier, + note: Note, + onClick: (Note) -> Unit +) { + Card( + modifier = modifier, + shape = RoundedCornerShape(20.dp), + elevation = 4.dp + ) { + Column( + modifier = Modifier + .clickable { onClick(note) } + .padding(12.dp) + .fillMaxWidth() + ) { + Row( + verticalAlignment = Alignment.CenterVertically + ){ + if (note.pinned){ + Icon( + painter = painterResource(R.drawable.ic_pin_filled), + contentDescription = stringResource(R.string.pin_note), + tint = Orange, + modifier = Modifier + .size(16.dp) + ) + Spacer(Modifier.width(4.dp)) + } + Text( + note.title, + style = MaterialTheme.typography.body1.copy(fontWeight = FontWeight.Bold), + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + Spacer(Modifier.height(8.dp)) + MarkdownText( + markdown = note.content, + maxLines = 14, + onClick = {onClick(note)}, + fontSize = 12.sp + ) + Spacer(Modifier.height(8.dp)) + Text( + text = note.updatedDate.formatDateDependingOnDay(), + style = MaterialTheme.typography.caption.copy(color = Color.Gray), + modifier = Modifier.align(Alignment.End) + ) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/notes/NotesScreen.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/notes/NotesScreen.kt new file mode 100644 index 0000000..83c5817 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/notes/NotesScreen.kt @@ -0,0 +1,446 @@ +package com.mhss.app.mybrain.presentation.notes + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.grid.GridCells +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.grid.LazyVerticalGrid +import androidx.compose.foundation.lazy.grid.items +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid +import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells +import androidx.compose.foundation.lazy.staggeredgrid.items +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.* +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.hilt.navigation.compose.hiltViewModel +import androidx.navigation.NavHostController +import com.google.accompanist.flowlayout.FlowRow +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.domain.model.NoteFolder +import com.mhss.app.mybrain.presentation.util.Screen +import com.mhss.app.mybrain.util.Constants +import com.mhss.app.mybrain.util.settings.* + +@OptIn(ExperimentalFoundationApi::class) +@Composable +fun NotesScreen( + navController: NavHostController, + viewModel: NotesViewModel = hiltViewModel() +) { + val uiState = viewModel.notesUiState + var orderSettingsVisible by remember { mutableStateOf(false) } + var selectedTab by remember { mutableStateOf(0) } + var openCreateFolderDialog by remember { mutableStateOf(false) } + val scaffoldState = rememberScaffoldState() + LaunchedEffect(uiState.error) { + uiState.error?.let { + scaffoldState.snackbarHostState.showSnackbar( + it + ) + viewModel.onEvent(NoteEvent.ErrorDisplayed) + } + } + Scaffold( + scaffoldState = scaffoldState, + topBar = { + TopAppBar( + title = { + Text( + text = if (selectedTab == 0) stringResource(R.string.notes) else stringResource( + R.string.folders + ), + style = MaterialTheme.typography.h5.copy(fontWeight = FontWeight.Bold) + ) + }, + backgroundColor = MaterialTheme.colors.background, + elevation = 0.dp, + ) + }, + floatingActionButton = { + FloatingActionButton( + onClick = { + if (selectedTab == 0) { + navController.navigate( + Screen.NoteDetailsScreen.route.replace( + "{${Constants.NOTE_ID_ARG}}", + "${-1}" + ).replace( + "{${Constants.FOLDER_ID}}", + "-1" + ) + ) + } else { + openCreateFolderDialog = true + } + }, + backgroundColor = MaterialTheme.colors.primary, + ) { + Icon( + modifier = Modifier.size(25.dp), + painter = if (selectedTab == 0) painterResource(R.drawable.ic_add) else painterResource( + R.drawable.ic_create_folder + ), + contentDescription = stringResource(R.string.add_note), + tint = Color.White + ) + } + }, + ) { paddingValues -> + Column(modifier = Modifier.padding(paddingValues)) { + TabRow( + selectedTabIndex = selectedTab, + backgroundColor = MaterialTheme.colors.background + ) { + Tab( + text = { Text(stringResource(R.string.notes)) }, + selected = selectedTab == 0, + onClick = { + selectedTab = 0 + } + ) + Tab( + text = { Text(stringResource(R.string.folders)) }, + selected = selectedTab == 1, + onClick = { + selectedTab = 1 + } + ) + } + if (selectedTab == 0) { + if (uiState.notes.isEmpty()) + NoNotesMessage() + Row( + Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween + ) { + IconButton(onClick = { orderSettingsVisible = !orderSettingsVisible }) { + Icon( + modifier = Modifier.size(25.dp), + painter = painterResource(R.drawable.ic_settings_sliders), + contentDescription = stringResource(R.string.order_by) + ) + } + IconButton(onClick = { + navController.navigate(Screen.NoteSearchScreen.route) + }) { + Icon( + modifier = Modifier.size(25.dp), + painter = painterResource(id = R.drawable.ic_search), + contentDescription = stringResource(R.string.search) + ) + } + } + AnimatedVisibility(visible = orderSettingsVisible) { + NotesSettingsSection( + uiState.notesOrder, + uiState.noteView, + onOrderChange = { + viewModel.onEvent(NoteEvent.UpdateOrder(it)) + }, + onViewChange = { + viewModel.onEvent(NoteEvent.UpdateView(it)) + } + ) + } + if (uiState.noteView == ItemView.LIST) { + LazyColumn( + verticalArrangement = Arrangement.spacedBy(8.dp), + contentPadding = PaddingValues( + top = 12.dp, + bottom = 24.dp, + start = 12.dp, + end = 12.dp + ) + ) { + items(uiState.notes, key = { it.id }) { note -> + NoteItem( + note = note, + onClick = { + navController.navigate( + Screen.NoteDetailsScreen.route.replace( + "{${Constants.NOTE_ID_ARG}}", + "${note.id}" + ).replace( + "{${Constants.FOLDER_ID}}", + "-1" + ) + ) + }, + modifier = Modifier.animateItemPlacement() + ) + } + } + } else { + LazyVerticalStaggeredGrid( + columns = StaggeredGridCells.Adaptive(150.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), + contentPadding = PaddingValues(12.dp) + ) { + items(uiState.notes) { note -> + key(note.id) { + NoteItem( + note = note, + onClick = { + navController.navigate( + Screen.NoteDetailsScreen.route.replace( + "{${Constants.NOTE_ID_ARG}}", + "${note.id}" + ).replace( + "{${Constants.FOLDER_ID}}", + "-1" + ) + ) + }, + modifier = Modifier.padding(bottom = 12.dp) + ) + } + } + } + } + } else { + FoldersTab(uiState.folders) { + navController.navigate( + Screen.NoteFolderDetailsScreen.route.replace( + "{${Constants.FOLDER_ID}}", + "${it.id}" + ) + ) + } + if (openCreateFolderDialog) + CreateFolderDialog( + onCreate = { + viewModel.onEvent(NoteEvent.CreateFolder(NoteFolder(it.trim()))) + openCreateFolderDialog = false + }, + onDismiss = { + openCreateFolderDialog = false + } + ) + } + } + } +} + +@Composable +fun FoldersTab( + folders: List, + onItemClick: (NoteFolder) -> Unit +) { + LazyVerticalGrid( + columns = GridCells.Fixed(2), + verticalArrangement = Arrangement.spacedBy(12.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), + contentPadding = PaddingValues( + top = 12.dp, + bottom = 24.dp, + start = 12.dp, + end = 12.dp + ) + ) { + items(folders) { folder -> + Card( + modifier = Modifier.height(180.dp), + shape = RoundedCornerShape(20.dp), + elevation = 8.dp + ) { + Column( + Modifier + .fillMaxSize() + .clickable { onItemClick(folder) }, + verticalArrangement = Arrangement.Center, + horizontalAlignment = Alignment.CenterHorizontally + ) { + Icon( + painter = painterResource(R.drawable.ic_folder), + contentDescription = folder.name, + modifier = Modifier.size(100.dp) + ) + Text( + text = folder.name, + style = MaterialTheme.typography.h6.copy(fontWeight = FontWeight.Bold), + maxLines = 2, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.fillMaxWidth(), + textAlign = TextAlign.Center + ) + } + } + } + } +} + +@Composable +fun NotesSettingsSection( + order: Order, + view: ItemView, + onOrderChange: (Order) -> Unit, + onViewChange: (ItemView) -> Unit +) { + val orders = listOf( + Order.DateModified(), + Order.DateCreated(), + Order.Alphabetical() + ) + val orderTypes = listOf( + OrderType.ASC(), + OrderType.DESC() + ) + val noteViews = listOf( + ItemView.LIST, + ItemView.GRID + ) + Column( + Modifier.background(color = MaterialTheme.colors.background) + ) { + Text( + text = stringResource(R.string.order_by), + style = MaterialTheme.typography.body1, + modifier = Modifier.padding(start = 8.dp) + ) + FlowRow( + modifier = Modifier.padding(end = 8.dp) + ) { + orders.forEach { + Row(verticalAlignment = Alignment.CenterVertically) { + RadioButton( + selected = order.orderTitle == it.orderTitle, + onClick = { + if (order.orderTitle != it.orderTitle) + onOrderChange( + it.copy(orderType = order.orderType) + ) + } + ) + Text(text = it.orderTitle, style = MaterialTheme.typography.body1) + } + } + } + Divider() + FlowRow { + orderTypes.forEach { + Row(verticalAlignment = Alignment.CenterVertically) { + RadioButton( + selected = order.orderType.orderTitle == it.orderTitle, + onClick = { + if (order.orderTitle != it.orderTitle) + onOrderChange( + order.copy(it) + ) + } + ) + Spacer(modifier = Modifier.width(4.dp)) + Text(text = it.orderTitle, style = MaterialTheme.typography.body1) + } + } + } + Divider() + Text( + text = stringResource(R.string.view_as), + style = MaterialTheme.typography.body1, + modifier = Modifier.padding(start = 8.dp, top = 8.dp) + ) + FlowRow { + noteViews.forEach { + Row(verticalAlignment = Alignment.CenterVertically) { + RadioButton( + selected = view.title == it.title, + onClick = { + if (view.title != it.title) + onViewChange( + it + ) + } + ) + Spacer(modifier = Modifier.width(4.dp)) + Text(text = stringResource(it.title), style = MaterialTheme.typography.body1) + } + } + } + Spacer(Modifier.height(8.dp)) + } +} + +@Composable +fun NoNotesMessage() { + Column( + modifier = Modifier.fillMaxSize(), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center + ) { + Text( + text = stringResource(R.string.no_notes_message), + style = MaterialTheme.typography.body1.copy(fontWeight = FontWeight.Bold), + color = Color.Gray, + textAlign = TextAlign.Center + ) + Spacer(modifier = Modifier.height(12.dp)) + Image( + modifier = Modifier.size(125.dp), + painter = painterResource(id = R.drawable.notes_img), + contentDescription = stringResource(R.string.no_notes_message), + alpha = 0.7f + ) + } +} + +@Composable +fun CreateFolderDialog( + onCreate: (String) -> Unit, + onDismiss: () -> Unit +) { + var name by remember { mutableStateOf("") } + AlertDialog( + onDismissRequest = { onDismiss() }, + title = { + Text( + text = stringResource(id = R.string.create_folder), + style = MaterialTheme.typography.h6 + ) + }, + text = { + TextField( + value = name, + onValueChange = { name = it }, + label = { + Text( + text = stringResource(id = R.string.name), + style = MaterialTheme.typography.body1 + ) + }, + ) + }, + confirmButton = { + Button( + shape = RoundedCornerShape(25.dp), + onClick = { + onCreate(name) + }, + ) { + Text(stringResource(R.string.create_folder), color = Color.White) + } + }, + dismissButton = { + TextButton( + shape = RoundedCornerShape(25.dp), + onClick = { onDismiss() }, + ) { + Text(stringResource(R.string.cancel), color = Color.White) + } + } + ) +} diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/notes/NotesSearchScreen.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/notes/NotesSearchScreen.kt new file mode 100644 index 0000000..4ddcb3a --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/notes/NotesSearchScreen.kt @@ -0,0 +1,103 @@ +package com.mhss.app.mybrain.presentation.notes + +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid +import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells +import androidx.compose.foundation.lazy.staggeredgrid.items +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.OutlinedTextField +import androidx.compose.material.Text +import androidx.compose.runtime.* +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.hilt.navigation.compose.hiltViewModel +import androidx.navigation.NavHostController +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.presentation.util.Screen +import com.mhss.app.mybrain.util.Constants +import com.mhss.app.mybrain.util.settings.ItemView + +@OptIn(ExperimentalFoundationApi::class) +@Composable +fun NotesSearchScreen( + navController: NavHostController, + viewModel: NotesViewModel = hiltViewModel() +) { + val state = viewModel.notesUiState + Column( + modifier = Modifier.fillMaxSize(), + ) { + var query by rememberSaveable { + mutableStateOf("") + } + LaunchedEffect(query){viewModel.onEvent(NoteEvent.SearchNotes(query))} + val focusRequester = remember { FocusRequester() } + LaunchedEffect(true){focusRequester.requestFocus()} + OutlinedTextField( + value = query, + onValueChange = {query = it}, + label = { Text(stringResource(R.string.search_notes)) }, + shape = RoundedCornerShape(15.dp), + modifier = Modifier + .fillMaxWidth() + .padding(16.dp) + .focusRequester(focusRequester) + ) + if (state.noteView == ItemView.LIST){ + LazyColumn( + verticalArrangement = Arrangement.spacedBy(8.dp), + contentPadding = PaddingValues(12.dp) + ) { + items(state.searchNotes, key = {it.id}) { note -> + NoteItem( + note = note, + onClick = { + navController.navigate( + Screen.NoteDetailsScreen.route.replace( + "{${Constants.NOTE_ID_ARG}}", + "${note.id}" + ).replace( + "{${Constants.FOLDER_ID}}", + "" + ) + ) + } + ) + } + } + } else { + LazyVerticalStaggeredGrid( + columns = StaggeredGridCells.Adaptive(150.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), + contentPadding = PaddingValues(12.dp) + ){ + items(state.searchNotes){ note -> + key(note.id) { + NoteItem( + note = note, + onClick = { + navController.navigate( + Screen.NoteDetailsScreen.route.replace( + "{${Constants.NOTE_ID_ARG}}", + "${note.id}" + ).replace( + "{${Constants.FOLDER_ID}}", + "" + ) + ) + }, + modifier = Modifier.padding(bottom = 12.dp) + ) + } + } + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/notes/NotesViewModel.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/notes/NotesViewModel.kt new file mode 100644 index 0000000..8c79d7a --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/notes/NotesViewModel.kt @@ -0,0 +1,196 @@ +package com.mhss.app.mybrain.presentation.notes + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.datastore.preferences.core.intPreferencesKey +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.app.getString +import com.mhss.app.mybrain.domain.model.Note +import com.mhss.app.mybrain.domain.model.NoteFolder +import com.mhss.app.mybrain.domain.use_case.notes.* +import com.mhss.app.mybrain.domain.use_case.settings.GetSettingsUseCase +import com.mhss.app.mybrain.domain.use_case.settings.SaveSettingsUseCase +import com.mhss.app.mybrain.util.Constants +import com.mhss.app.mybrain.util.settings.* +import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.* +import kotlinx.coroutines.launch +import javax.inject.Inject + +@HiltViewModel +class NotesViewModel @Inject constructor( + private val allNotes: GetAllNotesUseCase, + private val getNote: GetNoteUseCase, + private val updateNote: UpdateNoteUseCase, + private val addNote: AddNoteUseCase, + private val searchNotes: SearchNotesUseCase, + private val deleteNote: DeleteNoteUseCase, + private val getSettings: GetSettingsUseCase, + private val saveSettings: SaveSettingsUseCase, + private val getAllFolders: GetAllNoteFoldersUseCase, + private val createFolder: AddNoteFolderUseCass, + private val deleteFolder: DeleteNoteFolderUseCass, + private val updateFolder: UpdateNoteFolderUseCass, + private val getFolderNotes: GetNotesByFolderUseCase, +) : ViewModel() { + + var notesUiState by mutableStateOf((UiState())) + private set + + private var getNotesJob: Job? = null + private var getFolderNotesJob: Job? = null + + init { + viewModelScope.launch { + combine( + getSettings( + intPreferencesKey(Constants.NOTES_ORDER_KEY), + Order.DateModified(OrderType.ASC()).toInt() + ), + getSettings( + intPreferencesKey(Constants.NOTE_VIEW_KEY), + ItemView.LIST.value + ), + getAllFolders() + ) { order, view, folders -> + notesUiState = notesUiState.copy(notesOrder = order.toOrder(), folders = folders) + getNotes(order.toOrder()) + if (notesUiState.noteView.value != view) { + notesUiState = notesUiState.copy(noteView = view.toNotesView()) + } + }.collect() + } + } + + fun onEvent(event: NoteEvent) { + when (event) { + is NoteEvent.AddNote -> viewModelScope.launch { + notesUiState = if (event.note.title.isBlank() && event.note.content.isBlank()) { + notesUiState.copy(navigateUp = true) + } else { + addNote( + event.note.copy( + createdDate = System.currentTimeMillis(), + updatedDate = System.currentTimeMillis() + ) + ) + notesUiState.copy(navigateUp = true) + } + } + is NoteEvent.DeleteNote -> viewModelScope.launch { + deleteNote(event.note) + notesUiState = notesUiState.copy(navigateUp = true) + } + is NoteEvent.GetNote -> viewModelScope.launch { + val note = getNote(event.noteId) + val folder = getAllFolders().first().firstOrNull { it.id == note.folderId } + notesUiState = notesUiState.copy(note = note, folder = folder) + } + is NoteEvent.SearchNotes -> viewModelScope.launch { + val notes = searchNotes(event.query) + notesUiState = notesUiState.copy(searchNotes = notes) + } + is NoteEvent.UpdateNote -> viewModelScope.launch { + notesUiState = if (event.note.title.isBlank() && event.note.content.isBlank()) + notesUiState.copy(error = getString(R.string.error_empty_note)) + else { + updateNote(event.note.copy(updatedDate = System.currentTimeMillis())) + notesUiState.copy(navigateUp = true) + } + } + is NoteEvent.UpdateOrder -> viewModelScope.launch { + saveSettings( + intPreferencesKey(Constants.NOTES_ORDER_KEY), + event.order.toInt() + ) + } + is NoteEvent.ErrorDisplayed -> notesUiState = notesUiState.copy(error = null) + NoteEvent.ToggleReadingMode -> notesUiState = + notesUiState.copy(readingMode = !notesUiState.readingMode) + is NoteEvent.PinNote -> viewModelScope.launch { + updateNote(notesUiState.note?.copy(pinned = !notesUiState.note?.pinned!!)!!) + } + is NoteEvent.UpdateView -> viewModelScope.launch { + saveSettings( + intPreferencesKey(Constants.NOTE_VIEW_KEY), + event.view.value + ) + } + is NoteEvent.CreateFolder -> viewModelScope.launch { + if (event.folder.name.isBlank()) { + notesUiState = notesUiState.copy(error = getString(R.string.error_empty_title)) + } else { + if (!notesUiState.folders.contains(event.folder)) { + createFolder(event.folder) + } else { + notesUiState = notesUiState.copy(error = getString(R.string.error_folder_exists)) + } + } + } + is NoteEvent.DeleteFolder -> viewModelScope.launch { + deleteFolder(event.folder) + notesUiState = notesUiState.copy(navigateUp = true) + } + is NoteEvent.UpdateFolder -> viewModelScope.launch { + if (event.folder.name.isBlank()) { + notesUiState = notesUiState.copy(error = getString(R.string.error_empty_title)) + } else { + if (!notesUiState.folders.contains(event.folder)) { + updateFolder(event.folder) + notesUiState = notesUiState.copy(folder = event.folder) + } else { + notesUiState = notesUiState.copy(error = getString(R.string.error_folder_exists)) + } + } + } + is NoteEvent.GetFolderNotes -> { + getNotesFromFolder(event.id, notesUiState.notesOrder) + } + is NoteEvent.GetFolder -> viewModelScope.launch { + val folder = getAllFolders().first().firstOrNull { it.id == event.id } + notesUiState = notesUiState.copy(folder = folder) + } + } + } + + data class UiState( + val notes: List = emptyList(), + val note: Note? = null, + val notesOrder: Order = Order.DateModified(OrderType.ASC()), + val error: String? = null, + val noteView: ItemView = ItemView.LIST, + val navigateUp: Boolean = false, + val readingMode: Boolean = true, + val searchNotes: List = emptyList(), + val folders: List = emptyList(), + val folderNotes: List = emptyList(), + val folder: NoteFolder? = null + ) + + private fun getNotes(order: Order) { + getNotesJob?.cancel() + getNotesJob = allNotes(order) + .onEach { notes -> + notesUiState = notesUiState.copy( + notes = notes, + notesOrder = order + ) + }.launchIn(viewModelScope) + } + + private fun getNotesFromFolder(id: Int, order: Order) { + getFolderNotesJob?.cancel() + getFolderNotesJob = getFolderNotes(id, order) + .onEach { notes -> + val noteFolder = getAllFolders().first().firstOrNull() { it.id == id } + notesUiState = notesUiState.copy( + folderNotes = notes, + folder = noteFolder + ) + }.launchIn(viewModelScope) + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/settings/ImportExportScreen.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/settings/ImportExportScreen.kt new file mode 100644 index 0000000..d4f4360 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/settings/ImportExportScreen.kt @@ -0,0 +1,200 @@ +package com.mhss.app.mybrain.presentation.settings + +import android.app.Activity +import android.content.Context +import android.content.ContextWrapper +import android.content.Intent +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.* +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.hilt.navigation.compose.hiltViewModel +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.presentation.main.MainActivity + +@Composable +fun ImportExportScreen( + viewModel: SettingsViewModel = hiltViewModel() +) { + val encrypted by remember { + mutableStateOf(false) + } + val password by remember { + mutableStateOf("") + } + val context = LocalContext.current + val activity = remember { + context.findActivity() + } + val pickFileLauncher = rememberLauncherForActivityResult( + ActivityResultContracts.OpenDocument() + ) { uri -> + uri?.let { + viewModel.importDatabase(it, encrypted, password) + } + } + val chooseDirectoryLauncher = rememberLauncherForActivityResult( + ActivityResultContracts.OpenDocumentTree() + ) { uri -> + uri?.let { + viewModel.exportDatabase(it, encrypted, password) + } + } + val backupResult by viewModel.backupResult.collectAsState() + + LaunchedEffect(backupResult) { + if (backupResult == SettingsViewModel.BackupResult.ImportSuccess) { + activity?.let { + val intent = Intent(it, MainActivity::class.java).apply { + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + } + it.startActivity(intent) + it.finish() + Runtime.getRuntime().exit(0) + } + } + } + Scaffold( + topBar = { + TopAppBar( + title = { + Text( + text = stringResource(R.string.export_import), + style = MaterialTheme.typography.h5.copy(fontWeight = FontWeight.Bold) + ) + }, + backgroundColor = MaterialTheme.colors.background, + elevation = 0.dp, + ) + } + ) { paddingValues -> + Column( + Modifier + .fillMaxSize() + .padding(paddingValues) + ) { + // encryption will be added in a future version +// Row( +// verticalAlignment = Alignment.CenterVertically +// ) { +// Checkbox(checked = encrypted, onCheckedChange = { encrypted = it }) +// Text( +// text = stringResource(R.string.encrypted), +// style = MaterialTheme.typography.h6.copy(fontWeight = FontWeight.Bold), +// modifier = Modifier.padding(12.dp) +// ) +// } +// AnimatedVisibility(encrypted) { +// OutlinedTextField( +// value = password, +// onValueChange = { password = it }, +// label = { +// Text(text = stringResource(R.string.password)) +// }, +// modifier = Modifier +// .fillMaxWidth() +// .padding(12.dp), +// shape = RoundedCornerShape(15.dp), +// ) +// } + Button( + onClick = { + chooseDirectoryLauncher.launch(null) + }, + modifier = Modifier + .fillMaxWidth() + .align(Alignment.CenterHorizontally) + .padding(12.dp), + shape = RoundedCornerShape(8.dp) + ) { + Icon(painterResource(id = R.drawable.ic_export), null) + Text( + text = stringResource( + R.string.export + ), + style = MaterialTheme.typography.h6.copy(fontWeight = FontWeight.Bold), + modifier = Modifier.padding(12.dp) + ) + } + + if (backupResult == SettingsViewModel.BackupResult.ExportFailed) { + Text( + text = stringResource(R.string.export_failed), + modifier = Modifier.fillMaxWidth(), + style = MaterialTheme.typography.body2.copy(fontWeight = FontWeight.Bold), + textAlign = TextAlign.Center, + color = MaterialTheme.colors.error + ) + } + if (backupResult == SettingsViewModel.BackupResult.ExportSuccess) { + Text( + text = stringResource(R.string.export_success), + modifier = Modifier.fillMaxWidth(), + style = MaterialTheme.typography.body2.copy(fontWeight = FontWeight.Bold), + textAlign = TextAlign.Center + ) + } + + Button( + onClick = { + pickFileLauncher.launch(arrayOf("application/*")) + }, + modifier = Modifier + .fillMaxWidth() + .align(Alignment.CenterHorizontally) + .padding(12.dp), + shape = RoundedCornerShape(8.dp) + ) { + Icon(painterResource(id = R.drawable.ic_import), null) + Text( + text = stringResource(R.string.import_data), + style = MaterialTheme.typography.h6.copy(fontWeight = FontWeight.Bold), + modifier = Modifier.padding(12.dp) + ) + } + + + if (backupResult == SettingsViewModel.BackupResult.ImportFailed) { + Text( + text = stringResource(R.string.import_failed), + modifier = Modifier + .fillMaxWidth() + .padding(12.dp), + style = MaterialTheme.typography.body2.copy(fontWeight = FontWeight.Bold), + textAlign = TextAlign.Center, + color = MaterialTheme.colors.error + ) + } + if (backupResult == SettingsViewModel.BackupResult.Loading) { + CircularProgressIndicator( + Modifier + .align(Alignment.CenterHorizontally) + .padding(12.dp) + ) + } + + } + } +} + +fun Context.findActivity(): Activity? { + var context = this + while (context is ContextWrapper) { + if (context is Activity) return context + context = context.baseContext + } + return null +} diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/settings/SettingsBasicLinkItem.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/settings/SettingsBasicLinkItem.kt new file mode 100644 index 0000000..2cc3cfd --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/settings/SettingsBasicLinkItem.kt @@ -0,0 +1,58 @@ +package com.mhss.app.mybrain.presentation.settings + +import android.content.Intent +import android.net.Uri +import androidx.annotation.DrawableRes +import androidx.annotation.StringRes +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.width +import androidx.compose.material.Icon +import androidx.compose.material.MaterialTheme +import androidx.compose.material.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp + +@Composable +fun SettingsBasicLinkItem( + @StringRes + title: Int, + subtitle: String = "", + @DrawableRes + icon: Int, + link: String = "", + onClick: () -> Unit = {} +) { + val context = LocalContext.current + SettingsItemCard( + cornerRadius = 16.dp, + onClick = { + if (link.isNotBlank()) { + val intent = Intent(Intent.ACTION_VIEW) + intent.data = Uri.parse(link) + context.startActivity(intent) + } else onClick() + } + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + Icon( + painter = painterResource(id = icon), + contentDescription = stringResource(id = title) + ) + Spacer(Modifier.width(12.dp)) + Text( + text = stringResource(id = title), + style = MaterialTheme.typography.body1, + ) + } + Text( + text = subtitle, + style = MaterialTheme.typography.body2, + ) + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/settings/SettingsItemCard.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/settings/SettingsItemCard.kt new file mode 100644 index 0000000..3caf7f8 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/settings/SettingsItemCard.kt @@ -0,0 +1,39 @@ +package com.mhss.app.mybrain.presentation.settings + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.Card +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp + +@Composable +fun SettingsItemCard( + modifier: Modifier = Modifier, + cornerRadius: Dp = 25.dp, + hPadding: Dp = 12.dp, + vPadding: Dp = 16.dp, + onClick: () -> Unit = {}, + content: @Composable RowScope.() -> Unit, +) { + Card( + modifier = modifier + .fillMaxWidth() + .padding(vertical = 8.dp, horizontal = 12.dp), + shape = RoundedCornerShape(cornerRadius), + elevation = 6.dp, + ) { + Row( + Modifier + .fillMaxWidth() + .clickable { onClick() } + .padding(horizontal = hPadding, vertical = vPadding), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween, + content = content + ) + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/settings/SettingsViewModel.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/settings/SettingsViewModel.kt new file mode 100644 index 0000000..3772963 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/settings/SettingsViewModel.kt @@ -0,0 +1,79 @@ +package com.mhss.app.mybrain.presentation.settings + +import android.net.Uri +import androidx.datastore.preferences.core.Preferences +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.mhss.app.mybrain.domain.repository.RoomBackupRepository +import com.mhss.app.mybrain.domain.use_case.settings.GetSettingsUseCase +import com.mhss.app.mybrain.domain.use_case.settings.SaveSettingsUseCase +import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import javax.inject.Inject + +@HiltViewModel +class SettingsViewModel @Inject constructor( + private val saveSettingsUseCase: SaveSettingsUseCase, + private val getSettingsUseCase: GetSettingsUseCase, + private val backupRepository: RoomBackupRepository +) : ViewModel() { + + private val _backupResult = MutableStateFlow(BackupResult.None) + val backupResult: StateFlow = _backupResult + + fun getSettings(key: Preferences.Key, defaultValue: T): Flow { + return getSettingsUseCase(key, defaultValue) + } + + fun saveSettings(key: Preferences.Key, value: T) { + viewModelScope.launch { + saveSettingsUseCase(key, value) + } + } + + fun importDatabase( + uri: Uri, + encrypted: Boolean, + password: String + ) { + viewModelScope.launch { + _backupResult.update { BackupResult.Loading } + val result = backupRepository.importDatabase(uri, encrypted, password) + if (result) { + _backupResult.update { BackupResult.ImportSuccess } + } else { + _backupResult.update { BackupResult.ImportFailed } + } + } + } + + fun exportDatabase( + uri: Uri, + encrypted: Boolean, + password: String + ) { + viewModelScope.launch { + _backupResult.update { BackupResult.Loading } + val result = backupRepository.exportDatabase(uri, encrypted, password) + if (result) { + _backupResult.update { BackupResult.ExportSuccess } + } else { + _backupResult.update { BackupResult.ExportFailed } + } + } + } + + sealed class BackupResult { + data object ExportSuccess : BackupResult() + data object ExportFailed : BackupResult() + data object ImportSuccess : BackupResult() + data object ImportFailed : BackupResult() + data object Loading : BackupResult() + data object None : BackupResult() + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/AddTaskBottomSheetContent.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/AddTaskBottomSheetContent.kt new file mode 100644 index 0000000..ec8f8d9 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/AddTaskBottomSheetContent.kt @@ -0,0 +1,345 @@ +package com.mhss.app.mybrain.presentation.tasks + +import android.app.DatePickerDialog +import android.app.TimePickerDialog +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.foundation.* +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.* +import androidx.compose.material.TabRowDefaults.tabIndicatorOffset +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.ArrowDropDown +import androidx.compose.runtime.* +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.domain.model.SubTask +import com.mhss.app.mybrain.domain.model.Task +import com.mhss.app.mybrain.util.date.formatDateDependingOnDay +import com.mhss.app.mybrain.util.settings.TaskFrequency +import com.mhss.app.mybrain.util.settings.Priority +import com.mhss.app.mybrain.util.settings.toInt +import com.mhss.app.mybrain.util.settings.toPriority +import com.mhss.app.mybrain.util.settings.toTaskFrequency +import java.util.* + +@Composable +fun AddTaskBottomSheetContent( + onAddTask: (Task) -> Unit, + focusRequester: FocusRequester +) { + var title by rememberSaveable { mutableStateOf("") } + var description by rememberSaveable { mutableStateOf("") } + var priority by rememberSaveable { mutableStateOf(Priority.LOW) } + var dueDate by rememberSaveable { mutableStateOf(Calendar.getInstance()) } + var dueDateExists by rememberSaveable { mutableStateOf(false) } + var recurring by rememberSaveable { mutableStateOf(false) } + var frequency by rememberSaveable { mutableIntStateOf(0) } + var frequencyAmount by rememberSaveable { mutableIntStateOf(1) } + val subTasks = remember { mutableStateListOf() } + val priorities = listOf(Priority.LOW, Priority.MEDIUM, Priority.HIGH) + val context = LocalContext.current + val formattedDate by remember { + derivedStateOf { + dueDate.timeInMillis.formatDateDependingOnDay() + } + } + + Column( + modifier = Modifier + .defaultMinSize(minHeight = 1.dp) + .padding(horizontal = 16.dp, vertical = 24.dp) + .verticalScroll(rememberScrollState()) + ) { + SheetHandle(Modifier.align(Alignment.CenterHorizontally)) + Text( + text = stringResource(R.string.add_task), + style = MaterialTheme.typography.h5 + ) + Spacer(Modifier.height(16.dp)) + OutlinedTextField( + value = title, + onValueChange = { title = it }, + label = { Text(text = stringResource(R.string.title)) }, + shape = RoundedCornerShape(15.dp), + modifier = Modifier + .fillMaxWidth() + .focusRequester(focusRequester), + ) + Spacer(Modifier.height(12.dp)) + Column { + subTasks.forEachIndexed { index, item -> + SubTaskItem( + subTask = item, + onChange = { subTasks[index] = it }, + onDelete = { subTasks.removeAt(index) } + ) + } + } + Row( + Modifier + .fillMaxWidth() + .clickable { + subTasks.add( + SubTask( + title = "", + isCompleted = false, + ) + ) + }, + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = stringResource(R.string.add_sub_task), + modifier = Modifier.padding(vertical = 8.dp) + ) + Icon( + modifier = Modifier.size(10.dp), + painter = painterResource(id = R.drawable.ic_add), + contentDescription = stringResource( + id = R.string.add_sub_task + ) + ) + } + Spacer(Modifier.height(12.dp)) + Text( + text = stringResource(R.string.priority), + style = MaterialTheme.typography.body1.copy(fontWeight = FontWeight.Bold) + ) + Spacer(Modifier.height(12.dp)) + PriorityTabRow( + priorities = priorities, + priority, + onChange = { priority = it } + ) + Spacer(Modifier.height(12.dp)) + Row( + verticalAlignment = Alignment.CenterVertically + ) { + Checkbox(checked = dueDateExists, onCheckedChange = { dueDateExists = it }) + Spacer(Modifier.width(4.dp)) + Text( + text = stringResource(R.string.due_date), + style = MaterialTheme.typography.body2 + ) + } + AnimatedVisibility(dueDateExists) { + Column { + Row( + Modifier + .fillMaxWidth() + .clickable { + val date = + if (dueDate.timeInMillis == 0L) Calendar.getInstance() else dueDate + val tempDate = Calendar.getInstance() + val timePicker = TimePickerDialog( + context, + { _, hour, minute -> + tempDate[Calendar.HOUR_OF_DAY] = hour + tempDate[Calendar.MINUTE] = minute + dueDate = tempDate + }, date[Calendar.HOUR_OF_DAY], date[Calendar.MINUTE], false + ) + val datePicker = DatePickerDialog( + context, + { _, year, month, day -> + tempDate[Calendar.YEAR] = year + tempDate[Calendar.MONTH] = month + tempDate[Calendar.DAY_OF_MONTH] = day + timePicker.show() + }, + date[Calendar.YEAR], + date[Calendar.MONTH], + date[Calendar.DAY_OF_MONTH] + ) + datePicker.show() + } + .padding(8.dp), + horizontalArrangement = Arrangement.SpaceBetween, + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + Icon( + painter = painterResource(R.drawable.ic_alarm), + stringResource(R.string.due_date) + ) + Spacer(Modifier.width(8.dp)) + Text( + text = stringResource(R.string.due_date), + style = MaterialTheme.typography.body1 + ) + } + Text( + text = formattedDate, + style = MaterialTheme.typography.body2 + ) + } + Row( + verticalAlignment = Alignment.CenterVertically + ) { + Checkbox(checked = recurring, onCheckedChange = { + recurring = it + if (!it) frequency = 0 + }) + Spacer(Modifier.width(4.dp)) + Text( + text = stringResource(R.string.recurring), + style = MaterialTheme.typography.body2 + ) + } + AnimatedVisibility(recurring) { + var expanded by remember { mutableStateOf(false) } + Column { + Box { + DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) { + TaskFrequency.values().forEach { f -> + DropdownMenuItem( + onClick = { + expanded = false + frequency = f.ordinal + } + ) { + Text(text = stringResource(f.title)) + } + } + } + Row( + Modifier + .clickable { expanded = true } + .padding(8.dp) + , + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = stringResource( + frequency.toTaskFrequency().title + ) + ) + Icon( + imageVector = Icons.Default.ArrowDropDown, + contentDescription = stringResource(R.string.recurring), + modifier = Modifier.size(22.dp) + ) + } + } + Spacer(Modifier.height(8.dp)) + NumberPicker( + stringResource(R.string.repeats_every), + frequencyAmount + ) { + if (it > 0) frequencyAmount = it + } + } + } + } + } + Spacer(Modifier.height(12.dp)) + OutlinedTextField( + value = description, + onValueChange = { description = it }, + label = { Text(text = stringResource(R.string.description)) }, + shape = RoundedCornerShape(15.dp), + modifier = Modifier.fillMaxWidth() + ) + Button( + onClick = { + onAddTask( + Task( + title = title, + description = description, + priority = priority.toInt(), + dueDate = if (dueDateExists) dueDate.timeInMillis else 0L, + recurring = recurring, + frequency = frequency, + frequencyAmount = frequencyAmount, + createdDate = System.currentTimeMillis(), + updatedDate = System.currentTimeMillis(), + subTasks = subTasks.toList() + ) + ) + title = "" + description = "" + priority = Priority.LOW + dueDate = Calendar.getInstance() + dueDateExists = false + subTasks.clear() + }, + modifier = Modifier + .fillMaxWidth() + .padding(8.dp), + shape = RoundedCornerShape(25.dp) + ) { + Text( + text = stringResource(R.string.add_task), + style = MaterialTheme.typography.h6.copy(Color.White) + ) + } + Spacer(modifier = Modifier.height(54.dp)) + } +} + +@Composable +fun PriorityTabRow( + priorities: List, + selectedPriority: Priority, + onChange: (Priority) -> Unit +) { + val indicator = @Composable { tabPositions: List -> + AnimatedTabIndicator(Modifier.tabIndicatorOffset(tabPositions[selectedPriority.toInt()])) + } + TabRow( + selectedTabIndex = selectedPriority.toInt(), + indicator = indicator, + modifier = Modifier.clip(RoundedCornerShape(14.dp)) + ) { + priorities.forEachIndexed { index, it -> + Tab( + text = { Text(stringResource(it.title)) }, + selected = selectedPriority.toInt() == index, + onClick = { + onChange(index.toPriority()) + }, + modifier = Modifier.background(it.color) + ) + } + } +} + +@Composable +fun AnimatedTabIndicator(modifier: Modifier = Modifier) { + Box( + modifier = modifier + .padding(5.dp) + .fillMaxSize() + .border(BorderStroke(2.dp, Color.White), RoundedCornerShape(8.dp)) + ) +} + +@Composable +fun SheetHandle(modifier: Modifier = Modifier) { + Box( + modifier = modifier + .clip(RoundedCornerShape(10.dp)) + .size(width = 60.dp, height = 4.dp) + .background(Color.Gray) + .padding(5.dp) + ) +} + +@Preview +@Composable +fun AddTaskSheetPreview() { + AddTaskBottomSheetContent(onAddTask = {}, FocusRequester()) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/AddTaskTileService.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/AddTaskTileService.kt new file mode 100644 index 0000000..c130943 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/AddTaskTileService.kt @@ -0,0 +1,21 @@ +package com.mhss.app.mybrain.presentation.tasks + +import android.content.Intent +import android.service.quicksettings.TileService +import androidx.core.net.toUri +import com.mhss.app.mybrain.presentation.main.MainActivity +import com.mhss.app.mybrain.util.Constants + +class AddTaskTileService: TileService() { + + override fun onClick() { + super.onClick() + val intent = Intent( + Intent.ACTION_VIEW, + "${Constants.TASKS_SCREEN_URI}/true".toUri(), + this, + MainActivity::class.java + ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + startActivityAndCollapse(intent) + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/NumberPicker.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/NumberPicker.kt new file mode 100644 index 0000000..46825b8 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/NumberPicker.kt @@ -0,0 +1,31 @@ +package com.mhss.app.mybrain.presentation.tasks + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.material.MaterialTheme +import androidx.compose.material.Text +import androidx.compose.material.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment + +@Composable +fun NumberPicker( + label: String, + value: Int, + onValueChange: (Int) -> Unit, +) { + Column( + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Text(text = label, style = MaterialTheme.typography.body1) + Row(verticalAlignment = Alignment.CenterVertically) { + TextButton(onClick = { onValueChange(value - 1) }) { + Text(text = "-", style = MaterialTheme.typography.body1) + } + Text(text = value.toString(), style = MaterialTheme.typography.body1) + TextButton(onClick = { onValueChange(value + 1) }) { + Text(text = "+", style = MaterialTheme.typography.body1) + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/SubTaskItem.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/SubTaskItem.kt new file mode 100644 index 0000000..5c372fe --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/SubTaskItem.kt @@ -0,0 +1,54 @@ +package com.mhss.app.mybrain.presentation.tasks + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.material.* +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.style.TextDecoration +import androidx.compose.ui.unit.dp +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.domain.model.SubTask + +@Composable +fun SubTaskItem( + subTask: SubTask, + onChange: (SubTask) -> Unit, + onDelete: () -> Unit +) { + Row( + Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + painter = painterResource(R.drawable.ic_delete), + contentDescription = stringResource(R.string.delete_sub_task), + modifier = Modifier.clickable { onDelete() } + ) + Checkbox( + checked = subTask.isCompleted, + onCheckedChange = { onChange(subTask.copy(isCompleted = it)) }, + ) + Spacer(Modifier.width(8.dp)) + BasicTextField( + value = subTask.title, + onValueChange = { + onChange(subTask.copy(title = it)) + }, + textStyle = if (subTask.isCompleted) + TextStyle( + textDecoration = TextDecoration.LineThrough, + color = MaterialTheme.colors.onBackground + ) + else + MaterialTheme.typography.body2.copy(color = MaterialTheme.colors.onBackground), + modifier = Modifier.fillMaxWidth() + ) + + } +} diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/TaskDashboardItem.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/TaskDashboardItem.kt new file mode 100644 index 0000000..cd57383 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/TaskDashboardItem.kt @@ -0,0 +1,124 @@ +package com.mhss.app.mybrain.presentation.tasks + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.Card +import androidx.compose.material.Icon +import androidx.compose.material.MaterialTheme +import androidx.compose.material.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextDecoration +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.domain.model.Task +import com.mhss.app.mybrain.util.date.formatDateDependingOnDay +import com.mhss.app.mybrain.util.date.isDueDateOverdue +import com.mhss.app.mybrain.util.settings.toPriority + +@Composable +fun TaskDashboardItem( + modifier: Modifier = Modifier, + task: Task, + onComplete: () -> Unit, + onClick: () -> Unit +) { + Card( + modifier = modifier + .padding(horizontal = 8.dp), + shape = RoundedCornerShape(16.dp), + elevation = 8.dp + ) { + Column( + Modifier + .clickable { + onClick() + } + .padding(10.dp) + ) { + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + TaskDashboardCheckBox( + isComplete = task.isCompleted, + task.priority.toPriority().color, + onComplete = { onComplete() } + ) + Spacer(Modifier.width(6.dp)) + Text( + text = task.title, + style = MaterialTheme.typography.body1, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + textDecoration = if (task.isCompleted) TextDecoration.LineThrough else TextDecoration.None + ) + } + if (task.dueDate != 0L) { + Spacer(Modifier.height(4.dp)) + Row(verticalAlignment = Alignment.CenterVertically) { + Icon( + modifier = Modifier.size(10.dp), + painter = painterResource(R.drawable.ic_alarm), + contentDescription = stringResource(R.string.due_date), + tint = if (task.dueDate.isDueDateOverdue()) Color.Red else MaterialTheme.colors.onSurface + ) + Spacer(Modifier.width(3.dp)) + Text( + text = task.dueDate.formatDateDependingOnDay(), + style = MaterialTheme.typography.subtitle2, + color = if (task.dueDate.isDueDateOverdue()) Color.Red else MaterialTheme.colors.onSurface, + ) + } + } + } + } +} + +@Composable +fun TaskDashboardCheckBox( + isComplete: Boolean, + borderColor: Color, + onComplete: () -> Unit +) { + Box(modifier = Modifier + .size(22.dp) + .clip(CircleShape) + .border(2.dp, borderColor, CircleShape) + .clickable { + onComplete() + }, contentAlignment = Alignment.Center + ) { + AnimatedVisibility(visible = isComplete) { + Icon( + modifier = Modifier.size(14.dp), + painter = painterResource(id = R.drawable.ic_check), + contentDescription = null + ) + } + } +} + +@Preview +@Composable +fun TaskDashboardItemPreview() { + TaskDashboardItem( + task = Task( + title = "Task 1", + description = "Task 1 description", + dueDate = 1666999999999L, + priority = 1, + isCompleted = false + ), + onComplete = {}, + onClick = {} + ) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/TaskDetailScreen.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/TaskDetailScreen.kt new file mode 100644 index 0000000..dc587df --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/TaskDetailScreen.kt @@ -0,0 +1,408 @@ +package com.mhss.app.mybrain.presentation.tasks + +import android.app.DatePickerDialog +import android.app.TimePickerDialog +import androidx.activity.compose.BackHandler +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.* +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.ArrowDropDown +import androidx.compose.runtime.* +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.hilt.navigation.compose.hiltViewModel +import androidx.navigation.NavHostController +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.domain.model.SubTask +import com.mhss.app.mybrain.domain.model.Task +import com.mhss.app.mybrain.presentation.util.Screen +import com.mhss.app.mybrain.util.date.formatDateDependingOnDay +import com.mhss.app.mybrain.util.settings.TaskFrequency +import com.mhss.app.mybrain.util.settings.Priority +import com.mhss.app.mybrain.util.settings.toTaskFrequency +import com.mhss.app.mybrain.util.settings.toInt +import com.mhss.app.mybrain.util.settings.toPriority +import java.util.* + +@Composable +fun TaskDetailScreen( + navController: NavHostController, + taskId: Int, + viewModel: TasksViewModel = hiltViewModel() +) { + LaunchedEffect(true) { + viewModel.onEvent(TaskEvent.GetTask(taskId)) + } + val uiState = viewModel.taskDetailsUiState + val scaffoldState = rememberScaffoldState() + var openDialog by rememberSaveable { mutableStateOf(false) } + + var title by rememberSaveable { mutableStateOf("") } + var description by rememberSaveable { mutableStateOf("") } + var priority by rememberSaveable { mutableStateOf(Priority.LOW) } + var dueDate by rememberSaveable { mutableLongStateOf(0L) } + var recurring by rememberSaveable { mutableStateOf(false) } + var frequency by rememberSaveable { mutableIntStateOf(0) } + var frequencyAmount by rememberSaveable { mutableIntStateOf(1) } + var dueDateExists by rememberSaveable { mutableStateOf(false) } + var completed by rememberSaveable { mutableStateOf(false) } + val subTasks = remember { mutableStateListOf() } + val priorities = listOf(Priority.LOW, Priority.MEDIUM, Priority.HIGH) + val context = LocalContext.current + val formattedDate by remember { + derivedStateOf { + dueDate.formatDateDependingOnDay() + } + } + + LaunchedEffect(uiState.task) { + title = uiState.task.title + description = uiState.task.description + priority = uiState.task.priority.toPriority() + dueDate = uiState.task.dueDate + dueDateExists = uiState.task.dueDate != 0L + completed = uiState.task.isCompleted + recurring = uiState.task.recurring + frequency = uiState.task.frequency + frequencyAmount = uiState.task.frequencyAmount + subTasks.addAll(uiState.task.subTasks) + } + LaunchedEffect(uiState) { + if (uiState.navigateUp) { + openDialog = false + navController.popBackStack(Screen.TaskSearchScreen.route, false) + navController.navigateUp() + } + if (uiState.error != null) { + scaffoldState.snackbarHostState.showSnackbar( + uiState.error + ) + viewModel.onEvent(TaskEvent.ErrorDisplayed) + } + } + BackHandler { + updateTaskIfChanged( + uiState.task, + uiState.task.copy( + title = title, + description = description, + dueDate = if (dueDateExists) dueDate else 0L, + priority = priority.toInt(), + subTasks = subTasks, + recurring = recurring, + frequency = frequency, + frequencyAmount = frequencyAmount + ), + { + navController.popBackStack(Screen.TaskSearchScreen.route, false) + navController.navigateUp() + } + ) { + viewModel.onEvent(TaskEvent.UpdateTask(it, dueDate != uiState.task.dueDate)) + } + } + Scaffold( + scaffoldState = scaffoldState, + topBar = { + TopAppBar( + title = {}, + actions = { + IconButton(onClick = { openDialog = true }) { + Icon( + painter = painterResource(id = R.drawable.ic_delete), + contentDescription = stringResource(R.string.delete_task) + ) + } + }, + backgroundColor = MaterialTheme.colors.background, + elevation = 0.dp, + ) + } + ) { paddingValues -> + Column( + Modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(12.dp) + .padding(paddingValues) + ) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically + ) { + TaskCheckBox( + isComplete = completed, + borderColor = priority.color + ) { + completed = !completed + viewModel.onEvent( + TaskEvent.CompleteTask( + uiState.task, + completed + ) + ) + } + Spacer(Modifier.width(8.dp)) + OutlinedTextField( + value = title, + onValueChange = { title = it }, + label = { Text(text = stringResource(R.string.title)) }, + shape = RoundedCornerShape(15.dp), + modifier = Modifier.fillMaxWidth() + ) + } + Spacer(Modifier.height(12.dp)) + Column { + subTasks.forEachIndexed { index, item -> + SubTaskItem( + subTask = item, + onChange = { subTasks[index] = it }, + onDelete = { subTasks.removeAt(index) } + ) + } + } + Row( + Modifier + .fillMaxWidth() + .clickable { + subTasks.add( + SubTask( + title = "", + isCompleted = false, + ) + ) + }, + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = stringResource(R.string.add_sub_task), + modifier = Modifier.padding(vertical = 8.dp) + ) + Icon( + modifier = Modifier.size(10.dp), + painter = painterResource(id = R.drawable.ic_add), + contentDescription = stringResource( + id = R.string.add_sub_task + ) + ) + } + Spacer(Modifier.height(12.dp)) + Text( + text = stringResource(R.string.priority), + style = MaterialTheme.typography.body1.copy(fontWeight = FontWeight.Bold) + ) + Spacer(Modifier.height(12.dp)) + PriorityTabRow( + priorities = priorities, + priority, + onChange = { priority = it } + ) + Spacer(Modifier.height(12.dp)) + Row( + verticalAlignment = Alignment.CenterVertically + ) { + Checkbox(checked = dueDateExists, onCheckedChange = { + dueDateExists = it + if (it) + dueDate = Calendar.getInstance().timeInMillis + }) + Spacer(Modifier.width(4.dp)) + Text( + text = stringResource(R.string.due_date), + style = MaterialTheme.typography.body2 + ) + } + AnimatedVisibility(dueDateExists) { + Column { + Row( + Modifier + .fillMaxWidth() + .clickable { + val date = + if (dueDate == 0L) Calendar.getInstance() else Calendar + .getInstance() + .apply { timeInMillis = dueDate } + val tempDate = Calendar.getInstance() + val timePicker = TimePickerDialog( + context, + { _, hour, minute -> + tempDate[Calendar.HOUR_OF_DAY] = hour + tempDate[Calendar.MINUTE] = minute + dueDate = tempDate.timeInMillis + }, date[Calendar.HOUR_OF_DAY], date[Calendar.MINUTE], false + ) + val datePicker = DatePickerDialog( + context, + { _, year, month, day -> + tempDate[Calendar.YEAR] = year + tempDate[Calendar.MONTH] = month + tempDate[Calendar.DAY_OF_MONTH] = day + timePicker.show() + }, + date[Calendar.YEAR], + date[Calendar.MONTH], + date[Calendar.DAY_OF_MONTH] + ) + datePicker.show() + } + .padding(vertical = 8.dp, horizontal = 16.dp), + horizontalArrangement = Arrangement.SpaceBetween, + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + Icon( + painter = painterResource(R.drawable.ic_alarm), + stringResource(R.string.due_date), + modifier = Modifier.size(22.dp) + ) + Spacer(Modifier.width(8.dp)) + Text( + text = stringResource(R.string.due_date), + style = MaterialTheme.typography.body1 + ) + } + Text( + text = formattedDate, + style = MaterialTheme.typography.body2 + ) + } + Row( + verticalAlignment = Alignment.CenterVertically + ) { + Checkbox(checked = recurring, onCheckedChange = { + recurring = it + if (!it) frequency = 0 + }) + Spacer(Modifier.width(4.dp)) + Text( + text = stringResource(R.string.recurring), + style = MaterialTheme.typography.body2 + ) + } + AnimatedVisibility(recurring) { + var frequencyMenuVisible by remember { mutableStateOf(false) } + Column { + Box { + DropdownMenu( + expanded = frequencyMenuVisible, + onDismissRequest = { frequencyMenuVisible = false }) { + TaskFrequency.values().forEach { f -> + DropdownMenuItem( + onClick = { + frequencyMenuVisible = false + frequency = f.value + } + ) { + Text(text = stringResource(f.title)) + } + } + } + Row( + Modifier + .clickable { frequencyMenuVisible = true } + .padding(vertical = 8.dp, horizontal = 16.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = stringResource( + frequency.toTaskFrequency().title + ) + ) + Icon( + imageVector = Icons.Default.ArrowDropDown, + contentDescription = stringResource(R.string.recurring), + modifier = Modifier.size(22.dp) + ) + } + } + Spacer(Modifier.height(8.dp)) + NumberPicker( + stringResource(R.string.repeats_every), + frequencyAmount + ) { + if (it > 0) frequencyAmount = it + } + } + } + } + } + Spacer(Modifier.height(12.dp)) + OutlinedTextField( + value = description, + onValueChange = { description = it }, + label = { Text(text = stringResource(R.string.description)) }, + shape = RoundedCornerShape(15.dp), + modifier = Modifier.fillMaxWidth() + ) + } + } + if (openDialog) + AlertDialog( + shape = RoundedCornerShape(25.dp), + onDismissRequest = { openDialog = false }, + title = { Text(stringResource(R.string.delete_task_confirmation_title)) }, + text = { + Text( + stringResource( + R.string.delete_task_confirmation_message, + uiState.task.title + ) + ) + }, + confirmButton = { + Button( + colors = ButtonDefaults.buttonColors(backgroundColor = Color.Red), + shape = RoundedCornerShape(25.dp), + onClick = { + viewModel.onEvent(TaskEvent.DeleteTask(uiState.task)) + }, + ) { + Text(stringResource(R.string.delete_task), color = Color.White) + } + }, + dismissButton = { + Button( + shape = RoundedCornerShape(25.dp), + onClick = { + openDialog = false + }) { + Text(stringResource(R.string.cancel), color = Color.White) + } + } + ) +} + +private fun updateTaskIfChanged( + task: Task, + newTask: Task, + onNotChanged: () -> Unit = {}, + onUpdate: (Task) -> Unit, +) { + if (taskChanged(task, newTask)) onUpdate(newTask) else onNotChanged() +} + +private fun taskChanged( + task: Task, + newTask: Task +): Boolean { + return task.title != newTask.title || + task.description != newTask.description || + task.dueDate != newTask.dueDate || + task.priority != newTask.priority || + task.subTasks != newTask.subTasks || + task.recurring != newTask.recurring || + task.frequency != newTask.frequency || + task.frequencyAmount != newTask.frequencyAmount +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/TaskEvent.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/TaskEvent.kt new file mode 100644 index 0000000..56e721c --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/TaskEvent.kt @@ -0,0 +1,16 @@ +package com.mhss.app.mybrain.presentation.tasks + +import com.mhss.app.mybrain.domain.model.Task +import com.mhss.app.mybrain.util.settings.Order + +sealed class TaskEvent { + data class CompleteTask(val task: Task, val complete: Boolean) : TaskEvent() + data class GetTask(val taskId: Int) : TaskEvent() + data class AddTask(val task: Task) : TaskEvent() + data class SearchTasks(val query: String) : TaskEvent() + data class UpdateOrder(val order: Order) : TaskEvent() + data class ShowCompletedTasks(val showCompleted: Boolean) : TaskEvent() + data class UpdateTask(val task: Task, val dueDateUpdated: Boolean) : TaskEvent() + data class DeleteTask(val task: Task) : TaskEvent() + data object ErrorDisplayed: TaskEvent() +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/TaskItem.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/TaskItem.kt new file mode 100644 index 0000000..7d604b0 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/TaskItem.kt @@ -0,0 +1,128 @@ +package com.mhss.app.mybrain.presentation.tasks + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyItemScope +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.Card +import androidx.compose.material.Icon +import androidx.compose.material.MaterialTheme +import androidx.compose.material.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextDecoration +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.domain.model.Task +import com.mhss.app.mybrain.util.date.formatDateDependingOnDay +import com.mhss.app.mybrain.util.date.isDueDateOverdue +import com.mhss.app.mybrain.util.settings.toPriority + +@OptIn(ExperimentalFoundationApi::class) +@Composable +fun LazyItemScope.TaskItem( + modifier: Modifier = Modifier, + task: Task, + onComplete: () -> Unit, + onClick: () -> Unit +) { + Card( + modifier = modifier + .padding(horizontal = 8.dp) + .animateItemPlacement(), + shape = RoundedCornerShape(16.dp), + elevation = 8.dp + ) { + Column( + Modifier + .clickable { + onClick() + } + .padding(12.dp) + ) { + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + TaskCheckBox( + isComplete = task.isCompleted, + task.priority.toPriority().color, + onComplete = { onComplete() } + ) + Spacer(Modifier.width(8.dp)) + Text( + text = task.title, + style = MaterialTheme.typography.h6, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + textDecoration = if (task.isCompleted) TextDecoration.LineThrough else TextDecoration.None + ) + } + if (task.dueDate != 0L) { + Spacer(Modifier.height(8.dp)) + Row(verticalAlignment = Alignment.CenterVertically) { + Icon( + modifier = Modifier.size(13.dp), + painter = painterResource(R.drawable.ic_alarm), + contentDescription = stringResource(R.string.due_date), + tint = if (task.dueDate.isDueDateOverdue()) Color.Red else MaterialTheme.colors.onSurface + ) + Spacer(Modifier.width(4.dp)) + Text( + text = task.dueDate.formatDateDependingOnDay(), + style = MaterialTheme.typography.body2, + color = if (task.dueDate.isDueDateOverdue()) Color.Red else MaterialTheme.colors.onSurface + ) + } + } + } + } +} + +@Composable +fun TaskCheckBox( + isComplete: Boolean, + borderColor: Color, + onComplete: () -> Unit +) { + Box(modifier = Modifier + .size(30.dp) + .clip(CircleShape) + .border(2.dp, borderColor, CircleShape) + .clickable { + onComplete() + }, contentAlignment = Alignment.Center + ) { + AnimatedVisibility(visible = isComplete) { + Icon( + modifier = Modifier.size(20.dp), + painter = painterResource(id = R.drawable.ic_check), + contentDescription = null + ) + } + } +} + +@Preview +@Composable +fun LazyItemScope.TaskItemPreview() { + TaskItem( + task = Task( + title = "Task 1", + description = "Task 1 description", + dueDate = 1666999999999L, + priority = 1, + isCompleted = false + ), + onComplete = {}, + onClick = {} + ) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/TaskWidgetItem.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/TaskWidgetItem.kt new file mode 100644 index 0000000..ca6d09c --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/TaskWidgetItem.kt @@ -0,0 +1,142 @@ +package com.mhss.app.mybrain.presentation.tasks + +import androidx.compose.runtime.Composable +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.glance.GlanceModifier +import androidx.glance.Image +import androidx.glance.ImageProvider +import androidx.glance.action.Action +import androidx.glance.action.actionParametersOf +import androidx.glance.action.clickable +import androidx.glance.appwidget.action.actionRunCallback +import androidx.glance.appwidget.cornerRadius +import androidx.glance.background +import androidx.glance.layout.* +import androidx.glance.text.FontWeight +import androidx.glance.text.Text +import androidx.glance.text.TextDecoration +import androidx.glance.text.TextStyle +import androidx.glance.unit.ColorProvider +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.domain.model.Task +import com.mhss.app.mybrain.presentation.glance_widgets.* +import com.mhss.app.mybrain.util.date.formatDateDependingOnDay +import com.mhss.app.mybrain.util.date.isDueDateOverdue +import com.mhss.app.mybrain.util.settings.Priority +import com.mhss.app.mybrain.util.settings.toPriority + +@Composable +fun TaskWidgetItem( + task: Task +) { + Box( + GlanceModifier.padding(bottom = 3.dp) + ) { + Column( + GlanceModifier + .background(ImageProvider(R.drawable.small_item_rounded_corner_shape)) + .padding(10.dp) + .clickable( + actionRunCallback( + parameters = actionParametersOf( + taskId to task.id + ) + ) + ) + ) { + Row(GlanceModifier + .fillMaxWidth() + .clickable( + actionRunCallback( + parameters = actionParametersOf( + taskId to task.id + ) + )) + , verticalAlignment = Alignment.CenterVertically) { + TaskWidgetCheckBox( + isComplete = task.isCompleted, + task.priority.toPriority().color, + onComplete = actionRunCallback( + parameters = actionParametersOf( + taskId to task.id, + completed to !task.isCompleted + ) + ) + ) + Spacer(GlanceModifier.width(6.dp)) + Text( + task.title, + style = TextStyle( + color = ColorProvider(Color.White), + fontWeight = FontWeight.Bold, + fontSize = 15.sp, + textDecoration = if (task.isCompleted) TextDecoration.LineThrough else TextDecoration.None + ), + maxLines = 2, + modifier = GlanceModifier.clickable(actionRunCallback( + parameters = actionParametersOf( + taskId to task.id, + completed to !task.isCompleted + ) + )) + ) + } + if (task.dueDate != 0L) { + Spacer(GlanceModifier.height(4.dp)) + Row(verticalAlignment = Alignment.CenterVertically) { + Image( + modifier = GlanceModifier.size(10.dp), + provider = if (task.dueDate.isDueDateOverdue()) ImageProvider(R.drawable.ic_alarm_red) else ImageProvider( + R.drawable.ic_alarm + ), + contentDescription = "", + ) + Spacer(GlanceModifier.width(3.dp)) + Text( + text = task.dueDate.formatDateDependingOnDay(), + style = TextStyle( + color = if (task.dueDate.isDueDateOverdue()) ColorProvider(Color.Red) else ColorProvider( + Color.White + ), + fontWeight = FontWeight.Bold, + fontSize = 10.sp, + ) + ) + } + } + } + } +} + +@Composable +fun TaskWidgetCheckBox( + isComplete: Boolean, + borderColor: Color, + onComplete: Action +) { + Box( + modifier = GlanceModifier + .size(25.dp) + .cornerRadius(99.dp) + .background(ImageProvider( + when (borderColor){ + Priority.LOW.color -> R.drawable.task_check_box_background_green + Priority.MEDIUM.color -> R.drawable.task_check_box_background_orange + else -> R.drawable.task_check_box_background_red + })) + .clickable( + onClick = onComplete + ).padding(3.dp), + contentAlignment = Alignment.Center + ) { + if (isComplete) { + Image( + modifier = GlanceModifier.size(14.dp), + provider = ImageProvider(R.drawable.ic_check), + contentDescription = null + ) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/TasksDashboardWidget.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/TasksDashboardWidget.kt new file mode 100644 index 0000000..2813c83 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/TasksDashboardWidget.kt @@ -0,0 +1,97 @@ +package com.mhss.app.mybrain.presentation.tasks + +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.Card +import androidx.compose.material.Icon +import androidx.compose.material.MaterialTheme +import androidx.compose.material.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.domain.model.Task +import com.mhss.app.mybrain.ui.theme.LightGray + +@OptIn(ExperimentalFoundationApi::class) +@Composable +fun TasksDashboardWidget( + modifier: Modifier = Modifier, + tasks: List, + onTaskClick: (Task) -> Unit = {}, + onCheck: (Task) -> Unit = {}, + onAddClick: () -> Unit = {}, + onClick: () -> Unit = {} +) { + Card( + shape = RoundedCornerShape(24.dp), + elevation = 8.dp, + modifier = Modifier + .fillMaxWidth() + .padding(8.dp) + ) { + val isDark = !MaterialTheme.colors.isLight + Column( + modifier = modifier + .clickable { onClick() } + .padding(8.dp) + ) { + Row( + Modifier + .fillMaxWidth() + .padding(4.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Text(stringResource(R.string.tasks), style = MaterialTheme.typography.body1) + Icon( + painterResource(R.drawable.ic_add), + stringResource(R.string.add_event), + modifier = Modifier + .size(18.dp) + .clickable { + onAddClick() + } + ) + } + Spacer(Modifier.height(8.dp)) + LazyColumn( + modifier = Modifier + .fillMaxSize() + .clip(RoundedCornerShape(20.dp)) + .background(if (isDark) Color.DarkGray else LightGray), + contentPadding = PaddingValues(vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + if (tasks.isEmpty()){ + item { + Text( + text = stringResource(R.string.no_tasks_message), + style = MaterialTheme.typography.body2, + modifier = Modifier.fillMaxWidth(), + textAlign = TextAlign.Center + ) + } + } else items(tasks) { + TaskDashboardItem( + task = it, + onClick = { onTaskClick(it) }, + onComplete = { onCheck(it.copy(isCompleted = !it.isCompleted)) }, + modifier = Modifier.animateItemPlacement() + ) + } + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/TasksHomeScreenWidget.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/TasksHomeScreenWidget.kt new file mode 100644 index 0000000..5038651 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/TasksHomeScreenWidget.kt @@ -0,0 +1,102 @@ +package com.mhss.app.mybrain.presentation.tasks + +import androidx.compose.runtime.Composable +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.glance.* +import androidx.glance.action.clickable +import androidx.glance.appwidget.action.actionRunCallback +import androidx.glance.appwidget.cornerRadius +import androidx.glance.appwidget.lazy.LazyColumn +import androidx.glance.appwidget.lazy.items +import androidx.glance.layout.* +import androidx.glance.text.FontWeight +import androidx.glance.text.Text +import androidx.glance.text.TextAlign +import androidx.glance.text.TextStyle +import androidx.glance.unit.ColorProvider +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.app.getString +import com.mhss.app.mybrain.domain.model.Task +import com.mhss.app.mybrain.presentation.glance_widgets.AddTaskAction +import com.mhss.app.mybrain.presentation.glance_widgets.NavigateToTasksAction + +@Composable +fun TasksHomeScreenWidget( + tasks: List +) { + Box( + modifier = GlanceModifier + .fillMaxWidth() + .background(ImageProvider(R.drawable.large_item_rounded_corner_shape)) + .cornerRadius(25.dp) + ) { + Column( + modifier = GlanceModifier.padding(8.dp) + ) { + Row( + GlanceModifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalAlignment = Alignment.CenterHorizontally + ) { + Text( + getString(R.string.tasks), + style = TextStyle( + color = ColorProvider(Color.White), + fontWeight = FontWeight.Bold, + fontSize = 16.sp + ), + modifier = GlanceModifier + .padding(horizontal = 8.dp) + .clickable(actionRunCallback()), + ) + Row( + modifier = GlanceModifier + .fillMaxWidth() + .padding(horizontal = 8.dp) + .clickable(actionRunCallback()), + horizontalAlignment = Alignment.End + ) { + Image( + provider = ImageProvider(R.drawable.ic_add), + modifier = GlanceModifier + .size(22.dp) + .clickable(actionRunCallback()) + , + contentDescription = "Add task" + ) + } + } + Spacer(GlanceModifier.height(8.dp)) + LazyColumn( + modifier = GlanceModifier + .fillMaxSize() + .padding(horizontal = 6.dp) + .background(ImageProvider(R.drawable.large_inner_item_rounded_corner_shape)) + .cornerRadius(20.dp), + horizontalAlignment = Alignment.CenterHorizontally + ) { + if (tasks.isEmpty()) { + item { + Text( + text = getString(R.string.no_tasks_message), + modifier = GlanceModifier.padding(16.dp), + style = TextStyle( + color = ColorProvider(Color.White), + fontWeight = FontWeight.Normal, + fontSize = 16.sp, + textAlign = TextAlign.Center + ) + ) + } + } else { + item { Spacer(GlanceModifier.height(6.dp)) } + items(tasks) { task -> + TaskWidgetItem(task) + } + } + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/TasksScreen.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/TasksScreen.kt new file mode 100644 index 0000000..953e1a5 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/TasksScreen.kt @@ -0,0 +1,285 @@ +package com.mhss.app.mybrain.presentation.tasks + +import androidx.activity.compose.BackHandler +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.* +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.hilt.navigation.compose.hiltViewModel +import androidx.navigation.NavHostController +import com.google.accompanist.flowlayout.FlowRow +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.presentation.util.Screen +import com.mhss.app.mybrain.util.Constants +import com.mhss.app.mybrain.util.settings.Order +import com.mhss.app.mybrain.util.settings.OrderType +import kotlinx.coroutines.launch + +@OptIn(ExperimentalMaterialApi::class) +@Composable +fun TasksScreen( + navController: NavHostController, + addTask: Boolean = false, + viewModel: TasksViewModel = hiltViewModel() +) { + var orderSettingsVisible by remember { mutableStateOf(false) } + val focusRequester = remember { FocusRequester() } + val uiState = viewModel.tasksUiState + val scaffoldState = rememberScaffoldState() + val sheetState = rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden) + val scope = rememberCoroutineScope() + BackHandler { + if (sheetState.isVisible) + scope.launch { + sheetState.hide() + + } + else + navController.popBackStack() + } + Scaffold( + scaffoldState = scaffoldState, + topBar = { + TopAppBar( + title = { + Text( + text = stringResource(R.string.tasks), + style = MaterialTheme.typography.h5.copy(fontWeight = FontWeight.Bold) + ) + }, + backgroundColor = MaterialTheme.colors.background, + elevation = 0.dp, + ) + }, + floatingActionButton = { + FloatingActionButton( + onClick = { + scope.launch { + sheetState.show() + focusRequester.requestFocus() + } + }, + backgroundColor = MaterialTheme.colors.primary, + ) { + Icon( + modifier = Modifier.size(25.dp), + painter = painterResource(R.drawable.ic_add), + contentDescription = stringResource(R.string.add_task), + tint = Color.White + ) + } + }, + ) {paddingValues -> + ModalBottomSheetLayout( + modifier = Modifier.padding(paddingValues), + sheetState = sheetState, + sheetShape = RoundedCornerShape(topEnd = 25.dp, topStart = 25.dp), + sheetContent = { + AddTaskBottomSheetContent( + onAddTask = { + viewModel.onEvent(TaskEvent.AddTask(it)) + scope.launch { sheetState.hide() } + focusRequester.freeFocus() + }, + focusRequester + ) + }) { + LaunchedEffect(uiState.error) { + uiState.error?.let { + scaffoldState.snackbarHostState.showSnackbar( + uiState.error + ) + viewModel.onEvent(TaskEvent.ErrorDisplayed) + } + } + LaunchedEffect(true){ + if (addTask) scope.launch { + sheetState.show() + focusRequester.requestFocus() + } + } + if (uiState.tasks.isEmpty()) + NoTasksMessage() + LazyColumn( + verticalArrangement = Arrangement.spacedBy(8.dp), + contentPadding = PaddingValues(vertical = 12.dp, horizontal = 4.dp) + ) { + item { + Column( + Modifier.fillMaxWidth() + ) { + Row( + Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween + ) { + IconButton(onClick = { orderSettingsVisible = !orderSettingsVisible }) { + Icon( + modifier = Modifier.size(25.dp), + painter = painterResource(R.drawable.ic_settings_sliders), + contentDescription = stringResource(R.string.order_by) + ) + } + IconButton(onClick = { + navController.navigate(Screen.TaskSearchScreen.route) + }) { + Icon( + modifier = Modifier.size(25.dp), + painter = painterResource(id = R.drawable.ic_search), + contentDescription = stringResource(R.string.search) + ) + } + } + AnimatedVisibility(visible = orderSettingsVisible) { + TasksSettingsSection( + uiState.taskOrder, + uiState.showCompletedTasks, + onShowCompletedChange = { + viewModel.onEvent( + TaskEvent.ShowCompletedTasks( + it + ) + ) + }, + onOrderChange = { + viewModel.onEvent(TaskEvent.UpdateOrder(it)) + } + ) + } + } + } + items(uiState.tasks, key = { it.id }) { task -> + TaskItem( + task = task, + onComplete = { + viewModel.onEvent( + TaskEvent.CompleteTask( + task, + !task.isCompleted + ) + ) + }, + onClick = { + navController.navigate( + Screen.TaskDetailScreen.route.replace( + "{${Constants.TASK_ID_ARG}}", + "${task.id}" + ) + ) + }, + ) + } + } + } + } +} + +@Composable +fun NoTasksMessage(){ + Column( + modifier = Modifier.fillMaxSize(), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center + ) { + Text( + text = stringResource(R.string.no_tasks_message), + style = MaterialTheme.typography.body1.copy(fontWeight = FontWeight.Bold), + color = Color.Gray, + textAlign = TextAlign.Center + ) + Spacer(modifier = Modifier.height(12.dp)) + Image( + modifier = Modifier.size(125.dp), + painter = painterResource(id = R.drawable.tasks_img), + contentDescription = stringResource(R.string.no_tasks_message), + alpha = 0.7f + ) + } +} +@Composable +fun TasksSettingsSection( + order: Order, + showCompleted: Boolean, + onOrderChange: (Order) -> Unit, + onShowCompletedChange: (Boolean) -> Unit +) { + val orders = listOf( + Order.DateModified(), + Order.DueDate(), + Order.DateCreated(), + Order.Alphabetical(), + Order.Priority() + ) + val orderTypes = listOf( + OrderType.ASC(), + OrderType.DESC() + ) + Column( + Modifier.background(color = MaterialTheme.colors.background) + ) { + Text( + text = stringResource(R.string.order_by), + style = MaterialTheme.typography.body1, + modifier = Modifier.padding(start = 8.dp) + ) + FlowRow( + modifier = Modifier.padding(end = 8.dp) + ) { + orders.forEach { + Row(verticalAlignment = Alignment.CenterVertically) { + RadioButton( + selected = order.orderTitle == it.orderTitle, + onClick = { + if (order.orderTitle != it.orderTitle) + onOrderChange( + it.copy(orderType = order.orderType) + ) + } + ) + Text(text = it.orderTitle, style = MaterialTheme.typography.body1) + } + } + } + Divider() + FlowRow { + orderTypes.forEach { + Row(verticalAlignment = Alignment.CenterVertically) { + RadioButton( + selected = order.orderType.orderTitle == it.orderTitle, + onClick = { + if (order.orderTitle != it.orderTitle) + onOrderChange( + order.copy(it) + ) + } + ) + Spacer(modifier = Modifier.width(4.dp)) + Text(text = it.orderTitle, style = MaterialTheme.typography.body1) + } + } + } + Divider() + Row(verticalAlignment = Alignment.CenterVertically) { + Checkbox(checked = showCompleted, onCheckedChange = { onShowCompletedChange(it) }) + Text( + text = stringResource(R.string.show_completed_tasks), + style = MaterialTheme.typography.body1, + modifier = Modifier.padding(start = 8.dp) + ) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/TasksSearchScreen.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/TasksSearchScreen.kt new file mode 100644 index 0000000..f58c458 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/TasksSearchScreen.kt @@ -0,0 +1,76 @@ +package com.mhss.app.mybrain.presentation.tasks + +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.runtime.* +import androidx.compose.material.OutlinedTextField +import androidx.compose.material.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.hilt.navigation.compose.hiltViewModel +import androidx.navigation.NavHostController +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.presentation.util.Screen +import com.mhss.app.mybrain.util.Constants + +@Composable +fun TasksSearchScreen( + navController: NavHostController, + viewModel: TasksViewModel = hiltViewModel() +) { + val state = viewModel.tasksUiState + Column( + modifier = Modifier.fillMaxSize(), + ) { + var query by rememberSaveable { + mutableStateOf("") + } + LaunchedEffect(query){viewModel.onEvent(TaskEvent.SearchTasks(query))} + val focusRequester = remember { FocusRequester() } + LaunchedEffect(true){focusRequester.requestFocus()} + OutlinedTextField( + value = query, + onValueChange = {query = it}, + label = {Text(stringResource(R.string.search_tasks))}, + shape = RoundedCornerShape(15.dp), + modifier = Modifier + .fillMaxWidth() + .padding(16.dp) + .focusRequester(focusRequester) + ) + LazyColumn( + verticalArrangement = Arrangement.spacedBy(8.dp), + contentPadding = PaddingValues(top = 12.dp, bottom = 12.dp) + ) { + items(state.searchTasks, key = {it.id}){ task -> + TaskItem( + task = task, + onComplete = { + viewModel.onEvent( + TaskEvent.CompleteTask( + task, + !task.isCompleted + ) + ) + }, + onClick = { + navController.navigate( + Screen.TaskDetailScreen.route.replace( + "{${Constants.TASK_ID_ARG}}", + "${task.id}" + ) + ) + }, + ) + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/TasksViewModel.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/TasksViewModel.kt new file mode 100644 index 0000000..f008485 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/tasks/TasksViewModel.kt @@ -0,0 +1,183 @@ +package com.mhss.app.mybrain.presentation.tasks + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.datastore.preferences.core.booleanPreferencesKey +import androidx.datastore.preferences.core.intPreferencesKey +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.app.getString +import com.mhss.app.mybrain.domain.model.Alarm +import com.mhss.app.mybrain.domain.model.Task +import com.mhss.app.mybrain.domain.use_case.alarm.AddAlarmUseCase +import com.mhss.app.mybrain.domain.use_case.alarm.DeleteAlarmUseCase +import com.mhss.app.mybrain.domain.use_case.settings.GetSettingsUseCase +import com.mhss.app.mybrain.domain.use_case.settings.SaveSettingsUseCase +import com.mhss.app.mybrain.domain.use_case.tasks.* +import com.mhss.app.mybrain.util.Constants +import com.mhss.app.mybrain.util.settings.Order +import com.mhss.app.mybrain.util.settings.OrderType +import com.mhss.app.mybrain.util.settings.toInt +import com.mhss.app.mybrain.util.settings.toOrder +import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.* +import kotlinx.coroutines.launch +import javax.inject.Inject + +@HiltViewModel +class TasksViewModel @Inject constructor( + private val addTask: AddTaskUseCase, + private val getAllTasks: GetAllTasksUseCase, + private val getTaskUseCase: GetTaskByIdUseCase, + private val updateTask: UpdateTaskUseCase, + private val completeTask: UpdateTaskCompletedUseCase, + getSettings: GetSettingsUseCase, + private val saveSettings: SaveSettingsUseCase, + private val addAlarm: AddAlarmUseCase, + private val deleteAlarm: DeleteAlarmUseCase, + private val deleteTask: DeleteTaskUseCase, + private val searchTasksUseCase: SearchTasksUseCase +): ViewModel() { + + var tasksUiState by mutableStateOf(UiState()) + private set + var taskDetailsUiState by mutableStateOf(TaskUiState()) + private set + + private var getTasksJob: Job? = null + private var searchTasksJob: Job? = null + + init { + viewModelScope.launch { + combine( + getSettings( + intPreferencesKey(Constants.TASKS_ORDER_KEY), + Order.DateModified(OrderType.ASC()).toInt() + ), + getSettings( + booleanPreferencesKey(Constants.SHOW_COMPLETED_TASKS_KEY), + false + ) + ){ order, showCompleted -> + getTasks(order.toOrder(), showCompleted) + }.collect() + } + } + + fun onEvent(event: TaskEvent) { + when (event) { + is TaskEvent.AddTask -> { + if (event.task.title.isNotBlank()) { + viewModelScope.launch { + val taskId = addTask(event.task) + if (event.task.dueDate != 0L) + addAlarm( + Alarm( + taskId.toInt(), + event.task.dueDate, + ) + ) + } + + }else + tasksUiState = tasksUiState.copy(error = getString(R.string.error_empty_title)) + } + is TaskEvent.CompleteTask -> viewModelScope.launch { + completeTask(event.task.id, event.complete) + } + TaskEvent.ErrorDisplayed -> { + tasksUiState = tasksUiState.copy(error = null) + taskDetailsUiState = taskDetailsUiState.copy(error = null) + } + is TaskEvent.UpdateOrder -> viewModelScope.launch { + saveSettings( + intPreferencesKey(Constants.TASKS_ORDER_KEY), + event.order.toInt() + ) + } + is TaskEvent.ShowCompletedTasks -> viewModelScope.launch { + saveSettings( + booleanPreferencesKey(Constants.SHOW_COMPLETED_TASKS_KEY), + event.showCompleted + ) + } + is TaskEvent.SearchTasks -> { + viewModelScope.launch { + searchTasks(event.query) + } + } + is TaskEvent.UpdateTask -> viewModelScope.launch { + if (event.task.title.isBlank()) + taskDetailsUiState = taskDetailsUiState.copy(error = getString(R.string.error_empty_title)) + else { + updateTask(event.task.copy(updatedDate = System.currentTimeMillis())) + if (event.task.dueDate != taskDetailsUiState.task.dueDate){ + if (event.task.dueDate != 0L) + addAlarm( + Alarm( + event.task.id, + event.task.dueDate + ) + ) + else + deleteAlarm(event.task.id) + } + taskDetailsUiState = taskDetailsUiState.copy(navigateUp = true) + } + } + is TaskEvent.DeleteTask -> viewModelScope.launch { + deleteTask(event.task) + if (event.task.dueDate != 0L) + deleteAlarm(event.task.id) + taskDetailsUiState = taskDetailsUiState.copy(navigateUp = true) + } + is TaskEvent.GetTask -> viewModelScope.launch { + taskDetailsUiState = taskDetailsUiState.copy( + task = getTaskUseCase(event.taskId) + ) + } + } + } + + data class UiState( + val tasks: List = emptyList(), + val taskOrder: Order = Order.DateModified(OrderType.ASC()), + val showCompletedTasks: Boolean = false, + val error: String? = null, + val searchTasks: List = emptyList() + ) + + data class TaskUiState( + val task: Task = Task(""), + val navigateUp: Boolean = false, + val error: String? = null + ) + + private fun getTasks(order: Order, showCompleted: Boolean) { + getTasksJob?.cancel() + getTasksJob = getAllTasks(order) + .map { list -> + if (showCompleted) + list + else + list.filter { !it.isCompleted } + }.onEach { tasks -> + tasksUiState = tasksUiState.copy( + tasks = tasks, + taskOrder = order, + showCompletedTasks = showCompleted + ) + }.launchIn(viewModelScope) + } + private fun searchTasks(query: String){ + searchTasksJob?.cancel() + searchTasksJob = searchTasksUseCase(query).onEach { tasks -> + tasksUiState = tasksUiState.copy( + searchTasks = tasks + ) + }.launchIn(viewModelScope) + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/util/BottomNavigationItem.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/util/BottomNavigationItem.kt new file mode 100644 index 0000000..f91d3ab --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/util/BottomNavigationItem.kt @@ -0,0 +1,11 @@ +package com.mhss.app.mybrain.presentation.util + +import com.mhss.app.mybrain.R + +sealed class BottomNavItem(val title: Int, val icon: Int, val iconSelected: Int, val route: String){ + + object Dashboard : BottomNavItem(R.string.dashboard, R.drawable.ic_home, R.drawable.ic_home_filled, Screen.DashboardScreen.route) + object Spaces : BottomNavItem(R.string.spaces, R.drawable.ic_spaces, R.drawable.ic_spaces_filled, Screen.SpacesScreen.route) + object Settings: BottomNavItem(R.string.settings, R.drawable.ic_settings, R.drawable.ic_settings_filled, Screen.SettingsScreen.route) + +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/presentation/util/Screen.kt b/app/src/main/java/com/mhss/app/mybrain/presentation/util/Screen.kt new file mode 100644 index 0000000..1b62f3d --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/presentation/util/Screen.kt @@ -0,0 +1,27 @@ +package com.mhss.app.mybrain.presentation.util + +import com.mhss.app.mybrain.util.Constants + +sealed class Screen(val route: String) { + object Main : Screen("main_screen") + object SpacesScreen : Screen("spaces_screen") + object DashboardScreen : Screen("dashboard_screen") + object SettingsScreen : Screen("settings_screen") + object TasksScreen : Screen("tasks_screen?${Constants.ADD_TASK_ARG}={${Constants.ADD_TASK_ARG}}") + object TaskDetailScreen : Screen("task_detail_screen/{${Constants.TASK_ID_ARG}}") + object TaskSearchScreen : Screen("task_search_screen") + object NotesScreen : Screen("notes_screen") + object NoteDetailsScreen : Screen("note_detail_screen/{${Constants.NOTE_ID_ARG}}?${Constants.FOLDER_ID}={${Constants.FOLDER_ID}}") + object NoteSearchScreen : Screen("note_search_screen") + object DiaryScreen : Screen("diary_screen") + object DiaryDetailScreen : Screen("diary_detail_screen/{${Constants.DIARY_ID_ARG}}") + object DiarySearchScreen : Screen("diary_search_screen") + object DiaryChartScreen : Screen("diary_chart_screen") + object BookmarksScreen : Screen("bookmarks_screen") + object BookmarkDetailScreen : Screen("bookmark_detail_screen/{${Constants.BOOKMARK_ID_ARG}}") + object BookmarkSearchScreen : Screen("bookmark_search_screen") + object CalendarScreen : Screen("calendar_screen") + object CalendarEventDetailsScreen : Screen("calendar_event_details_screen/{${Constants.CALENDAR_EVENT_ARG}}") + object NoteFolderDetailsScreen : Screen("note_folder_details_screen/{${Constants.FOLDER_ID}}") + object ImportExportScreen : Screen("import_export_screen") +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/ui/theme/Color.kt b/app/src/main/java/com/mhss/app/mybrain/ui/theme/Color.kt new file mode 100644 index 0000000..02c2dda --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/ui/theme/Color.kt @@ -0,0 +1,18 @@ +package com.mhss.app.mybrain.ui.theme + +import androidx.compose.ui.graphics.Color + +val PrimaryColor = Color(0xFF2DD1E7) +val PrimaryDarkColor = Color(0xFF00B0B0) +val SecondaryColor = Color(0xFF5939CE) +val DarkGray = Color(0xFF090909) + +//val SurfaceGray = Color(0xFF121212) +val Red = Color(0xFFD53A2F) +val Blue = Color(0xFF2965C9) +val Green = Color(0xFF1E9651) +val Orange = Color(0xFFFF9800) +val Purple = Color(0xFF6F4CAD) + +val Gray = Color(0xFF7E7979) +val LightGray = Color(0xFFECECEC) diff --git a/app/src/main/java/com/mhss/app/mybrain/ui/theme/Shape.kt b/app/src/main/java/com/mhss/app/mybrain/ui/theme/Shape.kt new file mode 100644 index 0000000..5f92dc6 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/ui/theme/Shape.kt @@ -0,0 +1,11 @@ +package com.mhss.app.mybrain.ui.theme + +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.Shapes +import androidx.compose.ui.unit.dp + +val Shapes = Shapes( + small = RoundedCornerShape(4.dp), + medium = RoundedCornerShape(4.dp), + large = RoundedCornerShape(0.dp) +) \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/ui/theme/Theme.kt b/app/src/main/java/com/mhss/app/mybrain/ui/theme/Theme.kt new file mode 100644 index 0000000..6815d39 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/ui/theme/Theme.kt @@ -0,0 +1,45 @@ +package com.mhss.app.mybrain.ui.theme + +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.material.MaterialTheme +import androidx.compose.material.darkColors +import androidx.compose.material.lightColors +import androidx.compose.runtime.Composable +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.font.FontFamily + +private val DarkColorPalette = darkColors( + primary = PrimaryColor, + primaryVariant = PrimaryDarkColor, + secondary = SecondaryColor, + surface = DarkGray, + background = Color.Black, + onSurface = Color.White, + onBackground = Color.White +) + +private val LightColorPalette = lightColors( + primary = PrimaryColor, + primaryVariant = PrimaryDarkColor, + secondary = SecondaryColor, + background = Color.White, +) + +@Composable +fun MyBrainTheme( + darkTheme: Boolean = isSystemInDarkTheme(), + fontFamily: FontFamily = Rubik, + content: @Composable () -> Unit) { + val colors = if (darkTheme) { + DarkColorPalette + } else { + LightColorPalette + } + val typography = getTypography(fontFamily) + MaterialTheme( + colors = colors, + typography = typography, + shapes = Shapes, + content = content + ) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/ui/theme/Type.kt b/app/src/main/java/com/mhss/app/mybrain/ui/theme/Type.kt new file mode 100644 index 0000000..dc8f18c --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/ui/theme/Type.kt @@ -0,0 +1,72 @@ +package com.mhss.app.mybrain.ui.theme + +import androidx.compose.material.Typography +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.Font +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.sp +import com.mhss.app.mybrain.R + +val Rubik = FontFamily( + Font(R.font.rubik_regular), + Font(R.font.rubik_bold, FontWeight.Bold) +) +// Set of Material typography styles to start with +fun getTypography(font: FontFamily) = Typography( + defaultFontFamily = font, + body1 = TextStyle( + fontWeight = FontWeight.Normal, + fontSize = 16.sp + ), + body2 = TextStyle( + fontWeight = FontWeight.Normal, + fontSize = 14.sp + ), + button = TextStyle( + fontWeight = FontWeight.W500, + fontSize = 14.sp + ), + h1 = TextStyle( + fontWeight = FontWeight.Normal, + fontSize = 96.sp + ), + h2 = TextStyle( + fontWeight = FontWeight.Normal, + fontSize = 60.sp + ), + h3 = TextStyle( + fontWeight = FontWeight.Normal, + fontSize = 48.sp + ), + h4 = TextStyle( + fontWeight = FontWeight.Normal, + fontSize = 34.sp + ), + h5 = TextStyle( + fontWeight = FontWeight.Normal, + fontSize = 24.sp + ), + h6 = TextStyle( + fontWeight = FontWeight.Normal, + fontSize = 20.sp + ), + subtitle1 = TextStyle( + fontWeight = FontWeight.Normal, + fontSize = 16.sp + ), + subtitle2 = TextStyle( + fontWeight = FontWeight.Normal, + fontSize = 12.sp + ) + /* Other default text styles to override + button = TextStyle( + fontWeight = FontWeight.W500, + fontSize = 14.sp + ), + caption = TextStyle( + fontWeight = FontWeight.Normal, + fontSize = 12.sp + ) + */ +) \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/util/BackupUtil.kt b/app/src/main/java/com/mhss/app/mybrain/util/BackupUtil.kt new file mode 100644 index 0000000..759cc90 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/util/BackupUtil.kt @@ -0,0 +1,46 @@ +package com.mhss.app.mybrain.util + +import com.squareup.moshi.* +import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory +import java.util.* + +object BackupUtil { + + inline fun List.toJson(): String{ + val moshi = Moshi.Builder().add(UUIDAdapter()).addLast(KotlinJsonAdapterFactory()).build() + val adapter: JsonAdapter> = moshi.adapter(Types.newParameterizedType(List::class.java, T::class.java)) + return adapter.toJson(this) + } + + inline fun T.toJson(): String{ + val moshi = Moshi.Builder().add(UUIDAdapter()).addLast(KotlinJsonAdapterFactory()).build() + val adapter: JsonAdapter = moshi.adapter(T::class.java) + return adapter.toJson(this) + } + + inline fun String.objectFromJson(): T?{ + val moshi = Moshi.Builder().add(UUIDAdapter()).addLast(KotlinJsonAdapterFactory()).build() + val adapter: JsonAdapter = moshi.adapter(T::class.java) + return adapter.fromJson(this) + } + + inline fun String.listFromJson(): List?{ + val moshi = Moshi.Builder().add(UUIDAdapter()).addLast(KotlinJsonAdapterFactory()).build() + val adapter: JsonAdapter> = moshi.adapter(Types.newParameterizedType(List::class.java, T::class.java)) + return adapter.fromJson(this) + } + + +} + +class UUIDAdapter { + @FromJson + fun fromJson(json: String): UUID { + return UUID.fromString(json) + } + + @ToJson + fun toJson(uuid: UUID): String { + return uuid.toString() + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/util/Constants.kt b/app/src/main/java/com/mhss/app/mybrain/util/Constants.kt new file mode 100644 index 0000000..e768f13 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/util/Constants.kt @@ -0,0 +1,52 @@ +package com.mhss.app.mybrain.util + +object Constants { + + // Alarm & Notification + const val REMINDERS_CHANNEL_ID = "reminders_notification_channel" + const val TASK_ID_EXTRA = "task_Id" + const val ACTION_COMPLETE = "com.mhss.app.mybrain.COMPLETE_ACTION" + + // Settings + const val SETTINGS_PREFERENCES = "settings_preferences" + const val SETTINGS_THEME_KEY = "settings_theme" + const val DEFAULT_START_UP_SCREEN_KEY = "default_start_up_screen" + const val SHOW_COMPLETED_TASKS_KEY = "show_completed_tasks" + const val TASKS_ORDER_KEY = "tasks_order" + const val NOTE_VIEW_KEY = "note_view" + const val BOOKMARK_VIEW_KEY = "bookmark_view" + const val NOTES_ORDER_KEY = "notes_order" + const val BOOKMARK_ORDER_KEY = "bookmark_order" + const val DIARY_ORDER_KEY = "diary_order" + const val EXCLUDED_CALENDARS_KEY = "excluded_calendars" + const val APP_FONT_KEY = "app_font" + const val BLOCK_SCREENSHOTS_KEY = "block_screen_shots" + + // Navigation + const val TASK_ID_ARG = "task_id" + const val TASK_DETAILS_URI = "app://com.mhss.app.mybrain/task_details" + const val ADD_TASK_ARG = "add_task" + const val TASKS_SCREEN_URI = "app://com.mhss.app.mybrain/tasks" + const val CALENDAR_SCREEN_URI = "app://com.mhss.app.mybrain/calendar" + const val CALENDAR_DETAILS_SCREEN_URI = "app://com.mhss.app.mybrain/calendar_event_details" + const val NOTE_ID_ARG = "note_id" + const val BOOKMARK_ID_ARG = "bookmark_id" + const val DIARY_ID_ARG = "diary_id" + const val CALENDAR_EVENT_ARG = "calendar_event" + const val FOLDER_ID = "folder_id" + + // lINKS + const val PROJECT_GITHUB_LINK = "https://github.com/mhss1/ByBrain" + const val PROJECT_ROADMAP_LINK = "https://github.com/users/mhss1/projects/2/" + const val PRIVACY_POLICY_LINK = "https://github.com/mhss1/ByBrain/blob/master/privacy-policy.md" + const val GITHUB_ISSUES_LINK = "https://github.com/mhss1/ByBrain/issues" + const val GITHUB_RELEASES_LINK = "https://github.com/mhss1/ByBrain/releases" + + // Backup + const val EXPORT_DIR = "MyBrain Export" + const val BACKUP_NOTES_FILE_NAME = "mybrain_notes.txt" + const val BACKUP_TASKS_FILE_NAME = "mybrain_tasks.txt" + const val BACKUP_DIARY_FILE_NAME = "mybrain_diary.txt" + const val BACKUP_BOOKMARKS_FILE_NAME = "mybrain_bookmarks.txt" + +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/util/alarms/AlarmReceiver.kt b/app/src/main/java/com/mhss/app/mybrain/util/alarms/AlarmReceiver.kt new file mode 100644 index 0000000..8159102 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/util/alarms/AlarmReceiver.kt @@ -0,0 +1,76 @@ +package com.mhss.app.mybrain.util.alarms + +import android.app.NotificationManager +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import com.mhss.app.mybrain.domain.model.Alarm +import com.mhss.app.mybrain.domain.use_case.alarm.AddAlarmUseCase +import com.mhss.app.mybrain.domain.use_case.alarm.DeleteAlarmUseCase +import com.mhss.app.mybrain.domain.use_case.tasks.GetTaskByIdUseCase +import com.mhss.app.mybrain.domain.use_case.tasks.UpdateTaskUseCase +import com.mhss.app.mybrain.util.Constants +import com.mhss.app.mybrain.util.settings.TaskFrequency +import dagger.hilt.android.AndroidEntryPoint +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import java.util.Calendar +import javax.inject.Inject + +@AndroidEntryPoint +class AlarmReceiver : BroadcastReceiver() { + + @Inject + lateinit var deleteAlarmUseCase: DeleteAlarmUseCase + @Inject + lateinit var addAlarmUseCase: AddAlarmUseCase + + @Inject + lateinit var getTaskByIdUseCase: GetTaskByIdUseCase + @Inject + lateinit var updateTaskUseCase: UpdateTaskUseCase + + private val scope = CoroutineScope(Dispatchers.Default) + + override fun onReceive(context: Context?, intent: Intent?) { + val pendingResult = goAsync() + scope.launch { + val task = + intent?.getIntExtra(Constants.TASK_ID_EXTRA, 0)?.let { getTaskByIdUseCase(it) } + ?: kotlin.run { + pendingResult.finish() + return@launch + } + val notificationJob = launch { + val manager = + context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + manager.sendNotification(task, context, task.id) + if (!task.recurring) deleteAlarmUseCase(task.id) + } + val recurrenceJob = launch { + if (task.recurring) { + val calendar = Calendar.getInstance().apply { timeInMillis = task.dueDate } + when (task.frequency) { + TaskFrequency.EVERY_MINUTES.value -> calendar.add(Calendar.MINUTE, task.frequencyAmount) + TaskFrequency.HOURLY.value -> calendar.add(Calendar.HOUR, task.frequencyAmount) + TaskFrequency.DAILY.value -> calendar.add(Calendar.DAY_OF_YEAR, task.frequencyAmount) + TaskFrequency.WEEKLY.value -> calendar.add(Calendar.WEEK_OF_YEAR, task.frequencyAmount) + TaskFrequency.MONTHLY.value -> calendar.add(Calendar.MONTH, task.frequencyAmount) + TaskFrequency.ANNUAL.value -> calendar.add(Calendar.YEAR, task.frequencyAmount) + else -> calendar.add(Calendar.DAY_OF_YEAR, task.frequencyAmount) + } + val newTask = task.copy( + dueDate = calendar.timeInMillis, + ) + updateTaskUseCase(newTask) + addAlarmUseCase(Alarm(newTask.id, newTask.dueDate)) + } + } + + notificationJob.join() + recurrenceJob.join() + pendingResult.finish() + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/util/alarms/AlarmUtil.kt b/app/src/main/java/com/mhss/app/mybrain/util/alarms/AlarmUtil.kt new file mode 100644 index 0000000..1b199c4 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/util/alarms/AlarmUtil.kt @@ -0,0 +1,34 @@ +package com.mhss.app.mybrain.util.alarms + +import android.app.AlarmManager +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import androidx.core.app.AlarmManagerCompat +import com.mhss.app.mybrain.domain.model.Alarm +import com.mhss.app.mybrain.util.Constants + +fun AlarmManager.scheduleAlarm(alarm: Alarm, context: Context) { + + val intent = Intent(context, AlarmReceiver::class.java) + intent.putExtra(Constants.TASK_ID_EXTRA, alarm.id) + val pendingIntent = PendingIntent.getBroadcast( + context, + alarm.id, + intent, + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT + ) + AlarmManagerCompat.setExactAndAllowWhileIdle(this, AlarmManager.RTC_WAKEUP, alarm.time, pendingIntent) +} + +fun AlarmManager.cancelAlarm(alarmId: Int, context: Context) { + + val intent = Intent(context, AlarmReceiver::class.java) + val pendingIntent = PendingIntent.getBroadcast( + context, + alarmId, + intent, + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT + ) + cancel(pendingIntent) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/util/alarms/BootBroadcastReceiver.kt b/app/src/main/java/com/mhss/app/mybrain/util/alarms/BootBroadcastReceiver.kt new file mode 100644 index 0000000..dc554bb --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/util/alarms/BootBroadcastReceiver.kt @@ -0,0 +1,31 @@ +package com.mhss.app.mybrain.util.alarms + +import android.app.AlarmManager +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import com.mhss.app.mybrain.domain.use_case.alarm.GetAllAlarmsUseCase +import dagger.hilt.android.AndroidEntryPoint +import kotlinx.coroutines.runBlocking +import javax.inject.Inject + +@AndroidEntryPoint +class BootBroadcastReceiver : BroadcastReceiver() { + + @Inject + lateinit var getAllAlarms: GetAllAlarmsUseCase + + override fun onReceive(context: Context?, intent: Intent?) { + if (intent?.action == Intent.ACTION_BOOT_COMPLETED) { + val alarmManager = context?.getSystemService(Context.ALARM_SERVICE) as AlarmManager + runBlocking { + val alarms = getAllAlarms() + alarms.forEach { + alarmManager.scheduleAlarm(it, context) + } + } + } + + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/util/alarms/NotificationUtil.kt b/app/src/main/java/com/mhss/app/mybrain/util/alarms/NotificationUtil.kt new file mode 100644 index 0000000..153783e --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/util/alarms/NotificationUtil.kt @@ -0,0 +1,60 @@ +package com.mhss.app.mybrain.util.alarms + +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import androidx.core.app.NotificationCompat +import androidx.core.app.TaskStackBuilder +import androidx.core.net.toUri +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.app.getString +import com.mhss.app.mybrain.domain.model.Task +import com.mhss.app.mybrain.presentation.main.MainActivity +import com.mhss.app.mybrain.util.Constants +import com.mhss.app.mybrain.util.settings.Priority +import com.mhss.app.mybrain.util.settings.toInt + +fun NotificationManager.sendNotification(task: Task, context: Context, id: Int) { + val completeIntent = Intent(context, TaskActionButtonBroadcastReceiver::class.java).apply { + action = Constants.ACTION_COMPLETE + putExtra(Constants.TASK_ID_EXTRA, task.id) + } + val completePendingIntent: PendingIntent = + PendingIntent.getBroadcast( + context, + task.id, + completeIntent, + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT + ) + + val taskDetailIntent = Intent( + Intent.ACTION_VIEW, + "${Constants.TASK_DETAILS_URI}/${task.id}".toUri(), + context, + MainActivity::class.java + ) + val taskDetailsPendingIntent: PendingIntent? = TaskStackBuilder.create(context).run { + addNextIntentWithParentStack(taskDetailIntent) + getPendingIntent(0, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) + } + + val notification = NotificationCompat.Builder(context, Constants.REMINDERS_CHANNEL_ID) + .setSmallIcon(R.drawable.notification_icon) + .setContentTitle(task.title) + .setContentText(task.description) + .setContentIntent(taskDetailsPendingIntent) + .setPriority( + when (task.priority) { + Priority.LOW.toInt() -> NotificationCompat.PRIORITY_DEFAULT + Priority.MEDIUM.toInt() -> NotificationCompat.PRIORITY_HIGH + Priority.HIGH.toInt() -> NotificationCompat.PRIORITY_MAX + else -> NotificationCompat.PRIORITY_DEFAULT + } + ) + .addAction(R.drawable.ic_check, getString(R.string.complete), completePendingIntent) + .setAutoCancel(true) + .build() + + notify(id, notification) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/util/alarms/TaskActionButtonBroadcastReceiver.kt b/app/src/main/java/com/mhss/app/mybrain/util/alarms/TaskActionButtonBroadcastReceiver.kt new file mode 100644 index 0000000..be213cf --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/util/alarms/TaskActionButtonBroadcastReceiver.kt @@ -0,0 +1,29 @@ +package com.mhss.app.mybrain.util.alarms + +import android.app.NotificationManager +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import com.mhss.app.mybrain.domain.use_case.tasks.UpdateTaskCompletedUseCase +import com.mhss.app.mybrain.util.Constants +import dagger.hilt.android.AndroidEntryPoint +import kotlinx.coroutines.runBlocking +import javax.inject.Inject + +@AndroidEntryPoint +class TaskActionButtonBroadcastReceiver : BroadcastReceiver() { + + @Inject + lateinit var updateTaskCompleted: UpdateTaskCompletedUseCase + + override fun onReceive(context: Context, intent: Intent?) { + if (intent?.action == Constants.ACTION_COMPLETE) { + runBlocking { + val taskId = intent.getIntExtra(Constants.TASK_ID_EXTRA, 0) + updateTaskCompleted(taskId, true) + val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + manager.cancel(taskId) + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/util/bookmarks/BookmarksUtil.kt b/app/src/main/java/com/mhss/app/mybrain/util/bookmarks/BookmarksUtil.kt new file mode 100644 index 0000000..17779ec --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/util/bookmarks/BookmarksUtil.kt @@ -0,0 +1,8 @@ +package com.mhss.app.mybrain.util.bookmarks + +import android.util.Patterns + + +fun String.isValidUrl(): Boolean { + return Patterns.WEB_URL.matcher(this).matches() +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/util/calendar/CalendarUtil.kt b/app/src/main/java/com/mhss/app/mybrain/util/calendar/CalendarUtil.kt new file mode 100644 index 0000000..1b80b27 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/util/calendar/CalendarUtil.kt @@ -0,0 +1,78 @@ +package com.mhss.app.mybrain.util.calendar + +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.app.getString +import com.mhss.app.mybrain.domain.model.CalendarEvent + +const val CALENDAR_FREQ_DAILY = "DAILY" +const val CALENDAR_FREQ_WEEKLY = "WEEKLY" +const val CALENDAR_FREQ_MONTHLY = "MONTHLY" +const val CALENDAR_FREQ_YEARLY = "YEARLY" +const val CALENDAR_FREQ_NEVER = "NEVER" + +fun String.toUIFrequency(): String { + return when (this) { + CALENDAR_FREQ_DAILY -> getString(R.string.every_day) + CALENDAR_FREQ_WEEKLY -> getString(R.string.every_week) + CALENDAR_FREQ_MONTHLY -> getString(R.string.every_month) + CALENDAR_FREQ_YEARLY -> getString(R.string.every_year) + else -> getString(R.string.do_not_repeat) + } +} + +fun CalendarEvent.getEventDuration(): String { + return "P${(end - start) / 1000}S" +} + +fun String.extractEndFromDuration(start: Long): Long { + return try { + val duration = this.substring(1, this.length - 1).toLong() * 1000 + start + duration + }catch (e: Exception) { + start + } +} + +fun CalendarEvent.getEventRRule(): String { + return buildString { + append("FREQ=${frequency}") + // will be implemented later +// if (until > 0) { +// val formattedUntil = SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'", Locale.US).format(until) +// append(";UNTIL=${formattedUntil}") +// } +// if (count > 0) { +// append(";COUNT=${count}") +// } +// if (interval > 0) { +// append(";INTERVAL=${interval}") +// } + } +} + +fun String.extractFrequency(): String { + return if (this.contains("FREQ=")) { + val freq = this.substringAfter("FREQ=") + freq.substringBefore(";") + } else CALENDAR_FREQ_NEVER +} + +// will be implemented later +//fun String.extractUntil(): Long { +// return if (this.contains("UNTIL=")) { +// val until = this.substringAfter("UNTIL=") +// SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'", Locale.US).parse(until.substringBefore(";"))?.time ?: 0 +// } else 0 +//} +//fun String.extractCount(): Int { +// return if (this.contains("COUNT=")) { +// val count = this.substringAfter("COUNT=") +// count.substringBefore(";").toInt() +// } else 0 +//} +//fun String.extractInterval(): Int { +// return if (this.contains("INTERVAL=")) { +// val interval = this.substringAfter("INTERVAL=") +// interval.substringBefore(";").toInt() +// } else 0 +//} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/util/date/DateUtils.kt b/app/src/main/java/com/mhss/app/mybrain/util/date/DateUtils.kt new file mode 100644 index 0000000..4fd5170 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/util/date/DateUtils.kt @@ -0,0 +1,97 @@ +package com.mhss.app.mybrain.util.date + +import android.text.format.DateFormat +import android.text.format.DateUtils +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.app.MyBrainApplication.Companion.appContext +import com.mhss.app.mybrain.app.getString +import java.text.SimpleDateFormat +import java.util.* + +fun Long.formatDateDependingOnDay(): String { + val hourPatternString = if (is24Hour()) "H:mm" else "h:mm a" + + val sdf = if (DateUtils.isToday(this)) + SimpleDateFormat(hourPatternString, Locale.getDefault()) + else + SimpleDateFormat("MMM dd,yyyy $hourPatternString", Locale.getDefault()) + + + return sdf.format(this) +} + +fun Long.fullDate(): String { + val hourPatternString = if (is24Hour()) "H:mm" else "h:mm a" + val sdf = SimpleDateFormat("MMM dd,yyyy $hourPatternString", Locale.getDefault()) + return sdf.format(this) +} + +fun Long.formatDateForMapping(): String { + val sdf = SimpleDateFormat("EEEE d, MMM yyy", Locale.getDefault()) + return sdf.format(this) +} + +fun Long.formatTime(): String { + val is24 = is24Hour() + val sdf = SimpleDateFormat(if (is24) "H:mm" else "h:mm a", Locale.getDefault()) + val sdfNoMinutes = SimpleDateFormat(if (is24) "H:mm" else "h a", Locale.getDefault()) + val minutes = SimpleDateFormat("mm", Locale.getDefault()).format(this) + return if (minutes == "00") sdfNoMinutes.format(this) else sdf.format(this) +} + +fun Long.formatDate(): String { + val sdf = SimpleDateFormat("EEE, MMM dd, yyyy", Locale.getDefault()) + return sdf.format(this) +} + +fun Long.monthName(): String { + val sdf = if (this.isCurrentYear()) + SimpleDateFormat("MMMM", Locale.getDefault()) + else + SimpleDateFormat("MMMM yyyy", Locale.getDefault()) + return sdf.format(this) +} + +fun Long.inTheLast30Days(): Boolean { + val calendar = Calendar.getInstance() + calendar.add(Calendar.MONTH, -1) + return this > calendar.timeInMillis +} +fun Long.inTheLastYear(): Boolean { + val calendar = Calendar.getInstance() + calendar.add(Calendar.YEAR, -1) + return this > calendar.timeInMillis +} + +fun Long.inTheLastWeek(): Boolean { + val calendar = Calendar.getInstance() + calendar.add(Calendar.WEEK_OF_MONTH, -1) + return this > calendar.timeInMillis +} + +fun Long.isCurrentYear(): Boolean { + val sdf = SimpleDateFormat("yyyy", Locale.getDefault()) + return sdf.format(this) == sdf.format(Date()) +} + +fun Long.isDueDateOverdue(): Boolean { + return this < System.currentTimeMillis() +} + +fun formatEventStartEnd(start: Long, end: Long, location: String?, allDay: Boolean): String { + return if (allDay) + getString(R.string.all_day) + else + getString( + if (!location.isNullOrBlank()) + R.string.event_time_at + else R.string.event_time, + start.formatTime(), + end.formatTime(), + location ?: "" + ) +} + +fun is24Hour() = DateFormat.is24HourFormat(appContext) + +const val HOUR_IN_MILLIS = 60 * 60 * 1000L \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/util/diary/Mood.kt b/app/src/main/java/com/mhss/app/mybrain/util/diary/Mood.kt new file mode 100644 index 0000000..3906765 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/util/diary/Mood.kt @@ -0,0 +1,15 @@ +package com.mhss.app.mybrain.util.diary + +import androidx.annotation.DrawableRes +import androidx.annotation.StringRes +import androidx.compose.ui.graphics.Color +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.ui.theme.* + +enum class Mood(@DrawableRes val icon: Int, val color: Color, @StringRes val title: Int, val value: Int) { + AWESOME(R.drawable.ic_very_happy, Green, R.string.awesome, 5), + GOOD(R.drawable.ic_happy, Blue, R.string.good, 4), + OKAY(R.drawable.ic_ok_face, Purple, R.string.okay, 3), + BAD(R.drawable.ic_sad, Orange, R.string.bad, 2), + TERRIBLE(R.drawable.ic_very_sad, Color.Red, R.string.terrible, 1) +} \ No newline at end of file diff --git a/app/src/main/java/com/mhss/app/mybrain/util/settings/SettingsUtil.kt b/app/src/main/java/com/mhss/app/mybrain/util/settings/SettingsUtil.kt new file mode 100644 index 0000000..c29c975 --- /dev/null +++ b/app/src/main/java/com/mhss/app/mybrain/util/settings/SettingsUtil.kt @@ -0,0 +1,176 @@ +package com.mhss.app.mybrain.util.settings + +import androidx.annotation.StringRes +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.font.FontFamily +import com.mhss.app.mybrain.R +import com.mhss.app.mybrain.app.getString +import com.mhss.app.mybrain.ui.theme.Green +import com.mhss.app.mybrain.ui.theme.Orange +import com.mhss.app.mybrain.ui.theme.Red +import com.mhss.app.mybrain.ui.theme.Rubik + + +enum class ThemeSettings(val value: Int) { + LIGHT(0), + DARK(1), + AUTO(2) +} + +enum class StartUpScreenSettings(val value: Int) { + DASHBOARD(0), + SPACES(1) +} +sealed class OrderType(val orderTitle: String) { + class ASC(val title: String = getString(R.string.ascending)) : OrderType(title) + class DESC(val title: String = getString(R.string.descending)) : OrderType(title) +} +sealed class Order(val orderType: OrderType, val orderTitle: String){ + abstract fun copy(orderType: OrderType): Order + data class Alphabetical(val type: OrderType = OrderType.ASC(), val title: String = getString(R.string.alphabetical)) : Order(type, title) { + override fun copy(orderType: OrderType): Order { + return this.copy(type = orderType) + } + } + + data class DateCreated(val type: OrderType = OrderType.ASC(), val title: String = getString(R.string.date_created)) : Order(type, title) { + override fun copy(orderType: OrderType): Order { + return this.copy(type = orderType) + } + } + + data class DateModified(val type: OrderType = OrderType.ASC(), val title: String = getString(R.string.date_modified)) : Order(type, title) { + override fun copy(orderType: OrderType): Order { + return this.copy(type = orderType) + } + } + + data class Priority(val type: OrderType = OrderType.ASC(), val title: String = getString(R.string.priority)) : Order(type, title) { + override fun copy(orderType: OrderType): Order { + return this.copy(type = orderType) + } + } + + data class DueDate(val type: OrderType = OrderType.ASC(), val title: String = getString(R.string.due_date)) : Order(type, title) { + override fun copy(orderType: OrderType): Order { + return this.copy(type = orderType) + } + } +} + +enum class TaskFrequency(@StringRes val title: Int, val value: Int) { + EVERY_MINUTES(R.string.every_minute, 0), + HOURLY(R.string.every_hour, 1), + DAILY(R.string.every_day, 2), + WEEKLY(R.string.every_week, 3), + MONTHLY(R.string.every_month, 4), + ANNUAL(R.string.every_year, 5) +} +enum class Priority( @StringRes val title: Int, val color: Color) { + LOW(R.string.low, Green), + MEDIUM(R.string.medium, Orange), + HIGH(R.string.high, Red) +} + +enum class ItemView(@StringRes val title: Int, val value: Int) { + LIST(R.string.list, 0), + GRID(R.string.grid, 1) +} + +fun Int.toNotesView(): ItemView { + return ItemView.values().first { it.value == this } +} + + +fun Int.toPriority(): Priority { + return when (this) { + 0 -> Priority.LOW + 1 -> Priority.MEDIUM + 2 -> Priority.HIGH + else -> Priority.LOW + } +} + +fun Priority.toInt(): Int { + return when (this) { + Priority.LOW -> 0 + Priority.MEDIUM -> 1 + Priority.HIGH -> 2 + } +} + +fun Int.toTaskFrequency(): TaskFrequency { + return TaskFrequency.values().firstOrNull { it.value == this } ?: TaskFrequency.DAILY +} + +fun Int.toOrder(): Order { + return when(this){ + 0 -> Order.Alphabetical(OrderType.ASC()) + 1 -> Order.DateCreated(OrderType.ASC()) + 2 -> Order.DateModified(OrderType.ASC()) + 3 -> Order.Priority(OrderType.ASC()) + 8 -> Order.DueDate(OrderType.ASC()) + 4 -> Order.Alphabetical(OrderType.DESC()) + 5 -> Order.DateCreated(OrderType.DESC()) + 6 -> Order.DateModified(OrderType.DESC()) + 7 -> Order.Priority(OrderType.DESC()) + 9 -> Order.DueDate(OrderType.DESC()) + else -> Order.Alphabetical(OrderType.ASC()) + } +} +fun Order.toInt(): Int { + return when (this.orderType) { + is OrderType.ASC -> { + when (this) { + is Order.Alphabetical -> 0 + is Order.DateCreated -> 1 + is Order.DateModified -> 2 + is Order.Priority -> 3 + is Order.DueDate -> 8 + } + } + is OrderType.DESC -> { + when (this) { + is Order.Alphabetical -> 4 + is Order.DateCreated -> 5 + is Order.DateModified -> 6 + is Order.Priority -> 7 + is Order.DueDate -> 9 + } + } + } +} + +fun Int.toFontFamily(): FontFamily { + return when (this) { + 0 -> FontFamily.Default + 1 -> Rubik + 2 -> FontFamily.Monospace + 3 -> FontFamily.SansSerif + else -> FontFamily.Default + } +} + +fun FontFamily.toInt(): Int { + return when (this) { + FontFamily.Default -> 0 + Rubik -> 1 + FontFamily.Monospace -> 2 + FontFamily.SansSerif -> 3 + else -> 0 + } +} + +fun FontFamily.getName(): String { + return when (this) { + FontFamily.Default -> getString(R.string.font_system_default) + Rubik -> "Rubik" + FontFamily.Monospace -> "Monospace" + FontFamily.SansSerif -> "Sans Serif" + else -> getString(R.string.font_system_default) + } +} + +fun Set.toIntList() = this.toList().map { it.toInt() } +fun MutableList.addAndToStringSet(id: Int) = apply { add(id) }.map { it.toString() }.toSet() +fun MutableList.removeAndToStringSet(id: Int) = apply { remove(id) }.map { it.toString() }.toSet() \ No newline at end of file diff --git a/app/src/main/res/drawable-v24/ic_launcher_foreground.png b/app/src/main/res/drawable-v24/ic_launcher_foreground.png new file mode 100644 index 0000000..6bedd35 Binary files /dev/null and b/app/src/main/res/drawable-v24/ic_launcher_foreground.png differ diff --git a/app/src/main/res/drawable/bookmarks_img.png b/app/src/main/res/drawable/bookmarks_img.png new file mode 100644 index 0000000..c297985 Binary files /dev/null and b/app/src/main/res/drawable/bookmarks_img.png differ diff --git a/app/src/main/res/drawable/calendar_img.png b/app/src/main/res/drawable/calendar_img.png new file mode 100644 index 0000000..12f8c52 Binary files /dev/null and b/app/src/main/res/drawable/calendar_img.png differ diff --git a/app/src/main/res/drawable/calendar_widget_preview_img.png b/app/src/main/res/drawable/calendar_widget_preview_img.png new file mode 100644 index 0000000..ec77f2b Binary files /dev/null and b/app/src/main/res/drawable/calendar_widget_preview_img.png differ diff --git a/app/src/main/res/drawable/diary_img.png b/app/src/main/res/drawable/diary_img.png new file mode 100644 index 0000000..0b43e3b Binary files /dev/null and b/app/src/main/res/drawable/diary_img.png differ diff --git a/app/src/main/res/drawable/ic_add.xml b/app/src/main/res/drawable/ic_add.xml new file mode 100644 index 0000000..b760740 --- /dev/null +++ b/app/src/main/res/drawable/ic_add.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_alarm.xml b/app/src/main/res/drawable/ic_alarm.xml new file mode 100644 index 0000000..37fdf85 --- /dev/null +++ b/app/src/main/res/drawable/ic_alarm.xml @@ -0,0 +1,18 @@ + + + + + + diff --git a/app/src/main/res/drawable/ic_alarm_red.xml b/app/src/main/res/drawable/ic_alarm_red.xml new file mode 100644 index 0000000..a1eb286 --- /dev/null +++ b/app/src/main/res/drawable/ic_alarm_red.xml @@ -0,0 +1,18 @@ + + + + + + diff --git a/app/src/main/res/drawable/ic_auto.xml b/app/src/main/res/drawable/ic_auto.xml new file mode 100644 index 0000000..c378a07 --- /dev/null +++ b/app/src/main/res/drawable/ic_auto.xml @@ -0,0 +1,11 @@ + + + diff --git a/app/src/main/res/drawable/ic_calendar.xml b/app/src/main/res/drawable/ic_calendar.xml new file mode 100644 index 0000000..755d686 --- /dev/null +++ b/app/src/main/res/drawable/ic_calendar.xml @@ -0,0 +1,18 @@ + + + + + + diff --git a/app/src/main/res/drawable/ic_chart.xml b/app/src/main/res/drawable/ic_chart.xml new file mode 100644 index 0000000..de66448 --- /dev/null +++ b/app/src/main/res/drawable/ic_chart.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_check.xml b/app/src/main/res/drawable/ic_check.xml new file mode 100644 index 0000000..83c464b --- /dev/null +++ b/app/src/main/res/drawable/ic_check.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_code.xml b/app/src/main/res/drawable/ic_code.xml new file mode 100644 index 0000000..8ef40bd --- /dev/null +++ b/app/src/main/res/drawable/ic_code.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_create_folder.xml b/app/src/main/res/drawable/ic_create_folder.xml new file mode 100644 index 0000000..a0bb1a6 --- /dev/null +++ b/app/src/main/res/drawable/ic_create_folder.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_dark.xml b/app/src/main/res/drawable/ic_dark.xml new file mode 100644 index 0000000..a677cde --- /dev/null +++ b/app/src/main/res/drawable/ic_dark.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_delete.xml b/app/src/main/res/drawable/ic_delete.xml new file mode 100644 index 0000000..de011dd --- /dev/null +++ b/app/src/main/res/drawable/ic_delete.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_description.xml b/app/src/main/res/drawable/ic_description.xml new file mode 100644 index 0000000..49be77f --- /dev/null +++ b/app/src/main/res/drawable/ic_description.xml @@ -0,0 +1,18 @@ + + + + + + diff --git a/app/src/main/res/drawable/ic_edit.xml b/app/src/main/res/drawable/ic_edit.xml new file mode 100644 index 0000000..1c9bd3e --- /dev/null +++ b/app/src/main/res/drawable/ic_edit.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_export.xml b/app/src/main/res/drawable/ic_export.xml new file mode 100644 index 0000000..46d5d58 --- /dev/null +++ b/app/src/main/res/drawable/ic_export.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_feature_issue.xml b/app/src/main/res/drawable/ic_feature_issue.xml new file mode 100644 index 0000000..ad66241 --- /dev/null +++ b/app/src/main/res/drawable/ic_feature_issue.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_folder.xml b/app/src/main/res/drawable/ic_folder.xml new file mode 100644 index 0000000..7ea2999 --- /dev/null +++ b/app/src/main/res/drawable/ic_folder.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_github.xml b/app/src/main/res/drawable/ic_github.xml new file mode 100644 index 0000000..91a6f88 --- /dev/null +++ b/app/src/main/res/drawable/ic_github.xml @@ -0,0 +1,32 @@ + + + + + + + + + + diff --git a/app/src/main/res/drawable/ic_happy.xml b/app/src/main/res/drawable/ic_happy.xml new file mode 100644 index 0000000..10fa37e --- /dev/null +++ b/app/src/main/res/drawable/ic_happy.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_home.xml b/app/src/main/res/drawable/ic_home.xml new file mode 100644 index 0000000..166ee51 --- /dev/null +++ b/app/src/main/res/drawable/ic_home.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_home_filled.xml b/app/src/main/res/drawable/ic_home_filled.xml new file mode 100644 index 0000000..7cd427a --- /dev/null +++ b/app/src/main/res/drawable/ic_home_filled.xml @@ -0,0 +1,15 @@ + + + + + diff --git a/app/src/main/res/drawable/ic_import.xml b/app/src/main/res/drawable/ic_import.xml new file mode 100644 index 0000000..dcfb784 --- /dev/null +++ b/app/src/main/res/drawable/ic_import.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_import_export.xml b/app/src/main/res/drawable/ic_import_export.xml new file mode 100644 index 0000000..c40dc3b --- /dev/null +++ b/app/src/main/res/drawable/ic_import_export.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_launcher_background.png b/app/src/main/res/drawable/ic_launcher_background.png new file mode 100644 index 0000000..9ad66cf Binary files /dev/null and b/app/src/main/res/drawable/ic_launcher_background.png differ diff --git a/app/src/main/res/drawable/ic_location.xml b/app/src/main/res/drawable/ic_location.xml new file mode 100644 index 0000000..bd87f1b --- /dev/null +++ b/app/src/main/res/drawable/ic_location.xml @@ -0,0 +1,12 @@ + + + + diff --git a/app/src/main/res/drawable/ic_ok_face.xml b/app/src/main/res/drawable/ic_ok_face.xml new file mode 100644 index 0000000..637dbbb --- /dev/null +++ b/app/src/main/res/drawable/ic_ok_face.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_open_link.xml b/app/src/main/res/drawable/ic_open_link.xml new file mode 100644 index 0000000..f0895a3 --- /dev/null +++ b/app/src/main/res/drawable/ic_open_link.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_pin.xml b/app/src/main/res/drawable/ic_pin.xml new file mode 100644 index 0000000..dc1997f --- /dev/null +++ b/app/src/main/res/drawable/ic_pin.xml @@ -0,0 +1,11 @@ + + + diff --git a/app/src/main/res/drawable/ic_pin_filled.xml b/app/src/main/res/drawable/ic_pin_filled.xml new file mode 100644 index 0000000..3428532 --- /dev/null +++ b/app/src/main/res/drawable/ic_pin_filled.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_privacy.xml b/app/src/main/res/drawable/ic_privacy.xml new file mode 100644 index 0000000..8d1648f --- /dev/null +++ b/app/src/main/res/drawable/ic_privacy.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_read_mode.xml b/app/src/main/res/drawable/ic_read_mode.xml new file mode 100644 index 0000000..b6fc229 --- /dev/null +++ b/app/src/main/res/drawable/ic_read_mode.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_refresh.xml b/app/src/main/res/drawable/ic_refresh.xml new file mode 100644 index 0000000..7501fd5 --- /dev/null +++ b/app/src/main/res/drawable/ic_refresh.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_roadmap.xml b/app/src/main/res/drawable/ic_roadmap.xml new file mode 100644 index 0000000..b00ff0a --- /dev/null +++ b/app/src/main/res/drawable/ic_roadmap.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_sad.xml b/app/src/main/res/drawable/ic_sad.xml new file mode 100644 index 0000000..9160ad6 --- /dev/null +++ b/app/src/main/res/drawable/ic_sad.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_save.xml b/app/src/main/res/drawable/ic_save.xml new file mode 100644 index 0000000..d1cacae --- /dev/null +++ b/app/src/main/res/drawable/ic_save.xml @@ -0,0 +1,12 @@ + + + + diff --git a/app/src/main/res/drawable/ic_search.xml b/app/src/main/res/drawable/ic_search.xml new file mode 100644 index 0000000..27b0e07 --- /dev/null +++ b/app/src/main/res/drawable/ic_search.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_settings.xml b/app/src/main/res/drawable/ic_settings.xml new file mode 100644 index 0000000..9427fe7 --- /dev/null +++ b/app/src/main/res/drawable/ic_settings.xml @@ -0,0 +1,14 @@ + + + + diff --git a/app/src/main/res/drawable/ic_settings_filled.xml b/app/src/main/res/drawable/ic_settings_filled.xml new file mode 100644 index 0000000..31dd628 --- /dev/null +++ b/app/src/main/res/drawable/ic_settings_filled.xml @@ -0,0 +1,11 @@ + + + diff --git a/app/src/main/res/drawable/ic_settings_sliders.xml b/app/src/main/res/drawable/ic_settings_sliders.xml new file mode 100644 index 0000000..646977c --- /dev/null +++ b/app/src/main/res/drawable/ic_settings_sliders.xml @@ -0,0 +1,15 @@ + + + + + diff --git a/app/src/main/res/drawable/ic_spaces.xml b/app/src/main/res/drawable/ic_spaces.xml new file mode 100644 index 0000000..24e4ad5 --- /dev/null +++ b/app/src/main/res/drawable/ic_spaces.xml @@ -0,0 +1,18 @@ + + + + + + diff --git a/app/src/main/res/drawable/ic_spaces_filled.xml b/app/src/main/res/drawable/ic_spaces_filled.xml new file mode 100644 index 0000000..917cbde --- /dev/null +++ b/app/src/main/res/drawable/ic_spaces_filled.xml @@ -0,0 +1,18 @@ + + + + + + diff --git a/app/src/main/res/drawable/ic_sun.xml b/app/src/main/res/drawable/ic_sun.xml new file mode 100644 index 0000000..8384197 --- /dev/null +++ b/app/src/main/res/drawable/ic_sun.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_time.xml b/app/src/main/res/drawable/ic_time.xml new file mode 100644 index 0000000..bdf91f9 --- /dev/null +++ b/app/src/main/res/drawable/ic_time.xml @@ -0,0 +1,6 @@ + + + + diff --git a/app/src/main/res/drawable/ic_very_happy.xml b/app/src/main/res/drawable/ic_very_happy.xml new file mode 100644 index 0000000..439e02a --- /dev/null +++ b/app/src/main/res/drawable/ic_very_happy.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_very_sad.xml b/app/src/main/res/drawable/ic_very_sad.xml new file mode 100644 index 0000000..01e5e15 --- /dev/null +++ b/app/src/main/res/drawable/ic_very_sad.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/large_inner_item_rounded_corner_shape.xml b/app/src/main/res/drawable/large_inner_item_rounded_corner_shape.xml new file mode 100644 index 0000000..d418abe --- /dev/null +++ b/app/src/main/res/drawable/large_inner_item_rounded_corner_shape.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/large_item_rounded_corner_shape.xml b/app/src/main/res/drawable/large_item_rounded_corner_shape.xml new file mode 100644 index 0000000..06c20d7 --- /dev/null +++ b/app/src/main/res/drawable/large_item_rounded_corner_shape.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/notes_img.png b/app/src/main/res/drawable/notes_img.png new file mode 100644 index 0000000..24e58bf Binary files /dev/null and b/app/src/main/res/drawable/notes_img.png differ diff --git a/app/src/main/res/drawable/notification_icon.png b/app/src/main/res/drawable/notification_icon.png new file mode 100644 index 0000000..803ac97 Binary files /dev/null and b/app/src/main/res/drawable/notification_icon.png differ diff --git a/app/src/main/res/drawable/small_item_rounded_corner_shape.xml b/app/src/main/res/drawable/small_item_rounded_corner_shape.xml new file mode 100644 index 0000000..a603ac6 --- /dev/null +++ b/app/src/main/res/drawable/small_item_rounded_corner_shape.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/task_check_box_background_green.xml b/app/src/main/res/drawable/task_check_box_background_green.xml new file mode 100644 index 0000000..3edb1f9 --- /dev/null +++ b/app/src/main/res/drawable/task_check_box_background_green.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/task_check_box_background_orange.xml b/app/src/main/res/drawable/task_check_box_background_orange.xml new file mode 100644 index 0000000..6745e20 --- /dev/null +++ b/app/src/main/res/drawable/task_check_box_background_orange.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/task_check_box_background_red.xml b/app/src/main/res/drawable/task_check_box_background_red.xml new file mode 100644 index 0000000..fe89480 --- /dev/null +++ b/app/src/main/res/drawable/task_check_box_background_red.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/tasks_img.png b/app/src/main/res/drawable/tasks_img.png new file mode 100644 index 0000000..8bc57d0 Binary files /dev/null and b/app/src/main/res/drawable/tasks_img.png differ diff --git a/app/src/main/res/drawable/tasks_widget_preview_img.png b/app/src/main/res/drawable/tasks_widget_preview_img.png new file mode 100644 index 0000000..5d81596 Binary files /dev/null and b/app/src/main/res/drawable/tasks_widget_preview_img.png differ diff --git a/app/src/main/res/font/rubik_bold.ttf b/app/src/main/res/font/rubik_bold.ttf new file mode 100644 index 0000000..dd50bbe Binary files /dev/null and b/app/src/main/res/font/rubik_bold.ttf differ diff --git a/app/src/main/res/font/rubik_regular.ttf b/app/src/main/res/font/rubik_regular.ttf new file mode 100644 index 0000000..dc90ef0 Binary files /dev/null and b/app/src/main/res/font/rubik_regular.ttf differ diff --git a/app/src/main/res/layout/calendar_preview_fake_item_1.xml b/app/src/main/res/layout/calendar_preview_fake_item_1.xml new file mode 100644 index 0000000..bc2b5b0 --- /dev/null +++ b/app/src/main/res/layout/calendar_preview_fake_item_1.xml @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/calendar_preview_fake_item_2.xml b/app/src/main/res/layout/calendar_preview_fake_item_2.xml new file mode 100644 index 0000000..b81fb90 --- /dev/null +++ b/app/src/main/res/layout/calendar_preview_fake_item_2.xml @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/calendar_preview_fake_list.xml b/app/src/main/res/layout/calendar_preview_fake_list.xml new file mode 100644 index 0000000..ddba353 --- /dev/null +++ b/app/src/main/res/layout/calendar_preview_fake_list.xml @@ -0,0 +1,15 @@ + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/calendar_widget_preview.xml b/app/src/main/res/layout/calendar_widget_preview.xml new file mode 100644 index 0000000..92d8eea --- /dev/null +++ b/app/src/main/res/layout/calendar_widget_preview.xml @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/tasks_preview_fake_list.xml b/app/src/main/res/layout/tasks_preview_fake_list.xml new file mode 100644 index 0000000..060f9c4 --- /dev/null +++ b/app/src/main/res/layout/tasks_preview_fake_list.xml @@ -0,0 +1,172 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/tasks_widget_preview.xml b/app/src/main/res/layout/tasks_widget_preview.xml new file mode 100644 index 0000000..ac89b9f --- /dev/null +++ b/app/src/main/res/layout/tasks_widget_preview.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/widget_initial.xml b/app/src/main/res/layout/widget_initial.xml new file mode 100644 index 0000000..bea76d0 --- /dev/null +++ b/app/src/main/res/layout/widget_initial.xml @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..b5fe611 --- /dev/null +++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..713466d --- /dev/null +++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher.png b/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..19064e9 Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_background.png b/app/src/main/res/mipmap-hdpi/ic_launcher_background.png new file mode 100644 index 0000000..8c5bf00 Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher_background.png differ diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png b/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..b46887a Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png differ diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_round.png b/app/src/main/res/mipmap-hdpi/ic_launcher_round.png new file mode 100644 index 0000000..2a503f6 Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_round_background.png b/app/src/main/res/mipmap-hdpi/ic_launcher_round_background.png new file mode 100644 index 0000000..8c5bf00 Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher_round_background.png differ diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_round_foreground.png b/app/src/main/res/mipmap-hdpi/ic_launcher_round_foreground.png new file mode 100644 index 0000000..b46887a Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher_round_foreground.png differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher.png b/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..9185416 Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_background.png b/app/src/main/res/mipmap-mdpi/ic_launcher_background.png new file mode 100644 index 0000000..11c72b2 Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher_background.png differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png b/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..86fe620 Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_round.png b/app/src/main/res/mipmap-mdpi/ic_launcher_round.png new file mode 100644 index 0000000..66d41fc Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_round_background.png b/app/src/main/res/mipmap-mdpi/ic_launcher_round_background.png new file mode 100644 index 0000000..11c72b2 Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher_round_background.png differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_round_foreground.png b/app/src/main/res/mipmap-mdpi/ic_launcher_round_foreground.png new file mode 100644 index 0000000..86fe620 Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher_round_foreground.png differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..cf39b03 Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_background.png b/app/src/main/res/mipmap-xhdpi/ic_launcher_background.png new file mode 100644 index 0000000..0f79019 Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher_background.png differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png b/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..a010740 Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png new file mode 100644 index 0000000..66ab493 Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_round_background.png b/app/src/main/res/mipmap-xhdpi/ic_launcher_round_background.png new file mode 100644 index 0000000..0f79019 Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher_round_background.png differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_round_foreground.png b/app/src/main/res/mipmap-xhdpi/ic_launcher_round_foreground.png new file mode 100644 index 0000000..a010740 Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher_round_foreground.png differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..095e57b Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_background.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher_background.png new file mode 100644 index 0000000..e598be5 Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_background.png differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..529f111 Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png new file mode 100644 index 0000000..a1ae172 Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_round_background.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round_background.png new file mode 100644 index 0000000..e598be5 Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round_background.png differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_round_foreground.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round_foreground.png new file mode 100644 index 0000000..529f111 Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round_foreground.png differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..d72eb74 Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_background.png b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_background.png new file mode 100644 index 0000000..9ad66cf Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_background.png differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..6bedd35 Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png new file mode 100644 index 0000000..7c04df5 Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round_background.png b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round_background.png new file mode 100644 index 0000000..9ad66cf Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round_background.png differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round_foreground.png b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round_foreground.png new file mode 100644 index 0000000..6bedd35 Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round_foreground.png differ diff --git a/app/src/main/res/resources.properties b/app/src/main/res/resources.properties new file mode 100644 index 0000000..63b46f9 --- /dev/null +++ b/app/src/main/res/resources.properties @@ -0,0 +1 @@ +unqualifiedResLocale=en \ No newline at end of file diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml new file mode 100644 index 0000000..ce9405d --- /dev/null +++ b/app/src/main/res/values-ar/strings.xml @@ -0,0 +1,168 @@ + + + My Brain + + لإرسال الاشعارات المتعلقة بالمهام + التذكيرات + إكمال + الرئيسية + الإعدادات + المساحات + وضع التطبيق + وضع النهار + الوضع الداكن + تلقائي + شاشة البداية + حول + إصدار التطبيق + التطبيق على Github + سياسة الخصوصية + التطبيق + الملاحظات + المهام + اليوميات + العلامات المرجعية + التقويم + إضافة مهمة + إضافة مهمة + البحث + العنوان + حذف المهمة الفرعية + إضافة مهام فرعية + الوصف + طلب ميزة / ابلاغ عن مشكلة + منخفض + متوسط + عالِ + الوقت + العنوال لا يمكن أن يكون فارغ + الأولوية + الترتيب حسب + أبجدي + تاريخ الإنشاء + تاريخ التعديل + تصاعدي + تنازلي + إظهار المهام المكملة + ابحث المهام + حفظ + حذف المهمة + حذف المهمة؟ + حذف الملاحظة؟ + حذف العلامة المرجعية؟ + حذف من اليوميات؟ + هل أنت متأكد من حذف هذه المهمة؟ + هل أنت متأكد من حذف هذه الملاحظة؟ + هل أنت متأكد من حذف هذه العلامة المرجعية؟ + هل أنت متأكد من حذف هذه من اليوميات؟ + إلغاء + ليس لديك أي مهام\n أظغط على زر + لإضافة مهام جديدة \n أو \n بواسطة الإختصار من قائمة الاعدادات السريعة بجهازك + ليس لديك أي ملاحظات.\n اضغط على + لإضافة ملاحظة جديدة + ليس لديك أي يوميات.\n اضغط على + لإضافة يومية جديدة + ليس لديك أي محفوظات. \n أضغط + لإضافة علامة مرجعة جديدة\n أو \n عن طريق مشاركة الرابط للتطبيق من أي متصفح + خارطة التطبيق + قائمة + شبكة + (يدعم صيفة Markdown) محتوى الملاحظة + إحذف الملاحظة + لا يمكن للملاحظة أن تكون فارغة + تثبيت الملاحظة + وضع القرائة + العرض ك + ابحث عن العنوان أو المحتوى + إضافة ملاحظة + رابط الإشارة المرجعية + إضافة الى المهام + تم الحفظ بنجاح + رابط غير صالح + إضافة إشارة مرجعية + افتح الرابط + ابحث الإشارات المرجعية + اذحف الإشارة المرجعية + الرابط + إلفاء التغييرات + إضافة يوبية + رائع + جيد + عادي + سيء + سيء جدا + خذف اليومية + المحتوى + حفظ اليومية + ابحث اليوميات + المزاج + %1$s - %2$s في %3$s + %1$s - %2$s + كل اليوم + إذن قرائة التقويم مطلوب لهذه الميزة. \n الرجاء منح الإذن للإستخدام + إذن الكتابة الى التقويم مطلوب لهذه الميزة. \n الرجاء منح الإذن للإستخدام + قبول الأذونات + الإنتقال الى الاعدادات + إضافة حدث + التقويمات المتضمنة : + تمت الإضافة اللى المهام + ملخص اليوميات + مزاجك على مدار الشهر + مزاجك على مدار السنة + %1$d%% + تغير المزاج + ملخص المزاج + "مزاجك كان " + " أغلب الوقت " + أخر 30 يوم + أخر عام + لا يوجد بيانات بعد + لا يوجد مواعيد بعد + ملخص المهام + لقد أكملت + من المهام في آخر اسبوع + لا يوجد مهام بعد + جاري التحميل… + أضغط زر التحديث إذا كنت قد منحت الاذن بالفعل + الخميس 30 + الأحد 5 + العشاء مع علي + محاضرة علوم الحاسب + زيارة طبيب الاسنان + شراء الاحتياجات من البقالة + الاتصال بأمي + نوع خط التطبيق + خط النظام الافتراضي + حذف الحدث + المكان + بدون تكرار + كل يوم + كل اسبوع + كل شهر + كل سنة + الحدث لا يمكن أن يكون في الماضي + حذف الحدث؟ + هل أنت متأكد من حذف هذا الحدث؟ + الملفات + انشاء ملف + الملف موجود بالفعل + الاسم + تغيير الملف + بدون ملف + حذف الملف + هل انت متأكد من حذف الملف و كل محنوياته؟ + حفظ + تعديل الملف + منع لقطات الشاشة + تصدير/استيراد البيانات + تصدير + تم تصدير البيانات + حدث خطأ أثناء التصدير + استيراد البيانات + تم تصدير %1$s + حدث خطأ أثناء الاستيراد. تأكد من عدم تخريب محتوى الملف + منح اذن التخزين للتصدير + يتم الاستيراد.... + متكرر + يتكرر كل + مشفر + كلمة السر + كل ساعة + كل دقيقة + \ No newline at end of file diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml new file mode 100644 index 0000000..e407de3 --- /dev/null +++ b/app/src/main/res/values-de/strings.xml @@ -0,0 +1,167 @@ + + My Brain + + Benachrichtigungskanal zum Senden von Aufgabenerinnerungen + Erinnerungen + Fertig + Dashboard + Einstellungen + Übersicht + App Design + Helles Design + Dunkles Design + Auto + Startbildschirm + Über + App Version + Projekt auf GitHub + Datenschutzrichtlinien + Produkt + Notizen + Aufgaben + Tagebuch + Lese-\n zeichen + Kalender + Aufgabe hinzufügen + Aufgabe zu My Brain hinzufügen + Suche + Titel + Unteraufgabe löschen + Unteraufgabe hinzufügen + Beschreibung + Fordere ein Feature an / Melde einen Fehler + Niedrig + Mittel + Hoch + Fälligkeitsdatum + Titel darf nicht leer sein + Priorität + Sortieren nach + Alphabetisch + Erstellungsdatum + Änderungsdatum + Aufsteigend + Absteigend + Erledigte Aufgaben anzeigen + Aufgabe suchen + Aufgabe speichern + Aufgabe löschen + Aufgabe löschen? + Notiz löschen? + Lesezeichen löschen? + Eintrag löschen? + Diese Aufgabe wirklich löschen? \n \"%1$s\"" + Diese Notiz wirklich löschen? \n \"%1$s\"" + Dieses Lesezeichen wirklich löschen?"" + Diesen Eintrag wirklich löschen?"" + Abbrechen + Du hast noch keine Aufgaben\n Klicke auf das + Symbol eine neue\n Aufgabe zu erstellen.\n Oder nutze den Shortcut in den\n Schnelleinstellungen + Du hast noch keine Notizen\n Klicke auf das + Symbol eine neue Notiz zu erstellen + Du hast noch keine Einträge\n Klicke auf das + Symbol um einen neuen Eintrag zu erstellen + Du hast noch keine Lesezeichen\n Klicke auf das + Symbol um ein neues\n Lesezeichen hinzuzufügen\n oder \nnutze die Teilen Funktion deines Browsers + Projektplan + Liste + Gitter + Notizinhalt (unterstützt Markdown) + Notiz löschen + Notiz darf nicht leer sein + Notiz anpinnen + Lesemodus + Zeige als + Suche nach Titel oder Inhalt + Notiz hinzufügen + Lesezeichen Link + Zu Aufgaben hinzufügen + Lesezeichen erfolgreich gespeichert + Ungültige URL + Füge Lesezeichen hinzu + Link öffnen + Lesezeichen suchen + Lesezeichen löschen + URL + Änderungen verwerfen + Eintrag hinzufügen + Unglaublich + Gut + Okay + Schlecht + Schrecklich + Eintrag löschen + Inhalt + Eintrag speichern + Tagebuch suchen + Stimmung + %1$s - %2$s um %3$s + %1$s - %2$s + Ganztags + Dieses Feature benötigt Leserechte\n für deinen Kalender.\n Bitte erteile deine Erlaubnis + Dieses Feature benötigt Schreibrechte\n für deinen Kalender.\n Bitte erteile deine Erlaubnis + Erlaubnis erteilen + Gehe zu den Einstellungen + Ereignis hinzufügen + Anzuzeigende Kalender: + Zu Aufgaben hinzugefügt + Tagebuch Diagramm + Deine Stimmung in diesem Monat + Deine Stimmung in diesem Jahr + %1$d%% + Stimmungs Tendenz + Stimmung + "Deine Stimmung war " + " die meiste Zeit " + In den letzten 30 Tagen + Im letzten Jahr + Keine Daten + Keine Ereignisse + Aufgaben Anzahl + Du bist fertig + mit den Aufgaben der letzten Woche + Keine Aufgaben + Lade… + Drücke den Aktualisieren Button wenn du bereits die Erlaubnis erteilt hast + Donnerstag 30 + Sonntag 5 + Abendessen mit Ali + CS Vortrag + Zahnarztbesuch + Lebensmittel kaufen + Mama anrufen + App Schriftart + Systemstandard + Ereignis löschen + Standort + Nicht wiederholen + Jeden Tag + Jede Woche + Jeden Monat + Jedes Jahr + Ereignis darf nicht in der Vergangenheit liegen + Ereignis löschen? + Dieses Ereignis wirklich löschen? + Ordner + Ordner erstellen + Ordner existiert bereits + Name + Ordner wechseln + Keine + Ordner löschen + Bist du dir sicher, dass du diesen Ordner und dessen Inhalt löschen möchtest? + Speichern + Ordner bearbeiten + Bildschirmfotos blockieren + Export/Import + Daten exportieren + Daten Erfolgreich nach\n \"/Documents/MyBrain Export\" exportiert + Export fehlgeschlagen + Daten importieren + Import Erfolgreich %1$s + Import fehlgeschlagen. Stelle sicher, dass der Dateiname und Inhalt richtig ist + Berechtigung zum Export notwendig + Importiere… + Wiederholend + Repeats every + Encrypted + Password + Every hour + Every minute + diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml new file mode 100644 index 0000000..0ea6fe0 --- /dev/null +++ b/app/src/main/res/values-hi/strings.xml @@ -0,0 +1,167 @@ + + + My Brain + रिमाइंडर्स + पूर्ण हुआ + डैशबोर्ड + सेटिंग्स + स्पेसेस + ऐप थीम + लाइट थीम + डार्क थीम + ऑटोमैटिक + कार्य संबंधी सूचनाएं भेजने के लिए + स्टार्टअप स्क्रीन + "बारे मैं " + एप्लीकेशन वर्शन + गिटहब पर प्रोजेक्ट + प्राइवेसी पालिसी + प्रोडक्ट + टिप्पणियाँ + कार्य + डायरी + बुकमार्क + कैलेंडर + कार्य जोड़ें + माय ब्रेन मैं टास्क जोड़े + खोजे + शीर्षक + उप कार्य हटाएं + उप कार्य जोड़ें + विवरण + कम + मध्यम + ज्यादा + नियत तारीख + प्राथमिकता + वर्णानुक्रमक + निर्माण की तिथि + परिवर्तन की तिथि + आरोही + अवरोही + कार्य सहेजें + कार्य हटाएं + कार्य हटाएं? + नोट हटाएं? + बुकमार्क हटाएं? + एंट्री हटाएं? + पूर्ण किए गए कार्य दिखाएं + कार्य खोजें + क्या आप वाकई टास्क को हटाना चाहते हैं + क्या आप वाकई नोट को हटाना चाहते हैं + क्या आप वाकई इस बुकमार्क को हटाना चाहते हैं + क्या आप वाकई इस एंट्री को हटाना चाहते हैं + रद्द करे + प्रोजेक्ट रोडमैप + सूची + ग्रिड + नोट कंटेंट (मार्कडाउन सहयोग) + नोट हटाएं + नोट खाली नहीं हो सकता + पिन नोट + रीडिंग मोड + में देखें + शीर्षक या कंटेंट के आधार पर खोजें + नोट जोड़े + बुकमार्क लिंक + कार्यों में जोड़ें + बुकमार्क सफलतापूर्वक सहेजा गया + अवैध यूआरएल + बुकमार्क जोड़ें + लिंक खोले + बुकमार्क खोजें + बुकमार्क हटाएं + यूआरएल + परिवर्तन रद्द करें + एंट्री जोड़ें + लाजवाब + बढ़िया + अच्छा + बुरा + बहुत बुरा + एंट्री हटाएं + कंटेंट + एंट्री सहेजें + डायरी खोजे + मनोदशा + पूरे दिन + कॉल माँ + किराने का सामान खरीदो + दंत चिकित्सा पर जाएँ + सीएस लेक्चर + रविवार 5 + गुरुवार 30 + यदि आपने पहले ही अनुमति दे दी है तो बटन पर क्लिक करके रिफ्रेश करे + लोड हो रहा है… + पिछले सप्ताह में कार्यों की + आपने पूरा किया + कार्य सारांश + अभी तक कोई ईवेंट नहीं + अभी तक कोई डेटा नहीं + पिछले साल + पिछले 30 दिनों में + सर्वाधिक समय + आपका मूड + मूड सारांश + मूड फ्लो + वर्ष के दौरान आपका मूड + महीने के दौरान आपका मूड + डायरी चार्ट + कार्यों में जोड़ा गया + इवेंट जोड़ें + सेटिंग्स में जाए + अनुमति अनुदान करे + %1$d%% + %1$s - %2$s + %1$s - %2$s पर %3$s + अभी तक कोई कार्य नहीं + अली के साथ डिनर + कैलेंडर शामिल करें : + इस सुविधा के उपलब्ध होने के लिए आवश्यक कैलेंडर अनुमति दें। कृपया अनुमति प्रदान करें + शीर्षक खाली नहीं रख सकते + सुविधा के लिए अनुरोध करें / बग रिपोर्ट करें + क्रमानुसार + आपके पास कोई कार्य नहीं है। एक नया कार्य जोड़ें या क्विक सेटिंग मेनू में शॉर्टकट का उपयोग करके + बटन पर क्लिक करें + आपके पास कोई नोट नहीं है। नया नोट जोड़ने के लिए + बटन पर क्लिक करें + आपके पास कोई एंट्री नहीं है। + बटन पर क्लिक करें एक नई एंट्री जोड़ें + आपके पास कोई बुकमार्क नहीं है। + बटन पर क्लिक करके एक नया बुकमार्क जोड़ें या किसी भी ब्राउज़र से शेयर विकल्प का उपयोग करे + ऐप फ़ॉन्ट + सिस्टम डिफ़ॉल्ट + इवेंट डिलीट करे + स्थान + दोहराहे नहीं + प्रतिदिन + प्रति सप्ताह + हर महीने + सालाना + घटना भूतकाल की नहीं होनी चाहिए + इवेंट मिटाएं? + निश्चित तौर पर क्या इस घटना को हटाना चाहते हैं? + इस सुविधा के उपलब्ध होने के लिए आवश्यक कैलेंडर अनुमति दें। कृपया अनुमति प्रदान करे। + फ़ोल्डर + फोल्डर बनाएं + फोल्डर पहले से मौजूद है + नाम + फोल्डर बदले + कोई नहीं + फोल्डर हटा दें + क्या आप वाकई इस फ़ोल्डर और इसकी सभी सामग्री को हटाना चाहते हैं? + बचाना + फोल्डर संपादित करें + Block screenshots + Export/Import + Export + Successfully exported data to \"Documents/MyBrain Export\" + Something went wrong while exporting + Import data + Successfully imported %1$s + Something went wrong while importing. make sure that the file name and content are not corrupted + Grant permission to export + Importing.... + Recurring + Repeats every + Encrypted + Password + Every hour + Every minute + \ No newline at end of file diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml new file mode 100644 index 0000000..968fd80 --- /dev/null +++ b/app/src/main/res/values-pl/strings.xml @@ -0,0 +1,168 @@ + + + My Brain + + Kanał powiadomień służący do wysyłania przypomnień wykonania zadań. + Przypomnienia + Ukończono + Panel + Ustawienia + Ekran główny + Motyw aplikacji + Jasny + Ciemny + Automatyczny + Karta startowa + O aplikacji + Wersja aplikacji + Strona projektu na GitHubie + Polityka Prywatności + Produkt + Notatki + Zadania + Dziennik + Zakładki + Kalendarz + Dodaj zadanie + Dodaj zadanie do My Brain + Szukaj + Tytuł + Usuń podzadanie + Dodaj podzadanie + Opis + Poproś o nowe funkcje / Zgłoś błąd + Niski + Średni + Wysoki + Data ukończenia + Tytuł nie może być pusty + Priorytet + Sortuj według + Nazwa + Data utworzenia + Data modyfikacji + Rosnąco + Malejąco + Pokaż wykonane zadania + Szukaj w zadaniach + Zapisz zadanie + Usuń zadanie + Usunąć zadanie? + Usunąć notatkę? + Usunąć zakłądkę? + Usunąć wpis? + Czy na pewno chcesz usunąć zadanie: \n \"%1$s\"" + Czy na pewno chcesz usunąć notatkę: \n \"%1$s\"" + Czy na pewno chcesz usunąć tą zakładkę"" + Czy na pewno chcesz usunąć ten wpis"" + Anuluj + Nie dodano żadnych zadań\n Aby dodać nowe Zadanie kliknij przycisk +\n lub \nużyj skrótu na pasku szybkich ustawień + Nie dodano żadnych notatek\n Aby dodać nową Notatkę kliknij przycisk + + Nie dodano żadnych wpisów\n Aby dodać nowy wpis kliknij przycisk + + Nie dodano żadnych zakładek\n Aby dodać nową zakładkę kliknij przycisk +\n lub \nużyj opcji udostępniania w dowolnej przeglądarce + Plan projektu + Lista + Siatka + Treść notatki (obsługuje język Markdown) + Usuń notatkę + Notatka nie może być pusta + Przypnij notatkę + Tryb czytania + Widok + Wyszukaj po tytule lub zawartości + Dodaj notatkę + Zapisz zakładkę + Dodaj zadanie + Pomyślnie zapisano zakładkę + Nieprawidłowy adres URL + Dodaj zakładkę + Otwórz link + Szukaj w zakładkach + Usuń zakładkę + URL + Anuluj zmiany + Dodaj wpis + Świetny + Dobry + Neutralny + Zły + Fatalny + Usuń wpis + Treść + Zapisz wpis + Szukaj w dzienniku + Nastrój + %1$s - %2$s w %3$s + %1$s - %2$s + Całodniowe + Aby ta funkcja działała poprawnie konieczne jest udzielenie zezwolenia na odczytywanie danych kalendarza.\nProsimy o udzielenie zezwolenia + Aby ta funkcja działała poprawnie wymagane jest udzielenie zezwolenia na zapisywanie danych w kalendarzu.\nProsimy o udzielenie zezwolenia + Udziel zezwolenia + Przejdź do ustawień + Dodaj wydarzenie + Wyświetlane kalendarze : + Dodano do zadań + Wykres dziennika + Twój nastrój na przestrzeni miesiąca + Twój nastrój na przestrzeni roku + %1$d%% + Wykres nastroju + Podsumowanie nastroju + "Miałeś " + " nastrój przez większość czasu " + Ostatnie 30 dni + Ostatni rok + Brak danych + Brak wydarzeń + Podsumowanie zadań + W ostatnim tygodniu wykonano + zadań + Brak zadań + Ładowanie… + Jeżeli udzieliłeś już zezwolenia kliknij przycisk Odśwież. + Czwartek 30 + Niedziela 5 + Kolacja z Alim + Wykład z informatyki + Pójdź do dentysty + Zrób zakupy + Zadzwoń do mamy + Czcionka + Systemowa + Usuń wydarzenie + Lokalizacja + Nie powtarzaj + Codziennie + Co tydzień + Co miesiąc + Co rok + Data wydarzenia nie powinna być w przeszłości + Usunąć wydarzenie? + Czy na pewno chcesz usunąć to wydarzenie? + Foldery + Utwórz folder + Folder już istnieje + Nazwa + Zmień folder + Brak + Usuń folder + Czy na pewno chcesz usunąć ten folder? + Zapisz + Edytuj folder + Blokuj wykonywanie zrzutów ekranu + Eksport/Import + Eksport danych + Pomyślnie wyeksportowano dane do \"Documents/MyBrain Export\" + Podczas eksportowania danych wystąpił błąd + Import danych + Pomyślnie zaimportowano %1$s + Podczas importowania danych wystąpił błąd. Upewnij się, że plik nie jest uszkodzony, a jego nazwa jest prawidłowa + Udziel zezwolenia, aby wyeksportować dane + Importowanie.... + Recurring + Repeats every + Encrypted + Password + Every hour + Every minute + \ No newline at end of file diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml new file mode 100644 index 0000000..e4c3190 --- /dev/null +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -0,0 +1,167 @@ + + My Brain + + Canal de notificação para enviar lembretes de tarefas + Lembretes + Concluído + Dashboard + Configurações + Spaces + Temas + Tema Claro + Tema Escuro + Automático + Tela de início + Sobre + Versão + Projeto no GitHub + Política de Privacidade + Produto + Notas + Tarefas + Diário + Favoritos + Agenda + Adicionar tarefa + Adicionar tarefa ao My Brain + Procurar + Título + Remover subtarefa + Adicionar subtarefa + Descrição + Solicite um recurso / Reporte um erro + Baixa + Média + Alta + Válido até + O título não pode estar vázio + Prioridade + Ordenar por + Alfabética + Data de criação + Data de modificação + Crescente + Decrescente + Mostrar tarefas concluídas + Procurar tarefas + Salvar Tarefa + Remover Tarefa + Remover Tarefa? + Remover Nota? + Remover Favorito? + Remover Entrada? + Você deseja realmente remover a Tarefa: \n \"%1$s\"" + Você deseja realmente remover a Nota: \n \"%1$s\"" + Você deseja realmente remover este bookmark"" + Você deseja realmente remover esta entrada"" + Cancelar + Você não tem nenhuma tarefa\n Clique no botão + para adicionar uma nova Tarefa\n ou \nuse o atalho no menu das configurações rápidas + Você não tem nenhuma nota\n Clique no botão + para adicionar uma nova Nota + Você não tem nenhuma entrada\n Clique no botão + para adicionar uma nova entrada + Você não tem nenhum favorito\n Clique no botão + para adicionar um novo favorito\n ou \nuse a opção de compartilhar de qualquer navegador + Metas do Projeto + Lista + Grade + Conteúdo da nota (suporta markdown) + Remover Nota + A Nota não pode estar vázia + Fixar nota + Modo de leitura + Ver como + Procurar por título ou conteúdo + Adicionar nota + Salvar link como favorito + Adicionar a tarefas + Favorito salvo com sucesso + URL Inválida + Adicionar favorito + Abrir link + Pesquisar Favoritos + Remover Favoritos + URL + Cancelar mudanças + Adicionar entrada + Ótimo + Bom + Regular + Mau + Péssimo + Remover entrada + Conteúdo + Salvar entrada + Pesquisar diário + Humor + %1$s - %2$s às %3$s + %1$s - %2$s + O dia todo + Permissão de Leitura na Agenda necessária para que este recurso esteja disponível.\nPor favor, conceda a permissão + Permissão de Escrita na Agenda necessária para que este recurso esteja disponível.\nPor favor, conceda a permissão + Conceda a permissão + Ir para configurações + Adicionar evento + Incluir agendas : + Adicionado a tarefas + Gráfico do Diário + Seu humor durante o mês + Seu humor durante o ano + %1$d%% + Humor + Humor + "Seu humor estava " + " na maior parte do tempo " + Últimos 30 dias + Último ano + Sem dados ainda + Sem eventos ainda + Tarefas + Você concluiu + das Tarefas na última semana + Sem tarefas ainda + Carregando… + Se você já concedeu a permissão, clique no botão atualizar + Quinta 30 + Domingo 5 + Jantar com o Ali + Aula de Computação + Consulta dentista + Fazer compras + Ligar para mamãe + Fonte + Padrão do Sistema + Remover evento + Localização + Não repetir + Todo dia + Toda semana + Todo mês + Todo ano + O Evento não deve ser no passado + Remover Evento? + Você tem certeza que deseja remover o evento? + Pastas + Criar pasta + A pasta já existe + Nome + Mudar pasta + Nenhum + Remover pasta + Você tem certeza que deseja remover esta pasta e todo o seu conteúdo? + Salvar + Editar pasta + Bloquear captura de tela + Exportar/Importar + Exportar + Arquivos exportados com sucesso para \"Documents/MyBrain Export\" + Algo deu errado ao exportar + Importar arquivo + Importado com sucesso %1$s + Algo deu errado ao importar. Assegure-se que o nome do arquivo e o conteúdo não estão corrompidos + Conceda permissão para exportar + Importando.... + Recurring + Repeats every + Encrypted + Password + Every hour + Every minute + diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml new file mode 100644 index 0000000..c3d2528 --- /dev/null +++ b/app/src/main/res/values-ro/strings.xml @@ -0,0 +1,167 @@ + + My Brain + + Canal de notificare pentru trimiterea de notificări de reamintire a sarcinilor + Mementouri + Complet + Panou + Setări + Spații + Tema aplicației + Temă luminoasă + Temă întunecată + Automat + Ecran de pornire + Despre + Versiunea aplicației + Proiectul pe GitHub + Politica de confidențialitate + Produs + Note + Sarcini + Jurnal + Marcaje + Calendar + Adaugă sarcină + Adaugă sarcina la My Brain + Caută + Titlu + Șterge sub-sarcină + Adaugă sub-sarcină + Descriere + Solicită o funcție / Raportează un bug + Scăzută + Medie + Înaltă + Data limită + Titlul nu poate fi gol + Prioritate + Ordonează după + Alfabetic + Data creării + Data modificării + Crescător + Descrescător + Arată sarcinile completate + Caută sarcini + Salvează sarcina + Șterge sarcina + Ștergeți sarcina? + Ștergeți nota? + Ștergeți marcajul? + Ștergeți intrarea? + Sigur dorești ștergerea sarcinii: \n \"%1$s\""? + Sigur dorești ștergerea notei: \n \"%1$s\""? + Sigur dorești ștergerea marcajului""? + Sigur dorești ștergerea acestei intrări""? + Anulare + Nu aveți nicio sarcină\n Faceți clic pe butonul + pentru a adăuga o nouă sarcină\n sau \nprin utilizarea comenzii rapide din meniul de setări rapide + Nu aveți nicio notă\n Faceți clic pe butonul + pentru a adăuga o nouă notă + Nu aveți nicio intrare\n Faceți clic pe butonul + pentru a adăuga o nouă intrare + Nu aveți niciun marcaj\n Faceți clic pe butonul + pentru a adăuga un nou marcaj\n sau \nprin utilizarea opțiunii de distribuire din orice browser + Harta proiectului + Listă + Grilă + Conținutul notei (suportă markdown) + Șterge nota + Nota nu poate fi goală + Fixează nota + Modul de citire + Vezi ca + Căutare după titlu sau conținut + Adaugă notă + Marchează link-ul + Adaugă la sarcini + Marcaj salvat cu succes + Adresă URL invalidă + Adaugă marcaj + Deschide link + Caută marcaje + Șterge marcajul + Adresă URL + Anulează modificările + Adaugă intrare + Minunat + Bun + Okay + Rău + Teribil + Șterge intrarea + Conținut + Salvează intrarea + Caută în Jurnal + Dispoziție + %1$s - %2$s at %3$s + %1$s - %2$s + Toată ziua + Este necesară permisiunea de citire a calendarului pentru ca această funcție să fie disponibilă.\nTe rog să acorzi permisiunea + Este necesară permisiunea de scriere a calendarului pentru ca această funcție să fie disponibilă.\nTe rog să acorzi permisiunea + Acordă permisiunea + Accesează setările + Adaugă eveniment + Include calendarele: + Adăugat la sarcini + Graficul jurnalului + Dispoziția ta pe parcursul lunii + Dispoziția ta pe parcursul anului + %1$d%% + Fluxul dispoziției + Rezumatul dispoziției + "Dispoziția ta a fost " + " majoritatea timpului " + Ultimele 30 de zile + Anul trecut + Nu există încă date + Niciun eveniment încă + Rezumatul sarcinilor + Ai finalizat + de sarcini în ultima săptămână + Nicio sarcină încă + Încărcare… + Faceți clic pe butonul de reîmprospătare dacă ați acordat deja permisiunea + Joi 30 + Duminică 5 + Cina cu Ali + Curs CS + Vizitează dentistul + Cumpără alimente + Sun-o pe mama + Fontul aplicației + Implicit al sistemului + Șterge evenimentul + Locație + Nu se repetă + În fiecare zi + În fiecare săptămână + În fiecare lună + În fiecare an + Evenimentul nu ar trebui să fie în trecut + Ștergeți evenimentul? + Sigur dorești ștergerea acestui eveniment? + Dosare + Creează un dosar + Dosarul există deja + Nume + Schimbă dosarul + None + Șterge dosarul + Sunteți sigur că doriți să ștergeți acest dosar și tot conținutul său? + Save + Editează dosarul + Blochează capturile de ecran + Exportă/Importă + Exportă + Date exportate cu succes în \"Documents/MyBrain Export\" + Ceva nu a mers în timpul importării + Importă date + %1$s importat cu succes + Ceva nu a mers în timpul importării. Asigurați-vă că numele fișerului și conținutul nu sunt corupte + Acordă permisiunea pentru a exporta + Se importă.... + Recurring + Repeats every + Encrypted + Password + Every hour + Every minute + \ No newline at end of file diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml new file mode 100644 index 0000000..8d5d6a7 --- /dev/null +++ b/app/src/main/res/values-ru/strings.xml @@ -0,0 +1,167 @@ + + My Brain + + Способ уведомления для напоминаний о задачах + Напоминания + Завершено + Обзор + Настройки + Разделы + Тема приложения + Светлая + Тёмная + Автоматически + Начальный экран + О приложении + Версия приложения + Проект на GitHub + Политика конфиденциальности + Проект + Заметки + Задачи + Дневник + Закладки + Календарь + Добавить задачу + Добавить задачу в My Brain + Поиск + Название + Удалить подзадачу + Добавить подзадачу + Описание + Предложить изменения / Сообщить об ошибке + Низкий + Средний + Высокий + Дата окончания + Название не может быть пустым + Приоритет + Упорядочить + По алфавиту + По дате создания + По последнему изменению + По возрастанию + По убыванию + Показать выполненные задачи + Искать задачи + Сохранить задачу + Удалить задачу + Удалить задачу? + Удалить заметку? + Удалить закладку? + Удалить запись? + Вы уверены, что хотите удалить задачу \"%1$s\""? + Вы уверены, что хотите удалить заметку \"%1$s\""? + Вы уверены, что хотите удалить эту закладку?"" + Вы уверены, что хотите удалить эту запись?"" + Отмена + У вас нет задач\nНажмите на +, чтобы добавить новую задачу\nили используйте кнопку\nв меню быстрого доступа + У вас нет заметок\nНажмите на +, чтобы добавить новую заметку + У вас нет записей\nНажмите на +, чтобы добавить новую запись + У вас нет закладок\nНажмите на +, чтобы добавить закладку\nили поделитесь закладкой с помощью браузера + План развития проекта + Список + Сетка + Содержание заметки (поддерживает markdown) + Удалить заметку + Заметка не может быть пустой + Закрепить заметку + Режим чтения + Вид + Искать по названию или содержанию + Добавить заметку + Добавить ссылку в закладки + Добавить в задачи + Закладка успешно сохранена + Недействительный URL + Добавить закладку + Перейти по ссылке + Искать закладки + Удалить закладку + Ссылка + Отменить изменения + Добавить запись + Отличное + Хорошое + Нормальное + Плохое + Ужасное + Удалить запись + Содержание + Сохранить запись + Поиск по календарю + Настроение + %1$s - %2$s в %3$s + %1$s - %2$s + Весь день + Необходимо разрешение для чтения калердаря.\nПожалуйста, разрешите приложению использовать календарь + Необходимо разрешение для работы с календарём.\nПожалуйста, разрешите приложению использовать календарь + Предоставить разрешение + Перейти в настройки + Добавить событие + Включает календари + Добавлено в задачи + График + Ваше настроение в течение месяца + Ваше настроение в течение года + %1$d%% + Изменение настроения + Обзор настроения + "Ваше настроение " + " большую часть времени" + Последние 30 дней + Последний год + Нет данных + Нет событий + Обзор задач + Вы выполнили + задач за последнюю неделю + Нет задач + Загрузка… + Нажмите на кнопку Обновить, если разрешение уже предоставлено + Четверг 30 + Воскресенье 5 + Ужин с Али + Лекция по информатике + Сходить к зубному + Купить продукты + Позвонить маме + Шрифт в приложении + Как в системе + Удалить событие + Местоположение + Не поворять + Каждый день + Каждую неделю + Каждый месяц + Каждый год + Событие не может быть создано + Удалить событие? + Вы уверены, что хотите удалить это событие? + Папки + Создать папку + Папка уже существует + Название + Сменить папку + Ничего + Удалить папку + Вы уверены, что хотите удалить папку и всё её содержимое? + Сохранить + Редактировать папку + Запретить скриншоты + Экспорт/Импорт + Экспортировать данные + Данные успешно экспортированы в\n\"Documents/MyBrain Export\" + Что-то пошло не так при экспорте + Импортировать данные + Успешно импортировал %1$s + Что-то пошло не так при импорте.\nУбедитесь, что имя файла правильное, и содержимое не повреждено + Предоставьте разрешение, чтобы экспортировать + Импортирование.... + Recurring + Repeats every + Encrypted + Password + Every hour + Every minute + \ No newline at end of file diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml new file mode 100644 index 0000000..6c6be24 --- /dev/null +++ b/app/src/main/res/values-tr/strings.xml @@ -0,0 +1,167 @@ + + My Brain + + Görev hatırlatma bildirimleri için bildirim kanalı + Hatırlatıcılar + Tamamla + Ana sayfa + Seçenekler + Benim Alanım + Uygulama teması + Açık tema + Koyu tema + Otomatik + Başlangıç ekranı + Hakkında + Uygulama sürümü + Projenin GitHub Sayfası + Gizlilik politikası + Proje + Notlar + Görevler + Günlük + Yer imleri + Takvim + Görev oluştur + Görev oluştur + Ara + Başlık + Alt görevi sil + Alt görev oluştur + Açıklama + Geri Bildirim / Hata Bildir + Düşük + Orta + Yüksek + Bitiş tarihi + Başlık boş olamaz + Öncelik + Sırala + Alfabetik + Oluşturulma tarihi + Güncellenme tarihi + Artan + Azalan + Tamamlanmış görevleri göster + Görev ara + Görevi kaydet + Görevi sil + Görev Sil + Not Sil + Yer İmi Sil + Günlük Girdisi Sil + Bu görevi silmek istediğinize emin misiniz: \n \"%1$s\""? + Bu notu silmek istediğinize emin misiniz: \n \"%1$s\""? + Bu yer imini silmek istediğinize emin misiniz""? + Bu günlük girdisini silmek istediğinize emin misiniz""? + İptal + Herhangi bir göreviniz yok\n Yeni görev oluşturmak için + butonuna tıklayın\n ya da \n hızlı ayarlar menüsünü kullanarak yeni görev oluşturun + Herhangi bir notunuz yok\n Yeni not oluşturmak için + butonuna tıklayın + Herhangi bir günlük girdiniz yok\n Yeni girdi oluşturmak için + butonuna tıklayın + Herhangi bir yer iminiz yok\n Yeni yer imi oluşturmak için + butonuna tıklayın\n ya da \nherhangi bir tarayıcıdan paylaş seçeneğini kullanın + Proje yol haritası + Liste + Tablo + Not içeriği (markdown destekler) + Not sil + Not boş olamaz + Notu sabitle + Okuma modu + Görüntüleme şekli + Başlık veya içeriğe göre ara + Not oluştur + Yer imi oluştur + Görevlere ekle + Yer imi kaydedildi + Geçersiz bağlantı + Yer imi oluştur + Bağlantıyı aç + Yer imi ara + Yer imi sil + Bağlantı + Değişiklikleri iptal et + Yeni girdi oluştur + Harika + İyi + Fena Değil + Kötü + Berbat + Girdiyi sil + İçerik + Girdiyi kaydet + Günlük girdisi ara + Ruh Hali + %1$s - %2$s at %3$s + %1$s - %2$s + Bütün gün + Bu özelliğin kullanılabilmesi için takvim izni gerekiyor.\nLütfen izni onaylayın + Bu özelliğin kullanılabilmesi için takvim izni gerekiyor.\Lütfen izni onaylayın + İzin ver + Ayarlara git + Olay ekle + Şu takvimleri ekle: + Görevlere eklendi + Günlük grafiği + Son aydaki ruh haliniz + Son yıldaki ruh haliniz + %1$d%% + Ruh hali akışı + Ruh hali özeti + "Genel ruh haliniz: " + " " + Son 30 gün + Son yıl + Henüz bir veri yok + Henüz bir olay yok + Görev özeti + Son haftada görevlerinizin + \'ını tamamladınız + Henüz görev yok + Yükleniyor… + Eğer izin verdiyseniz yenile butonuna tıklayın + Perşembe 30 + Pazar 5 + Ali ile akşam yemeği + Bilisayar dersi + Dişçi ziyareti + Bakkala gidilecek + Annemi arayacağım + Yazı fontu + Sistem varsayılanı + Olayı sil + Konum + Sadece bir kez + Her gün + Her hafta + Her ay + Her yıl + Olay geçmiş tarihte olmamalı + Olay Sil + Bu olayı silmek istediğinize emin misiniz? + Klasörler + Klasör oluştur + Klasör zaten var + İsim + Klasör değiştir + Hiçbiri + Klasörü sil + Bu klasörü ve içindeki tüm notları silmek istediğinize emin misiniz? + Kaydet + Klasörü düzenle + Ekran görüntülerini engelle + Dışa aktar/İçe aktar + Dışa aktar + Dışa aktarma başarılı, dosya konumu: \n\"/Documents/MyBrain Export\" + Dışa aktarırken bir sorun oluştu + İçe aktar + İçe aktarma başarılı %1$s + İçe aktarırken bir sorun oluştu. Dosya isimleri veya içerikleri bozuk olabilir + Dışa aktarmak için izin ver + İçe aktarılıyor.... + Recurring + Repeats every + Encrypted + Password + Every hour + Every minute + \ No newline at end of file diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml new file mode 100644 index 0000000..348e1b2 --- /dev/null +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -0,0 +1,167 @@ + + + My Brain + 任务提醒 + 提醒 + 完成 + 概览 + 设置 + 空间 + 主题 + 浅色模式 + 深色模式 + 自动模式 + 开始页面 + 关于 + 软件版本 + GitHub项目 + 隐私政策 + 产品 + 笔记 + 待办事项 + 日记本 + 书签 + 日历 + 添加事项 + 添加事项到My Brain + 搜索 + 标题 + 删除子任务 + 添加子任务 + 描述 + 反馈/bug提交 + + + + 截止日期 + 标题不能为空 + 优先级 + 排序 + 名称 + 创建日期 + 修改日期d + 升序 + 降序 + 显示已完成事项 + 搜索事项 + 保存事项 + 删除事项 + 删除事项? + 删除笔记? + 删除书签? + 删除日记? + 你确定要删除这个事项吗? + 你确定要删除这篇笔记吗? + 你确定要删除这个书签吗? + 你确定要删除这篇日记吗? + 取消 + 目前没有待办事项\n 点击+按钮创建待办事项\n 或使用快速设置菜单中的快捷方式 + 目前没有笔记\n 点击+按钮创建笔记 + 目前没有日记\n 点击+按钮创建日记 + 目前没有书签\n 点击+按钮创建书签\n 或使用任意浏览器的分享功能 + 项目路线图 + 列表 + 网格 + 笔记内容 (支持Markdown) + 删除笔记 + 笔记不能为空 + 置顶笔记 + 阅读模式 + 视图 + 输入标题或内容以搜索 + 添加笔记 + 书签链接 + 添加到待办事项 + 书签已存储 + 无效的网址 + 添加书签 + 打开链接k + 搜索书签 + 删除书签 + 网址 + 取消修改 + 添加日记 + 棒极了 + 很好 + 还行 + 糟糕 + 糟透了 + 删除日记 + 内容 + 保存日记 + 搜索日记 + 心情 + %1$s - %2$s at %3$s + %1$s - %2$s + 全天 + 请允许日历访问权限以使用该功能 + 请允许日历编辑权限以使用该功能 + 获取权限 + 设置s + 添加事件 + 使用以下日历: + 添加到待办事项 + 统计图表 + 本月心情 + 年度心情 + %1$d%% + 情绪波动 + 情绪统计 + "在大部分时候你的情绪是" + "的" + 最近一个月 + 最近一年 + 暂无数据 + 暂无事项 + 事项摘要 + 上周你完成了 + 的待办事项 + 暂无待办事项 + 加载中… + 获取权限后请点击刷新 + 星期四 30号 + 星期天 5号 + 与Ali共进晚餐 + CS课程 + 牙医诊所预约 + 日常采购 + 打电话给妈妈 + 软件字体 + 默认设置 + 删除事件 + 位置 + 不重复 + 每天 + 每周 + 每月 + 每年 + 不能创建过去的事项 + 删除事项? + 你确定要删除这个事项吗? + 文件夹 + 创建文件夹 + 文件夹已存在 + 名称 + 变更文件夹 + + 删除文件夹 + 你确定要删除这个文件夹以及其中的内容吗? + 保存 + 编辑文件夹 + 阻止截屏 + 导出/导入数据 + 导出数据 + 数据已导出至\"Documents/MyBrain Export\" + 导出失败 + 导入数据 + 已成功导入 %1$s + 导入失败,请确认文件名及内容无误 + 获取导出权限 + 导入中.... + Recurring + Repeats every + Encrypted + Password + Every hour + Every minute + diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..f8c6127 --- /dev/null +++ b/app/src/main/res/values/colors.xml @@ -0,0 +1,10 @@ + + + #FFBB86FC + #FF6200EE + #FF3700B3 + #FF03DAC5 + #FF018786 + #FF000000 + #FFFFFFFF + \ No newline at end of file diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..be33dae --- /dev/null +++ b/app/src/main/res/values/strings.xml @@ -0,0 +1,167 @@ + + My Brain + + Notification channel for sending tasks reminders notification + Reminders + Complete + Dashboard + Settings + Spaces + App theme + Light theme + Dark theme + Auto + Startup screen + About + App version + Project on GitHub + Privacy policy + Product + Notes + Tasks + Diary + Bookmarks + Calendar + Add task + Add task to My Brain + Search + Title + Delete sub task + Add sub task + Description + Request a feature / Report a bug + Low + Medium + High + Due date + Title cannot be empty + Priority + Order By + Alphabetical + Date created + Date modified + Ascending + Descending + Show completed tasks + Search tasks + Save task + Delete task + Delete task? + Delete note? + Delete bookmark? + Delete entry? + Are you sure you want to delete the task: \n \"%1$s\""? + Are you sure you want to delete the note: \n \"%1$s\""? + Are you sure you want to delete this bookmark""? + Are you sure you want to delete this entry""? + Cancel + You don\'t have any tasks\n Click the + button to add a new Task\n or \nby using the shortcut in the quick settings menu + You don\'t have any notes\n Click the + button to add a new Note + You don\'t have any entries\n Click the + button to add a new entry + You don\'t have any bookmarks\n Click the + button to add a new bookmark\n or \nby using the share option from any browser + Project roadmap + List + Grid + Note content (supports markdown) + Delete note + Note cannot be empty + Pin note + Reading mode + View as + Search by title or content + Add note + Bookmark link + Add to tasks + Bookmark saved successfully + Invalid URL + Add bookmark + Open link + Search bookmarks + Delete bookmark + URL + Cancel changes + Add entry + Awesome + Good + Okay + Bad + Terrible + Delete entry + Content + Save entry + Search diary + Mood + %1$s - %2$s at %3$s + %1$s - %2$s + All day + Read Calendar permission required for this feature to be available.\nPlease grant the permission + Write Calendar permission required for this feature to be available.\nPlease grant the permission + Grant permission + Go to settings + Add event + Include calendars : + Added to tasks + Diary chart + Your mood during the month + Your mood during the year + %1$d%% + Mood flow + Mood summary + "Your mood was " + " most of the time " + Last 30 days + Last year + No data yet + No events yet + Tasks summary + You completed + of tasks in the last week + No tasks yet + Loading… + Click the refresh button if you already granted the permission + Thursday 30 + Sunday 5 + Dinner with Ali + CS lecture + Visit dentist + Buy groceries + Call mom + App font + System default + Delete event + Location + Do not repeat + Every day + Every week + Every month + Every year + Event should not be in the past + Delete event? + Are you sure you want do delete this event? + Folders + Create folder + Folder already exists + Name + Change folder + None + Delete folder + Are you sure you want to delete this folder and all of its content? + Save + Edit folder + Block screenshots + Export/Import + Export data + Successfully exported data" + Something went wrong while exporting + Import data + Successfully imported %1$s + Something went wrong while importing. Make sure the file content are not corrupted + Grant permission to export + Importing.... + Recurring + Repeats every + Encrypted + Password + Every hour + Every minute + \ No newline at end of file diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..0dd82e0 --- /dev/null +++ b/app/src/main/res/values/themes.xml @@ -0,0 +1,7 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/xml-v31/calendar_widget_info.xml b/app/src/main/res/xml-v31/calendar_widget_info.xml new file mode 100644 index 0000000..bf35b7f --- /dev/null +++ b/app/src/main/res/xml-v31/calendar_widget_info.xml @@ -0,0 +1,14 @@ + + \ No newline at end of file diff --git a/app/src/main/res/xml-v31/tasks_widget_info.xml b/app/src/main/res/xml-v31/tasks_widget_info.xml new file mode 100644 index 0000000..8f14ac8 --- /dev/null +++ b/app/src/main/res/xml-v31/tasks_widget_info.xml @@ -0,0 +1,13 @@ + + \ No newline at end of file diff --git a/app/src/main/res/xml/calendar_widget_info.xml b/app/src/main/res/xml/calendar_widget_info.xml new file mode 100644 index 0000000..379372f --- /dev/null +++ b/app/src/main/res/xml/calendar_widget_info.xml @@ -0,0 +1,12 @@ + + \ No newline at end of file diff --git a/app/src/main/res/xml/tasks_widget_info.xml b/app/src/main/res/xml/tasks_widget_info.xml new file mode 100644 index 0000000..2dbcdbd --- /dev/null +++ b/app/src/main/res/xml/tasks_widget_info.xml @@ -0,0 +1,11 @@ + + \ No newline at end of file diff --git a/app/src/test/java/com/mhss/app/mybrain/ExampleUnitTest.kt b/app/src/test/java/com/mhss/app/mybrain/ExampleUnitTest.kt new file mode 100644 index 0000000..cf15a47 --- /dev/null +++ b/app/src/test/java/com/mhss/app/mybrain/ExampleUnitTest.kt @@ -0,0 +1,17 @@ +package com.mhss.app.mybrain + +import org.junit.Test + +import org.junit.Assert.* + +/** + * Example local unit test, which will execute on the development machine (host). + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +class ExampleUnitTest { + @Test + fun addition_isCorrect() { + assertEquals(4, 2 + 2) + } +} \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..a1dda36 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,6 @@ +plugins { + id("com.android.application") version "8.1.1" apply false + id("org.jetbrains.kotlin.android") version "1.9.0" apply false + id ("com.google.dagger.hilt.android") version "2.48" apply false + id("com.google.devtools.ksp") version "1.9.0-1.0.13" apply false +} \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/changelogs/1.txt b/fastlane/metadata/android/en-US/changelogs/1.txt new file mode 100644 index 0000000..d44251f --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/1.txt @@ -0,0 +1 @@ +The First release of My Brain \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/changelogs/2.txt b/fastlane/metadata/android/en-US/changelogs/2.txt new file mode 100644 index 0000000..cac3fef --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/2.txt @@ -0,0 +1,4 @@ +- Added Font options in settings. +- Added Folders for Notes. +- Added Hindi language support. +- Bug fixes. \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/changelogs/3.txt b/fastlane/metadata/android/en-US/changelogs/3.txt new file mode 100644 index 0000000..266aec4 --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/3.txt @@ -0,0 +1,10 @@ +- Added Russian translation by @Ftonans +- Added polish translation by @maciej-klupp +- Added Chinese (Simplified) translation by @Daietto +- Android 13 support +- Added support for per-app language on Android 13 +- Bug fixes + +Features coming soon: +- Backup data +- Folders for more spaces \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/changelogs/4.txt b/fastlane/metadata/android/en-US/changelogs/4.txt new file mode 100644 index 0000000..786817f --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/4.txt @@ -0,0 +1,8 @@ +- Added export/import data +- Added block screenshots option +- Changed the grid view in notes to staggered grid view +- Added Romanian translation by @SebiTalent04 +- Added Brazilian Portuguese translation by @abChimp +- Added German translation by @SteveMutter +- Fixed recurring events shows only one instance +- Bug fixes \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/changelogs/5.txt b/fastlane/metadata/android/en-US/changelogs/5.txt new file mode 100644 index 0000000..973809b --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/5.txt @@ -0,0 +1,5 @@ +- Updated translations +- Fixed new calendar event duplicates +- Fixed strike-through remains on task after marking it incomplete +- Fixed clicking on "Export data" navigates to app settings +- Fixed Export data fails in android 9 and lower \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/changelogs/6.txt b/fastlane/metadata/android/en-US/changelogs/6.txt new file mode 100644 index 0000000..c3438e8 --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/6.txt @@ -0,0 +1,7 @@ +- Added recurring tasks +- Added support for Material You icon theming +- Added Turkish translation +- Added sorting tasks by due date +- Fixed widgets errors +- Performance improvements +- But fixes \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/changelogs/7.txt b/fastlane/metadata/android/en-US/changelogs/7.txt new file mode 100644 index 0000000..ec43ccd --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/7.txt @@ -0,0 +1,8 @@ +- Added more options to recurring tasks +- Added last modified date & word count for Notes +- Added markdown support for Diary +- Added support for 24-hour time format +- Fixed backup issues +- Bug fixes + +- Coming soon: Encrypted backups \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/full_description.txt b/fastlane/metadata/android/en-US/full_description.txt new file mode 100644 index 0000000..ba7c180 --- /dev/null +++ b/fastlane/metadata/android/en-US/full_description.txt @@ -0,0 +1,10 @@ +My Brain is an Open source, All in one productivity app for Tasks, Notes, Calendar, Diary and Bookmarks. + +Features : +- Private with no data collection and no internet permission at all. +- Create tasks with priority, sub-tasks, description and due date and reminders. +- Create Notes that supports markdown which enables you to use Headers, lists, links etc.. +- Record your mood daily and view your mood summary with beautiful graphs. +- Save bookmarks for later by using the share menu from any other app. +- View your calendar events in a modern view and also with a beautiful home screen widget. +- Dashboard screen to see your tasks, calendar events, and more to see your day at a glance. \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/images/icon.png b/fastlane/metadata/android/en-US/images/icon.png new file mode 100644 index 0000000..e42a9eb Binary files /dev/null and b/fastlane/metadata/android/en-US/images/icon.png differ diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/1.png b/fastlane/metadata/android/en-US/images/phoneScreenshots/1.png new file mode 100644 index 0000000..53ebce5 Binary files /dev/null and b/fastlane/metadata/android/en-US/images/phoneScreenshots/1.png differ diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/2.jpg b/fastlane/metadata/android/en-US/images/phoneScreenshots/2.jpg new file mode 100644 index 0000000..1018888 Binary files /dev/null and b/fastlane/metadata/android/en-US/images/phoneScreenshots/2.jpg differ diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/3.jpg b/fastlane/metadata/android/en-US/images/phoneScreenshots/3.jpg new file mode 100644 index 0000000..94a4e96 Binary files /dev/null and b/fastlane/metadata/android/en-US/images/phoneScreenshots/3.jpg differ diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/4.jpg b/fastlane/metadata/android/en-US/images/phoneScreenshots/4.jpg new file mode 100644 index 0000000..db573e3 Binary files /dev/null and b/fastlane/metadata/android/en-US/images/phoneScreenshots/4.jpg differ diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/5.jpg b/fastlane/metadata/android/en-US/images/phoneScreenshots/5.jpg new file mode 100644 index 0000000..05e5cbe Binary files /dev/null and b/fastlane/metadata/android/en-US/images/phoneScreenshots/5.jpg differ diff --git a/fastlane/metadata/android/en-US/short_description.txt b/fastlane/metadata/android/en-US/short_description.txt new file mode 100644 index 0000000..9d2cca4 --- /dev/null +++ b/fastlane/metadata/android/en-US/short_description.txt @@ -0,0 +1 @@ +All in one app for Tasks, Notes, Events and more \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/title.txt b/fastlane/metadata/android/en-US/title.txt new file mode 100644 index 0000000..17c2be6 --- /dev/null +++ b/fastlane/metadata/android/en-US/title.txt @@ -0,0 +1 @@ +My Brain \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..cd0519b --- /dev/null +++ b/gradle.properties @@ -0,0 +1,23 @@ +# Project-wide Gradle settings. +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true +# AndroidX package structure to make it clearer which packages are bundled with the +# Android operating system, and which are packaged with your app"s APK +# https://developer.android.com/topic/libraries/support-library/androidx-rn +android.useAndroidX=true +# Kotlin code style for this project: "official" or "obsolete": +kotlin.code.style=official +# Enables namespacing of each library's R class so that its R class includes only the +# resources declared in the library itself and none from the library's dependencies, +# thereby reducing the size of the R class for that library +android.nonTransitiveRClass=true \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e708b1c Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..e9acb89 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Thu Sep 21 12:40:08 EET 2023 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..4f906e0 --- /dev/null +++ b/gradlew @@ -0,0 +1,185 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# 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 +# +# https://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. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/privacy-policy.md b/privacy-policy.md new file mode 100644 index 0000000..f5269ed --- /dev/null +++ b/privacy-policy.md @@ -0,0 +1,5 @@ +# My Brain Privacy Policy + +All data is stored locally on the device and never leaves the device to any server owned by me or any 3rd party + +There are no ads or trackers in the app and no data is collected. The app does not access the internet and does not have permission to access the internet. diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..d2550d7 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,17 @@ +pluginManagement { + repositories { + gradlePluginPortal() + google() + mavenCentral() + } +} +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + maven { url 'https://jitpack.io' } + } +} +rootProject.name = "My Brain" +include ':app'