pax_global_header00006660000000000000000000000064142330441110014503gustar00rootroot0000000000000052 comment=0e382ba1636bb9df61775599ad80adedc8596562 apostrophe-v2.6.3/000077500000000000000000000000001423304411100140655ustar00rootroot00000000000000apostrophe-v2.6.3/.gitignore000066400000000000000000000002441423304411100160550ustar00rootroot00000000000000*.pyc __pycache__/ _build/* build/ *.*~ .vscode/ .idea/ builddir/* build-aux/flatpak/_build/* build-aux/flatpak/.flatpak-builder/* flatpak/* .mypy_cache/ .flatpak/ apostrophe-v2.6.3/.gitlab-ci.yml000066400000000000000000000010431423304411100165170ustar00rootroot00000000000000include: 'https://gitlab.gnome.org/GNOME/citemplates/raw/master/flatpak/flatpak_ci_initiative.yml' flatpak: image: 'registry.gitlab.gnome.org/gnome/gnome-runtime-images/gnome:41' variables: MANIFEST_PATH: "build-aux/flatpak/org.gnome.gitlab.somas.Apostrophe.json" MESON_ARGS: "-Dprofile=Devel" FLATPAK_MODULE: "apostrophe" APP_ID: "org.gnome.gitlab.somas.Apostrophe" RUNTIME_REPO: "https://nightly.gnome.org/gnome-nightly.flatpakrepo" BUNDLE: "apostrophe-dev.flatpak" extends: .flatpak apostrophe-v2.6.3/.gitlab/000077500000000000000000000000001423304411100154055ustar00rootroot00000000000000apostrophe-v2.6.3/.gitlab/issue_templates/000077500000000000000000000000001423304411100206135ustar00rootroot00000000000000apostrophe-v2.6.3/.gitlab/issue_templates/bug_report.md000066400000000000000000000011311423304411100233010ustar00rootroot00000000000000**Describe the bug** A clear and concise description of what the bug is. **To Reproduce** Steps to reproduce the behavior: 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' 4. See error **Expected behavior** A clear and concise description of what you expected to happen. **Screenshots** If applicable, add screenshots to help explain your problem. **Environment(please complete the following information):** - Linux distribution: - Desktop Enviroment: - DE version: - GTK version: **Additional context** Add any other context about the problem here. /label ~bug ~triage /assign @somas apostrophe-v2.6.3/.gitlab/issue_templates/feature_request.md000066400000000000000000000010211423304411100243320ustar00rootroot00000000000000**Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here. /label ~"feature request" /assign @somasapostrophe-v2.6.3/AUTHORS000066400000000000000000000003001423304411100151260ustar00rootroot00000000000000Wolf Vollprecht Vova Kolobok Manuel Genovés Gonçalo Silva Thomas Lavend apostrophe-v2.6.3/CODE_OF_CONDUCT.md000066400000000000000000000064341423304411100166730ustar00rootroot00000000000000# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at manuel.genoves@gmail.com. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq apostrophe-v2.6.3/LICENSE000066400000000000000000001045131423304411100150760ustar00rootroot00000000000000 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 . apostrophe-v2.6.3/NEWS000066400000000000000000000131211423304411100145620ustar00rootroot00000000000000Version 2.6.3 ~~~~~~~~~~~~~~~ Released: 2022-04-29 Bugfixes: - Fix a bug where the preview wouldn't be shown when opening a file from Files or the CLI - Fix a bug where horizontal preview wouldn't request enough space at startup - Removed swipe gestures from the preview panel Features: - Added Persian translations, updated Catalan, German , Finnish and Turkish ones Version 2.6.2 ~~~~~~~~~~~~~~~ Released: 2022-03-31 Bugfixes: - Fix handling of windowed preview mode on some circumstances Features: - Add proper titles to the preview window - Update translations Version 2.6.1 ~~~~~~~~~~~~~~~ Released: 2022-03-20 Bugfixes: - A small bug in 2.6 which didn't allow to save files Version 2.6 ~~~~~~~~~~~~~~~ Released: 2022-03-19 Features: - Implemented multiwindow support - Save window state on exit - Ported to libhandy - Improved the overall UI - New animations - Follow the Dark Mode global preference - Add an "automatic" color mode - Improve the High Contrast styles - Improve inline preview markup Version 2.5 ~~~~~~~~~~~~~~~ Released: 2021-08-28 Features: - Added Sepia Mode - Improved exported HTML on small screens - Updated metadata and runtime version Version 2.4 ~~~~~~~~~~~~~~~ Released: 2021-03-10 Bugfixes: - Fixed a bug where the cursor could go over the bottom of the window - Fixed a bug where in certain circumstances the bottom line couldn't be clicked - Improved behaviour when dealing with unsaved files. - Improved start/end sentence detection in Focus Mode - Small improvements in the headerbar title - Cleaned a little bit the Shortcuts Window Version 2.3 ~~~~~~~~~~~~~~~ Released: 2021-03-01 Features: - New export dialog - Improved Reveal.js slideshow exports - Better input/output handling - Inhibit logout if the document is not saved - Migrate to xelatex - Better internal path handling - New animated progressbar on saving - Strict sandboxing support Bugfixes: - Undo/redo improvements - Fixes for bad markdown parsing of unordered lists Version 2.2.0.3 ~~~~~~~~~~~~~~~ Released: 2020-05-04 Bugfixes: - Better wording for some areas - Fixed some issues where Apostrophe couldn't open files from CLI/context menu - Now Apostrophe checks if there is unsaved work before exiting via CTRL + Q/W - Better parsing of weblinks and links to files - Fixed a bug where the bottom portion of the screen was insensitive to mouse input Version 2.2.0.2 ~~~~~~~~~~~~~~~ Released: 2020-04-20 Bugfixes: - Fixes for the Elementary OS platform - Fixed some links and metadata Version 2.2.0.1 ~~~~~~~~~~~~~~~ Released: 2020-04-18 Features: - New headerbar design - New preview modes, with the option to sync them to the edit view - New preview mode selector - New theme selector - Rework the autohiding mechanism; now the headerbar fades away when typing, only to reappear when the cursor moves to the top portion of the window - Now the content of the texview goes visually bellow the headerbar - Overall better styling - Added Hemingway mode, which disables the backspace key - Added Github Flavoured Markdow, MultiMarkdown, Pandoc's Markdown and Commonmark support, being CommonMark the default from now on - New stats counter, with the option to show count of characters/words/sentences/paragrafs/reading time - Better handling of DnD events - Export to A4 by default - Technical improvements * Port of the buildsystem to Meson. Now you can hit the "build" button on Builder and everything works as expected * Port to gspell * Partial port to gresources * Overall refactorization of the codebase * General bugfixes and improvements Version 2.1.5 ~~~~~~~~~~~~~ Released: 2019-03-10 Features: - Added italian language - Initial themes support: now apostrophe adapts his colors to the current GTK theme - Disabled scroll gradient, can be enabled in the preferences dialog - Allow to disable headerbar autohidding in Dconf - Now a single click is enough to open files in the recent files popover - Spellchecking status is now saved between sessions - Minor UI fixes - Added -d flag to enable webdev tools Version 2.1.4 ~~~~~~~~~~~~~ Released: 2018-12-06 Features: - Updated css styles. Version 2.1.3 ~~~~~~~~~~~~~ Released: 2018-11-28 Features: - This release features a new logo, polishes the Appmenu, fixes usability bugs and flatpak related bugs. Version 2.1.2 ~~~~~~~~~~~~~ Released: 2018-07-27 Features: - This release provides a fix to a bug that caused Apostrophe to not mark properly **bold**, *cursive*, and ***bold and cursive*** words. Version 2.1.1 ~~~~~~~~~~~~~ Released: 2018-07-26 Bugfixes: - One on focus mode which caused the lines to be highlighted on edit rather than on click - Non symbolic icons on the searchbar Version 2.1.0 ~~~~~~~~~~~~~ Released: 2018-07-18 Features: - Drop AppMenu support - HeaderBar and menus redesign, with a new unified menu and quick access buttons on the headerbar - Now the fullscreen view shows a headerbar when the cursor approaches the top of the screen - A new unified export dialog, with updated options, and quick access to pdf, odt and html export - Bugfixes. Version 2.0.4 ~~~~~~~~~~~~~ Released: 2018-06-24 Features: - Now the menu is a Popover instead a regular menu. - The headerbar matches the theme selected for the application. - Updated translations. Version 2.0.3 ~~~~~~~~~~~~~ Released: 2018-06-14 Bugfixes: - Small bug fixes, updated links. Version 2.0.2 ~~~~~~~~~~~~~ Released: 2018-05-16 Bugfixes: - Fix a bug with the preview mode. Version 2.0.1 ~~~~~~~~~~~~~ Released: 2018-05-14 Bugfixes: - Don’t use env variable to check if in flatpak. Version 2.0.0 ~~~~~~~~~~~~~ Released: 2018-05-12 Features: - First re-release apostrophe-v2.6.3/README.md000066400000000000000000000060431423304411100153470ustar00rootroot00000000000000[![Please do not theme this app](https://stopthemingmy.app/badge.svg)](https://stopthemingmy.app) # Apostrophe ![](screenshots/main.png) ## About Apostrophe is a [GTK+](https://www.gtk.org) based distraction free Markdown editor, originally developed by Wolf Vollprecht and currently developed and maintained by Manuel Genovés. It uses pandoc as back-end for parsing Markdown and offers a very clean and sleek user interface. ## Install Download on Flathub Also several unofficial builds are available: * Nix(OS): [`pkgs.apostrophe`](https://github.com/NixOS/nixpkgs/blob/master/pkgs/applications/editors/apostrophe/default.nix) * Arch Linux (AUR) * [Fedora](https://src.fedoraproject.org/rpms/apostrophe): `sudo dnf install apostrophe` ## Translation If you want to help translating the project, please join us at [Damned Lies](https://l10n.gnome.org/module/apostrophe/). Any help is appreciated! ## Building ### Building using GNOME Builder GNOME Builder offers the easiest method to build Apostrophe. Just follow [this guide](https://wiki.gnome.org/Newcomers/BuildProject) and you'll be up and running in a minute. ### Building from Git To build Apostrophe from source you need to have the following dependencies installed: - Build system: `meson ninja-build` - Pandoc, the program used to convert Markdown to basically anything else: `pandoc` - GTK3 and GLib development packages: `libgtk-3-dev libglib2.0-dev` - Rendering the preview panel: `libwebkit2gtk` - Spell checking libraries: `gobject-introspection libgirepository1.0-dev gir1.2-gspell1 gettext` - Python dependencies: `python3 python3-regex python3-setuptools python3-levenshtein python3-enchant python3-gi python3-cairo python3-pypandoc` - *optional:* AppStream utility: `appstream-util` - *optional:* pdftex module: `texlive texlive-latex-extra` - *optional:* formula preview: `libjs-mathjax` Depending on your setup you may need to install these schemas before building: ```bash $ sudo cp data/org.gnome.gitlab.somas.Apostrophe.gschema.xml /usr/share/glib-2.0/schemas/org.gnome.gitlab.somas.Apostrophe.gschema.xml $ sudo glib-compile-schemas /usr/share/glib-2.0/schemas ``` Once all dependencies are installed you can build Apostrophe using the following commands: ```bash $ git clone https://gitlab.gnome.org/World/apostrophe/ $ cd apostrophe $ meson builddir --prefix=/usr -Dprofile=development $ sudo ninja -C builddir install ``` Then you can run the installed package: ```bash $ apostrophe ``` Or a local version which runs from the source tree ```bash $ ./builddir/local-apostrophe ``` ### Building a flatpak package It's also possible to build, run and debug a flatpak package. All you need is to setup [flatpak-builder](https://docs.flatpak.org/en/latest/first-build.html) and run the following commands: ```bash $ cd build-aux/flatpak $ flatpak-builder --force-clean --install --user _build org.gnome.gitlab.somas.Apostrophe.json ``` apostrophe-v2.6.3/apostrophe.doap000066400000000000000000000017701423304411100171230ustar00rootroot00000000000000 Apostrophe Edit Markdown in style Python Manuel Genovés somas apostrophe-v2.6.3/apostrophe.in000077500000000000000000000036071423304411100166120ustar00rootroot00000000000000#!/usr/bin/env python3 # -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- ### BEGIN LICENSE # Copyright (C) 2019, Wolf Vollprecht # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 . ### END LICENSE ### DO NOT EDIT THIS FILE ### import sys import os import pkg_resources import gettext import locale _LOCAL = @LOCAL_BUILD@ if _LOCAL: # In the local use case, use apostrophe module from the sourcetree sys.path.insert(1, '@PYTHON_DIR@') # In the local use case the installed schemas go in /data os.environ["XDG_DATA_DIRS"] = '@SCHEMAS_DIR@:' + os.environ.get("XDG_DATA_DIRS", "") from gi.repository import Gio import apostrophe localedir = '@LOCALE_DIR@' pkgdatadir = '@PKGDATA_DIR@' # L10n locale.textdomain('apostrophe') locale.bindtextdomain('apostrophe', localedir) gettext.textdomain('apostrophe') gettext.bindtextdomain('apostrophe', localedir) def run_application(): from apostrophe.application import Application app = Application('@APP_ID@') return app.run(sys.argv) def main(): resource = Gio.resource_load( os.path.join(pkgdatadir, 'apostrophe.gresource')) Gio.Resource._register(resource) return run_application() if __name__ == '__main__': if _LOCAL: print('Running from source tree, using local files.') sys.exit(main()) apostrophe-v2.6.3/apostrophe/000077500000000000000000000000001423304411100162515ustar00rootroot00000000000000apostrophe-v2.6.3/apostrophe/.pylintrc000066400000000000000000000426411423304411100201250ustar00rootroot00000000000000[MASTER] # A comma-separated list of package or module names from where C extensions may # be loaded. Extensions are loading into the active Python interpreter and may # run arbitrary code. extension-pkg-whitelist= # Add files or directories to the blacklist. They should be base names, not # paths. ignore=CVS # Add files or directories matching the regex patterns to the blacklist. The # regex matches against base names, not paths. ignore-patterns= # Python code to execute, usually for sys.path manipulation such as # pygtk.require(). #init-hook= # Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the # number of processors available to use. jobs=1 # Control the amount of potential inferred values when inferring a single # object. This can help the performance when dealing with large functions or # complex, nested conditions. limit-inference-results=100 # List of plugins (as comma separated values of python modules names) to load, # usually to register additional checkers. load-plugins= # Pickle collected data for later comparisons. persistent=yes # Specify a configuration file. #rcfile= # When enabled, pylint would attempt to guess common misconfiguration and emit # user-friendly hints instead of false-positive error messages. suggestion-mode=yes # Allow loading of arbitrary C extensions. Extensions are imported into the # active Python interpreter and may run arbitrary code. unsafe-load-any-extension=no [MESSAGES CONTROL] # Only show warnings with the listed confidence levels. Leave empty to show # all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED. confidence= # Disable the message, report, category or checker with the given id(s). You # can either give multiple identifiers separated by comma (,) or put this # option multiple times (only on the command line, not in the configuration # file where it should appear only once). You can also use "--disable=all" to # disable everything first and then reenable specific checks. For example, if # you want to run only the similarities checker, you can use "--disable=all # --enable=similarities". If you want to run only the classes checker, but have # no Warning level messages displayed, use "--disable=all --enable=classes # --disable=W". disable=print-statement, parameter-unpacking, unpacking-in-except, old-raise-syntax, backtick, long-suffix, old-ne-operator, old-octal-literal, import-star-module-level, non-ascii-bytes-literal, raw-checker-failed, bad-inline-option, locally-disabled, locally-enabled, file-ignored, suppressed-message, useless-suppression, deprecated-pragma, use-symbolic-message-instead, apply-builtin, basestring-builtin, buffer-builtin, cmp-builtin, coerce-builtin, execfile-builtin, file-builtin, long-builtin, raw_input-builtin, reduce-builtin, standarderror-builtin, unicode-builtin, xrange-builtin, coerce-method, delslice-method, getslice-method, setslice-method, no-absolute-import, old-division, dict-iter-method, dict-view-method, next-method-called, metaclass-assignment, indexing-exception, raising-string, reload-builtin, oct-method, hex-method, nonzero-method, cmp-method, input-builtin, round-builtin, intern-builtin, unichr-builtin, map-builtin-not-iterating, zip-builtin-not-iterating, range-builtin-not-iterating, filter-builtin-not-iterating, using-cmp-argument, eq-without-hash, div-method, idiv-method, rdiv-method, exception-message-attribute, invalid-str-codec, sys-max-int, bad-python3-import, deprecated-string-function, deprecated-str-translate-call, deprecated-itertools-function, deprecated-types-field, next-method-defined, dict-items-not-iterating, dict-keys-not-iterating, dict-values-not-iterating, deprecated-operator-function, deprecated-urllib-function, xreadlines-attribute, deprecated-sys-function, exception-escape, comprehension-escape # Enable the message, report, category or checker with the given id(s). You can # either give multiple identifier separated by comma (,) or put this option # multiple time (only on the command line, not in the configuration file where # it should appear only once). See also the "--disable" option for examples. enable=c-extension-no-member [REPORTS] # Python expression which should return a note less than 10 (10 is the highest # note). You have access to the variables errors warning, statement which # respectively contain the number of errors / warnings messages and the total # number of statements analyzed. This is used by the global evaluation report # (RP0004). evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) # Template used to display messages. This is a python new-style format string # used to format the message information. See doc for all details. #msg-template= # Set the output format. Available formats are text, parseable, colorized, json # and msvs (visual studio). You can also give a reporter class, e.g. # mypackage.mymodule.MyReporterClass. output-format=msvs # Tells whether to display a full report or only the messages. reports=yes # Activate the evaluation score. score=yes [REFACTORING] # Maximum number of nested blocks for function / method body max-nested-blocks=5 # Complete name of functions that never returns. When checking for # inconsistent-return-statements if a never returning function is called then # it will be considered as an explicit return statement and no message will be # printed. never-returning-functions=sys.exit [FORMAT] # Expected format of line ending, e.g. empty (any line ending), LF or CRLF. expected-line-ending-format= # Regexp for a line that is allowed to be longer than the limit. ignore-long-lines=^\s*(# )??$ # Number of spaces of indent required inside a hanging or continued line. indent-after-paren=4 # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 # tab). indent-string=' ' # Maximum number of characters on a single line. max-line-length=100 # Maximum number of lines in a module. max-module-lines=1000 # List of optional constructs for which whitespace checking is disabled. `dict- # separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. # `trailing-comma` allows a space between comma and closing bracket: (a, ). # `empty-line` allows space-only lines. no-space-check=trailing-comma, dict-separator # Allow the body of a class to be on the same line as the declaration if body # contains single statement. single-line-class-stmt=no # Allow the body of an if to be on the same line as the test if there is no # else. single-line-if-stmt=no [LOGGING] # Logging modules to check that the string format arguments are in logging # function parameter format. logging-modules=logging [SPELLING] # Limits count of emitted suggestions for spelling mistakes. max-spelling-suggestions=4 # Spelling dictionary name. Available dictionaries: he (hspell), en_IE # (hunspell), es_BO (hunspell), en_NZ (hunspell), es_DO (hunspell), es_MX # (hunspell), en_ZA (hunspell), en_IN (hunspell), en_TT (hunspell), ca # (aspell), ca_FR (hunspell), es_HN (hunspell), ca_AD (hunspell), es_SV # (hunspell), es_PA (hunspell), en_DK (hunspell), es_NI (hunspell), es_PE # (hunspell), en_SG (hunspell), es_UY (hunspell), en_BS (hunspell), en_BW # (hunspell), es_CL (hunspell), es_AR (hunspell), en_BZ (hunspell), es_CO # (hunspell), en_ZW (hunspell), en_HK (hunspell), es_CR (hunspell), en_NA # (hunspell), es_PR (hunspell), en_JM (hunspell), es_VE (hunspell), en_AG # (hunspell), es_CU (hunspell), en_NG (hunspell), ca_ES (hunspell), es_ES # (hunspell), es_ANY (hunspell), es_EC (hunspell), es_GT (hunspell), en_PH # (hunspell), en_GB (hunspell), en_US (hunspell), ca_IT (hunspell), es_PY # (hunspell), en_GH (hunspell).. spelling-dict= # List of comma separated words that should not be checked. spelling-ignore-words= # A path to a file that contains private dictionary; one word per line. spelling-private-dict-file= # Tells whether to store unknown words to indicated private dictionary in # --spelling-private-dict-file option instead of raising a message. spelling-store-unknown-words=no [SIMILARITIES] # Ignore comments when computing similarities. ignore-comments=yes # Ignore docstrings when computing similarities. ignore-docstrings=yes # Ignore imports when computing similarities. ignore-imports=no # Minimum lines number of a similarity. min-similarity-lines=4 [TYPECHECK] # List of decorators that produce context managers, such as # contextlib.contextmanager. Add to this list to register other decorators that # produce valid context managers. contextmanager-decorators=contextlib.contextmanager # List of members which are set dynamically and missed by pylint inference # system, and so shouldn't trigger E1101 when accessed. Python regular # expressions are accepted. generated-members= # Tells whether missing members accessed in mixin class should be ignored. A # mixin class is detected if its name ends with "mixin" (case insensitive). ignore-mixin-members=yes # Tells whether to warn about missing members when the owner of the attribute # is inferred to be None. ignore-none=yes # This flag controls whether pylint should warn about no-member and similar # checks whenever an opaque object is returned when inferring. The inference # can return multiple potential results while evaluating a Python object, but # some branches might not be evaluated, which results in partial inference. In # that case, it might be useful to still emit no-member and other checks for # the rest of the inferred objects. ignore-on-opaque-inference=yes # List of class names for which member attributes should not be checked (useful # for classes with dynamically set attributes). This supports the use of # qualified names. ignored-classes=optparse.Values,thread._local,_thread._local # List of module names for which member attributes should not be checked # (useful for modules/projects where namespaces are manipulated during runtime # and thus existing member attributes cannot be deduced by static analysis. It # supports qualified module names, as well as Unix pattern matching. ignored-modules= # Show a hint with possible names when a member name was not found. The aspect # of finding the hint is based on edit distance. missing-member-hint=yes # The minimum edit distance a name should have in order to be considered a # similar match for a missing member name. missing-member-hint-distance=1 # The total number of similar names that should be taken in consideration when # showing a hint for a missing member. missing-member-max-choices=1 [BASIC] # Naming style matching correct argument names. argument-naming-style=snake_case # Regular expression matching correct argument names. Overrides argument- # naming-style. #argument-rgx= # Naming style matching correct attribute names. attr-naming-style=snake_case # Regular expression matching correct attribute names. Overrides attr-naming- # style. #attr-rgx= # Bad variable names which should always be refused, separated by a comma. bad-names=foo, bar, baz, toto, tutu, tata # Naming style matching correct class attribute names. class-attribute-naming-style=any # Regular expression matching correct class attribute names. Overrides class- # attribute-naming-style. #class-attribute-rgx= # Naming style matching correct class names. class-naming-style=PascalCase # Regular expression matching correct class names. Overrides class-naming- # style. #class-rgx= # Naming style matching correct constant names. const-naming-style=UPPER_CASE # Regular expression matching correct constant names. Overrides const-naming- # style. #const-rgx= # Minimum line length for functions/classes that require docstrings, shorter # ones are exempt. docstring-min-length=-1 # Naming style matching correct function names. function-naming-style=snake_case # Regular expression matching correct function names. Overrides function- # naming-style. #function-rgx= # Good variable names which should always be accepted, separated by a comma. good-names=i, j, k, ex, Run, _ # Include a hint for the correct naming format with invalid-name. include-naming-hint=yes # Naming style matching correct inline iteration names. inlinevar-naming-style=any # Regular expression matching correct inline iteration names. Overrides # inlinevar-naming-style. #inlinevar-rgx= # Naming style matching correct method names. method-naming-style=snake_case # Regular expression matching correct method names. Overrides method-naming- # style. #method-rgx= # Naming style matching correct module names. module-naming-style=snake_case # Regular expression matching correct module names. Overrides module-naming- # style. #module-rgx= # Colon-delimited sets of names that determine each other's naming style when # the name regexes allow several styles. name-group= # Regular expression which should only match function or class names that do # not require a docstring. no-docstring-rgx=^_ # List of decorators that produce properties, such as abc.abstractproperty. Add # to this list to register other decorators that produce valid properties. property-classes=abc.abstractproperty # Naming style matching correct variable names. variable-naming-style=snake_case # Regular expression matching correct variable names. Overrides variable- # naming-style. #variable-rgx= [VARIABLES] # List of additional names supposed to be defined in builtins. Remember that # you should avoid to define new builtins when possible. additional-builtins= # Tells whether unused global variables should be treated as a violation. allow-global-unused-variables=yes # List of strings which can identify a callback function by name. A callback # name must start or end with one of those strings. callbacks=cb_, _cb # A regular expression matching the name of dummy variables (i.e. expected to # not be used). dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ # Argument names that match this expression will be ignored. Default to name # with leading underscore. ignored-argument-names=_.*|^ignored_|^unused_ # Tells whether we should check for unused import in __init__ files. init-import=no # List of qualified module names which can have objects that can redefine # builtins. redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io [MISCELLANEOUS] # List of note tags to take in consideration, separated by a comma. notes=FIXME, XXX, TODO [CLASSES] # List of method names used to declare (i.e. assign) instance attributes. defining-attr-methods=__init__, __new__, setUp # List of member names, which should be excluded from the protected access # warning. exclude-protected=_asdict, _fields, _replace, _source, _make # List of valid names for the first argument in a class method. valid-classmethod-first-arg=cls # List of valid names for the first argument in a metaclass class method. valid-metaclass-classmethod-first-arg=cls [DESIGN] # Maximum number of arguments for function / method. max-args=5 # Maximum number of attributes for a class (see R0902). max-attributes=7 # Maximum number of boolean expressions in an if statement. max-bool-expr=5 # Maximum number of branch for function / method body. max-branches=12 # Maximum number of locals for function / method body. max-locals=15 # Maximum number of parents for a class (see R0901). max-parents=7 # Maximum number of public methods for a class (see R0904). max-public-methods=20 # Maximum number of return / yield for function / method body. max-returns=6 # Maximum number of statements in function / method body. max-statements=50 # Minimum number of public methods for a class (see R0903). min-public-methods=2 [IMPORTS] # Allow wildcard imports from modules that define __all__. allow-wildcard-with-all=no # Analyse import fallback blocks. This can be used to support both Python 2 and # 3 compatible code, which means that the block might have code that exists # only in one or another interpreter, leading to false positives when analysed. analyse-fallback-blocks=no # Deprecated modules which should not be used, separated by a comma. deprecated-modules=optparse,tkinter.tix # Create a graph of external dependencies in the given file (report RP0402 must # not be disabled). ext-import-graph= # Create a graph of every (i.e. internal and external) dependencies in the # given file (report RP0402 must not be disabled). import-graph= # Create a graph of internal dependencies in the given file (report RP0402 must # not be disabled). int-import-graph= # Force import order to recognize a module as part of the standard # compatibility libraries. known-standard-library= # Force import order to recognize a module as part of a third party library. known-third-party=enchant [EXCEPTIONS] # Exceptions that will emit a warning when being caught. Defaults to # "Exception". overgeneral-exceptions=Exception apostrophe-v2.6.3/apostrophe/__init__.py000066400000000000000000000015121423304411100203610ustar00rootroot00000000000000# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- ### BEGIN LICENSE # Copyright (C) 2019, Wolf Vollprecht # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 . ### END LICENSE import pkgutil __path__ = pkgutil.extend_path(__path__, __name__)apostrophe-v2.6.3/apostrophe/application.py000066400000000000000000000241211423304411100211260ustar00rootroot00000000000000# Copyright (C) 2022, Manuel Genovés # 2019, Wolf Vollprecht # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 <http://www.gnu.org/licenses/>. import gi gi.require_version('Gtk', '3.0') gi.require_version('Handy', '1') from gi.repository import GLib, Gio, Gtk, Gdk, Handy from apostrophe.main_window import MainWindow from apostrophe.settings import Settings from apostrophe.helpers import set_up_logging from apostrophe.preferences_dialog import ApostrophePreferencesDialog from apostrophe.inhibitor import Inhibitor from apostrophe.theme_switcher import Theme class Application(Gtk.Application): def __init__(self, application_id, *args, **kwargs): super().__init__(*args, application_id=application_id, flags=Gio.ApplicationFlags.HANDLES_OPEN | Gio.ApplicationFlags.NON_UNIQUE, **kwargs) self.add_main_option("verbose", b"v", GLib.OptionFlags.NONE, GLib.OptionArg.NONE, "Verbose output", None) # Hardcode Adwaita to prevent issues with third party themes gtk_settings = Gtk.Settings.get_default() self._set_theme(gtk_settings) gtk_settings.connect("notify::gtk-theme-name", self._set_theme) gtk_settings.connect("notify::gtk-icon-theme-name", self._set_theme) # Set css theme css_provider_file = Gio.File.new_for_uri( "resource:///org/gnome/gitlab/somas/Apostrophe/media/css/gtk/Adwaita.css") self.style_provider = Gtk.CssProvider() self.style_provider.load_from_file(css_provider_file) Gtk.StyleContext.add_provider_for_screen( Gdk.Screen.get_default(), self.style_provider, Gtk.STYLE_PROVIDER_PRIORITY_USER) # Style manager style_manager = Handy.StyleManager.get_default() style_manager.connect("notify::dark", self._set_color_scheme) style_manager.connect("notify::high-contrast", self._set_color_scheme) # Set editor keybindings # SCSS is not fit for this, so we do it in an external css file css_bindings_file = Gio.File.new_for_uri( "resource:///org/gnome/gitlab/somas/Apostrophe/media/css/gtk/bindings.css") self.bindings_provider = Gtk.CssProvider() self.bindings_provider.load_from_file(css_bindings_file) Gtk.StyleContext.add_provider_for_screen( Gdk.Screen.get_default(), self.bindings_provider, Gtk.STYLE_PROVIDER_PRIORITY_USER) # Set icons Gtk.IconTheme.get_default().add_resource_path( "/org/gnome/gitlab/somas/Apostrophe/icons" ) Handy.init() self.windows = [] self.settings = Settings.new() self.inhibitor = None self._application_id = application_id def do_startup(self, *args, **kwargs): Gtk.Application.do_startup(self) color_scheme = self.settings.get_string("color-scheme") action = Gio.SimpleAction.new_stateful( "color_scheme", GLib.VariantType.new("s"), GLib.Variant.new_string(color_scheme)) action.connect("activate", self._set_color_scheme) self.add_action(action) action = Gio.SimpleAction.new("new_window", None) action.connect("activate", self.on_new_window) self.add_action(action) action = Gio.SimpleAction.new("preferences", None) action.connect("activate", self.on_preferences) self.add_action(action) action = Gio.SimpleAction.new("shortcuts", None) action.connect("activate", self.on_shortcuts) self.add_action(action) action = Gio.SimpleAction.new("about", None) action.connect("activate", self.on_about) self.add_action(action) action = Gio.SimpleAction.new("quit", None) action.connect("activate", self.on_quit) self.add_action(action) # Stats Menu stat_default = self.settings.get_string("stat-default") action = Gio.SimpleAction.new_stateful( "stat_default", GLib.VariantType.new("s"), GLib.Variant.new_string(stat_default)) action.connect("activate", self.on_stat_default) self.add_action(action) # Shortcuts # TODO: be aware that a couple of shortcuts are defined in base.css self.set_accels_for_action("win.focus_mode", ["d"]) self.set_accels_for_action("win.hemingway_mode", ["t"]) self.set_accels_for_action("win.fullscreen", ["F11"]) self.set_accels_for_action("win.find", ["f"]) self.set_accels_for_action("win.find_replace", ["h"]) self.set_accels_for_action("app.spellcheck", ["F7"]) self.set_accels_for_action("win.new", ["n"]) self.set_accels_for_action("win.open", ["o"]) self.set_accels_for_action("win.save", ["s"]) self.set_accels_for_action("win.save_as", ["s"]) self.set_accels_for_action("app.quit", ["w", "q"]) # Inhibitor self.inhibitor = Inhibitor() def do_activate(self, *args, **kwargs): if not self.windows: self.settings.connect("changed", self.on_settings_changed) self.windows.append(MainWindow(self)) if self._application_id == 'org.gnome.gitlab.somas.Apostrophe.Devel': for window in self.windows: window.get_style_context().add_class('devel') self._set_color_scheme() self.windows[-1].present() def do_handle_local_options(self, options): if options.contains("verbose") or self._application_id \ == 'org.gnome.gitlab.somas.Apostrophe.Devel': set_up_logging(1) return -1 def do_open(self, files, _n_files, _hint): self.activate() for i, file in enumerate(files): if i == 0: window = self.windows[0] else: window = MainWindow(self) window.load_file(file) window.present() self.windows.append(window) def _set_theme(self, settings, *_pspec): # Third party themes cause issues with Apostrophe custom stylesheets # If the user has a third party theme selected, we just change it to # Adwaita to prevent those issues # TODO: GTK4 - remove this theme_name = settings.get_property("gtk-theme-name") icon_theme_name = settings.get_property("gtk-icon-theme-name") if (theme_name not in ["Adwaita", "HighContrast", "HighContrastInverse"]): settings.set_property("gtk-theme-name", "Adwaita") def _set_color_scheme(self, *args, **kwargs): # TODO: GTK4 - remove this theme = Theme.get_current() style_manager = Handy.StyleManager.get_default() dark = style_manager.get_dark() sepia = theme.name == "sepia" hc = style_manager.get_high_contrast() if not self.windows: return if sepia: if hc: self.style_provider.load_from_file(theme.gtk_css_hc) else: self.style_provider.load_from_file(theme.gtk_css) elif dark: if hc: self.style_provider.load_from_file(Theme.get_for_name("dark").gtk_css_hc) else: self.style_provider.load_from_file(Theme.get_for_name("dark").gtk_css) else: if hc: self.style_provider.load_from_file(Theme.get_for_name("light").gtk_css_hc) else: self.style_provider.load_from_file(Theme.get_for_name("light").gtk_css) def on_settings_changed(self, settings, key): # TODO: change this ffs if not self.windows: return if key == "color-scheme": self._set_color_scheme() elif key == "input-format": for window in self.windows: window.reload_preview() elif key == "sync-scroll": for window in self.windows: window.reload_preview(reshow=True) elif key == "stat-default": for window in self.windows: window.update_default_stat() def on_new_window(self, _action, _value): window = MainWindow(self) window.present() self.windows.append(window) def on_preferences(self, _action, _value): preferences_dialog = ApostrophePreferencesDialog() preferences_dialog.set_transient_for(self.get_active_window()) preferences_dialog.show() def on_shortcuts(self, _action, _param): builder = Gtk.Builder() builder.add_from_resource( "/org/gnome/gitlab/somas/Apostrophe/ui/Shortcuts.ui") builder.get_object("shortcuts").set_transient_for(self.get_active_window()) builder.get_object("shortcuts").show() def on_about(self, _action, _param): # TODO: what about non-csd builder = Gtk.Builder() builder.add_from_resource( "/org/gnome/gitlab/somas/Apostrophe/About.ui") about_dialog = builder.get_object("AboutDialog") about_dialog.set_transient_for(self.get_active_window()) about_dialog.present() def on_quit(self, _action, _param): quit = True for window in self.windows: window.present() if window.on_delete_called(self): quit = False if quit: self.quit() def on_stat_default(self, action, value): action.set_state(value) self.settings.set_string("stat-default", value.get_string()) apostrophe-v2.6.3/apostrophe/export_dialog.py000066400000000000000000000352371423304411100214750ustar00rootroot00000000000000# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- # BEGIN LICENSE # Copyright (C) 2019, Wolf Vollprecht # 2021, Manuel Genovés # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 . # END LICENSE """Manages all the export operations and dialogs """ # pylint: disable=no-member import logging import os from gettext import gettext as _ from zipfile import ZipFile import json import gi gi.require_version('Gtk', '3.0') gi.require_version('Handy', '1') from gi.repository import Gtk, Gdk, Gio, GObject, Handy from apostrophe import helpers from apostrophe.theme_switcher import Theme LOGGER = logging.getLogger('apostrophe') class Format(GObject.Object): def __init__(self, name, ext, to, **kwargs): super().__init__(**kwargs) self.name: str = name self.ext: str = ext self.to: str = to @property def has_pages(self): return self.to in {"pdf", "odt", "docx"} @property def is_html(self): return self.to == "html5" @property def has_syntax(self): return self.ext in {"html", "tex", "docx", "pdf"} @property def is_presentation(self): return self.to in {"beamer", "revealjs", "dzslides"} @property def requires_texlive(self): return self.ext in {"tex", "pdf"} class ExportDialog: __gtype_name__ = "ExportDialog" formats = { "pdf": { "name": "PDF", "extension": "pdf", "to": "pdf", "mimetype": "application/pdf", "args": ["--pdf-engine=xelatex", "--variable=papersize:a4"] }, "html": { "name": "HTML", "extension": "html", "to": "html5", "mimetype": "text/html", "args": ["--self-contained", "--css=%s" % Theme.get_current().web_css, "--mathjax", "--lua-filter=%s" % helpers.get_media_path('/lua/relative_to_absolute.lua'), "--lua-filter=%s" % helpers.get_media_path('/lua/task-list.lua')] }, "odt": { "name": "ODT", "extension": "odt", "to": "odt", "mimetype": "application/vnd.oasis.opendocument.text", "args": ["--variable=papersize:a4"] } } def __init__(self, file, _format, text): self.format = _format self.text = text self._show_texlive_warning = (self.format == "pdf" and not helpers.exist_executable("pdftex")) if (self._show_texlive_warning): self.dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT, Gtk.MessageType.ERROR, Gtk.ButtonsType.CLOSE ) self.dialog.get_message_area().add(TexliveWarning()) else: self.dialog = Gtk.FileChooserNative.new( _("Export"), None, Gtk.FileChooserAction.SAVE, _("Export to %s") % self.formats[self.format]["name"], _("Cancel")) dialog_filter = Gtk.FileFilter.new() dialog_filter.set_name(self.formats[self.format]["name"]) dialog_filter.add_mime_type(self.formats[self.format]["mimetype"]) self.dialog.add_filter(dialog_filter) self.dialog.set_do_overwrite_confirmation(True) self.dialog.set_current_name( file.name + '.' + self.formats[self.format]["extension"]) def export(self): response = self.dialog.run() if not self._show_texlive_warning: file = self.dialog.get_file() fmt = self.formats[self.format]["to"] args = self.formats[self.format]["args"] if response == Gtk.ResponseType.ACCEPT: try: export(self.text, file, fmt, args) except (NotADirectoryError, RuntimeError) as e: helpers.show_error( None, _("An error happened while trying to export:\n\n" "{err_msg}") .format(err_msg=str(e).encode() .decode("unicode-escape"))) self.dialog.destroy() @Gtk.Template(resource_path='/org/gnome/gitlab/somas/Apostrophe/ui/Export.ui') class AdvancedExportDialog(Handy.Window): __gtype_name__ = "AdvancedExportDialog" headerbar = Gtk.Template.Child() formats_list = Gtk.Template.Child() leaflet = Gtk.Template.Child() options_page = Gtk.Template.Child() formats_page = Gtk.Template.Child() # #### --option properties-- ##### sw_standalone = Gtk.Template.Child() sw_toc = Gtk.Template.Child() sw_numbers = Gtk.Template.Child() cmb_page_size = Gtk.Template.Child() sw_self_contained = Gtk.Template.Child() sw_syntax_highlighting = Gtk.Template.Child() cmb_syntax_highlighting = Gtk.Template.Child() sw_incremental_bullets = Gtk.Template.Child() # #### ---------------------- ##### formats = Gio.ListStore.new(Format) page_sizes = ['A4', 'Letter'] syntax_styles = ['pygments', 'kate', 'monochrome', 'espresso', 'zenburn', 'haddock', 'tango'] def __init__(self, file, text, **kwargs): super().__init__(**kwargs) self.file = file self.text = text if not self.formats: with open(helpers.get_media_path("/media/formats.json")) as f: _formats_list = json.load(f) for _i, format in enumerate(_formats_list): self.formats.append(Format(format["name"], format["ext"], format["to"])) self.formats_list.bind_model(self.formats, self.row_constructor, None) self.formats_list.select_row(self.formats_list.get_row_at_index(0)) page_sizes_list = helpers.liststore_from_list(self.page_sizes) self.cmb_page_size.bind_name_model(page_sizes_list, self.get_hdy_name, None, None) syntax_styles_list = helpers.liststore_from_list(self.syntax_styles) self.cmb_syntax_highlighting.bind_name_model(syntax_styles_list, self.get_hdy_name, None, None) @GObject.Property(type=str) def title(self): name = self.formats_list.get_selected_row().item.name return _("Export to {}").format(name) @GObject.Property(type=bool, default=False) def show_page_size_options(self): return self.formats_list.get_selected_row().item.has_pages @GObject.Property(type=bool, default=False) def show_html_options(self): return self.formats_list.get_selected_row().item.is_html @GObject.Property(type=bool, default=False) def show_syntax_options(self): return self.formats_list.get_selected_row().item.has_syntax @GObject.Property(type=bool, default=False) def show_presentation_options(self): return self.formats_list.get_selected_row().item.is_presentation @GObject.Property(type=bool, default=False) def show_texlive_warning(self): is_tex = self.formats_list.get_selected_row().item.requires_texlive texlive_installed = helpers.exist_executable("pdftex") return is_tex and not texlive_installed @GObject.Property(type=bool, default=False) def show_go_back_button(self): folded = self.leaflet.props.folded on_options_page = (self.leaflet.get_visible_child() == self.options_page) return folded and on_options_page @GObject.Property(type=str, default="options") def options_page_name(self): name = "texlive_warning" if self.show_texlive_warning else "options" return name @GObject.Property(type=bool, default=False) def exports_multiple_files(self): return self.formats_list.get_selected_row().item.to == "revealjs" def row_constructor(self, item, _user_data): row = Handy.ActionRow.new() row.item = item row.set_title(item.name) return row def get_hdy_name(self, item, _user_data, _user_data_free): return item.dup_string() def get_hdy_comborow_name(self, hdy_cmbrow): model = hdy_cmbrow.get_model() index = hdy_cmbrow.get_selected_index() item = model.get_item(index) return item.dup_string() @Gtk.Template.Callback() def reveal_go_back(self, _widget, *args): self.notify("show_go_back_button") @Gtk.Template.Callback() def go_back(self, _widget): self.leaflet.set_visible_child(self.formats_page) @Gtk.Template.Callback() def on_format_selected(self, _widget, _row): self.leaflet.set_visible_child(self.options_page) self.notify("show_page_size_options") self.notify("show_html_options") self.notify("show_syntax_options") self.notify("show_presentation_options") self.notify("show_texlive_warning") self.notify("options_page_name") self.notify("title") @Gtk.Template.Callback() def on_destroy(self, _widget): self.destroy() @Gtk.Template.Callback() def export(self, widget): self.retrieve_args() if self.exports_multiple_files: export_dialog = Gtk.FileChooserNative.new( _("Export"), None, Gtk.FileChooserAction.SELECT_FOLDER, _("Select folder"), _("Cancel")) else: export_dialog = Gtk.FileChooserNative.new( _("Export"), None, Gtk.FileChooserAction.SAVE, _("Export to %s") % self.formats_list.get_selected_row().item.name, _("Cancel")) export_dialog.set_current_name( self.file.name + '.' + self.formats_list.get_selected_row().item.ext) export_dialog.set_transient_for(self) export_dialog.set_do_overwrite_confirmation(True) response = export_dialog.run() if self.exports_multiple_files: folder = export_dialog.get_file() with ZipFile(helpers.get_media_path("/media/reveal.js.zip"), "r") as zipObj: zipObj.extractall(folder.get_path()) export_file = folder.get_child(self.file.name + '.' + self.formats_list.get_selected_row().item.ext) else: export_file = export_dialog.get_file() fmt = self.formats_list.get_selected_row().item.to args = self.retrieve_args() if response == Gtk.ResponseType.ACCEPT: try: export(self.text, export_file, fmt, args) except (NotADirectoryError, RuntimeError) as e: helpers.show_error( None, _("An error happened while trying to export:\n\n{err_msg}") .format(err_msg=str(e).encode().decode("unicode-escape"))) export_dialog.destroy() self.destroy() def retrieve_args(self): args = [] if self.formats_list.get_selected_row().item.ext == "pdf": args.append("--pdf-engine=xelatex") if self.sw_standalone.get_active(): args.append("--standalone") if self.sw_toc.get_active(): args.append("--toc") if self.sw_numbers.get_active(): args.append("--number-sections") if (self.show_page_size_options and self.cmb_page_size.get_selected_index() == 0): if ((fmt := self.formats_list.get_selected_row().item.to) in {"pdf", "latex", "context"}): args.append("--variable=papersize:a4") elif fmt in ("odt", "docx"): args.append("--reference-doc=" + helpers.get_media_path( "/reference_files/reference-a4." + fmt)) if self.show_html_options: args.append("--css=%s" % Theme.get_current().web_css) args.append("--mathjax") args.append("--lua-filter=%s" % helpers.get_media_path( '/lua/relative_to_absolute.lua')) args.append("--lua-filter=%s" % helpers.get_media_path( '/lua/task-list.lua')) if self.sw_self_contained.get_active(): args.append("--self-contained") if self.show_syntax_options: if self.sw_syntax_highlighting.get_enable_expansion(): selected_style = self.get_hdy_comborow_name( self.cmb_syntax_highlighting) args.append("--highlight-style={}".format(selected_style)) if self.show_presentation_options: if self.sw_incremental_bullets.get_active(): args.append("--incremental") if self.formats_list.get_selected_row().item.to == "revealjs": args.extend(["-V", "revealjs-url=reveal.js"]) return args @Gtk.Template(resource_path='/org/gnome/gitlab/somas/Apostrophe/ui/TexliveWarning.ui') class TexliveWarning(Gtk.Stack): __gtype_name__ = 'TexliveWarning' command = Gtk.Template.Child() def __init__(self): super().__init__() child_name = "flatpak" if os.path.isfile("/.flatpak-info") else "distro" self.set_visible_child_name(child_name) @Gtk.Template.Callback() def copy(self, _widget): cb = Gtk.Clipboard.get_default(Gdk.Display.get_default()) cb.set_text(self.command.get_text(), -1) def export(text, file, _format, args): """Export the given text using the specified format. For advanced export, this includes special flags for the enabled options. Keyword Arguments: text {str} -- Text to export (default: {""}) """ to = _format helpers.pandoc_convert( text, to=to, args=args, outputfile=file.get_path()) apostrophe-v2.6.3/apostrophe/fix_table.py000066400000000000000000000151561423304411100205700ustar00rootroot00000000000000import re import gi gi.require_version('Gtk', '3.0') import logging logger = logging.getLogger('apostrophe') class FixTable(): def __init__(self, TextBuffer): self.TextBuffer = TextBuffer @staticmethod def create_seperator(widths, char): """ Generate a line of + and - as sepeartor Example: >>> create_separarator([2, 4], '-') '+----+------+' """ line = [] for w in widths: line.append("+" + char * (w + 2)) line.append("+") return ''.join(line) @staticmethod def create_line(columns, widths): """ Crea una fila de la tabla separando los campos con un '|'. El argumento `columns` es una lista con las celdas que se quieren imprimir y el argumento `widths` tiene el ancho de cada columna. Si la columna es mas ancha que el texto a imprimir se agregan espacios vacíos. Example >>> create_line(['nombre', 'apellido'], [7, 10]) '| nombre | apellido |' """ line = zip(columns, widths) result = [] for text, width in line: spaces = " " * (width - len(text)) text = "| " + text + spaces + " " result.append(text) result.append("|") return ''.join(result) @staticmethod def create_table(content): """Imprime una tabla en formato restructuredText. El argumento `content` tiene que ser una lista de celdas. Example: >>> print create_table([['software', 'vesion'], ['python', '3.2'], ['vim', '7.3']]) +----------+--------+ | software | vesion | +==========+========+ | python | 3.2 | +----------+--------+ | vim | 7.3 | +----------+--------+ """ # obtiene las columnas de toda la tabla. columns = zip(*content) # calcula el tamano maximo que debe tener cada columna. # replace with len() widths = [max([len(x) for x in i]) for i in columns] result = [] result.append(FixTable.create_seperator(widths, '-')) print(content, widths) result.append(FixTable.create_line(content[0], widths)) result.append(FixTable.create_seperator(widths, '=')) for line in content[1:]: result.append(FixTable.create_line(line, widths)) result.append(FixTable.create_seperator(widths, '-')) return '\n'.join(result) @staticmethod def are_in_a_table(current_line): "Line in a table?" return "|" in current_line or "+" in current_line @staticmethod def are_in_a_paragraph(current_line): "Line in a paragraph?" return len(current_line.strip()) >= 1 def get_table_bounds(self, are_in_callback): """ Gets the row number where the table begins and ends. are_in_callback argument must be a function                 indicating whether a particular line belongs or not                 to the table to be measured (or create).                 Returns two values ​​as a tuple """ top = 0 buf = self.TextBuffer start_iter = buf.get_start_iter() end_iter = buf.get_end_iter() text = self.TextBuffer.get_text( start_iter, end_iter, False).split('\n') logger.debug(text) length = len(text) bottom = length - 1 insert_mark = self.TextBuffer.get_insert() insert_iter = self.TextBuffer.get_iter_at_mark(insert_mark) current_row_index = insert_iter.get_line() for a in range(current_row_index, top, -1): if not are_in_callback(text[a]): top = a + 1 break for b in range(current_row_index, length): if not are_in_callback(text[b]): bottom = b - 1 break return top, bottom @staticmethod def remove_spaces(string): """Remove unnecessary spaces""" return re.sub("\\s\\s+", " ", string) @staticmethod def create_separators_removing_spaces(string): return re.sub("\\s\\s+", "|", string) @staticmethod def extract_cells_as_list(string): "Extrae el texto de una fila de tabla y lo retorna como una lista." string = FixTable.remove_spaces(string) return [item.strip() for item in string.split('|') if item] @staticmethod def extract_table(text, top, bottom): full_table_text = text[top:bottom] # selecciona solamente las lineas que tienen celdas con texto. only_text_lines = [x for x in full_table_text if '|' in x] # extrae las celdas y descarta los separadores innecesarios. return [FixTable.extract_cells_as_list(x) for x in only_text_lines] @staticmethod def extract_words_as_lists(text, top, bottom): "Genera una lista de palabras para crear una lista." lines = text[top:bottom + 1] return [FixTable.create_separators_removing_spaces( line).split('|') for line in lines] def fix_table(self): """ Fix Table, so all columns have the same width (again) `initial_row` is a int idicationg the current row index """ cursor_mark = self.TextBuffer.get_insert() cursor_iter = self.TextBuffer.get_iter_at_mark(cursor_mark) cursor_iter.set_line(cursor_iter.get_line()) end_line = cursor_iter.copy() end_line.forward_to_line_end() line_text = self.TextBuffer.get_text(cursor_iter, end_line, False) if FixTable.are_in_a_table(line_text): # obtiene el indice donde comienza y termina la tabla. r1, r2 = self.get_table_bounds(FixTable.are_in_a_table) logger.debug('asdasd ') # extrae de la tabla solo las celdas de texto buf = self.TextBuffer start_iter = buf.get_start_iter() end_iter = buf.get_end_iter() text = self.TextBuffer.get_text( start_iter, end_iter, False).split('\n') table_as_list = FixTable.extract_table(text, r1, r2) logger.debug(table_as_list) # genera una nueva tabla tipo restructured text y la dibuja en el # buffer. table_content = FixTable.create_table(table_as_list) logger.debug(table_content) # Insert table back into Buffer ... self.TextBuffer.insert(start_iter, table_content, -1) else: logger.debug("Not in a table") print("Not in table") apostrophe-v2.6.3/apostrophe/headerbars.py000066400000000000000000000046311423304411100207270ustar00rootroot00000000000000# Copyright (C) 2022, Manuel Genovés # 2019, Wolf Vollprecht # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 . # END LICENSE """Manage all the headerbars related stuff """ import gi from gettext import gettext as _ gi.require_version('Gtk', '3.0') from gi.repository import Gtk, GLib, GObject, Handy from .settings import Settings from .theme_switcher import ThemeSwitcher from .preview_layout_switcher import PreviewLayoutSwitcher from .open_popover import ApostropheOpenPopover @Gtk.Template(resource_path='/org/gnome/gitlab/somas/Apostrophe/ui/Headerbar.ui') class BaseHeaderbar(Gtk.Revealer): __gtype_name__ = "BaseHeaderbar" """Base class for all headerbars """ headerbar = Gtk.Template.Child() tutorial_button = Gtk.Template.Child() preview_layout_switcher = Gtk.Template.Child() is_fullscreen = GObject.property(type=bool, default=False) title = GObject.Property(type=str) subtitle = GObject.Property(type=str) @GObject.Property(type=int) def allocated_height(self): return self.get_allocated_height() def __init__(self, **kwargs): super().__init__(**kwargs) self.bind_property("is-fullscreen", self.headerbar, "show-close-button", 6) tutorial = GLib.Variant.new_string("resource:///org/gnome/gitlab/somas/" "Apostrophe/media/apostrophe_markdown.md") self.tutorial_button.set_action_target_value(tutorial) self.settings = Settings.new() #self.select_preview_layout_row() @Gtk.Template.Callback() def on_show_hide(self, widget, event): ''' The crossfade animation doesn't hide the alocated space for the headerbar. This prevents having an empty space there ''' if not self.get_child_revealed(): self.set_visible(False) apostrophe-v2.6.3/apostrophe/helpers.py000066400000000000000000000073201423304411100202670ustar00rootroot00000000000000# Copyright (C) 2022, Manuel Genovés # 2019, Wolf Vollprecht # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 . # END LICENSE """Helpers for the application.""" import logging import os import shutil from contextlib import contextmanager from typing import List from gettext import gettext as _ import gi import pypandoc from gi.overrides.Pango import Pango gi.require_version('Gtk', '3.0') gi.require_version('Handy', '1') from gi.repository import Gtk, Gio, Handy # pylint: disable=E0611 from apostrophe.settings import Settings from apostrophe import config __apostrophe_data_directory__ = '../data/' App = Gio.Application.get_default @contextmanager def user_action(text_buffer): text_buffer.begin_user_action() yield text_buffer text_buffer.end_user_action() def get_media_path(path): """Return the full path of a given path under the media dir (doesn't start with file:///) """ media_path = "{}{}".format(config.PKGDATA_DIR, path) if not os.path.exists(media_path): media_path = None return media_path class NullHandler(logging.Handler): def emit(self, _record): pass def set_up_logging(level): # add a handler to prevent basicConfig root = logging.getLogger() null_handler = NullHandler() root.addHandler(null_handler) formatter = logging.Formatter( "%(levelname)s:%(name)s: %(funcName)s() '%(message)s'") logger = logging.getLogger('apostrophe') logger_sh = logging.StreamHandler() logger_sh.setFormatter(formatter) logger.addHandler(logger_sh) # Set the logging level to show debug messages. if level == 1: logger.setLevel(logging.DEBUG) logger.debug('logging enabled') def show_error(parent, message): dialog = Gtk.MessageDialog( parent, Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT, Gtk.MessageType.ERROR, Gtk.ButtonsType.CLOSE, message) dialog.set_title(_("Error")) dialog.run() dialog.destroy() def exist_executable(command): """return if a command can be executed in the SO Arguments: command {str} -- a command Returns: {bool} -- if the given command exists in the system """ return shutil.which(command) is not None def liststore_from_list(str_list: List[str]): """return a Gtk.ListStore object of Handy.TypeValues constructed after a list of strings Arguments: str_list {List[str]} -- a list of strings Returns: {Gtk.ListStore} -- a ListStore of Handy.ValueObjects """ list_store = Gio.ListStore.new(Handy.ValueObject) for element in str_list: obj = Handy.ValueObject.new(element) list_store.append(obj) return list_store def get_char_width(widget): return Pango.units_to_double( widget.get_pango_context().get_metrics().get_approximate_char_width()) def pandoc_convert(text, to="html5", args=[], outputfile=None): fr = Settings.new().get_value('input-format').get_string() or "markdown" # args.extend(["--quiet"]) return pypandoc.convert_text( text, to, fr, extra_args=args, outputfile=outputfile) apostrophe-v2.6.3/apostrophe/inhibitor.py000066400000000000000000000026551423304411100206220ustar00rootroot00000000000000# Copyright (C) 2022 Manuel Genovés # Copyright (C) 2017 Jason Gray # Copyright (C) 2017 Franz Dietrich # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 . # END LICENSE from gettext import gettext as _ from apostrophe.helpers import App class Inhibitor: def __init__(self): self.__cookie = 0 def inhibit(self, flags): """ Disable flags @param flags as Gtk.ApplicationInhibitFlags """ if not self.__cookie: self.__cookie = App().inhibit( App().get_active_window(), flags, _("Unsaved documents")) def uninhibit(self): """ Remove all the powermanagement settings """ if self.__cookie: App().uninhibit(self.__cookie) self.__cookie = 0 apostrophe-v2.6.3/apostrophe/inline_preview.py000066400000000000000000000307301423304411100216450ustar00rootroot00000000000000# Copyright (C) 2022, Manuel Genovés # 2019, Wolf Vollprecht # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 . # END LICENSE import re import os import telnetlib from gettext import gettext as _ from urllib.parse import unquote import gi gi.require_version("Gtk", "3.0") gi.require_version("WebKit2", "4.0") from gi.repository import Gtk, Gdk, GdkPixbuf, GLib from gi.repository import WebKit2 from apostrophe import latex_to_PNG, markup_regex from apostrophe.settings import Settings class DictAccessor: reEndResponse = re.compile(br"^[2-5][0-58][0-9] .*\r\n$", re.DOTALL + re.MULTILINE) reDefinition = re.compile(br"^151(.*?)^\.", re.DOTALL + re.MULTILINE) def __init__(self, host="dict.dict.org", port=2628, timeout=60): self.telnet = telnetlib.Telnet(host, port) self.timeout = timeout self.login_response = self.telnet.expect([self.reEndResponse], self.timeout)[2] def run_command(self, cmd): self.telnet.write(cmd.encode("utf-8") + b"\r\n") return self.telnet.expect([self.reEndResponse], self.timeout)[2] def get_matches(self, database, strategy, word): if database in ["", "all"]: d = "*" else: d = database if strategy in ["", "default"]: s = "." else: s = strategy w = word.replace("\"", r"\\\"") tsplit = self.run_command( "MATCH {} {} \"{}\"".format( d, s, w)).splitlines() mlist = list() if tsplit[-1].startswith(b"250 ok") and tsplit[0].startswith(b"1"): mlines = tsplit[1:-2] for line in mlines: lsplit = line.strip().split() db = lsplit[0] word = unquote(" ".join(lsplit[1:])) mlist.append((db, word)) return mlist def get_definition(self, database, word): if database in ["", "all"]: d = "*" else: d = database w = word.replace("\"", r"\\\"") dsplit = self.run_command( "DEFINE {} \"{}\"".format( d, w)).splitlines(True) dlist = list() if dsplit[-1].startswith(b"250 ok") and dsplit[0].startswith(b"1"): dlines = dsplit[1:-1] dtext = b"".join(dlines) dlist = [dtext] return dlist def close(self): t = self.run_command("QUIT") self.telnet.close() return t def parse_wordnet(self, response): # consisting of group (n,v,adj,adv) # number, description, examples, synonyms, antonyms lines = response.splitlines() lines = lines[2:] lines = " ".join(lines) lines = re.sub(r"\s+", " ", lines).strip() lines = re.split(r"( adv | adj | n | v |^adv |^adj |^n |^v )", lines) res = [] act_res = {"defs": [], "class": "none", "num": "None"} for l in lines: l = l.strip() if not l: continue if l in ["adv", "adj", "n", "v"]: if act_res: res.append(act_res.copy()) act_res = {"defs": [], "class": l} else: ll = re.split(r"(?: |^)(\d): ", l) act_def = {} for lll in ll: if lll.strip().isdigit() or not lll.strip(): if "description" in act_def and act_def["description"]: act_res["defs"].append(act_def.copy()) act_def = {"num": lll} continue a = re.findall(r"(\[(syn|ant): (.+?)\] ??)+", lll) for n in a: if n[1] == "syn": act_def["syn"] = re.findall(r"{(.*?)}.*?", n[2]) else: act_def["ant"] = re.findall(r"{(.*?)}.*?", n[2]) tbr = re.search(r"\[.+\]", lll) if tbr: lll = lll[:tbr.start()] lll = lll.split(";") act_def["examples"] = [] act_def["description"] = [] for llll in lll: llll = llll.strip() if llll.strip().startswith("\""): act_def["examples"].append(llll) else: act_def["description"].append(llll) if act_def and "description" in act_def: act_res["defs"].append(act_def.copy()) res.append(act_res.copy()) return res def get_dictionary(term): da = DictAccessor() output = da.get_definition("wn", term) if output: output = output[0] else: return None return da.parse_wordnet(output.decode(encoding="UTF-8")) class InlinePreview: WIDTH = 400 HEIGHT = 300 def __init__(self, text_view): self.settings = Settings.new() self.text_view = text_view self.text_view.connect("button-press-event", self.on_button_press_event) self.text_buffer = text_view.get_buffer() self.cursor_mark = self.text_buffer.create_mark( "click", self.text_buffer.get_iter_at_mark(self.text_buffer.get_insert())) self.latex_converter = latex_to_PNG.LatexToPNG() self.characters_per_line = self.settings.get_int("characters-per-line") self.popover = Gtk.Popover.new(self.text_view) self.popover.get_style_context().add_class("quick-preview-popup") self.popover.set_modal(True) self.preview_fns = { markup_regex.MATH: self.get_view_for_math, markup_regex.IMAGE: self.get_view_for_image, markup_regex.LINK: self.get_view_for_link, markup_regex.LINK_ALT: self.get_view_for_link, markup_regex.FOOTNOTE_ID: self.get_view_for_footnote, re.compile(r"(?P\w+)"): self.get_view_for_lexikon } def on_button_press_event(self, _text_view, event): if event.button == 1 and event.state & Gdk.ModifierType.CONTROL_MASK: x, y = self.text_view.window_to_buffer_coords(2, int(event.x), int(event.y)) self.text_buffer.move_mark( self.cursor_mark, self.text_view.get_iter_at_location(x, y).iter) self.open_popover(self.text_view) def get_view_for_math(self, match): success, result = self.latex_converter.generatepng(match.group("text")) if success: return Gtk.Image.new_from_file(result) else: error = _("Formula looks incorrect:") error += "\n\n“{}”".format(result) return Gtk.Label(label=error) def get_view_for_image(self, match): path = match.group("url") if path.startswith(("https://", "http://", "www.")): return self.get_view_for_link(match) if path.startswith(("file://")): path = path[7:] if not path.startswith(("/", "file://")): path = os.path.join( self.settings.get_string("open-file-path"), path) path = unquote(path) return Gtk.Image.new_from_pixbuf( GdkPixbuf.Pixbuf.new_from_file_at_size(path, self.WIDTH, self.HEIGHT)) def get_view_for_link(self, match): url = match.group("url") web_view = WebKit2.WebView(zoom_level=0.3125) # ~1280x960 web_view.set_size_request(self.WIDTH, self.HEIGHT) if GLib.uri_parse_scheme(url) is None: url = "http://{}".format(url) web_view.load_uri(url) return web_view def get_view_for_footnote(self, match): footnote_id = match.group("id") fn_matches = re.finditer( markup_regex.FOOTNOTE, self.text_buffer.props.text) for fn_match in fn_matches: if fn_match.group("id") == footnote_id: if fn_match: footnote = re.sub("\n[\t ]+", "\n", fn_match.group("text")) else: footnote = _("No matching footnote found") label = Gtk.Label(label=footnote) label.set_max_width_chars(self.characters_per_line) label.set_line_wrap(True) return label return None def get_view_for_lexikon(self, match): term = match.group("text") lexikon_dict = get_dictionary(term) if lexikon_dict: grid = Gtk.Grid.new() grid.get_style_context().add_class("lexikon") grid.set_row_spacing(2) grid.set_column_spacing(4) i = 0 for entry in lexikon_dict: if not entry["defs"]: continue elif entry["class"].startswith("n"): word_type = _("noun") elif entry["class"].startswith("v"): word_type = _("verb") elif entry["class"].startswith("adj"): word_type = _("adjective") elif entry["class"].startswith("adv"): word_type = _("adverb") else: continue vocab_label = Gtk.Label.new(term + " ~ " + word_type) vocab_label.get_style_context().add_class("header") if i == 0: vocab_label.get_style_context().add_class("first") vocab_label.set_halign(Gtk.Align.START) vocab_label.set_justify(Gtk.Justification.LEFT) grid.attach(vocab_label, 0, i, 3, 1) for definition in entry["defs"]: i = i + 1 num_label = Gtk.Label.new(definition["num"] + ".") num_label.get_style_context().add_class("number") num_label.set_valign(Gtk.Align.START) grid.attach(num_label, 0, i, 1, 1) def_label = Gtk.Label( label=" ".join( definition["description"])) def_label.get_style_context().add_class("description") def_label.set_halign(Gtk.Align.START) def_label.set_max_width_chars(self.characters_per_line) def_label.set_line_wrap(True) def_label.set_justify(Gtk.Justification.FILL) grid.attach(def_label, 1, i, 1, 1) i = i + 1 if i > 0: return grid return None def open_popover(self, _editor, _data=None): start_iter = self.text_buffer.get_iter_at_mark(self.cursor_mark) line_offset = start_iter.get_line_offset() end_iter = start_iter.copy() start_iter.set_line_offset(0) end_iter.forward_to_line_end() text = self.text_buffer.get_text(start_iter, end_iter, False) for regex, get_view_fn in self.preview_fns.items(): matches = re.finditer(regex, text) for match in matches: if match.start() <= line_offset <= match.end(): prev_view = self.popover.get_child() if prev_view: prev_view.destroy() view = get_view_fn(match) if view: view.show_all() self.popover.add(view) rect = self.text_view.get_iter_location( self.text_buffer.get_iter_at_mark(self.cursor_mark)) rect.x, rect.y = self.text_view.buffer_to_window_coords( Gtk.TextWindowType.TEXT, rect.x, rect.y) self.popover.set_pointing_to(rect) GLib.idle_add(self.popover.popup) return apostrophe-v2.6.3/apostrophe/latex_to_PNG.py000066400000000000000000000106421423304411100211510ustar00rootroot00000000000000# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- """ Based on latex2png.py from Stuart Rackham AUTHOR Written by Stuart Rackham, The code was inspired by Kjell Magne Fauske"s code: http://fauskes.net/nb/htmleqII/ See also: http://www.amk.ca/python/code/mt-math http://code.google.com/p/latexmath2png/ COPYING Copyright (C) 2010 Stuart Rackham. Free use of this software is granted under the terms of the MIT License. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import os import subprocess import tempfile class LatexToPNG: TEX_HEADER = r"""\documentclass{article} \usepackage{amsmath} \usepackage{amsthm} \usepackage{amssymb} \usepackage{bm} \newcommand{\mx}[1]{\mathbf{\bm{#1}}} % Matrix command \newcommand{\vc}[1]{\mathbf{\bm{#1}}} % Vector command \newcommand{\T}{\text{T}} % Transpose \pagestyle{empty} \begin{document}""" TEX_FOOTER = r"""\end{document}""" def __init__(self): self.temp_result = tempfile.NamedTemporaryFile(suffix=".png") def latex2png(self, tex, outfile, dpi, modified): """Convert LaTeX input file infile to PNG file named outfile.""" outfile = os.path.abspath(outfile) outdir = os.path.dirname(outfile) texfile = tempfile.mktemp(suffix=".tex", dir=os.path.dirname(outfile)) basefile = os.path.splitext(texfile)[0] dvifile = basefile + ".dvi" temps = [basefile + ext for ext in (".tex", ".dvi", ".aux", ".log")] skip = False tex = "{}\n{}\n{}\n".format(self.TEX_HEADER, tex.strip(), self.TEX_FOOTER) open(texfile, "w").write(tex) saved_pwd = os.getcwd() os.chdir(outdir) args = ["latex", "-halt-on-error", texfile] p = subprocess.Popen(args, stderr=subprocess.STDOUT, stdout=subprocess.PIPE) output = p.stdout output_lines = output.readlines() if os.path.isfile(dvifile): # DVI File exists # Convert DVI file to PNG. args = ["dvipng", "-D", str(dpi), "-T", "tight", "-x", "1000", "-z", "9", "-bg", "Transparent", "-o", outfile, dvifile] p = subprocess.Popen(args) p.communicate() else: self.clean_up(temps) """ Errors in Latex output start with "! " Stripping exclamation marks and superflous newlines and telling the user what he"s done wrong. """ i = [] error = "" for line in output_lines: line = line.decode("utf-8") if line.startswith("!"): error += line[2:] # removing "! " if error.endswith("\n"): error = error[:-1] raise Exception(error) def generatepng(self, formula): try: self.temp_result = tempfile.NamedTemporaryFile(suffix=".png") formula = "$" + formula + "$" self.latex2png(formula, self.temp_result.name, 300, False) return True, self.temp_result.name except Exception as e: self.temp_result.close() return False, e.args[0] def clean_up(self, files): for f in files: if os.path.isfile(f): os.remove(f) apostrophe-v2.6.3/apostrophe/main_window.py000066400000000000000000000615271423304411100211510ustar00rootroot00000000000000# Copyright (C) 2022, Manuel Genovés # 2019, Wolf Vollprecht # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 . # END LICENSE import logging import os from gettext import gettext as _ from dataclasses import dataclass import chardet import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, Gdk, GObject, GLib, Gio, Handy from apostrophe.export_dialog import ExportDialog, AdvancedExportDialog from apostrophe.preview_handler import PreviewHandler from apostrophe.stats_handler import StatsHandler from apostrophe.text_view import ApostropheTextView from apostrophe.search_and_replace import ApostropheSearchBar from apostrophe.settings import Settings from apostrophe.tweener import Tweener from apostrophe.helpers import App from apostrophe import helpers from .headerbars import BaseHeaderbar LOGGER = logging.getLogger('apostrophe') @Gtk.Template(resource_path='/org/gnome/gitlab/somas/Apostrophe/ui/Window.ui') class MainWindow(Handy.ApplicationWindow): __gtype_name__ = "ApostropheWindow" editor_scrolledwindow = Gtk.Template.Child() save_progressbar = Gtk.Template.Child() headerbar = Gtk.Template.Child() headerbar_eventbox = Gtk.Template.Child() searchbar = Gtk.Template.Child() stats_revealer = Gtk.Template.Child() stats_button = Gtk.Template.Child() flap = Gtk.Template.Child() # TODO ?? preview_stack = Gtk.Template.Child() text_view = Gtk.Template.Child() editor = Gtk.Template.Child() subtitle = GObject.Property(type=str) is_fullscreen = GObject.Property(type=bool, default=False) headerbar_visible = GObject.Property(type=bool, default=True) bottombar_visible = GObject.Property(type=bool, default=True) preview = GObject.Property(type=bool, default=False) preview_layout = GObject.Property(type=int, default=1) did_change = GObject.Property(type=bool, default=False) def __init__(self, app): """Set up the main window""" super().__init__(application=Gio.Application.get_default(), title="Apostrophe") #TODO: size # Preferences self.settings = Settings.new() # Create new, empty file # TODO: load last opened file? self.current = File() # Setup text editor self.text_view.get_buffer().connect('changed', self.on_text_changed) self.text_view.grab_focus() # Setup save progressbar an its animator self.progressbar_initiate_tw = Tweener(self.save_progressbar, self.save_progressbar.set_fraction, 0, 0.125, 40) self.progressbar_finalize_tw = Tweener(self.save_progressbar, self.save_progressbar.set_fraction, 0.125, 1, 400) self.progressbar_opacity_tw = Tweener(self.save_progressbar, self.save_progressbar.set_opacity, 1, 0, 300, 200, callback = self.save_progressbar.set_visible, callback_arg = False) # Setup stats counter self.stats_handler = StatsHandler(self.stats_button, self.text_view) # Setup preview self.preview_handler = PreviewHandler(self, self.text_view, self.flap) # Setting up spellcheck self.settings.bind("spellcheck", self.text_view, "spellcheck", Gio.SettingsBindFlags.GET) # Setting up text size self.settings.bind("bigger-text", self.text_view, "bigger_text", Gio.SettingsBindFlags.GET) self.settings.bind("characters-per-line", self.text_view, "line_chars", Gio.SettingsBindFlags.GET) # Search and replace initialization self.searchbar.attach(self.text_view) # Actions action = Gio.PropertyAction.new("find", self.searchbar, "search-mode-enabled") self.add_action(action) action = Gio.PropertyAction.new("find_replace", self.searchbar, "replace-mode-enabled") self.add_action(action) action = Gio.PropertyAction.new("focus_mode", self.text_view, "focus-mode") self.add_action(action) action = Gio.PropertyAction.new("hemingway_mode", self.text_view, "hemingway-mode") self.add_action(action) action = Gio.PropertyAction.new("fullscreen", self, "is-fullscreen") self.add_action(action) action = Gio.PropertyAction.new("preview", self, "preview") self.add_action(action) self.connect("notify::preview", self.toggle_preview) action = Gio.SimpleAction.new("new", None) action.connect("activate", self.new_document) self.add_action(action) action = Gio.SimpleAction.new("open", None) action.connect("activate", self.open_document) self.add_action(action) action = Gio.SimpleAction.new("open_file", GLib.VariantType("s")) action.connect("activate", self.open_from_gvariant) self.add_action(action) action = Gio.SimpleAction.new("save", None) action.connect("activate", self.save_document) self.add_action(action) action = Gio.SimpleAction.new("save_as", None) action.connect("activate", self.save_document_as) self.add_action(action) action = Gio.SimpleAction.new("export", GLib.VariantType("s")) action.connect("activate", self.open_export) self.add_action(action) action = Gio.SimpleAction.new("advanced_export", None) action.connect("activate", self.open_advanced_export) self.add_action(action) action = Gio.SimpleAction.new("copy_html", None) action.connect("activate", self.copy_html_to_clipboard) self.add_action(action) # not really necessary but we'll keep a preview_layout property on the window # and bind it both to the switcher and the renderer self.preview_layout = self.settings.get_enum("preview-mode") self.bind_property("preview_layout", self.headerbar.preview_layout_switcher, "preview_layout", GObject.BindingFlags.BIDIRECTIONAL|GObject.BindingFlags.SYNC_CREATE) self.bind_property("preview_layout", self.preview_handler.preview_renderer, "preview_layout", GObject.BindingFlags.SYNC_CREATE) self.preview = self.settings.get_boolean("preview-active") self.text_view.hemingway_mode = self.settings.get_boolean("hemingway-mode") self.new_document() # TODO: change to closures on GTK4 # "Bind" scrolled window's scrollbar margin to headerbar visibility @Gtk.Template.Callback() def headerbar_revealed_cb(self, widget, *args): scrollbar = self.editor_scrolledwindow.get_vscrollbar() scrollbar.set_margin_top(46 if widget.get_reveal_child() else 0) def on_text_changed(self, *_args): """called when the text changes, sets the self.did_change to true and updates the title and the counters to reflect that """ if self.did_change is False: self.did_change = True self.update_headerbar_title(True, True) if self.settings.get_value("autohide-headerbar"): self.hide_headerbar_bottombar() @Gtk.Template.Callback() def _on_fullscreen(self, *args, **kwargs): """Puts the application in fullscreen mode and show/hides the poller for motion in the top border """ if self.is_fullscreen == True: self.fullscreen() self.hide_headerbar_bottombar() else: self.unfullscreen() self.reveal_headerbar_bottombar() self.text_view.grab_focus() def toggle_preview(self, *args, **kwargs): """Toggle the preview mode """ if self.preview: self.text_view.grab_focus() self.preview_handler.show() else: self.preview_handler.hide() self.text_view.grab_focus() def save_document(self, _action=None, _value=None, sync: bool = False) -> bool: """Try to save buffer in the current gfile. If the file doesn't exist calls save_document_as Args: sync (bool, optional): Wheter the save operation should be done synchronously. Defaults to False. Returns: bool: True if the document was saved correctly """ if self.current.gfile: LOGGER.info("saving") # We try to encode the file with the given encoding # if that doesn't work, we try with UTF-8 # if that fails as well, we return False try: try: encoded_text = self.text_view.get_text()\ .encode(self.current.encoding) except UnicodeEncodeError: encoded_text = self.text_view.get_text()\ .encode("UTF-8") self.current.encoding = "UTF-8" except UnicodeEncodeError as error: helpers.show_error(self, str(error.reason)) LOGGER.warning(str(error.reason)) return False else: self.save_progressbar.set_opacity(1) self.save_progressbar.set_visible(True) self.progressbar_initiate_tw.start() # we allow synchronously saving operations # for result-dependant code if sync: try: res = self.current.gfile.replace_contents( encoded_text, etag=None, make_backup=False, flags=Gio.FileCreateFlags.NONE, cancellable=None) except GLib.GError as error: helpers.show_error(self, str(error.message)) LOGGER.warning(str(error.message)) self.progressbar_opacity_tw.start() self.did_change = True return False if res: self.progressbar_initiate_tw.stop() self.progressbar_finalize_tw.start() self.progressbar_opacity_tw.start() self.update_headerbar_title() self.did_change = False return True else: self.progressbar_opacity_tw.start() self.did_change = True return False else: self.current.gfile.replace_contents_bytes_async( GLib.Bytes.new(encoded_text), etag=None, make_backup=False, flags=Gio.FileCreateFlags.NONE, cancellable=None, callback=self._replace_contents_cb, user_data=None) return True # if there's no GFile we ask for one: else: return self.save_document_as(sync=sync) def save_document_as(self, _widget=None, _data=None, sync: bool = False) -> bool: """provide to the user a filechooser and save the document where they want. Call set_headbar_title after that """ filefilter = Gtk.FileFilter.new() filefilter.add_mime_type('text/x-markdown') filefilter.add_mime_type('text/plain') filefilter.set_name('Markdown (.md)') filechooser = Gtk.FileChooserNative.new( _("Save your File"), self, Gtk.FileChooserAction.SAVE, _("Save"), _("Cancel") ) filechooser.set_do_overwrite_confirmation(True) filechooser.set_local_only(False) filechooser.add_filter(filefilter) filechooser.set_modal(True) filechooser.set_transient_for(self) title = self.current.title if not title.endswith(".md"): title += ".md" filechooser.set_current_name(title) response = filechooser.run() if response == Gtk.ResponseType.ACCEPT: file = filechooser.get_file() if not file.query_exists(): try: file.create(Gio.FileCreateFlags.NONE) except GLib.GError as error: helpers.show_error(self, str(error.message)) LOGGER.warning(str(error.message)) return False self.current.gfile = file recents_manager = Gtk.RecentManager.get_default() recents_manager.add_item(self.current.gfile.get_uri()) self.update_headerbar_title(False, True) filechooser.destroy() return self.save_document() else: return False def _replace_contents_cb(self, gfile, result, _user_data=None): try: success, _etag = gfile.replace_contents_finish(result) except GLib.GError as error: helpers.show_error(self, str(error.message)) LOGGER.warning(str(error.message)) self.progressbar_opacity_tw.start() self.did_change = True return False if success: self.progressbar_initiate_tw.stop() self.progressbar_finalize_tw.start() self.progressbar_opacity_tw.start() self.update_headerbar_title() self.did_change = False else: self.did_change = True self.progressbar_opacity_tw.start() return success def copy_html_to_clipboard(self, _widget=None, _date=None): """Copies only html without headers etc. to Clipboard """ output = helpers.pandoc_convert(self.text_view.get_text()) clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD) clipboard.set_text(output, -1) clipboard.store() def open_document(self, _action, _value): """open the desired file """ response = self.check_change() if (response == Gtk.ResponseType.CANCEL or response == Gtk.ResponseType.DELETE_EVENT): return markdown_filter = Gtk.FileFilter.new() markdown_filter.add_mime_type('text/markdown') markdown_filter.add_mime_type('text/x-markdown') markdown_filter.set_name(_('Markdown Files')) plaintext_filter = Gtk.FileFilter.new() plaintext_filter.add_mime_type('text/plain') plaintext_filter.set_name(_('Plain Text Files')) filechooser = Gtk.FileChooserNative.new( _("Open a .md file"), self, Gtk.FileChooserAction.OPEN, _("Open"), _("Cancel") ) filechooser.set_local_only(False) filechooser.add_filter(markdown_filter) filechooser.add_filter(plaintext_filter) response = filechooser.run() if response == Gtk.ResponseType.ACCEPT: self.load_file(filechooser.get_file()) filechooser.destroy() elif response == Gtk.ResponseType.CANCEL: filechooser.destroy() def open_from_gvariant(self, _action, gvariant): self.load_file(Gio.File.new_for_uri(gvariant.get_string())) def load_file(self, file=None): """Open File from command line or open / open recent etc.""" LOGGER.info("trying to open %s", file.get_path()) response = self.check_change() if (response == Gtk.ResponseType.CANCEL or response == Gtk.ResponseType.DELETE_EVENT): return self.current.gfile = file self.current.gfile.load_contents_async(None, self._load_contents_cb, None) def _load_contents_cb(self, gfile, result, user_data=None): try: _success, contents, _etag = gfile.load_contents_finish(result) except GLib.GError as error: helpers.show_error(self, str(error.message)) LOGGER.warning(str(error.message)) return try: try: self.current.encoding = 'UTF-8' decoded = contents.decode(self.current.encoding) except UnicodeDecodeError: self.current.encoding = chardet.detect(contents)['encoding'] decoded = contents.decode(self.current.encoding) except UnicodeDecodeError as error: helpers.show_error(self, str(error.message)) LOGGER.warning(str(error.message)) return else: self.text_view.set_text(decoded) start_iter = self.text_view.get_buffer().get_start_iter() GLib.idle_add( lambda: self.text_view.get_buffer().place_cursor(start_iter)) ## add file to recents manager once it's fully loaded, # unless it is an internal resource if not self.current.gfile.get_uri().startswith("resource:"): recents_manager = Gtk.RecentManager.get_default() recents_manager.add_item(self.current.gfile.get_uri()) self.update_headerbar_title() self.did_change = False def check_change(self) -> Gtk.ResponseType: """Show dialog to prevent loss of unsaved changes """ if self.did_change and self.text_view.get_text(): dialog = Gtk.MessageDialog(self, Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT, Gtk.MessageType.WARNING, Gtk.ButtonsType.NONE, _("Save changes to document " + "“%s” before closing?") % self.current.title ) dialog.props.secondary_text = _("If you don’t save, " + "all your changes will be " + "permanently lost.") close_button = dialog.add_button(_("Close without saving"), Gtk.ResponseType.NO) dialog.add_button(_("Cancel"), Gtk.ResponseType.CANCEL) dialog.add_button(_("Save now"), Gtk.ResponseType.YES) close_button.get_style_context().add_class("destructive-action") dialog.set_default_response(Gtk.ResponseType.YES) response = dialog.run() dialog.destroy() if response == Gtk.ResponseType.YES: # If the saving fails, retry if self.save_document(sync=True) is False: return self.check_change() return response def new_document(self, *args, **kwargs): """create new document """ response = self.check_change() if (response == Gtk.ResponseType.CANCEL or response == Gtk.ResponseType.DELETE_EVENT): return self.text_view.clear() self.did_change = False self.current.gfile = None self.update_headerbar_title(False, False) def update_default_stat(self): self.stats_handler.update_default_stat() def reload_preview(self, reshow=False): self.preview_handler.reload(reshow=reshow) def open_export(self, _action, value): """open the export dialog """ text = bytes(self.text_view.get_text(), "utf-8") export_format = value.get_string() export_dialog = ExportDialog(self.current, export_format, text) export_dialog.dialog.set_transient_for(self) export_dialog.export() def open_advanced_export(self, *args, **kwargs): """open the advanced export dialog """ text = bytes(self.text_view.get_text(), "utf-8") export_dialog = AdvancedExportDialog(self.current, text) export_dialog.set_transient_for(self) export_dialog.show() @Gtk.Template.Callback() def reveal_headerbar_bottombar(self, _widget=None, _data=None): self.reveal_bottombar() if not self.headerbar_visible: self.headerbar_eventbox.hide() self.headerbar.set_visible(True) self.headerbar.set_reveal_child(True) self.get_style_context().remove_class("focus") self.headerbar_visible = True @Gtk.Template.Callback() def reveal_bottombar(self, _widget=None, _data=None): if not self.bottombar_visible: self.stats_revealer.set_reveal_child(True) self.stats_revealer.set_halign(Gtk.Align.END) self.stats_revealer.queue_resize() self.bottombar_visible = True def hide_headerbar_bottombar(self): if self.searchbar.get_search_mode(): return if self.headerbar_visible: self.headerbar.set_reveal_child(False) self.get_style_context().add_class("focus") self.headerbar_visible = False if self.bottombar_visible: self.stats_revealer.set_reveal_child(False) self.stats_revealer.set_halign(Gtk.Align.FILL) self.bottombar_visible = False self.headerbar_eventbox.show() # TODO: this has to go def update_headerbar_title(self, is_unsaved: bool = False, has_subtitle: bool = True): """update headerbar title and subtitle """ if is_unsaved: prefix = "• " # TODO: this doesn't really belong here App().inhibitor.inhibit(Gtk.ApplicationInhibitFlags.LOGOUT) else: prefix = "" App().inhibitor.uninhibit() title = prefix + self.current.title if has_subtitle: subtitle = self.current.path else: subtitle = "" self.set_title(title) self.subtitle = subtitle self.headerbar.set_tooltip_text(subtitle) def save_state(self): self.settings.set_enum("preview-mode", self.preview_layout) self.settings.set_boolean("preview-active", self.preview) self.settings.set_boolean("hemingway-mode", self.text_view.hemingway_mode) @Gtk.Template.Callback() def on_delete_called(self, _widget, _data=None): """Called when the ApostropheWindow is closed. """ LOGGER.info('delete called') response = self.check_change() if (response == Gtk.ResponseType.CANCEL or response == Gtk.ResponseType.DELETE_EVENT): return True # save state if we're the last window OR if only the preview window is left n_windows = len(self.get_application().get_windows()) if n_windows == 1 or \ (n_windows == 2 and self.preview_handler.preview_renderer.window): self.save_state() return False @dataclass class File(): """Class for keeping track of files, their attributes, and their methods""" def __init__(self, gfile=None, encoding="UTF-8"): self._settings = Settings.new() self.gfile = gfile self.encoding = encoding self.path = "" self.title = "" self.name = "" @property def gfile(self): return self._gfile @gfile.setter def gfile(self, file): if file: if file.is_native(): self.path = file.get_parent().get_path() base_path = file.get_parent().get_path() os.chdir(base_path) else: self.path = file.get_parent().get_uri() base_path = "/" file_info = file.query_info("standard", Gio.FileQueryInfoFlags.NONE, None) self.title = file_info.get_attribute_as_string( "standard::display-name") else: self.title = _("New File") base_path = "/" self.name = self.title if self.name.endswith(".md"): self.name = self.name[:-3] # TODO: remove path in favor of gfile self._settings.set_string("open-file-path", base_path) self._gfile = file apostrophe-v2.6.3/apostrophe/markup_regex.py000066400000000000000000000036601423304411100213210ustar00rootroot00000000000000import re ITALIC_ASTERISK = re.compile( r"(?.*?\S?.*?)(?.*?\S?.*?)(?.*?\S.*?)\1") BOLD_ITALIC = re.compile( r"((\*\*|__)([*_])|([*_])(\*\*|__))[^\s*](?P.*?\S.*?)(?:\5\4|\3\2)") STRIKETHROUGH = re.compile( r"~~(?P.*?\S.*?)~~") CODE = re.compile( r"(?`+)(?!`)(?P.+?)(?.*?)\]\((?P.+?)(?: \"(?P.+)\")?\)") LINK_ALT = re.compile( r"<(?P<text>(?P<url>[A-Za-z][A-Za-z0-9.+-]{1,31}:[^<>\x00-\x20]*|(?:[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)))>") IMAGE = re.compile( r"!\[(?P<text>.*)\]\((?P<url>.+?)(?: \"(?P<title>.+)\")?\)") HORIZONTAL_RULE = re.compile( r"(?:^|\n{2,})(?P<symbols> {0,3}[*\-_]{3,} *)(?:\n{2,}|$)") LIST = re.compile( r"(?:^|\n)(?P<content>(?P<indent>(?:\t| {4})*)[\-*+] (?:\t| {4})*(?P<text>.+(?:\n+ \2.+)*))") ORDERED_LIST = re.compile( r"(?:^|\n)(?P<content>(?P<indent>(?:\t| {4})*)(?P<prefix>(?:\d|[a-z])+[.)])(?:\t| {4}| )(?P<text>.+(?:\n+ {2}\2.+)*))") BLOCK_QUOTE = re.compile( r"^ {0,3}(?:> ?)+(?P<text>.+)", re.M) HEADER = re.compile( r"^ {0,3}(?P<level>#{1,6}) (?P<text>[^\n]+)", re.M) HEADER_UNDER = re.compile( r"(?:^\n*|\n\n)(?P<text>[^\s].+)\n {0,3}[=\-]+(?: +?\n|$)") CODE_BLOCK = re.compile( r"^ {0,3}(?P<block>([`~]{3})(?P<text>.+?)(?<! ) {0,3}\2)(?:\s+?$|$)", re.S|re.M) TABLE = re.compile( r"^[\-+]{5,}\n(?P<text>.+?)\n[\-+]{5,}\n", re.S) MATH = re.compile( r"([$]{1,2})(?P<text>[^`\\ ]{1,2}|[^` ].+?[^`\\ ])\1", re.S|re.M) FOOTNOTE_ID = re.compile( r"[^\s]+\[\^(?P<id>(?P<text>[^\s]+))\]") FOOTNOTE = re.compile( r"(?:^\n*|\n\n)\[\^(?P<id>[^\s]+)\]: (?P<text>(?:[^\n]+|\n+(?=(?:\t| {4})))+)(?:\n+|$)", re.M) ��������������������������������������������������������������������������������apostrophe-v2.6.3/apostrophe/open_popover.py��������������������������������������������������������0000664�0000000�0000000�00000007210�14233044111�0021336�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Copyright (C) 2022, Manuel Genovés <manuel.genoves@gmail.com> # 2021, Christian Hergert <chergert@redhat.com> # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 <http://www.gnu.org/licenses/>. # END LICENSE """Open/recents popover """ from os import close import gi from gettext import gettext as _ gi.require_version('Gtk', '3.0') from gi.repository import Gtk, Gio, GLib, GObject, Handy from .settings import Settings class RecentItem(GObject.Object): def __init__(self, name, path, uri, **kwargs): super().__init__(**kwargs) self.name: str = name self.path: str = path self.uri: str = uri @Gtk.Template(resource_path='/org/gnome/gitlab/somas/Apostrophe/ui/Recents.ui') class ApostropheOpenPopover(Gtk.Popover): __gtype_name__ = "ApostropheOpenPopover" """Open/recents popover """ list_box = Gtk.Template.Child() stack = Gtk.Template.Child() empty = Gtk.Template.Child() recent = Gtk.Template.Child() model = Gio.ListStore.new(RecentItem) recents_manager = Gtk.RecentManager.get_default() def __init__(self, **kwargs): super().__init__(**kwargs) self.list_box.bind_model(self.model, self.create_row) self.on_manager_changed() self.recents_manager.connect("changed", self.on_manager_changed) def create_row(self, item, **args): row = Handy.ActionRow.new() row.item = item row.set_title(item.name) row.set_subtitle(item.path) delete_button = Gtk.Button.new_from_icon_name("window-close-symbolic", Gtk.IconSize.BUTTON) delete_button.get_style_context().add_class("flat") delete_button.get_style_context().add_class("circular") delete_button.set_valign(Gtk.Align.CENTER) delete_button.set_visible(True) delete_button.connect("clicked", self.on_delete_click, item) row.add(delete_button) row.set_activatable(True) row.set_action_name("win.open_file") row.set_action_target_value(GLib.Variant.new_string(item.uri)) return row def on_manager_changed(self, *args, **kwargs): self.model.remove_all() for item in self.recents_manager.get_items(): self.model.append(RecentItem(item.get_display_name(), item.get_uri_display(), item.get_uri())) self.stack.set_visible_child(self.recent if self.model else self.empty) @Gtk.Template.Callback() def on_search_entry_changed_cb(self, search_entry): # TODO: implement nice filters in GTK4 recents_list = self.recents_manager.get_items() filtered_list = filter(lambda item: search_entry.get_text() in item.get_display_name(), recents_list) self.model.remove_all() for item in filtered_list: self.model.append(RecentItem(item.get_display_name(), item.get_uri_display(), item.get_uri())) @Gtk.Template.Callback() def on_search_entry_activate_cb(self, *arg, **kwargs): print("activate") @Gtk.Template.Callback() def on_search_entry_stop_cb(self, *arg, **kwargs): print("stop") def on_delete_click(self, _widget, item): self.recents_manager.remove_item(item.uri)����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������apostrophe-v2.6.3/apostrophe/preferences_dialog.py��������������������������������������������������0000664�0000000�0000000�00000010110�14233044111�0022434�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Copyright (C) 2022, Manuel Genovés <manuel.genoves@gmail.com> # 2019, Wolf Vollprecht <w.vollprecht@gmail.com> # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 <http://www.gnu.org/licenses/>. # END LICENSE """this dialog adjusts values in gsettings """ import webbrowser import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, Handy, Gio, GObject import logging logger = logging.getLogger('apostrophe') from apostrophe.settings import Settings class InputFormat(GObject.Object): def __init__(self, name, format, help, **kwargs): super().__init__(**kwargs) self.name: str = name self.format: str = format self.help: str = help @Gtk.Template(resource_path='/org/gnome/gitlab/somas/Apostrophe/ui/Preferences.ui') class ApostrophePreferencesDialog(Handy.PreferencesWindow): __gtype_name__ = "ApostrophePreferencesDialog" formats = [ { "name": "Pandoc's Markdown", "format": "markdown", "help": "https://pandoc.org/MANUAL.html#pandocs-markdown" }, { "name": "CommonMark", "format": "commonmark", "help": "https://commonmark.org" }, { "name": "GitHub Flavored Markdown", "format": "gfm", "help": "https://help.github.com/en/categories/writing-on-github" }, { "name": "MultiMarkdown", "format": "markdown_mmd", "help": "https://fletcherpenney.net/multimarkdown" }, { "name": "Plain Markdown", "format": "markdown_strict", "help": "https://daringfireball.net/projects/markdown" } ] autohide_headerbar_switch = Gtk.Template.Child() spellcheck_switch = Gtk.Template.Child() input_format_comborow = Gtk.Template.Child() bigger_text_switch = Gtk.Template.Child() settings = Settings.new() def __init__(self): super().__init__() input_formats = Gio.ListStore.new(InputFormat) for i, format in enumerate(self.formats): input_formats.append(InputFormat(format["name"], format["format"], format["help"])) if (format["format"] == self.settings.get_string("input-format")): current_format = i self.input_format_comborow.bind_name_model(input_formats, lambda item, *args: item.name, None, None) if current_format: self.input_format_comborow.set_selected_index(current_format) self.settings.bind("autohide-headerbar", self.autohide_headerbar_switch, "active", Gio.SettingsBindFlags.DEFAULT) self.settings.bind("spellcheck", self.spellcheck_switch, "active", Gio.SettingsBindFlags.DEFAULT) self.settings.bind("bigger-text", self.bigger_text_switch, "active", Gio.SettingsBindFlags.DEFAULT) @Gtk.Template.Callback() def on_input_format(self, _widget, _index): fmt = self.formats[self.input_format_comborow.get_selected_index()] self.settings.set_string("input-format", fmt["format"]) @Gtk.Template.Callback() def on_input_format_help(self, _): fmt = self.formats[self.input_format_comborow.get_selected_index()] webbrowser.open(fmt["help"]) ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������apostrophe-v2.6.3/apostrophe/preview_converter.py���������������������������������������������������0000664�0000000�0000000�00000003113�14233044111�0022371�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������from queue import Queue from threading import Thread from gi.repository import GLib from apostrophe import helpers from apostrophe.theme_switcher import Theme, ThemeSwitcher class PreviewConverter: """Converts markdown to html using a background thread.""" def __init__(self): super().__init__() self.queue = Queue() worker = Thread(target=self.__do_convert, name="preview-converter") worker.daemon = True worker.start() def convert(self, text, callback, *user_data): """Converts text to html, calling callback when done. The callback argument contains the result.""" self.queue.put((text, callback, user_data)) def stop(self): """Stops the background worker. PreviewConverter shouldn't be used after this.""" self.queue.put((None, None)) def __do_convert(self): while True: while True: (text, callback, user_data) = self.queue.get() if text is None and callback is None: return if self.queue.empty(): break args = ['--standalone', '--mathjax', '--css=' + Theme.get_current().web_css, '--lua-filter=' + helpers.get_media_path('/lua/relative_to_absolute.lua'), '--lua-filter=' + helpers.get_media_path('/lua/task-list.lua')] text = helpers.pandoc_convert(text, to="html5", args=args) GLib.idle_add(callback, text, *user_data) �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������apostrophe-v2.6.3/apostrophe/preview_handler.py�����������������������������������������������������0000664�0000000�0000000�00000016263�14233044111�0022011�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Copyright (C) 2022, Manuel Genovés <manuel.genoves@gmail.com> # 2019, Gonçalo Silva # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 <http://www.gnu.org/licenses/>. # END LICENSE import math import webbrowser from enum import auto, IntEnum import gi from apostrophe.preview_renderer import PreviewRenderer from apostrophe.settings import Settings gi.require_version('WebKit2', '4.0') from gi.repository import WebKit2, GLib, Gtk, GObject from apostrophe.preview_converter import PreviewConverter from apostrophe.preview_web_view import PreviewWebView class Step(IntEnum): CONVERT_HTML = auto() LOAD_WEBVIEW = auto() RENDER = auto() class PreviewHandler: """Handles showing/hiding the preview, and allows the user to toggle between modes. The rendering itself is handled by `PreviewRendered`. This class handles conversion/loading and connects it all together (including synchronization, ie. text changes, scroll).""" def __init__(self, window, text_view, flap): self.text_view = text_view self.web_view = None self.web_view_pending_html = None self.preview_converter = PreviewConverter() self.preview_renderer = PreviewRenderer( window, text_view, flap) window.connect("style-updated", self.reload) self.text_changed_handler_id = None self.settings = Settings.new() self.web_scroll_handler_id = None self.text_scroll_handler_id = None self.loading = False self.shown = False self.preview_visible = False def show(self): self.__show() self.preview_renderer.show() def __show(self, html=None, step=Step.CONVERT_HTML): if step == Step.CONVERT_HTML: # First step: convert text to HTML. buf = self.text_view.get_buffer() self.preview_converter.convert( buf.get_text(buf.get_start_iter(), buf.get_end_iter(), False), self.__show, Step.LOAD_WEBVIEW) elif step == Step.LOAD_WEBVIEW: # Second step: load HTML. self.loading = True if not self.web_view: self.web_view = PreviewWebView() self.web_view.get_settings().set_allow_universal_access_from_file_urls(True) #TODO: enable devtools on Devel profile self.web_view.get_settings().set_enable_developer_extras(True) # Show preview once the load is finished self.web_view.connect("load-changed", self.on_load_changed) # All links will be opened in default browser, but local files are opened in apps. self.web_view.connect("decide-policy", self.on_click_link) self.web_view.connect("context-menu", self.on_right_click) if self.web_view.is_loading(): self.web_view_pending_html = html else: self.web_view.load_html(html, "file://localhost/") elif step == Step.RENDER: # Last step: show the preview. This is a one-time step. if not self.preview_visible: self.preview_visible = True self.text_changed_handler_id = \ self.text_view.get_buffer().connect("changed", self.__show) self.__show() GLib.idle_add(self.web_view.set_scroll_scale, self.text_view.scroll_scale) if self.settings.get_boolean("sync-scroll"): self.web_scroll_handler_id = \ self.web_view.connect("scroll-scale-changed", self.on_web_view_scrolled) self.text_scroll_handler_id = \ self.text_view.connect("scroll-scale-changed", self.on_text_view_scrolled) def reload(self, *_widget, reshow=False): if self.preview_visible: if reshow: self.hide() self.show() def hide(self): if self.preview_visible: self.preview_visible = False #GLib.idle_add(self.text_view.scroll_scale, self.web_view.get_scroll_scale()) self.text_view.scroll_scale = self.web_view.get_scroll_scale() self.preview_renderer.hide() if self.text_scroll_handler_id: self.text_view.disconnect(self.text_scroll_handler_id) self.text_scroll_handler_id = None if self.web_scroll_handler_id: self.web_view.disconnect(self.web_scroll_handler_id) self.web_scroll_handler_id = None if self.text_changed_handler_id: self.text_view.get_buffer().disconnect(self.text_changed_handler_id) if self.loading: self.loading = False self.web_view.destroy() self.web_view = None def update_preview_mode(self): self.preview_renderer.update_mode(self.web_view) def on_load_changed(self, _web_view, event): if event == WebKit2.LoadEvent.FINISHED: self.loading = False if self.web_view_pending_html: self.__show(html=self.web_view_pending_html, step=Step.LOAD_WEBVIEW) self.web_view_pending_html = None else: # we only lazyload the webview once if not self.shown: self.preview_renderer.load_webview(self.web_view) self.shown = True self.__show(step=Step.RENDER) def on_text_view_scrolled(self, _text_view, scale): if self.preview_visible and not math.isclose(scale, self.web_view.get_scroll_scale(), rel_tol=1e-4): self.web_view.set_scroll_scale(scale) def on_web_view_scrolled(self, _web_view, scale): if self.preview_visible and self.text_view.get_mapped() and not math.isclose( scale, self.text_view.scroll_scale, rel_tol=1e-1): self.text_view.scroll_scale = scale @staticmethod def on_click_link(web_view, decision, _decision_type): if web_view.get_uri().startswith(("http://", "https://", "www.")): webbrowser.open(web_view.get_uri()) decision.ignore() return True @staticmethod def on_right_click(web_view, context_menu, _event, _hit_test): # disable some context menu option for item in context_menu.get_items(): if item.get_stock_action() in [WebKit2.ContextMenuAction.RELOAD, WebKit2.ContextMenuAction.GO_BACK, WebKit2.ContextMenuAction.GO_FORWARD, WebKit2.ContextMenuAction.STOP]: context_menu.remove(item) ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������apostrophe-v2.6.3/apostrophe/preview_layout_switcher.py���������������������������������������������0000664�0000000�0000000�00000010121�14233044111�0023604�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# BEGIN LICENSE # Copyright (C) 2022, Manuel Genovés <manuel.genoves@gmail.com> # Copyright (C) 2021, Adrien Plazas <kekun.plazas@laposte.net> # Copyright (C) 2021, Alexander Mikhaylenko <exalm7659@gmail.com> # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 <http://www.gnu.org/licenses/>. # END LICENSE from apostrophe.settings import Settings from gi.repository import Gtk, GObject from enum import IntEnum import enum from gettext import gettext as _ import gi gi.require_version('Gtk', '3.0') class PreviewLayout(IntEnum): # preview modes FULL_WIDTH = 0 HALF_WIDTH = 1 HALF_HEIGHT = 2 WINDOWED = 3 def get_text(self): if self == PreviewLayout.FULL_WIDTH: return _("Full-Width") elif self == PreviewLayout.HALF_WIDTH: return _("Half-Width") elif self == PreviewLayout.HALF_HEIGHT: return _("Half-Height") elif self == PreviewLayout.WINDOWED: return _("Windowed") else: raise ValueError("Unknown preview mode") def get_icon(self): if self == PreviewLayout.FULL_WIDTH: return "preview-layout-full-width-symbolic" elif self == PreviewLayout.HALF_WIDTH: return "preview-layout-half-width-symbolic" elif self == PreviewLayout.HALF_HEIGHT: return "preview-layout-half-height-symbolic" elif self == PreviewLayout.WINDOWED: return "preview-layout-windowed-symbolic" else: raise ValueError("Unknown preview mode") @Gtk.Template(resource_path='/org/gnome/gitlab/somas/Apostrophe/ui/PreviewLayoutSwitcherItem.ui') class PreviewLayoutSwitcherItem(Gtk.ListBoxRow): __gtype_name__ = "PreviewLayoutSwitcherItem" icon = Gtk.Template.Child() title = Gtk.Template.Child() checkmark = Gtk.Template.Child() selected = GObject.property(type=bool, default=False) def __init__(self, _layout): super().__init__() self.layout = _layout self.icon.set_from_icon_name(self.layout.get_icon(), 4) self.title.set_label(self.layout.get_text()) self.connect("notify::selected", self.on_selected) def on_selected(self, *args, **kwargs): self.checkmark.props.opacity = 1 if self.selected else 0 @Gtk.Template(resource_path='/org/gnome/gitlab/somas/Apostrophe/ui/PreviewLayoutSwitcher.ui') class PreviewLayoutSwitcher(Gtk.Box): __gtype_name__ = "PreviewLayoutSwitcher" list_box = Gtk.Template.Child() layout_image = Gtk.Template.Child() layout_popover = Gtk.Template.Child() preview_switcher_toggle = Gtk.Template.Child() items = [] preview_layout = GObject.property(type=int) settings = Settings.new() def __init__(self): super().__init__() for i, layout in enumerate(PreviewLayout): item = PreviewLayoutSwitcherItem(layout) self.list_box.add(item) self.items.append(item) self.update_ui() self.connect("notify::preview-layout", self.update_ui) @Gtk.Template.Callback() def update_ui(self, *args, **kwargs): self.layout_image.set_from_icon_name(PreviewLayout(self.preview_layout).get_icon(), 4) for item in self.items: item.selected = item.layout == self.preview_layout item = self.items[self.preview_layout] self.list_box.select_row(item) @Gtk.Template.Callback() def on_row_activated(self, _listbox, row): self.preview_layout = row.layout self.layout_popover.popdown() # TODO: remove @Gtk.Template.Callback() def on_menu_state_changed(self, _listbox, row): pass �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������apostrophe-v2.6.3/apostrophe/preview_renderer.py����������������������������������������������������0000664�0000000�0000000�00000022120�14233044111�0022167�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Copyright (C) 2022, Manuel Genovés <manuel.genoves@gmail.com> # 2019, Gonçalo Silva # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 <http://www.gnu.org/licenses/>. # END LICENSE from gettext import gettext as _ from gi.repository import Gtk, GLib, Handy, GObject from apostrophe.settings import Settings from apostrophe.preview_layout_switcher import PreviewLayout from apostrophe.preview_window import PreviewWindow from .tweener import Tweener class PreviewRenderer(GObject.Object): """Renders the preview according to the user selected mode.""" __gtype_name__ = "PreviewRenderer" preview_layout = GObject.Property(type=int, default=0) preview_window_title = GObject.Property(type=str, default="") def __init__( self, main_window, text_view, flap): super().__init__() self.main_window = main_window self.main_window.connect("delete-event", self.on_window_closed) self.main_window.connect("notify::title", self.on_window_title_changed) self.text_view = text_view self.window_size_cache = None self.settings = Settings.new() self.window = None self.preview_stack = self.main_window.preview_stack # we may get the preview layout changed underneath us, so we store # a cache for proper hidding the previous layout self.preview_layout_cache = None self.flap = flap self.connect("notify::preview-layout", self.update_mode) def show(self): """Show the preview, depending on the currently selected mode.""" # Windowed preview: create a window and show the preview in it. if self.preview_layout == PreviewLayout.WINDOWED and not self.window: # Create transient window of the main window. self.window = PreviewWindow() self.window.connect("delete-event", self.on_window_closed) self.window.preview_box.pack_start(self.preview_stack, False, True, 0) self.bind_property("preview_window_title", self.window, "title") # Position it next to the main window. width, height = self.main_window.get_size() self.window.resize(width, height) x, y = self.main_window.get_position() if x is not None and y is not None: self.main_window.move(x, y) self.window.move(x + width + 16, y) self.window.show() elif self.preview_layout == PreviewLayout.HALF_WIDTH: self.window_size_cache = self.main_window.get_size() requested_width_tw = Tweener(self.flap, self.flap.set_size_request, self.text_view.get_min_width(), self.text_view.get_min_width() * 2 + 2, 250, setter_args = [-1]) requested_width_tw.start() self.flap.set_reveal_flap(True) else: # if it's the first time we open the preview, set # the corresponding flap mode if self.preview_layout_cache is None: self.update_mode() self.flap.set_reveal_flap(True) def load_webview(self, webview): webview.show() self.main_window.preview_stack.add(webview) self.main_window.preview_stack.set_visible_child(webview) def hide(self): """Hide the preview, depending on the currently selected mode.""" self.flap.set_reveal_flap(False) # Windowed preview: remove preview and destroy window. if self.preview_layout_cache == PreviewLayout.WINDOWED: self.main_window.present() self.window.preview_box.remove(self.preview_stack) self.window.destroy() self.window = None else: # Half-width/height previews: remove preview and reset size # requirements. if self.preview_layout_cache == PreviewLayout.HALF_WIDTH: self.shrink_window() def shrink_window(self): self.flap.set_size_request(self.text_view.get_min_width(), -1) resize_tw = Tweener(self.main_window, self.main_window.resize, self.main_window.get_size()[0], self.window_size_cache[0], 250, setter_args = [self.window_size_cache[1]]) resize_tw.start() def update_mode(self, *args, web_view=None): """Update preview mode """ def set_flap_mode(*args, **kwargs): # TODO: use structural pattern matching in python3.10 if c and self.flap.get_reveal_progress() != 0: return if c: self.main_window.flap.disconnect(c) if self.preview_layout == PreviewLayout.FULL_WIDTH: if self.preview_layout_cache == PreviewLayout.HALF_WIDTH: self.shrink_window() self.flap.set_fold_policy(Handy.FlapFoldPolicy.ALWAYS) self.flap.set_orientation(Gtk.Orientation.HORIZONTAL) elif self.preview_layout == PreviewLayout.HALF_WIDTH: self.window_size_cache = self.main_window.get_size() requested_width_tw = Tweener(self.flap, self.flap.set_size_request, self.text_view.get_min_width(), self.text_view.get_min_width() * 2 + 2, 250, setter_args = [-1]) requested_width_tw.start() self.flap.set_fold_policy(Handy.FlapFoldPolicy.NEVER) self.flap.set_orientation(Gtk.Orientation.HORIZONTAL) elif self.preview_layout == PreviewLayout.HALF_HEIGHT: self.flap.set_fold_policy(Handy.FlapFoldPolicy.NEVER) self.flap.set_orientation(Gtk.Orientation.VERTICAL) else: raise ValueError("Unknown preview mode {}".format(self.preview_layout)) # don't automatically show the preview when syncing the preview-layout property first time if self.preview_layout_cache is not None: self.show() self.preview_layout_cache = self.preview_layout def reatach_stack(*args, **kwargs): if self.flap.get_reveal_progress() != 0: return self.main_window.flap.disconnect(d) self.main_window.flap.remove(self.main_window.flap.get_flap()) self.preview_layout_cache = self.preview_layout self.show() # none -> paned if (self.preview_layout in [PreviewLayout.FULL_WIDTH, PreviewLayout.HALF_WIDTH, PreviewLayout.HALF_HEIGHT] and self.preview_layout_cache is None): c = None set_flap_mode() # horizontal paned -> horizontal paned elif (self.preview_layout in [PreviewLayout.FULL_WIDTH, PreviewLayout.HALF_WIDTH] and self.preview_layout_cache in [PreviewLayout.FULL_WIDTH, PreviewLayout.HALF_WIDTH]): c = None set_flap_mode() # window -> paned elif (self.preview_layout_cache == PreviewLayout.WINDOWED and self.preview_layout in [PreviewLayout.FULL_WIDTH, PreviewLayout.HALF_WIDTH, PreviewLayout.HALF_HEIGHT]): self.hide() self.main_window.flap.set_flap(self.preview_stack) c = None set_flap_mode() # whatever -> paned elif (self.preview_layout in [PreviewLayout.FULL_WIDTH, PreviewLayout.HALF_WIDTH, PreviewLayout.HALF_HEIGHT]): self.hide() c = self.main_window.flap.connect("notify::reveal-progress", set_flap_mode) # paned -> windowed elif self.preview_layout == PreviewLayout.WINDOWED and self.preview_layout_cache in [PreviewLayout.FULL_WIDTH, PreviewLayout.HALF_WIDTH, PreviewLayout.HALF_HEIGHT]: self.hide() d = self.main_window.flap.connect("notify::reveal-progress", reatach_stack) # none -> windowed else: self.main_window.flap.remove(self.main_window.flap.get_flap()) self.preview_layout_cache = self.preview_layout def on_window_title_changed(self, *args, **kwargs): self.preview_window_title = self.main_window.get_title() + " - " + _("Preview") def on_window_closed(self, window, _event): self.main_window.lookup_action("preview").change_state(GLib.Variant.new_boolean(False)) ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������apostrophe-v2.6.3/apostrophe/preview_web_view.py����������������������������������������������������0000664�0000000�0000000�00000013340�14233044111�0022174�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Copyright (C) 2022, Manuel Genovés <manuel.genoves@gmail.com> # 2019, Gonçalo Silva # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 <http://www.gnu.org/licenses/>. # END LICENSE import webbrowser import gi gi.require_version('WebKit2', '4.0') from gi.repository import WebKit2, GLib, GObject class PreviewWebView(WebKit2.WebView): """A WebView that provides read/write access to scroll. It does so using JavaScript, by continuously monitoring it while loaded. The alternative is using a WebExtension and C-bindings (see reference), but that is more complicated implementation-wise, as well as build-wise until we start building with Meson. Reference: https://github.com/aperezdc/webkit2gtk-python-webextension-example """ SYNC_SCROLL_SCALE_JS = """ scale = {:.16f}; write = {}; // Configure MathJax. if (typeof hasMathJax === "undefined") {{ hasMathJax = false; if (typeof MathJax !== "undefined") {{ hasMathJax = typeof MathJax.Hub !== "undefined"; }} if (hasMathJax) {{ MathJax.Hub.Config({{ messageStyle: "none" }}); }} }} // Figure out if scrollable and rendered. e = document.documentElement; canScroll = e.scrollHeight > e.clientHeight; wasRendered = typeof isRendered !== "undefined" && isRendered; isRendered = wasRendered || !hasMathJax || MathJax.Hub.queue.running == 0 && MathJax.Hub.queue.pending == 0; // Write the current scroll if instructed or if it was just rendered. if (canScroll && (write || isRendered && !wasRendered)) {{ e.scrollTop = (e.scrollHeight - e.clientHeight) * scale; }} // Return the current scroll if scrollable and rendered, or -1. if (canScroll && isRendered) {{ e.scrollTop / (e.scrollHeight - e.clientHeight); }} else {{ -1; }} """.strip() __gsignals__ = { "scroll-scale-changed": (GObject.SIGNAL_RUN_LAST, None, (float,)), } def __init__(self): super().__init__() self.connect("size-allocate", self.on_size_allocate) self.connect("decide-policy", self.on_decide_policy) self.connect("load-changed", self.on_load_changed) self.connect("load-failed", self.on_load_failed) self.connect("destroy", self.on_destroy) self.props.expand = True self.scroll_scale = -1 self.state_loaded = False self.state_load_failed = False self.state_discard_read = False self.state_dirty = False self.state_waiting = False self.timeout_id = None def can_scroll(self): return self.scroll_scale != -1 def get_scroll_scale(self): return self.scroll_scale def set_scroll_scale(self, scale): self.state_dirty = scale != self.scroll_scale self.scroll_scale = scale self.state_loop() def on_size_allocate(self, *_): self.set_scroll_scale(self.scroll_scale) def on_decide_policy(self, _web_view, decision, decision_type): if decision_type == WebKit2.PolicyDecisionType.NAVIGATION_ACTION and \ decision.get_navigation_action().is_user_gesture(): webbrowser.open(decision.get_request().get_uri()) decision.ignore() # Do not follow the link in the WebView return True return False def on_load_changed(self, _web_view, event): self.state_loaded = event >= WebKit2.LoadEvent.COMMITTED and not self.state_load_failed self.state_load_failed = False self.state_discard_read = event == WebKit2.LoadEvent.STARTED and self.state_waiting self.state_dirty = True self.state_loop() def on_load_failed(self, _web_view, _event): self.state_loaded = False self.state_load_failed = True self.state_loop() def on_destroy(self, _widget): self.state_loaded = False self.state_loop() def sync_scroll_scale(self, scroll_scale, write): self.state_waiting = True self.run_javascript( self.SYNC_SCROLL_SCALE_JS.format( scroll_scale, "true" if write else "false"), None, self.finish_sync_scroll_scale) def finish_sync_scroll_scale(self, _web_view, result): self.state_waiting = False result = self.run_javascript_finish(result) self.state_loop(result.get_js_value().to_double()) def state_loop(self, scroll_scale=None, delay=16): # 16ms ~ 60hz # Remove any pending callbacks if self.timeout_id: GLib.source_remove(self.timeout_id) self.timeout_id = None # Set scroll scale if specified, and the state is not dirty if not self.state_discard_read and scroll_scale not in ( None, self.scroll_scale): self.scroll_scale = scroll_scale if self.scroll_scale != -1: self.emit("scroll-scale-changed", self.scroll_scale) self.state_discard_read = False # Handle the current state if not self.state_loaded or self.state_load_failed or self.state_waiting: return elif self.state_dirty or delay == 0: self.sync_scroll_scale(self.scroll_scale, self.state_dirty) self.state_dirty = False else: self.timeout_id = GLib.timeout_add(delay, self.state_loop, None, 0) ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������apostrophe-v2.6.3/apostrophe/preview_window.py������������������������������������������������������0000664�0000000�0000000�00000002163�14233044111�0021675�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Copyright (C) 2021, Manuel Genovés <manuel.genoves@gmail.com> # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 <http://www.gnu.org/licenses/>. # END LICENSE import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, Gdk, GObject, GLib, Gio, Handy @Gtk.Template(resource_path='/org/gnome/gitlab/somas/Apostrophe/ui/PreviewWindow.ui') class PreviewWindow(Handy.ApplicationWindow): __gtype_name__ = "ApostrophePreviewWindow" preview_box = Gtk.Template.Child() def __init__(self): super().__init__(application=Gio.Application.get_default(), title="Preview") �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������apostrophe-v2.6.3/apostrophe/search_and_replace.py��������������������������������������������������0000664�0000000�0000000�00000013631�14233044111�0022411�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Copyright (C) 2022, Manuel Genovés <manuel.genoves@gmail.com> # 2019, Wolf Vollprecht <w.vollprecht@gmail.com> # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 <http://www.gnu.org/licenses/>. # END LICENSE import logging import re import gi from apostrophe.helpers import user_action gi.require_version('Gtk', '3.0') from gi.repository import Gtk, GObject LOGGER = logging.getLogger('apostrophe') @Gtk.Template(resource_path='/org/gnome/gitlab/somas/Apostrophe/ui/SearchBar.ui') class ApostropheSearchBar(Gtk.SearchBar): """ Adds (regex) search and replace functionality to apostrophe """ __gtype_name__ = "ApostropheSearchBar" replace_mode_enabled = GObject.property(type=bool, default=False) search_entry = Gtk.Template.Child() regex = Gtk.Template.Child() case_sensitive = Gtk.Template.Child() replace_entry = Gtk.Template.Child() def __init__(self): self.textbuffer = None self.matches = [] self.active = 0 def attach(self, textview): self.textview = textview self.textbuffer = textview.get_buffer() self.highlight = self.textbuffer.create_tag('search_highlight', background="yellow") @Gtk.Template.Callback() def search_enabled(self, _widget, _data): if self.get_search_mode(): self.textbuffer = self.textview.get_buffer() if self.textbuffer.get_has_selection(): self.search_entry.set_text(self.textbuffer.get_slice(*self.textbuffer.get_selection_bounds(), False)) self.search_entry.grab_focus() self.search() else: self.textbuffer.remove_tag(self.highlight, self.textbuffer.get_start_iter(), self.textbuffer.get_end_iter()) self.matches = [] self.textview.grab_focus() @Gtk.Template.Callback() def replace_enabled(self, _widget, _data): if not self.get_search_mode(): self.set_search_mode(True) @Gtk.Template.Callback() def search(self, _widget=None, _data=None, scroll=True): if not self.textbuffer: return searchtext = self.search_entry.get_text() context_start = self.textbuffer.get_start_iter() context_end = self.textbuffer.get_end_iter() text = self.textbuffer.get_slice(context_start, context_end, False) self.textbuffer.remove_tag(self.highlight, context_start, context_end) # case sensitive? flags = False if not self.case_sensitive.get_active(): flags = flags | re.I ## regex? if not self.regex.get_active(): searchtext = re.escape(searchtext) matches = re.finditer(searchtext, text, flags) self.matches = [] self.active = 0 for match in matches: self.matches.append((match.start(), match.end())) start_iter = self.textbuffer.get_iter_at_offset(match.start()) end_iter = self.textbuffer.get_iter_at_offset(match.end()) self.textbuffer.apply_tag(self.highlight, start_iter, end_iter) if scroll: self.scrollto(self.active) LOGGER.debug(searchtext) @Gtk.Template.Callback() def scrolltonext(self, _widget, _data=None): self.scrollto(self.active + 1) @Gtk.Template.Callback() def scrolltoprev(self, _widget, _data=None): self.scrollto(self.active - 1) def scrollto(self, index): if not self.matches: return self.active = index % len(self.matches) match = self.matches[self.active] start_iter = self.textbuffer.get_iter_at_offset(match[0]) end_iter = self.textbuffer.get_iter_at_offset(match[1]) # create a mark at the start of the coincidence to scroll to it mark = self.textbuffer.create_mark(None, start_iter, False) self.textview.scroller.scroll_to_mark(mark, center=True) # select coincidence self.textbuffer.select_range(start_iter, end_iter) @Gtk.Template.Callback() def hide(self, *arg, **kwargs): self.set_search_mode(False) @Gtk.Template.Callback() def replace_clicked(self, _widget, _data=None): self.replace(self.active) @Gtk.Template.Callback() def replace_all(self, _widget=None, _data=None): with user_action(self.textbuffer): for match in reversed(self.matches): self.__do_replace(match) self.search(scroll=False) def replace(self, searchindex, _inloop=False): with user_action(self.textbuffer): self.__do_replace(self.matches[searchindex]) active = self.active self.search(scroll=False) self.active = active self.scrollto(self.active) def __do_replace(self, match): start_iter = self.textbuffer.get_iter_at_offset(match[0]) end_iter = self.textbuffer.get_iter_at_offset(match[1]) self.textbuffer.delete(start_iter, end_iter) start_iter = self.textbuffer.get_iter_at_offset(match[0]) self.textbuffer.insert(start_iter, self.replace_entry.get_text()) # Since the searchbar is overlayed to the textview we need to # update its margin when the searchbar appears @Gtk.Template.Callback() def update_textview_margin(self, _widget, allocation): self.textview.update_vertical_margin(allocation.height)�������������������������������������������������������������������������������������������������������apostrophe-v2.6.3/apostrophe/settings.py������������������������������������������������������������0000664�0000000�0000000�00000002251�14233044111�0020463�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Copyright (C) 2022, Manuel Genovés <manuel.genoves@gmail.com> # 2019, Wolf Vollprecht <w.vollprecht@gmail.com> # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 <http://www.gnu.org/licenses/>. # END LICENSE from gi.repository import Gio class Settings(Gio.Settings): """ Apostrophe Settings """ def __init__(self): """ Init Settings """ Gio.Settings.__init__(self) @classmethod def new(cls): """ Return a new Settings object """ settings = Gio.Settings.new("org.gnome.gitlab.somas.Apostrophe") settings.__class__ = Settings return settings �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������apostrophe-v2.6.3/apostrophe/stats_counter.py�������������������������������������������������������0000664�0000000�0000000�00000010745�14233044111�0021527�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������import re from multiprocessing import Process, Pipe from gi.repository import GLib from apostrophe.markup_regex import ITALIC_ASTERISK, ITALIC_UNDERSCORE,\ BOLD_ITALIC, BOLD, STRIKETHROUGH, IMAGE, LINK, LINK_ALT, HORIZONTAL_RULE,\ LIST, MATH, TABLE, CODE_BLOCK, HEADER_UNDER, HEADER, BLOCK_QUOTE,\ ORDERED_LIST, FOOTNOTE_ID, FOOTNOTE class StatsCounter: """Counts characters, words, sentences and read time using a worker process.""" # Regexp that matches any character, # except for newlines and subsequent spaces. CHARACTERS = re.compile(r"[^\s]|(?:[^\S\n](?!\s))") # Regexp that matches Asian letters, general symbols and hieroglyphs, # as well as sequences of word characters optionally containing non-word # characters in-between. WORDS = re.compile(r"[\u3040-\uffff]|(?:\w+\S?\w*)+", re.UNICODE) # Regexp that matches sentence-ending punctuation characters, ie. # full stop, question mark, exclamation mark, paragraph, and variants. SENTENCES = re.compile(r"[^\n][.。।෴۔።?՞;⸮؟?፧꘏⳺⳻⁇﹖⁈⁉‽!﹗!՜߹႟᥄\n]+") # Regexp that matches paragraphs, ie. # anything separated by at least 2 newlines. PARAGRAPHS = re.compile(r"[^\n]+(\n{2,}|$)") # List of regexp whose matches should be replaced by their "text" group. # Order is important. MARKUP_REGEXP_REPLACE = ( BOLD_ITALIC, ITALIC_ASTERISK, ITALIC_UNDERSCORE, BOLD, STRIKETHROUGH, IMAGE, LINK, LINK_ALT, LIST, ORDERED_LIST, BLOCK_QUOTE, HEADER, HEADER_UNDER, CODE_BLOCK, TABLE, MATH, FOOTNOTE_ID, FOOTNOTE ) # List of regexp whose matches should be removed. Order is important. MARKUP_REGEXP_REMOVE = ( HORIZONTAL_RULE, ) def __init__(self, callback): super().__init__() # Worker process to handle counting. self.counting = False self.count_pending_text = None self.parent_conn, child_conn = Pipe() Process(target=self.do_count, args=(child_conn,), daemon=True).start() GLib.io_add_watch( self.parent_conn.fileno(), GLib.PRIORITY_LOW, GLib.IO_IN, self.on_counted, callback) def count(self, text): """Count stats for text. In case counting is already running, it will re-count once it finishes. This ensure that the pipe doesn't fill (and block) if multiple requests are made in quick succession.""" if not self.counting: self.counting = True self.count_pending_text = None self.parent_conn.send(text) else: self.count_pending_text = text def do_count(self, child_conn): """Counts stats in a worker process. The result is in the format (characters, words, sentences, (hours, minutes, seconds))""" while True: while True: try: text = child_conn.recv() if not child_conn.poll(): break except EOFError: child_conn.close() return for regexp in self.MARKUP_REGEXP_REPLACE: text = re.sub(regexp, r"\g<text>", text) for regexp in self.MARKUP_REGEXP_REMOVE: text = re.sub(regexp, "", text) character_count = len(re.findall(self.CHARACTERS, text)) word_count = len(re.findall(self.WORDS, text)) sentence_count = len(re.findall(self.SENTENCES, text)) paragraph_count = len(re.findall(self.PARAGRAPHS, text)) read_m, read_s = divmod(word_count / 200 * 60, 60) read_h, read_m = divmod(read_m, 60) read_time = (int(read_h), int(read_m), int(read_s)) child_conn.send( (character_count, word_count, sentence_count, paragraph_count, read_time)) def on_counted(self, _source, _condition, callback): """Reads the counting result from the pipe and triggers any pending count.""" self.counting = False if self.count_pending_text is not None: # self.count clears the pending text. self.count(self.count_pending_text) try: if self.parent_conn.poll(): callback(self.parent_conn.recv()) return True except EOFError: return False def stop(self): """Stops the worker process. StatsCounter shouldn't be used after this.""" self.parent_conn.close() ���������������������������apostrophe-v2.6.3/apostrophe/stats_handler.py�������������������������������������������������������0000664�0000000�0000000�00000007072�14233044111�0021464�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������from gettext import gettext as _ from gettext import ngettext from gi.repository import GLib, Gio, Gtk from apostrophe.settings import Settings from apostrophe.stats_counter import StatsCounter class StatsHandler: """Shows a default statistic on the stats button, and allows the user to toggle which one.""" # Must match the order/index defined in gschema.xml CHARACTERS = 0 WORDS = 1 SENTENCES = 2 PARAGRAPHS = 3 READ_TIME = 4 def __init__(self, stats_button, text_view): super().__init__() self.stats_button = stats_button self.stats_button.connect("clicked", self.on_stats_button_clicked) self.stats_button.connect("destroy", self.on_destroy) self.text_view = text_view self.text_view.get_buffer().connect("changed", self.on_text_changed) self.popover = None self.characters = 0 self.words = 0 self.sentences = 0 self.paragraphs = 0 self.read_time = (0, 0, 0) self.settings = Settings.new() self.stats_counter = StatsCounter(self.update_stats) self.update_default_stat() def on_stats_button_clicked(self, _button): self.stats_button.set_state_flags(Gtk.StateFlags.CHECKED, False) menu = Gio.Menu() stats = self.settings.props.settings_schema.get_key( "stat-default").get_range()[1] for i, stat in enumerate(stats): menu_item = Gio.MenuItem.new(self.get_text_for_stat(i), None) menu_item.set_action_and_target_value( "app.stat_default", GLib.Variant.new_string(stat)) menu.append_item(menu_item) self.popover = Gtk.Popover.new_from_model(self.stats_button, menu) self.popover.connect('closed', self.on_popover_closed) self.popover.popup() def on_popover_closed(self, _popover): self.stats_button.unset_state_flags(Gtk.StateFlags.CHECKED) self.popover = None self.text_view.grab_focus() def on_text_changed(self, buf): self.stats_counter.count( buf.get_text( buf.get_start_iter(), buf.get_end_iter(), False)) def get_text_for_stat(self, stat): if stat == self.CHARACTERS: return ngettext("{:n} Character", "{:n} Characters", self.characters).format(self.characters) elif stat == self.WORDS: return ngettext("{:n} Word", "{:n} Words", self.words).format(self.words) elif stat == self.SENTENCES: return ngettext("{:n} Sentence", "{:n} Sentences", self.sentences).format(self.sentences) elif stat == self.PARAGRAPHS: return ngettext("{:n} Paragraph", "{:n} Paragraphs", self.paragraphs).format(self.paragraphs) elif stat == self.READ_TIME: return _("{:d}:{:02d}:{:02d} Read Time").format(*self.read_time) else: raise ValueError("Unknown stat {}".format(stat)) def update_stats(self, stats): (characters, words, sentences, paragraphs, read_time) = stats self.characters = characters self.words = words self.sentences = sentences self.paragraphs = paragraphs self.read_time = read_time self.update_default_stat(False) def update_default_stat(self, close_popover=True): stat = self.settings.get_enum("stat-default") text = self.get_text_for_stat(stat) self.stats_button.set_label(text) if close_popover and self.popover: self.popover.popdown() def on_destroy(self, _widget): self.stats_counter.stop() ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������apostrophe-v2.6.3/apostrophe/text_view.py�����������������������������������������������������������0000664�0000000�0000000�00000030650�14233044111�0020645�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Copyright (C) 2022, Manuel Genovés <manuel.genoves@gmail.com> # 2019, Gonçalo Silva # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 <http://www.gnu.org/licenses/>. # END LICENSE import gi from apostrophe.helpers import user_action from apostrophe.inline_preview import InlinePreview from apostrophe.text_view_drag_drop_handler import DragDropHandler,\ TARGET_URI, TARGET_TEXT from apostrophe.text_view_format_inserter import FormatInserter from apostrophe.text_view_markup_handler import MarkupHandler from apostrophe.text_view_scroller import TextViewScroller from apostrophe.text_view_undo_redo_handler import UndoRedoHandler gi.require_version('Gtk', '3.0') gi.require_version('Gspell', '1') from gi.repository import Gtk, Gdk, GObject, GLib, Gspell import logging LOGGER = logging.getLogger('apostrophe') DEFAULT_DPI = 98304 @Gtk.Template(resource_path='/org/gnome/gitlab/somas/Apostrophe/ui/TextView.ui') class ApostropheTextView(Gtk.TextView): """ApostropheTextView encapsulates all the features around the editor. It combines the following: - Undo / redo (via TextBufferUndoRedoHandler) - Format shortcuts (via TextBufferShortcutInserter) - Markup (via TextBufferMarkupHandler) - Preview popover (via TextBufferMarkupHandler) - Drag and drop (via TextViewDragDropHandler) - Scrolling (via TextViewScroller) - The various modes supported by Apostrophe (e. Focus Mode, Hemingway Mode) """ __gtype_name__ = "ApostropheTextView" __gsignals__ = { 'insert-italic': (GObject.SignalFlags.ACTION, None, ()), 'insert-bold': (GObject.SignalFlags.ACTION, None, ()), 'insert-hrule': (GObject.SignalFlags.ACTION, None, ()), 'insert-listitem': (GObject.SignalFlags.ACTION, None, ()), 'insert-header': (GObject.SignalFlags.ACTION, None, ()), 'insert-strikethrough': (GObject.SignalFlags.ACTION, None, ()), 'undo': (GObject.SignalFlags.ACTION, None, ()), 'redo': (GObject.SignalFlags.ACTION, None, ()), 'scroll-scale-changed': (GObject.SIGNAL_RUN_LAST, None, (float,)), } bigger_text = GObject.Property(type=bool, default=False) hemingway_mode = GObject.Property(type=bool, default=False) focus_mode = GObject.Property(type=bool, default=False) font_size = GObject.Property(type=int, default=16) line_chars = GObject.Property(type=int, default=66) spellcheck = GObject.Property(type=bool, default=True) scroller = None _scroll_scale = 0 @GObject.Property(type=float, default=0) def scroll_scale(self): return self.scroller.get_scroll_scale() if self.scroller else 0 @scroll_scale.setter def scroll_scale(self, scale): if self.scroller: self.scroller.set_scroll_scale(scale) def __init__(self): super().__init__() # Spell checking self.gspell_view = Gspell.TextView.get_from_gtk_text_view(self) self.gspell_view.basic_setup() # Undo / redo self.undo_redo = UndoRedoHandler() self.get_buffer().connect('begin-user-action', self.undo_redo.on_begin_user_action) self.get_buffer().connect('end-user-action', self.undo_redo.on_end_user_action) self.get_buffer().connect('insert-text', self.undo_redo.on_insert_text) self.get_buffer().connect('delete-range', self.undo_redo.on_delete_range) self.connect('undo', self.undo_redo.undo) self.connect('redo', self.undo_redo.redo) # Format shortcuts self.shortcut = FormatInserter() self.connect('insert-italic', self.shortcut.insert_italic) self.connect('insert-bold', self.shortcut.insert_bold) self.connect('insert-strikethrough', self.shortcut.insert_strikethrough) self.connect('insert-hrule', self.shortcut.insert_horizontal_rule) self.connect('insert-listitem', self.shortcut.insert_list_item) self.connect('insert-header', self.shortcut.insert_header) # Markup self.markup = MarkupHandler(self) self.connect('style-updated', self.markup.on_style_updated) self.connect('destroy', self.markup.stop) # Preview popover self.preview_popover = InlinePreview(self) # Drag and drop self.drag_drop = DragDropHandler(self, TARGET_URI, TARGET_TEXT) # While resizing the TextView, there is unwanted scroll upwards # if a top margin is present. # When a size allocation is detected, this variable will hold # the scroll to re-set until the UI is idle again. # TODO: Find a better way to handle unwanted scroll. self.frozen_scroll_scale = None def get_text(self): text_buffer = self.get_buffer() start_iter = text_buffer.get_start_iter() end_iter = text_buffer.get_end_iter() return text_buffer.get_text(start_iter, end_iter, False) def set_text(self, text): """Set text and clear undo history""" text_buffer = self.get_buffer() with user_action(text_buffer): text_buffer.set_text(text) self.undo_redo.clear() def update_vertical_margin(self, top_margin=0): if self.focus_mode: height = self.get_allocation().height + top_margin # The height/6 may seem strange. It's a workaround for a GTK bug # If a top-margin is larger than a certain amount of # the TextView height, jumps may occur when pressing enter. # TODO: check again in GTK4 self.set_top_margin(height / 2 + top_margin - height/6) self.set_bottom_margin(height / 2) else: self.props.top_margin = 80 + top_margin self.props.bottom_margin = 64 def clear(self): """Clear text and undo history""" self.set_text('') def smooth_scroll_to(self, mark=None): """Scrolls if needed to ensure mark is visible. If mark is unspecified, the cursor is used.""" if self.scroller is None: return if mark is None: mark = self.get_buffer().get_insert() GLib.idle_add(self.scroller.smooth_scroll_to_mark, mark, self.focus_mode) @Gtk.Template.Callback() def _on_button_release_event(self, _widget, _event): if self.focus_mode: self.markup.apply() return False @Gtk.Template.Callback() def _on_focus_mode_update(self, *args, **kwargs): self.update_vertical_margin() self.markup.apply() self.smooth_scroll_to() self._on_spellcheck_update() self.grab_focus() @Gtk.Template.Callback() def _on_key_press_event(self, _widget, event): if self.hemingway_mode: return event.keyval == Gdk.KEY_BackSpace or event.keyval == Gdk.KEY_Delete if event.state & Gdk.ModifierType.SHIFT_MASK == Gdk.ModifierType.SHIFT_MASK \ and event.keyval == Gdk.KEY_ISO_Left_Tab: # Capure Shift-Tab self._on_shift_tab() return True @Gtk.Template.Callback() def _on_mark_set(self, _text_buffer, _location, mark, _data=None): if mark.get_name() == 'selection_bound': self.markup.apply() if not self.get_buffer().get_has_selection(): self.smooth_scroll_to(mark) elif mark.get_name() == 'gtk_drag_target': self.smooth_scroll_to(mark) return True # TODO: this seems a little backwards way to hook things up @Gtk.Template.Callback() def _on_parent_set(self, *_): parent = self.get_parent() if parent: parent.set_size_request(self.get_min_width(), 500) self.scroller = TextViewScroller(self, parent) parent.get_vadjustment().connect("changed", self._on_vadjustment_changed) parent.get_vadjustment().connect("value-changed", self._on_vadjustment_changed) else: self.scroller = None @Gtk.Template.Callback() def _on_paste_done(self, *_): self.smooth_scroll_to() def _on_shift_tab(self): """Delete last character if it is a tab""" text_buffer = self.get_buffer() pen_iter = text_buffer.get_end_iter() pen_iter.backward_char() end_iter = text_buffer.get_end_iter() if pen_iter.get_char() == "\t": with user_action(text_buffer): text_buffer.delete(pen_iter, end_iter) @Gtk.Template.Callback() def _on_size_allocate(self, *_): self._update_horizontal_margin() self.markup.update_margins_indents() self.queue_draw() # TODO: Find a better way to handle unwanted scroll on resize. self.frozen_scroll_scale = self.scroll_scale GLib.idle_add(self._unfreeze_scroll_scale) @Gtk.Template.Callback() def _on_spellcheck_update(self, *args, **kwargs): self.gspell_view.set_inline_spell_checking( self.spellcheck and not self.focus_mode) @Gtk.Template.Callback() def _on_text_changed(self, *_): self.markup.apply() self.smooth_scroll_to() def _on_vadjustment_changed(self, *_): if self.frozen_scroll_scale is not None: self.scroll_scale = self.frozen_scroll_scale elif self.scroller.can_scroll(): self.emit("scroll-scale-changed", self.scroll_scale) def _unfreeze_scroll_scale(self): self.frozen_scroll_scale = None self.queue_draw() @Gtk.Template.Callback() def _update_horizontal_margin(self, *args, **kwargs): width = self.get_allocation().width # Ensure the appropriate font size is being used for font_size in self._get_font_sizes(): if width >= self.get_min_width(font_size): if font_size != self.font_size: self.font_size = font_size style_ctxt = self.get_style_context() for size_class in filter(lambda style_class: style_class.startswith("size"), style_ctxt.list_classes()): style_ctxt.remove_class(size_class) style_ctxt.add_class("size{}".format(font_size)) break else: return # Apply margin with the remaining space to allow for markup line_width = (self.line_chars + 1) *\ int(self._get_char_width(self.font_size)) - 1 horizontal_margin = (width - line_width) / 2 self.props.left_margin = horizontal_margin self.props.right_margin = horizontal_margin def _get_font_sizes(self): font_sizes_list = [20, 18, 17, 16, 15, 14] if self.bigger_text: font_sizes_list[:0] = [24, 22] return font_sizes_list def get_min_width(self, font_size=None): """Returns the minimum width of this text view.""" if font_size is None: font_size = self._get_font_sizes()[-1] return (self.line_chars + self._get_pad_chars(font_size) + 1) \ * self._get_char_width(font_size) - 1 def _get_pad_chars(self, font_size): """Returns the amount of character padding for font_size. Markup can use up to 7 in normal conditions.""" if self.bigger_text: return 8 * int((1 + (font_size - self._get_font_sizes()[-1])/3)) else: return 8 * (1 + font_size - self._get_font_sizes()[-1]) @staticmethod def _get_char_width(font_size): """Returns the font width for a given size. Note: specific to Fira Mono!""" # We scale by the text scale factor system-wide setting. # In the css the units are in em so they're automatically scaled # 14.666px == 1em settings = Gtk.Settings.get_default() scale_factor = settings.props.gtk_xft_dpi / DEFAULT_DPI return scale_factor * font_size * 1 / 1.6 ����������������������������������������������������������������������������������������apostrophe-v2.6.3/apostrophe/text_view_drag_drop_handler.py�����������������������������������������0000664�0000000�0000000�00000006536�14233044111�0024371�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������import mimetypes import urllib from gettext import gettext as _ from os.path import basename from apostrophe.settings import Settings from gi.repository import Gtk (TARGET_URI, TARGET_TEXT) = range(2) class DragDropHandler: TARGET_URI = None def __init__(self, text_view, *targets): super().__init__() self.settings = Settings.new() self.target_list = Gtk.TargetList.new([]) if TARGET_URI in targets: self.target_list.add_uri_targets(TARGET_URI) if TARGET_TEXT in targets: self.target_list.add_text_targets(TARGET_TEXT) text_view.drag_dest_set_target_list(self.target_list) text_view.connect_after( 'drag-data-received', self.on_drag_data_received) def on_drag_data_received( self, text_view, drag_context, _x, _y, data, info, time): """Handle drag and drop events""" text_buffer = text_view.get_buffer() if info == TARGET_URI: uris = data.get_uris() for uri in uris: name = basename(urllib.parse.unquote_plus(uri)) mime = mimetypes.guess_type(uri) if mime[0] is not None and mime[0].startswith('image/'): basepath = self.settings.get_string("open-file-path") basepath = urllib.parse.quote(basepath) if uri.startswith("file://"): uri = uri[7:] # for handling local URIs we need to substract the basepath # except when it is "/" (document not saved) if uri.startswith(basepath) and basepath != "/": uri = uri[len(basepath) + 1:] text = "![{}]({})".format(name, uri) limit_left = 2 limit_right = len(name) else: text = "[{}]({})".format(name, uri) limit_left = 1 limit_right = len(name) elif info == TARGET_TEXT: text = data.get_text() # delete automatically added DnD text insert_mark = text_buffer.get_insert() cursor_iter_r = text_buffer.get_iter_at_mark(insert_mark) cursor_iter_l = cursor_iter_r.copy() cursor_iter_l.backward_chars(len(data.get_text())) text_buffer.delete(cursor_iter_l, cursor_iter_r) if text.startswith(("http://", "https://", "www.")): text = "[{}]({})".format(_("web page"), text) limit_left = 1 limit_right = len(_("web page")) else: limit_left = 0 limit_right = 0 text_buffer.place_cursor(text_buffer.get_iter_at_mark( text_buffer.get_mark('gtk_drag_target'))) text_buffer.insert_at_cursor(text) insert_mark = text_buffer.get_insert() selection_bound = text_buffer.get_selection_bound() cursor_iter = text_buffer.get_iter_at_mark(insert_mark) cursor_iter.backward_chars(len(text) - limit_left) text_buffer.move_mark(insert_mark, cursor_iter) cursor_iter.forward_chars(limit_right) text_buffer.move_mark(selection_bound, cursor_iter) Gtk.drag_finish(drag_context, True, True, time) text_view.get_toplevel().present_with_time(time) return False ������������������������������������������������������������������������������������������������������������������������������������������������������������������apostrophe-v2.6.3/apostrophe/text_view_format_inserter.py�������������������������������������������0000664�0000000�0000000�00000015062�14233044111�0024130�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������from gettext import gettext as _ from apostrophe.helpers import user_action class FormatInserter: """Manages insertion of formatting. Methods can be called directly, as well as be used as signal callbacks.""" def insert_italic(self, text_view, _data=None): """Insert italic or mark a selection as bold""" self.__wrap(text_view, "_", _("italic text")) def insert_bold(self, text_view, _data=None): """Insert bold or mark a selection as bold""" self.__wrap(text_view, "**", _("bold text")) def insert_strikethrough(self, text_view, _data=None): """Insert strikethrough or mark a selection as strikethrough""" self.__wrap(text_view, "~~", _("strikethrough text")) def insert_horizontal_rule(self, text_view, _data=None): """Insert horizontal rule""" text_buffer = text_view.get_buffer() with user_action(text_buffer): text_buffer.insert_at_cursor("\n\n---\n") text_view.scroll_mark_onscreen(text_buffer.get_insert()) def insert_list_item(self, text_view, _data=None): """Insert list item or mark a selection as list item""" text_buffer = text_view.get_buffer() if text_buffer.get_has_selection(): (start, end) = text_buffer.get_selection_bounds() if start.starts_line(): with user_action(text_buffer): text = text_buffer.get_text(start, end, False) if text.startswith(("- ", "* ", "+ ")): delete_end = start.copy() delete_end.forward_chars(2) text_buffer.delete(start, delete_end) else: text_buffer.insert(start, "- ") else: helptext = _("Item") text_length = len(helptext) cursor_mark = text_buffer.get_insert() cursor_iter = text_buffer.get_iter_at_mark(cursor_mark) start_ext = cursor_iter.copy() start_ext.backward_lines(3) text = text_buffer.get_text(cursor_iter, start_ext, False) lines = text.splitlines() with user_action(text_buffer): for line in reversed(lines): if line and line.startswith(("- ", "* ", "+ ")): if cursor_iter.starts_line(): text_buffer.insert_at_cursor(line[:2] + helptext) else: text_buffer.insert_at_cursor( "\n" + line[:2] + helptext) break else: if not lines[-1] and not lines[-2]: text_buffer.insert_at_cursor("- " + helptext) elif not lines[-1]: if cursor_iter.starts_line(): text_buffer.insert_at_cursor("- " + helptext) else: text_buffer.insert_at_cursor("\n- " + helptext) else: text_buffer.insert_at_cursor("\n\n- " + helptext) break self.__select_text(text_view, 0, text_length) def insert_ordered_list_item(self, _text_view, _data=None): # TODO: implement ordered lists pass def insert_header(self, text_view, _data=None): """Insert header or mark a selection as a list header""" text_buffer = text_view.get_buffer() with user_action(text_buffer): if text_buffer.get_has_selection(): (start, end) = text_buffer.get_selection_bounds() text = text_buffer.get_text(start, end, False) text_buffer.delete(start, end) else: text = _("Header") text_buffer.insert_at_cursor("#" + " " + text) self.__select_text(text_view, 0, len(text)) @staticmethod def __wrap(text_view, wrap, helptext=""): """Inserts wrap format to the selected text (helper text when nothing selected)""" text_buffer = text_view.get_buffer() with user_action(text_buffer): if text_buffer.get_has_selection(): # Find current highlighting (start, end) = text_buffer.get_selection_bounds() moved = False if (start.get_offset() >= len(wrap) and end.get_offset() <= text_buffer.get_char_count() - len(wrap)): moved = True ext_start = start.copy() ext_start.backward_chars(len(wrap)) ext_end = end.copy() ext_end.forward_chars(len(wrap)) text = text_buffer.get_text(ext_start, ext_end, True) else: text = text_buffer.get_text(start, end, True) if moved and text.startswith(wrap) and text.endswith(wrap): text = text[len(wrap):-len(wrap)] new_text = text text_buffer.delete(ext_start, ext_end) move_back = 0 else: if moved: text = text[len(wrap):-len(wrap)] new_text = text.lstrip().rstrip() text = text.replace(new_text, wrap + new_text + wrap) text_buffer.delete(start, end) move_back = len(wrap) text_buffer.insert_at_cursor(text) text_length = len(new_text) else: text_buffer.insert_at_cursor(wrap + helptext + wrap) text_length = len(helptext) move_back = len(wrap) cursor_mark = text_buffer.get_insert() cursor_iter = text_buffer.get_iter_at_mark(cursor_mark) cursor_iter.backward_chars(move_back) text_buffer.move_mark_by_name('selection_bound', cursor_iter) cursor_iter.backward_chars(text_length) text_buffer.move_mark_by_name('insert', cursor_iter) @staticmethod def __select_text(text_view, offset, length): """Selects text starting at the current cursor minus offset, length characters.""" text_buffer = text_view.get_buffer() cursor_mark = text_buffer.get_insert() cursor_iter = text_buffer.get_iter_at_mark(cursor_mark) cursor_iter.backward_chars(offset) text_buffer.move_mark_by_name('selection_bound', cursor_iter) cursor_iter.backward_chars(length) text_buffer.move_mark_by_name('insert', cursor_iter) ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������apostrophe-v2.6.3/apostrophe/text_view_markup_handler.py��������������������������������������������0000664�0000000�0000000�00000042453�14233044111�0023725�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Copyright (C) 2022, Manuel Genovés <manuel.genoves@gmail.com> # 2019, Gonçalo Silva # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 <http://www.gnu.org/licenses/>. # END LICENSE from gi.repository import Pango from gi.repository import Gtk, GLib import re from multiprocessing import Pipe, Process import gi from apostrophe import helpers, markup_regex from apostrophe.markup_regex import STRIKETHROUGH, BOLD_ITALIC,\ BOLD, ITALIC_ASTERISK, ITALIC_UNDERSCORE, IMAGE, LINK, LINK_ALT,\ HORIZONTAL_RULE, LIST, ORDERED_LIST, BLOCK_QUOTE, HEADER, HEADER_UNDER,\ TABLE, MATH, CODE gi.require_version('Gtk', '3.0') class MarkupHandler: TAG_NAME_ITALIC = 'italic' TAG_NAME_BOLD = 'bold' TAG_NAME_BOLD_ITALIC = 'bold_italic' TAG_NAME_STRIKETHROUGH = 'strikethrough' TAG_NAME_CENTER = 'center' TAG_NAME_WRAP_NONE = 'wrap_none' TAG_NAME_PLAIN_TEXT = 'plain_text' TAG_NAME_GRAY_TEXT = 'gray_text' TAG_NAME_CODE_TEXT = 'code_text' TAG_NAME_CODE_BLOCK = 'code_block' TAG_NAME_UNFOCUSED_TEXT = 'unfocused_text' TAG_NAME_MARGIN_INDENT = 'margin_indent' def __init__(self, text_view): self.text_view = text_view self.text_buffer = text_view.get_buffer() self.marked_up_text = None # Tags. buffer = self.text_buffer self.tag_italic = buffer.create_tag(self.TAG_NAME_ITALIC, weight=Pango.Weight.NORMAL, style=Pango.Style.ITALIC) self.tag_bold = buffer.create_tag(self.TAG_NAME_BOLD, weight=Pango.Weight.BOLD, style=Pango.Style.NORMAL) self.tag_bold_italic = buffer.create_tag(self.TAG_NAME_BOLD_ITALIC, weight=Pango.Weight.BOLD, style=Pango.Style.ITALIC) self.tag_strikethrough = buffer.create_tag(self.TAG_NAME_STRIKETHROUGH, strikethrough=True) self.tag_center = buffer.create_tag(self.TAG_NAME_CENTER, justification=Gtk.Justification.CENTER) self.tag_wrap_none = buffer.create_tag(self.TAG_NAME_WRAP_NONE, wrap_mode=Gtk.WrapMode.NONE, pixels_above_lines=0, pixels_below_lines=0) self.tag_plain_text = buffer.create_tag(self.TAG_NAME_PLAIN_TEXT, weight=Pango.Weight.NORMAL, style=Pango.Style.NORMAL, strikethrough=False, justification=Gtk.Justification.LEFT) self.tag_gray_text = buffer.create_tag(self.TAG_NAME_GRAY_TEXT, foreground='gray', weight=Pango.Weight.NORMAL, style=Pango.Style.NORMAL) self.tag_code_text = buffer.create_tag(self.TAG_NAME_CODE_TEXT, weight=Pango.Weight.NORMAL, style=Pango.Style.NORMAL, strikethrough=False) self.tag_code_block = buffer.create_tag(self.TAG_NAME_CODE_BLOCK, weight=Pango.Weight.NORMAL, style=Pango.Style.NORMAL, strikethrough=False, indent=self.get_margin_indent(0, 1)[1]) self.tags_markup = { self.TAG_NAME_ITALIC: lambda args: self.tag_italic, self.TAG_NAME_BOLD: lambda args: self.tag_bold, self.TAG_NAME_BOLD_ITALIC: lambda args: self.tag_bold_italic, self.TAG_NAME_STRIKETHROUGH: lambda args: self.tag_strikethrough, self.TAG_NAME_CENTER: lambda args: self.tag_center, self.TAG_NAME_WRAP_NONE: lambda args: self.tag_wrap_none, self.TAG_NAME_PLAIN_TEXT: lambda args: self.tag_plain_text, self.TAG_NAME_GRAY_TEXT: lambda args: self.tag_gray_text, self.TAG_NAME_CODE_TEXT: lambda args: self.tag_code_text, self.TAG_NAME_CODE_BLOCK: lambda args: self.tag_code_block, self.TAG_NAME_MARGIN_INDENT: lambda args: self.get_margin_indent_tag( *args) } # Focus mode. self.tag_unfocused_text = buffer.create_tag(self.TAG_NAME_UNFOCUSED_TEXT, foreground='gray', weight=Pango.Weight.NORMAL, style=Pango.Style.NORMAL) # Margin and indents. # A baseline margin is set to allow negative offsets for formatting # headers, lists, etc. self.tags_margins_indents = {} self.baseline_margin = 0 self.char_width = 0 self.update_margins_indents() # Style. self.on_style_updated() # Worker process to handle parsing. self.parsing = False self.apply_pending = False self.parent_conn, child_conn = Pipe() Process(target=self.parse, args=(child_conn,), daemon=True).start() GLib.io_add_watch( self.parent_conn.fileno(), GLib.PRIORITY_DEFAULT, GLib.IO_IN, self.on_parsed) def on_style_updated(self, *_): style_context = self.text_view.get_style_context() (found, color) = style_context.lookup_color('code_bg_color') if not found: (_, color) = style_context.lookup_color('background_color') self.tag_code_text.set_property("background", color.to_string()) self.tag_code_block.set_property( "paragraph-background", color.to_string()) def apply(self): """Applies markup, parsing it in a worker process if the text has changed. In case parsing is already running, it will re-apply once it finishes. This ensure that the pipe doesn't fill (and block) if multiple requests are made in quick succession.""" if not self.parsing: self.parsing = True self.apply_pending = False text = self.text_buffer.get_slice( self.text_buffer.get_start_iter(), self.text_buffer.get_end_iter(), False) if text != self.marked_up_text: self.parent_conn.send(text) else: self.do_apply(text) else: self.apply_pending = True def parse(self, child_conn): """Parses markup in a worker process.""" while True: while True: try: text = child_conn.recv() if not child_conn.poll(): break except EOFError: child_conn.close() return # List of tuples in the form (tag_name, tag_args, tag_start, # tag_end). result = [] # Find: # - "_italic_" (italic) # - "**bold**" (bold) # - "***bolditalic***" (bold/italic) # - "~~strikethrough~~" (strikethrough) # - "`code`" (colorize) # - "$math$" (colorize) # - "---" table (wrap/pixels) regexps = ( (ITALIC_ASTERISK, self.TAG_NAME_ITALIC), (ITALIC_UNDERSCORE, self.TAG_NAME_ITALIC), (BOLD, self.TAG_NAME_BOLD), (BOLD_ITALIC, self.TAG_NAME_BOLD_ITALIC), (STRIKETHROUGH, self.TAG_NAME_STRIKETHROUGH), (CODE, self.TAG_NAME_CODE_TEXT), (MATH, self.TAG_NAME_CODE_TEXT), (TABLE, self.TAG_NAME_WRAP_NONE) ) for regexp, tag_name in regexps: matches = re.finditer(regexp, text) for match in matches: result.append((tag_name, (), match.start(), match.end())) # Find: # - "[description](url)" (gray out) # - "![description](image_url)" (gray out) regexps = ( (LINK, self.TAG_NAME_GRAY_TEXT), (IMAGE, self.TAG_NAME_GRAY_TEXT) ) for regexp, tag_name in regexps: matches = re.finditer(regexp, text) for match in matches: result.append( (tag_name, (), match.start(), match.start("text"))) result.append( (tag_name, (), match.end("text"), match.end())) # Find "<url>" links (gray out). matches = re.finditer(LINK_ALT, text) for match in matches: result.append(( self.TAG_NAME_GRAY_TEXT, (), match.start("text"), match.end("text"))) # Find "---" horizontal rule (center). matches = re.finditer(HORIZONTAL_RULE, text) for match in matches: result.append(( self.TAG_NAME_CENTER, (), match.start("symbols"), match.end("symbols"))) # Find "* list" (offset). matches = re.finditer(LIST, text) for match in matches: # Lists use character+space (eg. "* "). length = 2 nest = len(match.group("indent").replace(" ", "\t")) margin = -length - 2 * nest indent = -length - 2 * length * nest result.append(( self.TAG_NAME_MARGIN_INDENT, (margin, indent), match.start("content"), match.end("content") )) # Find "1. ordered list" (offset). matches = re.finditer(ORDERED_LIST, text) for match in matches: # Ordered lists use numbers/letters+dot/parens+space # (eg. "123. "). length = len(match.group("prefix")) + 1 nest = len(match.group("indent").replace(" ", "\t")) margin = -length - 2 * nest indent = -length - 2 * length * nest result.append(( self.TAG_NAME_MARGIN_INDENT, (margin, indent), match.start("content"), match.end("content") )) # Find "> blockquote" (offset). matches = re.finditer(BLOCK_QUOTE, text) for match in matches: result.append((self.TAG_NAME_MARGIN_INDENT, (2, -2), match.start(), match.end())) # Find "# Header" (offset+bold). matches = re.finditer(HEADER, text) for match in matches: margin = -len(match.group("level")) - 1 result.append(( self.TAG_NAME_MARGIN_INDENT, (margin, 0), match.start(), match.end())) result.append( (self.TAG_NAME_BOLD, (), match.start(), match.end())) # Find "=======" header underline (bold). matches = re.finditer(HEADER_UNDER, text) for match in matches: result.append( (self.TAG_NAME_BOLD, (), match.start(), match.end())) # Find "```" code block tag (offset + colorize paragraph). matches = re.finditer(markup_regex.CODE_BLOCK, text) for match in matches: result.append(( self.TAG_NAME_CODE_BLOCK, (), match.start("block"), match.end("block"))) # Send parsed data back. child_conn.send((text, result)) def on_parsed(self, _source, _condition): """Reads the parsing result from the pipe and triggers any pending apply.""" self.parsing = False if self.apply_pending: self.apply() # self.apply clears the apply pending flag. try: if self.parent_conn.poll(): self.do_apply(*self.parent_conn.recv()) return True except EOFError: return False def do_apply(self, original_text, result=[]): """Applies the result of parsing if the current text matches the original text.""" buffer = self.text_buffer start = buffer.get_start_iter() end = buffer.get_end_iter() text = self.text_buffer.get_slice(start, end, False) # Apply markup tags. if text == original_text and text != self.marked_up_text: buffer.remove_tag(self.tag_italic, start, end) buffer.remove_tag(self.tag_bold, start, end) buffer.remove_tag(self.tag_bold_italic, start, end) buffer.remove_tag(self.tag_strikethrough, start, end) buffer.remove_tag(self.tag_center, start, end) buffer.remove_tag(self.tag_plain_text, start, end) buffer.remove_tag(self.tag_gray_text, start, end) buffer.remove_tag(self.tag_code_text, start, end) buffer.remove_tag(self.tag_code_block, start, end) buffer.remove_tag(self.tag_wrap_none, start, end) for tag in self.tags_margins_indents.values(): buffer.remove_tag(tag, start, end) for tag_name, tag_args, tag_start, tag_end in result: buffer.apply_tag( self.tags_markup[tag_name](tag_args), buffer.get_iter_at_offset(tag_start), buffer.get_iter_at_offset(tag_end)) # Apply focus mode tag (grey out before/after current sentence). buffer.remove_tag(self.tag_unfocused_text, start, end) if self.text_view.focus_mode: cursor_iter = buffer.get_iter_at_mark(buffer.get_insert()) start_sentence = cursor_iter.copy() if not start_sentence.starts_sentence(): start_sentence.backward_sentence_start() end_sentence = cursor_iter.copy() if not end_sentence.ends_sentence(): end_sentence.forward_sentence_end() buffer.apply_tag(self.tag_unfocused_text, start, start_sentence) buffer.apply_tag(self.tag_unfocused_text, end_sentence, end) # Margin and indent are cumulative. They differ in two ways: # * Margin is always in the beginning, # which means it effectively only affects the first line # of multi-line text. Indent is applied to every line. # * Margin level can be negative, as a baseline margin exists # from which it can be subtracted. # Indent is always positive, or 0. def get_margin_indent_tag(self, margin_level, indent_level): level = (margin_level, indent_level) if level not in self.tags_margins_indents: margin, indent = self.get_margin_indent(margin_level, indent_level) tag = self.text_buffer.create_tag( "margin_indent_{}_{}".format(margin_level, indent_level), left_margin=margin, indent=indent) self.tags_margins_indents[level] = tag return tag else: return self.tags_margins_indents[level] def get_margin_indent(self, margin_level, indent_level, baseline_margin=None, char_width=None): if baseline_margin is None: baseline_margin = self.text_view.props.left_margin if char_width is None: char_width = helpers.get_char_width(self.text_view) margin = max(baseline_margin + char_width * margin_level, 0) indent = char_width * indent_level return margin, indent def update_margins_indents(self): baseline_margin = self.text_view.props.left_margin char_width = helpers.get_char_width(self.text_view) # Bail out if neither the baseline margin nor character width change if baseline_margin == self.baseline_margin and char_width == self.char_width: return self.baseline_margin = baseline_margin self.char_width = char_width # Adjust tab size tab_array = Pango.TabArray.new(1, True) tab_array.set_tab(0, Pango.TabAlign.LEFT, 4 * char_width) self.text_view.set_tabs(tab_array) # Adjust margins and indents for level, tag in self.tags_margins_indents.items(): margin, indent = self.get_margin_indent( *level, baseline_margin, char_width) tag.set_properties(left_margin=margin, indent=indent) def stop(self, *_): self.parent_conn.close() ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������apostrophe-v2.6.3/apostrophe/text_view_scroller.py��������������������������������������������������0000775�0000000�0000000�00000010632�14233044111�0022553�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Copyright (C) 2022, Manuel Genovés <manuel.genoves@gmail.com> # 2019, Gonçalo Silva # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 <http://www.gnu.org/licenses/>. # END LICENSE class TextViewScroller: def __init__(self, text_view, scrolled_window): super().__init__() self.text_view = text_view self.scrolled_window = scrolled_window self.smooth_scroller = None def can_scroll(self): vap = self.scrolled_window.get_vadjustment().props return vap.upper > vap.page_size def get_scroll_scale(self): vap = self.scrolled_window.get_vadjustment().props if vap.upper > vap.page_size: return vap.value / (vap.upper - vap.page_size) else: return 0 def set_scroll_scale(self, scale): vap = self.scrolled_window.get_vadjustment().props vap.value = (vap.upper - vap.page_size) * scale def scroll_to_mark(self, mark, center): """Scrolls until mark is visible, if needed.""" target_pos = self.get_target_pos_for_mark(mark, center) if target_pos: self.scrolled_window.get_vadjustment().set_value(target_pos) def smooth_scroll_to_mark(self, mark, center): """Smoothly scrolls until mark is visible, if needed.""" if self.smooth_scroller and self.smooth_scroller.is_started: self.smooth_scroller.end() target_pos = self.get_target_pos_for_mark(mark, center) if target_pos: source_pos = self.scrolled_window.get_vadjustment().props.value self.smooth_scroller = SmoothScroller( self.scrolled_window, source_pos, target_pos) self.smooth_scroller.start() def get_target_pos_for_mark(self, mark, center): margin = 32 mark_iter = self.text_view.get_buffer().get_iter_at_mark(mark) mark_rect = self.text_view.get_iter_location(mark_iter) vap = self.scrolled_window.get_vadjustment().props pos_y = mark_rect.y + mark_rect.height + self.text_view.props.top_margin pos_viewport_y = pos_y - vap.value target_pos = None if center: if pos_viewport_y != vap.page_size / 2: target_pos = pos_y - (vap.page_size / 2) elif pos_viewport_y > vap.page_size - margin: target_pos = pos_y - vap.page_size + margin elif pos_viewport_y < margin: target_pos = pos_y - margin - mark_rect.height return target_pos class SmoothScroller: def __init__(self, scrolled_window, source_pos, target_pos): super().__init__() self.scrolled_window = scrolled_window self.source_pos = source_pos self.target_pos = target_pos self.duration = max(100, (target_pos - source_pos) / 50) * 4000 self.is_started = False self.is_setup = False self.start_time = 0 self.end_time = 0 self.tick_callback_id = 0 def start(self): self.is_started = True self.tick_callback_id = self.scrolled_window.add_tick_callback( self.on_tick) def end(self): self.scrolled_window.remove_tick_callback(self.tick_callback_id) self.is_started = False def setup(self, time): self.start_time = time self.end_time = time + self.duration self.is_setup = True def on_tick(self, widget, frame_clock): def ease_out_cubic(value): return pow(value - 1, 3) + 1 now = frame_clock.get_frame_time() if not self.is_setup: self.setup(now) if now < self.end_time: time = float(now - self.start_time) / \ float(self.end_time - self.start_time) else: time = 1 self.end() time = ease_out_cubic(time) pos = self.source_pos + (time * (self.target_pos - self.source_pos)) widget.get_vadjustment().props.value = pos return True ������������������������������������������������������������������������������������������������������apostrophe-v2.6.3/apostrophe/text_view_undo_redo_handler.py�����������������������������������������0000664�0000000�0000000�00000020477�14233044111�0024406�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������import logging LOGGER = logging.getLogger('apostrophe') class UndoableInsert: """Something has been inserted into text_buffer""" def __init__(self, text_iter, text, length): self.offset = text_iter.get_offset() self.text = text self.length = length self.mergeable = not bool( self.length > 1 or self.text in ( "\r", "\n", " ")) def undo(self, text_buffer): offset = self.offset start = text_buffer.get_iter_at_offset(offset) stop = text_buffer.get_iter_at_offset(offset + self.length) text_buffer.place_cursor(start) text_buffer.delete(start, stop) def redo(self, text_buffer): start = text_buffer.get_iter_at_offset(self.offset) text_buffer.insert(start, self.text) new_cursor_pos = text_buffer.get_iter_at_offset( self.offset + self.length) text_buffer.place_cursor(new_cursor_pos) def merge(self, next_action): """Merge a following action into this insert, if possible can't merge if prev is not another insert can't merge if prev and cur are not mergeable in the first place can't merge when user set the input bar somewhere else can't merge across word boundaries""" if not isinstance(next_action, UndoableInsert): return False if not self.mergeable or not next_action.mergeable: return False if self.offset + self.length != next_action.offset: return False whitespace = (' ', '\t') if self.text in whitespace != next_action.text in whitespace: return False self.length += next_action.length self.text += next_action.text return True class UndoableDelete: """Something has been deleted from text_buffer""" def __init__(self, text_buffer, start_iter, end_iter): self.text = text_buffer.get_text(start_iter, end_iter, False) self.start = start_iter.get_offset() self.end = end_iter.get_offset() # Find out if backspace or delete were used to not mess up redo insert_iter = text_buffer.get_iter_at_mark(text_buffer.get_insert()) self.delete_key_used = bool(insert_iter.get_offset() <= self.start) self.mergeable = not bool( self.end - self.start > 1 or self.text in ( "\r", "\n", " ")) def undo(self, text_buffer): start = text_buffer.get_iter_at_offset(self.start) text_buffer.insert(start, self.text) if self.delete_key_used: text_buffer.place_cursor(start) else: stop = text_buffer.get_iter_at_offset(self.end) text_buffer.place_cursor(stop) def redo(self, text_buffer): start = text_buffer.get_iter_at_offset(self.start) stop = text_buffer.get_iter_at_offset(self.end) text_buffer.delete(start, stop) text_buffer.place_cursor(start) def merge(self, next_action): """Check if this delete can be merged with a previous action can't merge if prev is not another delete can't merge if prev and cur are not mergeable in the first place can't merge if delete and backspace key were both used can't merge across word boundaries""" if not isinstance(next_action, UndoableDelete): return False if not self.mergeable or not next_action.mergeable: return False if self.delete_key_used != next_action.delete_key_used: return False if self.start != next_action.start and self.start != next_action.end: return False whitespace = (' ', '\t') if self.text in whitespace != next_action.text in whitespace: return False if self.delete_key_used: self.text += next_action.text self.end += (next_action.end - next_action.start) else: self.text = "%s%s" % (next_action.text, self.text) self.start = next_action.start return True class UndoableGroup(list): """A list of undoable actions, usually corresponding to a single user action""" def undo(self, text_buffer): for undoable in reversed(self): undoable.undo(text_buffer) def redo(self, text_buffer): for undoable in self: undoable.redo(text_buffer) def merge(self, next_action): if len(self) == 1: return self[0].merge(next_action) else: return False class UndoRedoHandler: """Manages undo/redo for a given text_buffer. Methods can be called directly, as well as be used as signal callbacks.""" def __init__(self): self.undo_stack = [] self.redo_stack = [] self.current_undo_group = None self.undo_in_progress = False def undo(self, text_view, _data=None): """Undo insertions or deletions. Undone actions are moved to redo stack. This method can be registered to a custom undo signal, or used independently.""" if not self.undo_stack: return self.undo_in_progress = True undo_action = self.undo_stack.pop() self.redo_stack.append(undo_action) undo_action.undo(text_view.get_buffer()) self.undo_in_progress = False def redo(self, text_view, _data=None): """Redo insertions or deletions. Redone actions are moved to undo stack This method can be registered to a custom redo signal, or used independently.""" if not self.redo_stack: return self.undo_in_progress = True redo_action = self.redo_stack.pop() self.undo_stack.append(redo_action) redo_action.redo(text_view.get_buffer()) self.undo_in_progress = False def clear(self): self.undo_stack = [] self.redo_stack = [] def on_begin_user_action(self, _text_buffer): """Start of a user action. Refer to TextBuffer's "begin-user-action" signal. This method must be registered to TextBuffer's "begin-user-action" signal, or called manually followed by on_end_user_action.""" self.current_undo_group = UndoableGroup() def on_end_user_action(self, _text_buffer): """End of a user action. Refer to TextBuffer's "end-user-action" signal. This method must be registered to TextBuffer's "end-user-action" signal, or called manually preceded by on_start_user_action.""" if self.current_undo_group: self.undo_stack.append(self.current_undo_group) self.current_undo_group = None def on_insert_text(self, _text_buffer, text_iter, text, _length): """Records a text insert. Refer to TextBuffer's "insert-text" signal. This method must be registered to TextBuffer's "insert-text" signal, or called manually in between on_begin_user_action and on_end_user_action.""" self.__record_undoable(UndoableInsert(text_iter, text, len(text))) def on_delete_range(self, text_buffer, start_iter, end_iter): """Records a range deletion. Refer to TextBuffer's "delete-range" signal. This method must be registered to TextBuffer's "delete-range" signal, or called manually in between on_begin_user_action and on_end_user_action.""" self.__record_undoable( UndoableDelete( text_buffer, start_iter, end_iter)) def __record_undoable(self, undoable): """Records a change, merging it to a previous one if possible.""" if not self.undo_in_progress: self.redo_stack = [] else: return prev_group_undoable = self.current_undo_group[-1] if self.current_undo_group else None prev_stack_undoable = self.undo_stack[-1] if self.undo_stack else None if prev_group_undoable: merged = prev_group_undoable.merge(undoable) elif prev_stack_undoable: merged = prev_stack_undoable.merge(undoable) else: merged = False if not merged: if self.current_undo_group is None: LOGGER.warning("Recording a change without a user action.") self.undo_stack.append(undoable) else: self.current_undo_group.append(undoable) �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������apostrophe-v2.6.3/apostrophe/theme_switcher.py������������������������������������������������������0000664�0000000�0000000�00000011466�14233044111�0021645�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# BEGIN LICENSE # Copyright 2020, Manuel Genovés <manuel.genoves@gmail.com> # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 <http://www.gnu.org/licenses/>. # END LICENSE import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, GObject, Gio, Handy from .settings import Settings from apostrophe.helpers import get_media_path class Theme: '''Abstracts getters for the current theme related resources''' settings = Settings.new() def __init__(self, name, gtk_css, gtk_css_hc, web_css): self.name = name self.gtk_css = gtk_css self.gtk_css_hc = gtk_css_hc self.web_css = web_css @classmethod def get_for_name(cls, name, default=None): current_theme = default or defaultThemes[0] for theme in defaultThemes: if name == theme.name: current_theme = theme return current_theme @classmethod def get_current(cls): color_scheme = cls.settings.get_string("color-scheme") return cls.get_for_name(color_scheme) defaultThemes = [ Theme('light', Gio.File.new_for_uri("resource:///org/gnome/gitlab/somas/Apostrophe/media/css/gtk/Adwaita.css"), Gio.File.new_for_uri("resource:///org/gnome/gitlab/somas/Apostrophe/media/css/gtk/Adwaita-hc.css"), get_media_path('/media/css/web/adwaita.css')), Theme('dark', Gio.File.new_for_uri("resource:///org/gnome/gitlab/somas/Apostrophe/media/css/gtk/Adwaita-dark.css"), Gio.File.new_for_uri("resource:///org/gnome/gitlab/somas/Apostrophe/media/css/gtk/Adwaita-dark-hc.css"), get_media_path('/media/css/web/adwaita.css')), Theme('sepia', Gio.File.new_for_uri("resource:///org/gnome/gitlab/somas/Apostrophe/media/css/gtk/Adwaita-sepia.css"), Gio.File.new_for_uri("resource:///org/gnome/gitlab/somas/Apostrophe/media/css/gtk/Adwaita-sepia-hc.css"), get_media_path('/media/css/web/adwaita-sepia.css')), ] @Gtk.Template(resource_path='/org/gnome/gitlab/somas/Apostrophe/ui/ThemeSwitcher.ui') class ThemeSwitcher(Gtk.Box): __gtype_name__ = "ThemeSwitcher" color_scheme = "light" system_selector = Gtk.Template.Child() light_selector = Gtk.Template.Child() sepia_selector = Gtk.Template.Child() dark_selector = Gtk.Template.Child() settings = Settings.new() show_system = GObject.property(type=bool, default=True) @GObject.Property(type=str) def selected_color_scheme(self): """Read-write integer property.""" return self.color_scheme @selected_color_scheme.setter def selected_color_scheme(self, color_scheme): self.color_scheme = color_scheme if color_scheme == "auto": self.system_selector.set_active(True) self.style_manager.set_color_scheme(Handy.ColorScheme.PREFER_LIGHT) if color_scheme == "light": self.light_selector.set_active(True) self.style_manager.set_color_scheme(Handy.ColorScheme.FORCE_LIGHT) if color_scheme == "sepia": self.sepia_selector.set_active(True) self.style_manager.set_color_scheme(Handy.ColorScheme.FORCE_LIGHT) if color_scheme == "dark": self.dark_selector.set_active(True) self.style_manager.set_color_scheme(Handy.ColorScheme.FORCE_DARK) def __init__(self, **kwargs): super().__init__(**kwargs) self.style_manager = Handy.StyleManager.get_default() color_scheme = self.settings.get_string("color-scheme") self.color_scheme = color_scheme self.settings.bind( "color-scheme", self, "selected_color_scheme", Gio.SettingsBindFlags.DEFAULT) self.style_manager.bind_property("system-supports-color-schemes", self, "show_system", GObject.BindingFlags.SYNC_CREATE) @Gtk.Template.Callback() def _on_color_scheme_changed(self, widget, paramspec): if self.system_selector.get_active(): self.selected_color_scheme = "auto" if self.light_selector.get_active(): self.selected_color_scheme = "light" if self.sepia_selector.get_active(): self.selected_color_scheme = "sepia" if self.dark_selector.get_active(): self.selected_color_scheme = "dark" ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������apostrophe-v2.6.3/apostrophe/tweener.py�������������������������������������������������������������0000664�0000000�0000000�00000005772�14233044111�0020307�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Copyright 2022, Manuel Genovés <manuel.genoves@gmail.com> # Alexander Mikhaylenko # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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 <http://www.gnu.org/licenses/>. # END LICENSE # # Based on code by Alexander Mikhaylenko import gi gi.require_version('Gtk', '3.0') gi.require_version('Handy', '1') from gi.repository import GObject, Handy class Tweener(GObject.Object): def __init__(self, widget, setter, value_from, value_to, duration, offset=0, setter_args = None, callback = None, callback_arg = None): self.widget = widget self.value_from = value_from self.value_to = value_to self.duration = duration self.offset = offset if setter_args is None: self.setter_args = [] else: self.setter_args = setter_args self.callback = callback self.callback_arg = callback_arg self.start_time = 0 self.tick_cb_id = 0 self.setter = setter self.current_value = 0 def stop(self): if (self.tick_cb_id != 0): self.widget.remove_tick_callback(self.tick_cb_id) self.tick_cb_id = 0 if self.callback is not None: self.callback(self.callback_arg) def start(self): if (not Handy.get_enable_animations(self.widget) or not self.widget.get_mapped() or self.duration < 0): self.setter(self.value_to, *self.setter_args) self.widget.queue_draw() return if (self.tick_cb_id != 0): self.widget.remove_tick_callback(self.tick_cb_id) self.tick_cb_id = 0 self.setter(self.value_from, *self.setter_args) self.start_time = self.widget.get_frame_clock().get_frame_time() / 1000 self.tick_cb_id = self.widget.add_tick_callback(self.__tick_cb) def __tick_cb(self, widget, frame_clock): frame_time = frame_clock.get_frame_time() / 1000 t = (frame_time - self.start_time - self.offset) / self.duration if t >= 1: self.current_value = self.value_to self.stop() self.tick_cb_id = 0 self.setter(self.current_value, *self.setter_args) return False if t < 0: return True self.current_value = self.value_from\ + (self.value_to - self.value_from)\ * Handy.ease_out_cubic(t) self.setter(self.current_value, *self.setter_args) self.widget.queue_draw() return True ������apostrophe-v2.6.3/build-aux/������������������������������������������������������������������������0000775�0000000�0000000�00000000000�14233044111�0015757�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������apostrophe-v2.6.3/build-aux/flatpak/����������������������������������������������������������������0000775�0000000�0000000�00000000000�14233044111�0017401�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������apostrophe-v2.6.3/build-aux/flatpak/flatpak_texlive_flathub.json������������������������������������0000664�0000000�0000000�00000007150�14233044111�0025166�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������{ "id": "org.gnome.gitlab.somas.Apostrophe.Plugin.TexLive", "runtime": "org.gnome.gitlab.somas.Apostrophe", "branch": "stable", "runtime-version": "stable", "sdk": "org.gnome.Sdk//3.38", "build-extension": true, "separate-locales": false, "appstream-compose": false, "finish-args": [], "build-options" : { "prepend-path": "/app/extensions/TexLive", "env": { "PATH": "/app/extensions/TexLive/bin:/app/extensions/TexLive/2018/bin/x86_64-linux:/app/bin:/usr/bin" } }, "cleanup": ["/bin/wget"], "modules": [ { "name": "wget", "builddir": true, "build-options": { "prefix": "/app/extensions/TexLive" }, "sources": [ { "type": "archive", "url": "https://ftp.gnu.org/gnu/wget/wget-1.19.4.tar.gz", "sha256": "93fb96b0f48a20ff5be0d9d9d3c4a986b469cb853131f9d5fe4cc9cecbc8b5b5" } ] }, { "name": "p7zip", "no-autogen": true, "build-options": { "prefix": "/app/extensions/TexLive" }, "make-args": ["7z"], "cleanup": ["*"], "sources": [ { "type": "archive", "url": "https://sourceforge.net/projects/p7zip/files/p7zip/16.02/p7zip_16.02_src_all.tar.bz2", "sha256": "5eb20ac0e2944f6cb9c2d51dd6c4518941c185347d4089ea89087ffdd6e2341f" }, { "type": "shell", "commands": ["sed -i 's|/usr/local|/app/extensions/TexLive|g' makefile.common"] }, { "type": "patch", "path" : "p7zip-gcc10.patch" } ] }, { "name": "texlive", "buildsystem": "simple", "sources": [ { "type":"file", "url": "http://mirrors.ctan.org/systems/texlive/Images/texlive.iso", "sha512": "7c94bbcff5318e540dc0b03010896185d8985bcc2c2ac11906e831ec583fd574bf9720fce5efc29470c80bafe12f42ddaa392b96c460a27eda94f93c12e7b57d" }, { "type": "file", "path": "texlive.profile" }, { "type": "shell", "commands": ["7z x texlive.iso"] } ], "build-commands": [ "chmod +x install-tl", "echo \"In\" | TEXLIVE_INSTALL_PREFIX=/app/extensions/TexLive ./install-tl --profile texlive.profile", "rm -rf /app/extensions/TexLive/texmf-dist/doc" ] }, { "name": "appdata", "buildsystem": "simple", "build-commands": [ "mkdir -p /app/extensions/TexLive/share/appdata", "install -Dm644 org.gnome.gitlab.somas.Apostrophe.Plugin.TexLive.appdata.xml /app/extensions/TexLive/share/appdata/org.gnome.gitlab.somas.Apostrophe.Plugin.TexLive.appdata.xml", "appstream-compose --basename=org.gnome.gitlab.somas.Apostrophe.Plugin.TexLive --prefix=/app/extensions/TexLive --origin=flatpak org.gnome.gitlab.somas.Apostrophe.Plugin.TexLive" ], "sources": [ { "type": "file", "path": "org.gnome.gitlab.somas.Apostrophe.Plugin.TexLive.appdata.xml" } ] } ] } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������apostrophe-v2.6.3/build-aux/flatpak/org.gnome.gitlab.somas.Apostrophe.Plugin.TexLive.appdata.xml����0000664�0000000�0000000�00000001007�14233044111�0032746�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <component type="addon"> <id>org.gnome.gitlab.somas.Apostrophe.Plugin.TexLive</id> <extends>org.gnome.gitlab.somas.Apostrophe</extends> <name>TexLive Plugin</name> <summary>Allows to export to pdf and to show formulas in the inline preview</summary> <url type="homepage">https://www.tug.org/texlive//</url> <project_license>LPPL</project_license> <metadata_license>CC0-1.0</metadata_license> <update_contact>w.vollprecht_AT_gmail.com</update_contact> </component> �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������apostrophe-v2.6.3/build-aux/flatpak/org.gnome.gitlab.somas.Apostrophe.Plugin.TexLive.json�����������0000664�0000000�0000000�00000004465�14233044111�0031521�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������{ "id": "org.gnome.gitlab.somas.Apostrophe.Plugin.TexLive", "runtime": "org.gnome.gitlab.somas.Apostrophe", "branch": "stable", "sdk": "org.gnome.Sdk//3.36", "build-extension": true, "separate-locales": false, "appstream-compose": false, "finish-args": [ ], "build-options" : { "prefix": "/app/extensions/TexLive", "cflags": "-O2 -g", "cxxflags": "-O2 -g", "env": { "PATH": "/app/extensions/TexLive/bin:/app/extensions/TexLive/2019/bin/x86_64-linux:/app/bin:/usr/bin" } }, "cleanup": ["/bin/wget"], "modules": [ { "name": "wget", "builddir": true, "config-opts": ["--prefix=/app/extensions/TexLive"], "sources": [ { "type": "archive", "url": "https://ftp.gnu.org/gnu/wget/wget-1.19.4.tar.gz", "sha256": "93fb96b0f48a20ff5be0d9d9d3c4a986b469cb853131f9d5fe4cc9cecbc8b5b5" } ] }, { "name": "texlive", "builddir": false, "build-options" : { "build-args": ["--share=network"], "config-opts": ["--prefix=/app/extensions/TexLive"] }, "build-commands": [ ], "sources": [ { "type": "file", "path": "texlive_install.sh", "dest-filename": "configure" } ] }, { "name": "appdata", "buildsystem": "simple", "build-commands": [ "mkdir -p /app/extensions/TexLive/share/appdata", "install -Dm644 org.gnome.gitlab.somas.Apostrophe.Plugin.TexLive.appdata.xml /app/extensions/TexLive/share/appdata/org.gnome.gitlab.somas.Apostrophe.Plugin.TexLive.appdata.xml", "appstream-compose --basename=org.gnome.gitlab.somas.Apostrophe.Plugin.TexLive --prefix=/app/extensions/TexLive --origin=flatpak org.gnome.gitlab.somas.Apostrophe.Plugin.TexLive" ], "sources": [ { "type": "file", "path": "org.gnome.gitlab.somas.Apostrophe.Plugin.TexLive.appdata.xml" } ] } ] } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������apostrophe-v2.6.3/build-aux/flatpak/org.gnome.gitlab.somas.Apostrophe.json��������������������������0000664�0000000�0000000�00000015123�14233044111�0026676�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������{ "app-id" : "org.gnome.gitlab.somas.Apostrophe", "runtime" : "org.gnome.Platform", "runtime-version" : "41", "sdk" : "org.gnome.Sdk", "command" : "apostrophe", "finish-args" : [ "--socket=x11", "--socket=wayland", "--share=ipc", "--share=network", "--device=dri", "--filesystem=home:ro", "--env=PATH=/app/bin:/usr/bin:/app/extensions/TexLive/2018/bin/x86_64-linux/", "--metadata=X-DConf=migrate-path=/org/gnome/gitlab/somas/Apostrophe/" ], "add-extensions" : { "org.gnome.gitlab.somas.Apostrophe.Plugin" : { "directory" : "extensions", "version" : "stable", "subdirectories" : true, "no-autodownload" : true, "autodelete" : true } }, "modules" : [ { "name": "libhandy", "buildsystem": "meson", "builddir": true, "config-opts": [ "-Dexamples=false", "-Dtests=false" ], "sources": [ { "type": "git", "url": "https://gitlab.gnome.org/GNOME/libhandy.git", "branch": "main" } ] }, { "name" : "libsass", "cleanup" : [ "*" ], "sources" : [ { "type" : "archive", "url" : "https://github.com/sass/libsass/archive/3.6.4.tar.gz", "sha256" : "f9484d9a6df60576e791566eab2f757a97fd414fce01dd41fc0a693ea5db2889" }, { "type" : "script", "dest-filename" : "autogen.sh", "commands" : [ "autoreconf -si" ] } ] }, { "name" : "sassc", "cleanup" : [ "*" ], "sources" : [ { "type" : "archive", "url" : "https://github.com/sass/sassc/archive/3.6.1.tar.gz", "sha256" : "8cee391c49a102b4464f86fc40c4ceac3a2ada52a89c4c933d8348e3e4542a60" }, { "type" : "script", "dest-filename" : "autogen.sh", "commands" : [ "autoreconf -si" ] } ] }, { "name" : "gspell", "sources" : [ { "type" : "archive", "url" : "https://download.gnome.org/sources/gspell/1.8/gspell-1.8.3.tar.xz", "sha256" : "5ae514dd0216be069176accf6d0049d6a01cfa6a50df4bc06be85f7080b62de8" } ] }, { "name" : "pandoc", "only-arches" : [ "x86_64" ], "buildsystem" : "simple", "build-commands" : [ "cp bin/pandoc /app/bin/pandoc" ], "sources" : [ { "type" : "archive", "url" : "https://github.com/jgm/pandoc/releases/download/2.11.3.1/pandoc-2.11.3.1-linux-amd64.tar.gz", "sha256" : "848fd7e6ccfe8a8d5a9ff81ea9b6a3024e8d0e8da6365d304584d93b87da8996" } ] }, { "name" : "pipdeps", "buildsystem" : "simple", "build-commands" : [ "pip3 install --no-index --find-links=\"file://${PWD}\" --prefix=${FLATPAK_DEST} regex pypandoc chardet" ], "sources" : [ { "type" : "file", "url" : "https://files.pythonhosted.org/packages/75/28/521c6dc7fef23a68368efefdcd682f5b3d1d58c2b90b06dc1d0b805b51ae/wheel-0.34.2.tar.gz", "sha256" : "8788e9155fe14f54164c1b9eb0a319d98ef02c160725587ad60f14ddc57b6f96" }, { "type" : "file", "url" : "https://files.pythonhosted.org/packages/8e/76/66066b7bc71817238924c7e4b448abdb17eb0c92d645769c223f9ace478f/pip-20.0.2.tar.gz", "sha256" : "7db0c8ea4c7ea51c8049640e8e6e7fde949de672bfa4949920675563a5a6967f" }, { "type" : "file", "url" : "https://files.pythonhosted.org/packages/71/81/00184643e5a10a456b4118fc12c96780823adb8ed974eb2289f29703b29b/pypandoc-1.4.tar.gz", "sha256" : "e914e6d5f84a76764887e4d909b09d63308725f0cbb5293872c2c92f07c11a5b" }, { "type" : "file", "url" : "https://files.pythonhosted.org/packages/e8/76/8ac7f467617b9cfbafcef3c76df6f22b15de654a62bea719792b00a83195/regex-2020.2.20.tar.gz", "sha256" : "9e9624440d754733eddbcd4614378c18713d2d9d0dc647cf9c72f64e39671be5" }, { "type" : "file", "url" : "https://files.pythonhosted.org/packages/14/4b/6f7a3f2bb1e2fa4d3007126578cae0b9910ff46c4957bef5bd4b92733011/pyenchant-3.0.1.tar.gz", "sha256" : "1bd26a644abf80196a9de3f2d820ebafb7e7f78385e392ce77cb1552f164d559" }, { "type" : "file", "url" : "https://files.pythonhosted.org/packages/ee/2d/9cdc2b527e127b4c9db64b86647d567985940ac3698eeabc7ffaccb4ea61/chardet-4.0.0.tar.gz", "sha256" : "0d6f53a15db4120f2b08c94f11e7d93d2c911ee118b6b30a04ec3ee8310179fa" } ] }, { "name" : "fonts", "buildsystem" : "simple", "build-commands" : [ "mkdir -p /app/share/fonts/", "cp ttf/* /app/share/fonts/" ], "sources" : [ { "type" : "git", "url" : "https://github.com/mozilla/Fira", "tag" : "4.202" } ] }, { "name" : "apostrophe", "buildsystem" : "meson", "config-opts" : [ "-Dprofile=development" ], "sources" : [ { "type" : "dir", "path" : "../../" } ], "post-install" : [ "install -d /app/extensions" ] } ], "build-options" : { "env" : { "" : null } } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������apostrophe-v2.6.3/build-aux/flatpak/p7zip-gcc10.patch�����������������������������������������������0000664�0000000�0000000�00000001355�14233044111�0022372�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������ --- a/CPP/Windows/ErrorMsg.cpp 2020-05-28 00:35:02.729896917 +0200 +++ b/CPP/Windows/ErrorMsg.cpp 2020-05-28 00:40:01.676442629 +0200 @@ -13,7 +13,7 @@ const char * txt = 0; AString msg; - switch(errorCode) { + switch(HRESULT(errorCode)) { case ERROR_NO_MORE_FILES : txt = "No more files"; break ; case E_NOTIMPL : txt = "E_NOTIMPL"; break ; case E_NOINTERFACE : txt = "E_NOINTERFACE"; break ; @@ -43,7 +43,7 @@ const char * txt = 0; AString msg; - switch(messageID) { + switch(HRESULT(messageID)) { case ERROR_NO_MORE_FILES : txt = "No more files"; break ; case E_NOTIMPL : txt = "E_NOTIMPL"; break ; case E_NOINTERFACE : txt = "E_NOINTERFACE"; break ; �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������apostrophe-v2.6.3/build-aux/flatpak/texlive.profile�������������������������������������������������0000664�0000000�0000000�00000002001�14233044111�0022434�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������selected_scheme scheme-basic TEXDIR /app/extensions/TexLive/2018 TEXMFCONFIG /app/extensions/TexLive/.texlive2018/texmf-config TEXMFHOME /app/extensions/TexLive/texmf TEXMFLOCAL /app/extensions/TexLive/texmf-local TEXMFSYSCONFIG /app/extensions/TexLive/2018/texmf-config TEXMFSYSVAR /app/extensions/TexLive/2018/texmf-var TEXMFVAR /app/extensions/TexLive/.texlive2018/texmf-var binary_x86_64-linux 1 collection-latex 1 collection-xetex 1 collection-latexrecommended 1 collection-binextra 1 collection-fontsrecommended 1 collection-unicodetex 1 instopt_adjustpath 0 instopt_adjustrepo 1 instopt_letter 0 instopt_portable 1 instopt_write18_restricted 1 tlpdbopt_autobackup 1 tlpdbopt_backupdir tlpkg/backups tlpdbopt_create_formats 1 tlpdbopt_desktop_integration 1 tlpdbopt_file_assocs 1 tlpdbopt_generate_updmap 0 tlpdbopt_install_docfiles 0 tlpdbopt_install_srcfiles 0 tlpdbopt_post_code 1 tlpdbopt_sys_bin /usr/local/bin tlpdbopt_sys_info /usr/local/share/info tlpdbopt_sys_man /usr/local/share/man tlpdbopt_w32_multi_user 1�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������apostrophe-v2.6.3/build-aux/flatpak/texlive_install.sh����������������������������������������������0000775�0000000�0000000�00000004103�14233044111�0023144�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Download the installer! # Currently using 2017 edition, upgrade to 2018 tomorrow! (just released, needs) # time to propagate everywhere wget ftp://tug.org/historic/systems/texlive/2019/install-tl-unx.tar.gz myhash=$(sha256sum install-tl-unx.tar.gz | cut -d' ' -f1) if [ $myhash != "44aa41b5783e345b7021387f19ac9637ff1ce5406a59754230c666642dfe7750" ] ; then echo "CHECKSUM MISMATCH!"; exit 1 ; fi tar xvf install-tl-unx.tar.gz # The texlive profile sets some variables for the installation # so the installer doesn't use the text user interface # Most importantly (besides the paths') is "selected-scheme" # Currently set to scheme-minimal which installs almost nothing # (which is great for testing, but less for actual usage! :) cat <<EOF > texlive.profile # texlive.profile written on Sat Apr 28 18:37:30 2018 UTC # It will NOT be updated and reflects only the # installation profile at installation time. selected_scheme scheme-basic TEXDIR /app/extensions/TexLive/2019 TEXMFCONFIG ~/.texlive2019/texmf-config TEXMFHOME ~/texmf TEXMFLOCAL /app/extensions/TexLive/texmf-local TEXMFSYSCONFIG /app/extensions/TexLive/2019/texmf-config TEXMFSYSVAR /app/extensions/TexLive/2019/texmf-var TEXMFVAR ~/.texlive2019/texmf-var binary_x86_64-linux 1 collection-latex 1 collection-binextra 1 collection-fontsrecommended 1 instopt_adjustpath 0 instopt_adjustrepo 1 instopt_letter 0 instopt_portable 1 instopt_write18_restricted 1 tlpdbopt_autobackup 1 tlpdbopt_backupdir tlpkg/backups tlpdbopt_create_formats 1 tlpdbopt_desktop_integration 1 tlpdbopt_file_assocs 1 tlpdbopt_generate_updmap 0 tlpdbopt_install_docfiles 0 tlpdbopt_install_srcfiles 0 tlpdbopt_post_code 1 tlpdbopt_sys_bin /usr/local/bin tlpdbopt_sys_info /usr/local/share/info tlpdbopt_sys_man /usr/local/share/man tlpdbopt_w32_multi_user 1 EOF # Makefile which is required by flatpak ... so this one is almost empty # except for the install command which uses the texlive installer to download # all the packages! cat <<EOF > Makefile all: echo "I am a pretty empty Makefile." install: ./install-tl-20190410/install-tl --profile texlive.profile EOF �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������apostrophe-v2.6.3/build-aux/meson_post_config.py����������������������������������������������������0000664�0000000�0000000�00000000663�14233044111�0022051�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python3 import os import subprocess build_root = os.environ.get('MESON_BUILD_ROOT') source_root = os.environ.get('MESON_SOURCE_ROOT') print('Install schemas in build dir...') subprocess.call(['glib-compile-schemas', source_root + '/data/']) subprocess.call(['mkdir', '-p', build_root + '/data/glib-2.0/schemas']) subprocess.call(['mv', source_root + '/data/gschemas.compiled', build_root + '/data/glib-2.0/schemas']) �����������������������������������������������������������������������������apostrophe-v2.6.3/build-aux/meson_post_install.py���������������������������������������������������0000775�0000000�0000000�00000000704�14233044111�0022251�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python3 from os import environ, path from subprocess import call if not environ.get('DESTDIR', ''): PREFIX = environ.get('MESON_INSTALL_PREFIX', '/usr/local') DATA_DIR = path.join(PREFIX, 'share') print('Updating icon cache...') call(['gtk-update-icon-cache', '-qtf', path.join(DATA_DIR, 'icons/hicolor')]) print("compiling new schemas") call(["glib-compile-schemas", path.join(DATA_DIR, 'glib-2.0/schemas')]) ������������������������������������������������������������apostrophe-v2.6.3/config.py.in����������������������������������������������������������������������0000664�0000000�0000000�00000000274�14233044111�0016314�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������APP_ID = "@APP_ID@" PKGDATA_DIR = "@PKGDATA_DIR@" PROFILE = "@PROFILE@" NAME_SUFFIX = "@NAME_SUFFIX@" VERSION = "@VERSION@" GETTEXT_PACKAGE = "@GETTEXT_PACKAGE@" LOCALEDIR = "@LOCALEDIR@" ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������apostrophe-v2.6.3/data/�����������������������������������������������������������������������������0000775�0000000�0000000�00000000000�14233044111�0014776�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������apostrophe-v2.6.3/data/apostrophe.gresource.xml�����������������������������������������������������0000664�0000000�0000000�00000004647�14233044111�0021714�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8"?> <gresources> <gresource prefix="/org/gnome/gitlab/somas/Apostrophe/"> <file compressed="true" alias="icons/preview-layout-full-width-symbolic.svg">media/icons/preview-layout-full-width-symbolic.svg</file> <file compressed="true" alias="icons/preview-layout-half-width-symbolic.svg">media/icons/preview-layout-half-width-symbolic.svg</file> <file compressed="true" alias="icons/preview-layout-windowed-symbolic.svg">media/icons/preview-layout-windowed-symbolic.svg</file> <file compressed="true" alias="icons/preview-layout-half-height-symbolic.svg">media/icons/preview-layout-half-height-symbolic.svg</file> <file compressed="true" alias="icons/checkmark-symbolic.svg">media/icons/checkmark-symbolic.svg</file> <file compressed="true">media/css/gtk/Adwaita.css</file> <file compressed="true">media/css/gtk/Adwaita-hc.css</file> <file compressed="true">media/css/gtk/Adwaita-dark.css</file> <file compressed="true">media/css/gtk/Adwaita-dark-hc.css</file> <file compressed="true">media/css/gtk/Adwaita-sepia.css</file> <file compressed="true">media/css/gtk/Adwaita-sepia-hc.css</file> <file compressed="true">media/css/gtk/bindings.css</file> <file compressed="true" preprocess="xml-stripblanks">ui/Export.ui</file> <file compressed="true" preprocess="xml-stripblanks">ui/Headerbar.ui</file> <file compressed="true" preprocess="xml-stripblanks">ui/Preferences.ui</file> <file compressed="true" preprocess="xml-stripblanks">ui/PreviewLayoutSwitcher.ui</file> <file compressed="true" preprocess="xml-stripblanks">ui/PreviewLayoutSwitcherItem.ui</file> <file compressed="true" preprocess="xml-stripblanks">ui/PreviewWindow.ui</file> <file compressed="true" preprocess="xml-stripblanks">ui/Recents.ui</file> <file compressed="true" preprocess="xml-stripblanks">ui/SearchBar.ui</file> <file compressed="true" preprocess="xml-stripblanks">ui/Shortcuts.ui</file> <file compressed="true" preprocess="xml-stripblanks">ui/TexliveWarning.ui</file> <file compressed="true" preprocess="xml-stripblanks">ui/TextView.ui</file> <file compressed="true" preprocess="xml-stripblanks">ui/ThemeSwitcher.ui</file> <file compressed="true" preprocess="xml-stripblanks">ui/Window.ui</file> <file compressed="true" preprocess="xml-stripblanks">About.ui</file> <file compressed="true">media/apostrophe_markdown.md</file> </gresource> </gresources> �����������������������������������������������������������������������������������������apostrophe-v2.6.3/data/icons/�����������������������������������������������������������������������0000775�0000000�0000000�00000000000�14233044111�0016111�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������apostrophe-v2.6.3/data/icons/de.wolfvollprecht.apostrophe.Source������������������������������������0000664�0000000�0000000�00000422442�14233044111�0025127�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?xml version="1.0" encoding="UTF-8" standalone="no"?> <svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" inkscape:export-ydpi="96" inkscape:export-xdpi="96" inkscape:export-filename="Template.png" width="192" height="152" id="svg11300" sodipodi:version="0.32" inkscape:version="1.0beta2 (2b71d25d45, 2019-12-03)" sodipodi:docname="org.gnome.gitlab.somas.Apostrophe.Source.svg" inkscape:output_extension="org.inkscape.output.svg.inkscape" version="1.0" style="display:inline;enable-background:new" viewBox="0 0 192 152"> <title id="title4162">Adwaita Icon Template image/svg+xml GNOME Design Team Adwaita Icon Template