pax_global_header00006660000000000000000000000064146515436300014521gustar00rootroot0000000000000052 comment=337db7fd9ae6ea97368f18afee3a140f0496b540 dialect-2.4.2/000077500000000000000000000000001465154363000131335ustar00rootroot00000000000000dialect-2.4.2/.codespellrc000066400000000000000000000000271465154363000154320ustar00rootroot00000000000000[codespell] skip = ./podialect-2.4.2/.github/000077500000000000000000000000001465154363000144735ustar00rootroot00000000000000dialect-2.4.2/.github/FUNDING.yml000066400000000000000000000013731465154363000163140ustar00rootroot00000000000000# These are supported funding model platforms github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] patreon: # Replace with a single Patreon username open_collective: dialect ko_fi: # Replace with a single Ko-fi username tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry liberapay: # Replace with a single Liberapay username issuehunt: # Replace with a single IssueHunt username otechie: # Replace with a single Otechie username lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] dialect-2.4.2/.github/workflows/000077500000000000000000000000001465154363000165305ustar00rootroot00000000000000dialect-2.4.2/.github/workflows/CI.yml000066400000000000000000000013501465154363000175450ustar00rootroot00000000000000on: push: branches: [main] pull_request: name: CI jobs: codespell: name: Check for spelling errors runs-on: ubuntu-latest steps: - uses: codespell-project/actions-codespell@master flatpak-builder: name: "Flatpak Builder" runs-on: ubuntu-latest container: image: bilelmoussaoui/flatpak-github-actions:gnome-nightly options: --privileged steps: - uses: actions/checkout@v3 with: submodules: recursive - uses: bilelmoussaoui/flatpak-github-actions/flatpak-builder@v6 with: bundle: "dialect-devel.flatpak" manifest-path: "build-aux/flatpak/app.drey.Dialect.Devel.json" run-tests: "true" cache-key: flatpak-builder-${{ github.sha }} dialect-2.4.2/.gitignore000066400000000000000000000040111465154363000151170ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ builddir/ build-dir/ _build/ .flatpak/ *.flatpak .flatpak-builder/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ pip-wheel-metadata/ share/python-wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover *.py,cover .hypothesis/ .pytest_cache/ # Translations *.mo # Django stuff: *.log local_settings.py db.sqlite3 db.sqlite3-journal # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # IPython profile_default/ ipython_config.py # pyenv .python-version # pipenv # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. # However, in case of collaboration, if having platform-specific dependencies or dependencies # having no cross-platform support, pipenv may install dependencies that don't work, or not # install all needed dependencies. #Pipfile.lock # PEP 582; used by e.g. github.com/David-OConnor/pyflow __pypackages__/ # Celery stuff celerybeat-schedule celerybeat.pid # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ .dmypy.json dmypy.json # Pyre type checker .pyre/ # Glade backup *.ui~ # Other backup files *.backup # VSCode Workspace settings .vscode/ # PyCharm settings .idea/ # Subprojects /subprojects/blueprint-compiler # Finder system file .DS_Store dialect-2.4.2/.gitmodules000066400000000000000000000001051465154363000153040ustar00rootroot00000000000000[submodule "po"] path = po url = https://github.com/dialect-app/po dialect-2.4.2/LICENSE000066400000000000000000001045151465154363000141460ustar00rootroot00000000000000 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 . dialect-2.4.2/NEWS.md000066400000000000000000000042741465154363000142400ustar00rootroot00000000000000 ### In Development ### 2.4.1 - Bug fixes ### 2.4.0 - Add DeepL provider - Bug fixes ### 2.3.0 - Make text views font size configurable and temporally modify it with shortcuts or scroll - Fix search provider always running in the background - Allow opening language selector with keyboard shortcuts - Add --selection CLI option to translate the primary clipboard - Use new GNOME 46 adaptive dialogs ### 2.2.0 - Refactored providers implementation to ease future features - Added Lingva Text-to-speech support in addition to Google's - Added Bing translation provider - Added Yandex translation provider - Updated preferences window - Languages list now have localized sorting - Fixed Lingva Translate provider bugs ### 2.1.1 - Updated translations - Fixed minor bugs ### 2.1.0 - Update to use libadwaita 1.2 widgets - Updated translations - Fixed minor bugs ### 2.0.2 - Fixed responsive implementation - Fixed small stylings - Updated translations ### 2.0.1 - Fixed an issue with scale factor ### 2.0.0 - Ported to GTK4 and libadwaita - New in-app color scheme switcher - Added Lingva Translate support - Google Translate module rewritten from scratch to not rely on external libraries and improve reliability. - GNOME Search Provider improvements - APP ID changed to app.drey.Dialect - Added API keys support for LibreTranslate - Added translation suggestions support for LibreTranslate - Fixed proxies by rewriting the http backend - Character limit is now service-dependent - Major code base refactoring - Fixed several bugs ### 1.4.1 - Fix shortcut bug ### 1.4.0 - Added accels for most actions - Added localized language names - Added new translations - Fixed several minor bugs ### 1.3.0 - Backend refactor - Added option to disable Google TTS - Fixed several minor bugs ### 1.2.0 - Switch to a new icon - Added LibreTranslate backend - Added Pronunciations support in Google Translate - Fixed several minor bugs ### 1.1.1 - Added a shortcuts window - Fixed several bugs ### 1.1.0 - Added a search provider for GNOME - Added support for "Did you mean" suggestions - Added a Ctrl+Q shortcut to quit - Fixed some issues with the icon - Fixed several bugs - Made some minor UI improvements ### 1.0.0 Initial release. dialect-2.4.2/README.md000066400000000000000000000051501465154363000144130ustar00rootroot00000000000000 # Dialect A translation app for GNOME. ![Dialect](preview.png?raw=true) ## Features - Translation based on Google Translate - Translation based on the LibreTranslate API, allowing you to use any public instance - Translation based on Lingva Translate API - Translation based on Bing - Translation based on Yandex - Translation history - Automatic language detection - Text to speech - Clipboard buttons ## Installation ### Flathub Download on Flathub ### AUR Arch-based distro users can install from the AUR: [`dialect`](https://aur.archlinux.org/packages/dialect) for the stable version or [`dialect-git`](https://aur.archlinux.org/packages/dialect-git/) for the latest git revision. ### Fedora Dialect is available for Fedora 33 and later: ```bash sudo dnf install dialect ``` ### Debian Dialect is available in Debian 12: ```bash sudo apt-get install dialect ``` ## Building ### Requirements - Python 3 `python` - PyGObject `python-gobject` - GTK4 `gtk4` - libadwaita (>= 1.4.0) `libadwaita` - libsoup (>= 3.0) `libsoup` - libsecret - GStreamer 1.0 `gstreamer` - Meson `meson` - Ninja `ninja` - gTTS `python-gtts` - Beautiful Soup `python-beautifulsoup4` If official packages are not available for any of the python dependencies, you can install them from pip: ```bash pip install gtts ``` ### Building from Git ```bash git clone --recurse-submodules https://github.com/dialect-app/dialect.git cd dialect meson builddir --prefix=/usr/local sudo ninja -C builddir install ``` For testing and development purposes, you may run a local build: ```bash git clone --recurse-submodules https://github.com/dialect-app/dialect.git cd dialect meson builddir meson configure builddir -Dprefix=$(pwd)/builddir/testdir ninja -C builddir install ninja -C builddir run ``` ## Contributing Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. ### Translations Dialect has already been translated into many languages (see the [translations repository](https://github.com/dialect-app/po/blob/main/README.md) file). Please help translate Dialect into more languages through [Weblate](https://hosted.weblate.org/engage/dialect/). Translation status ## License [GNU General Public License 3 or later](https://www.gnu.org/licenses/gpl-3.0.en.html) dialect-2.4.2/build-aux/000077500000000000000000000000001465154363000150255ustar00rootroot00000000000000dialect-2.4.2/build-aux/flatpak/000077500000000000000000000000001465154363000164475ustar00rootroot00000000000000dialect-2.4.2/build-aux/flatpak/app.drey.Dialect.Devel.json000066400000000000000000000023431465154363000234700ustar00rootroot00000000000000{ "app-id" : "app.drey.Dialect.Devel", "runtime" : "org.gnome.Platform", "runtime-version" : "master", "sdk" : "org.gnome.Sdk", "command" : "dialect", "finish-args" : [ "--share=network", "--share=ipc", "--device=dri", "--socket=fallback-x11", "--socket=wayland", "--socket=pulseaudio", "--own-name=app.drey.Dialect.Devel.SearchProvider" ], "cleanup" : [ "*blueprint*" ], "modules" : [ "pypi-dependencies.json", { "name": "blueprint", "buildsystem": "meson", "sources": [ { "type": "git", "url": "https://gitlab.gnome.org/jwestman/blueprint-compiler", "tag": "v0.10.0", "commit": "2a39a16391122af2f3d812e478c1c1398c98b972" } ] }, { "name" : "dialect", "buildsystem" : "meson", "run-tests": true, "config-opts": ["-Dprofile=development"], "sources" : [ { "type" : "dir", "path" : "../../." } ] } ] } dialect-2.4.2/build-aux/flatpak/app.drey.Dialect.json000066400000000000000000000021631465154363000224320ustar00rootroot00000000000000{ "app-id" : "app.drey.Dialect", "runtime" : "org.gnome.Platform", "runtime-version" : "46", "sdk" : "org.gnome.Sdk", "command" : "dialect", "finish-args" : [ "--share=network", "--share=ipc", "--device=dri", "--socket=fallback-x11", "--socket=wayland", "--socket=pulseaudio" ], "modules" : [ "pypi-dependencies.json", { "name": "blueprint", "buildsystem": "meson", "cleanup": [ "*" ], "sources": [ { "type": "git", "url": "https://gitlab.gnome.org/jwestman/blueprint-compiler", "tag": "v0.10.0", "commit": "2a39a16391122af2f3d812e478c1c1398c98b972" } ] }, { "name" : "dialect", "builddir" : true, "buildsystem" : "meson", "sources" : [ { "type" : "dir", "path" : "../../." } ] } ] }dialect-2.4.2/build-aux/flatpak/pypi-dependencies.json000066400000000000000000000074421465154363000227560ustar00rootroot00000000000000{ "name": "python3-modules", "buildsystem": "simple", "build-commands": [], "modules": [ { "name": "python3-beautifulsoup4", "buildsystem": "simple", "build-commands": [ "pip3 install --verbose --exists-action=i --no-index --find-links=\"file://${PWD}\" --prefix=${FLATPAK_DEST} \"beautifulsoup4\" --no-build-isolation" ], "sources": [ { "type": "file", "url": "https://files.pythonhosted.org/packages/57/f4/a69c20ee4f660081a7dedb1ac57f29be9378e04edfcb90c526b923d4bebc/beautifulsoup4-4.12.2-py3-none-any.whl", "sha256": "bd2520ca0d9d7d12694a53d44ac482d181b4ec1888909b035a3dbf40d0f57d4a" }, { "type": "file", "url": "https://files.pythonhosted.org/packages/49/37/673d6490efc51ec46d198c75903d99de59baffdd47aea3d071b80a9e4e89/soupsieve-2.4.1-py3-none-any.whl", "sha256": "1c1bfee6819544a3447586c889157365a27e10d88cde3ad3da0cf0ddf646feb8" } ] }, { "name": "python3-gtts", "buildsystem": "simple", "build-commands": [ "pip3 install --verbose --exists-action=i --no-index --find-links=\"file://${PWD}\" --prefix=${FLATPAK_DEST} \"gtts\" --no-build-isolation" ], "sources": [ { "type": "file", "url": "https://files.pythonhosted.org/packages/4e/b8/f5a25b22e803f0578e668daa33ba3701bb37858ec80e08a150bd7d2cf1b1/urllib3-1.26.8-py2.py3-none-any.whl", "sha256": "000ca7f471a233c2251c6c7023ee85305721bfdf18621ebff4fd17a8653427ed" }, { "type": "file", "url": "https://files.pythonhosted.org/packages/04/a2/d918dcd22354d8958fe113e1a3630137e0fc8b44859ade3063982eacd2a4/idna-3.3-py3-none-any.whl", "sha256": "84d9dd047ffa80596e0f246e2eab0b391788b0503584e8945f2368256d2735ff" }, { "type": "file", "url": "https://files.pythonhosted.org/packages/84/3e/1037abe6498e65d645ce7a22d3402605d49a3b2c7f20c3abb027760da4f0/charset_normalizer-2.0.10-py3-none-any.whl", "sha256": "cb957888737fc0bbcd78e3df769addb41fd1ff8cf950dc9e7ad7793f1bf44455" }, { "type": "file", "url": "https://files.pythonhosted.org/packages/37/45/946c02767aabb873146011e665728b680884cd8fe70dde973c640e45b775/certifi-2021.10.8-py2.py3-none-any.whl", "sha256": "d62a0163eb4c2344ac042ab2bdf75399a71a2d8c7d47eac2e2ee91b9d6339569" }, { "type": "file", "url": "https://files.pythonhosted.org/packages/2d/61/08076519c80041bc0ffa1a8af0cbd3bf3e2b62af10435d269a9d0f40564d/requests-2.27.1-py2.py3-none-any.whl", "sha256": "f22fa1e554c9ddfd16e6e41ac79759e17be9e492b3587efa038054674760e72d" }, { "type": "file", "url": "https://files.pythonhosted.org/packages/48/58/c8aa6a8e62cc75f39fee1092c45d6b6ba684122697d7ce7d53f64f98a129/click-8.0.3-py3-none-any.whl", "sha256": "353f466495adaeb40b6b5f592f9f91cb22372351c84caeb068132442a4518ef3" }, { "type": "file", "url": "https://files.pythonhosted.org/packages/e4/9e/fe139150719281309c6e52a799e86d7d8d19f6f2593b340e3693f6ef2c77/gTTS-2.2.3-py3-none-any.whl", "sha256": "8376d9bde85ac8cda95ea92dcd12bf31a3efe9e810edcb04437a4151cbec30d6" } ] } ] }dialect-2.4.2/data/000077500000000000000000000000001465154363000140445ustar00rootroot00000000000000dialect-2.4.2/data/app.drey.Dialect-symbolic.svg000066400000000000000000000013541465154363000214750ustar00rootroot00000000000000 dialect-2.4.2/data/app.drey.Dialect.Devel.svg000066400000000000000000000161151465154363000207150ustar00rootroot00000000000000 dialect-2.4.2/data/app.drey.Dialect.Source.svg000066400000000000000000001233071465154363000211200ustar00rootroot00000000000000 Adwaita Icon Template image/svg+xml GNOME Design Team Adwaita Icon Template D D dialect-2.4.2/data/app.drey.Dialect.desktop.in.in000077500000000000000000000011631465154363000215430ustar00rootroot00000000000000[Desktop Entry] Encoding=UTF-8 Version=1.0 Type=Application Terminal=false StartupNotify=true Exec=dialect Name=Dialect Comment=Translate between languages Categories=Network;GTK; Icon=@icon@ # Translators: These are search terms to find this application. Do NOT translate or localize the semicolons. The list MUST also end with a semicolon. Keywords=translate;translation;Google Translate;LibreTranslate;Lingva Translate;Bing Microsoft Translator;Bing Translator;Microsoft Translator;Yandex Translate; # Translators: Do NOT translate or transliterate this text (these are enum types)! X-Purism-FormFactor=Workstation;Mobile; dialect-2.4.2/data/app.drey.Dialect.gschema.xml.in000066400000000000000000000043751465154363000217000ustar00rootroot00000000000000 [800, 300] "auto" false false false true 0 false 0 [] "" "google" false [] [] "" "" "google" dialect-2.4.2/data/app.drey.Dialect.metainfo.xml.in.in000066400000000000000000000210741465154363000224730ustar00rootroot00000000000000 @app-id@ CC0-1.0 GPL-3.0-or-later Dialect Translate between languages

A translation app for GNOME.

Features:

  • Translation based on Google Translate
  • Translation based on the LibreTranslate API, allowing you to use any public instance
  • Translation based on Lingva Translate API
  • Translation based on Bing
  • Translation based on Yandex
  • Translation based on DeepL
  • Text to speech
  • Translation history
  • Automatic language detection
  • Clipboard buttons
https://dialectapp.org/ https://opencollective.com/dialect/ https://github.com/dialect-app/dialect/issues/ https://hosted.weblate.org/engage/dialect/ https://github.com/dialect-app/dialect/ The Dialect Authors The Dialect Authors @app-id@.desktop dialect https://raw.githubusercontent.com/dialect-app/dialect/main/preview.png https://raw.githubusercontent.com/dialect-app/dialect/main/preview-2.png https://raw.githubusercontent.com/dialect-app/dialect/main/preview-mobile.png
  • Bug fixes
  • Updated translations
  • Bug fixes
  • Add DeepL provider
  • Bug fixes
  • Make text views font size configurable and temporally modify it with shortcuts or scroll
  • Fix search provider always running in the background
  • Allow opening language selector with keyboard shortcuts
  • Add --selection CLI option to translate the primary clipboard
  • Use new GNOME 46 adaptive dialogs
  • Refactored providers implementation to ease future features
  • Added Lingva Text-to-speech support in addition to Google'ss
  • Added Bing translation provider
  • Added Yandex translation provider
  • Updated preferences window
  • Languages list now have localized sorting
  • Fixed Lingva Translate provider bugs
  • Updated translations
  • Fixed minor bugs
  • Updated translations
  • Fixed minor bugs
  • Update to use libadwaita 1.2 widgets
  • Updated translations
  • Fixed minor bugs
  • Fixed responsive implementation
  • Fixed small stylings
  • Updated translations
  • Fixed an issue with scale factor
  • Ported to GTK4 and libadwaita
  • New in-app color scheme switcher
  • Added Lingva Translate support
  • Google Translate module rewritten from scratch to not rely on external libraries and improve reliability.
  • GNOME Search Provider improvements
  • APP ID changed to app.drey.Dialect
  • Added API keys support for LibreTranslate
  • Added translation suggestions support for LibreTranslate
  • Fixed proxies by rewriting the http backend
  • Character limit is now service-dependent
  • Major code base refactoring
  • Fixed several bugs
  • Fix shortcut bug
  • Added accels for most actions
  • Added localized language names
  • Added new translations
  • Fixed several minor bugs
  • Backend refactor
  • Added option to disable Google TTS
  • Added Czech translation
  • Fixed several minor bugs
  • Switch to a new icon
  • Added LibreTranslate backend
  • Added Pronunciations support in Google Translate
  • Added Swedish translation
  • Added Croatian translation
  • Fixed several minor bugs
  • Added a shortcuts window
  • Added Indonesian translation
  • Added Portuguese (BR) translation
  • Fixed several bugs
  • Added a search provider for GNOME
  • Added support for "Did you mean" suggestions
  • Added a Ctrl+Q shortcut to quit
  • Added Hungarian translation
  • Added Italian translation
  • Added Persian translation
  • Added Russian translation
  • Added Turkish translation
  • Fixed some issues with the icon
  • Fixed several bugs
  • Made some minor UI improvements

Initial release.

ModernToolkit HiDpiIcon SearchProvider 360 keyboard pointing touch mobile [(108, 236, 156), (0, 0, 0)] #a1f6b4 #157b4c
dialect-2.4.2/data/app.drey.Dialect.svg000066400000000000000000000056711465154363000176640ustar00rootroot00000000000000 dialect-2.4.2/data/meson.build000066400000000000000000000042551465154363000162140ustar00rootroot00000000000000subdir('resources') # Install desktop desktop_conf = configuration_data() desktop_conf.set('icon', application_id) desktop_file = i18n.merge_file( input: configure_file( input: '@0@.desktop.in.in'.format(base_id), output: '@BASENAME@', configuration: desktop_conf ), output: '@0@.desktop'.format(application_id), type: 'desktop', po_dir: '../po', install: true, install_dir: join_paths(get_option('datadir'), 'applications') ) desktop_utils = find_program('desktop-file-validate', required: false) if desktop_utils.found() test('Validate desktop file', desktop_utils, args: [desktop_file.full_path()] ) endif # Install metainfo appdata_conf = configuration_data() appdata_conf.set('app-id', application_id) appstream_file = i18n.merge_file( input: configure_file( input: '@0@.metainfo.xml.in.in'.format(base_id), output: '@BASENAME@', configuration: appdata_conf ), output: '@0@.metainfo.xml'.format(application_id), po_dir: '../po', install: true, install_dir: join_paths(get_option('datadir'), 'metainfo') ) appstreamcli = find_program('appstreamcli', required: false) if appstreamcli.found() test('Validate appstream file', appstreamcli, args: ['validate', '--no-net', '--explain', appstream_file.full_path()] ) endif # Install gsettings schema gschema_conf = configuration_data() gschema_conf.set('app-id', application_id) configure_file( input: '@0@.gschema.xml.in'.format(base_id), output: '@0@.gschema.xml'.format(application_id), configuration: gschema_conf, install: true, install_dir: join_paths(get_option('datadir'), 'glib-2.0/schemas') ) compile_schemas = find_program('glib-compile-schemas', required: false) if compile_schemas.found() test('Validate schema file', compile_schemas, args: ['--strict', '--dry-run', meson.current_source_dir()] ) endif # Install colored icon install_data( '@0@.svg'.format(application_id), install_dir: join_paths(get_option('datadir'), 'icons/hicolor/scalable/apps') ) # Install symbolic icon install_data( '@0@-symbolic.svg'.format(base_id), install_dir: join_paths(get_option('datadir'), 'icons/hicolor/symbolic/apps'), rename: '@0@-symbolic.svg'.format(application_id) ) dialect-2.4.2/data/resources/000077500000000000000000000000001465154363000160565ustar00rootroot00000000000000dialect-2.4.2/data/resources/about.blp000066400000000000000000000010301465154363000176610ustar00rootroot00000000000000using Gtk 4.0; using Adw 1; Adw.AboutDialog about { application-name: _("Dialect"); developer-name: _("The Dialect Authors"); copyright: _("Copyright 2020–⁠2023 The Dialect Authors"); comments: _("A translation app for GNOME."); website: "https://dialectapp.org/"; issue-url: "https://github.com/dialect-app/dialect/issues"; support-url: "https://github.com/dialect-app/dialect/discussions"; /* Translators: Replace me with your names. */ translator-credits: _("translator-credits"); license-type: gpl_3_0; } dialect-2.4.2/data/resources/dialect-settings-symbolic.svg000066400000000000000000000046121465154363000236640ustar00rootroot00000000000000 dialect-2.4.2/data/resources/dialect.gresource.xml000066400000000000000000000017551465154363000222120ustar00rootroot00000000000000 style.css style-dark.css shortcuts.ui window.ui about.ui preferences.ui lang-selector.ui lang-row.ui theme-switcher.ui provider-preferences.ui dialect-settings-symbolic.svg dialect-2.4.2/data/resources/lang-row.blp000066400000000000000000000003361465154363000203050ustar00rootroot00000000000000using Gtk 4.0; template $LangRow : ListBoxRow { child: Box { spacing: 6; Label name { xalign: 0; } Image selection { icon-name: "object-select-symbolic"; visible: false; } }; } dialect-2.4.2/data/resources/lang-selector.blp000066400000000000000000000030731465154363000213170ustar00rootroot00000000000000using Gtk 4.0; using Adw 1; template $LangSelector : Adw.Bin { notify::selected => $_on_selected_changed(); MenuButton button { always-show-arrow: true; styles [ "raised", ] child: Box { spacing: 3; Label label { ellipsize: end; xalign: 0; } Label insight { ellipsize: end; xalign: 0; } }; popover: Popover popover { height-request: 300; show => $_popover_show(); closed => $_popover_closed(); styles [ "lang-selector", "menu", ] Box { orientation: vertical; Box search_box { orientation: vertical; SearchEntry search { placeholder-text: _("Search Languages…"); changed => $_on_search(); activate => $_on_search_activate(); } styles [ "search_box", ] } ScrolledWindow scroll { vexpand: true; child: Box { orientation: vertical; Revealer revealer { reveal-child: true; Box { orientation: vertical; ListBox recent_list { selection-mode: single; row-activated => $_activated(); } Separator separator { } } } ListBox lang_list { selection-mode: single; row-activated => $_activated(); } }; } } }; } }dialect-2.4.2/data/resources/meson.build000066400000000000000000000011661465154363000202240ustar00rootroot00000000000000pkgdatadir = join_paths(get_option('prefix'), get_option('datadir'), meson.project_name()) gnome = import('gnome') blueprints = custom_target('blueprints', input: files( 'about.blp', 'lang-selector.blp', 'lang-row.blp', 'provider-preferences.blp', 'shortcuts.blp', 'theme-switcher.blp', 'window.blp', ), output: '.', command: [find_program('blueprint-compiler'), 'batch-compile', '@OUTPUT@', '@CURRENT_SOURCE_DIR@', '@INPUT@'], ) gnome.compile_resources('dialect', 'dialect.gresource.xml', dependencies: blueprints, gresource_bundle: true, install: true, install_dir: pkgdatadir, ) dialect-2.4.2/data/resources/preferences.ui000066400000000000000000000160451465154363000207240ustar00rootroot00000000000000 dialect-2.4.2/data/resources/provider-preferences.blp000066400000000000000000000043651465154363000227160ustar00rootroot00000000000000using Gtk 4.0; using Adw 1; template $ProviderPreferences : Adw.NavigationPage { title: _("Provider Preferences"); Adw.ToolbarView { [top] Adw.HeaderBar { title-widget: Adw.WindowTitle title { title: _("Provider Preferences"); }; } Adw.PreferencesPage page { Adw.PreferencesGroup instance_group { Adw.EntryRow instance_entry { title: _("Instance URL"); tooltip-text: _("Enter an Instance URL for the Provider."); show-apply-button: true; apply => $_on_instance_apply(); notify::text => $_on_instance_changed(); Stack instance_stack { StackPage { name: "reset"; child: Button instance_reset { tooltip-text: _("Reset to Default"); icon-name: "view-refresh-symbolic"; valign: center; clicked => $_on_reset_instance(); styles ["flat"] }; } StackPage { name: "spinner"; child: Spinner instance_spinner { valign: center; }; } } } Adw.PasswordEntryRow api_key_entry { title: _("API Key"); tooltip-text: _("Enter an API Key for the Provider."); show-apply-button: true; apply => $_on_api_key_apply(); Stack api_key_stack { StackPage { name: "reset"; child: Button api_key_reset { tooltip-text: _("Reset to Default"); icon-name: "view-refresh-symbolic"; valign: center; clicked => $_on_reset_api_key(); styles ["flat"] }; } StackPage { name: "spinner"; child: Spinner api_key_spinner { valign: center; }; } } } } Adw.PreferencesGroup api_usage_group { title: _("Character Usage"); visible: false; Box { orientation: vertical; spacing: 3; LevelBar api_usage { } Label api_usage_label { } } } } } }dialect-2.4.2/data/resources/shortcuts.blp000066400000000000000000000051651465154363000206220ustar00rootroot00000000000000using Gtk 4.0; template $DialectShortcutsWindow : ShortcutsWindow { modal: true; show => $_on_show(); ShortcutsSection { section-name: "shortcuts"; max-height: 10; ShortcutsGroup { title: C_("shortcuts window", "Translator"); ShortcutsShortcut translate_shortcut { title: C_("shortcuts window", "Translate"); accelerator: "Return"; } ShortcutsShortcut switch_shortcut { title: C_("shortcuts window", "Switch Languages"); action-name: "win.switch"; } ShortcutsShortcut from_shortcut { title: C_("shortcuts window", "Select source language"); action-name: "win.from"; } ShortcutsShortcut to_shortcut { title: C_("shortcuts window", "Select destination language"); action-name: "win.to"; } ShortcutsShortcut { title: C_("shortcuts window", "Clear source text"); action-name: "win.clear"; } ShortcutsShortcut { title: C_("shortcuts window", "Copy translation"); action-name: "win.copy"; } ShortcutsShortcut { title: C_("shortcuts window", "Show Pronunciation"); action-name: "app.pronunciation"; } ShortcutsShortcut { title: C_("shortcuts window", "Increase font size"); action-name: "win.font-size-inc"; } ShortcutsShortcut { title: C_("shortcuts window", "Decrease font size"); action-name: "win.font-size-dec"; } } ShortcutsGroup { title: C_("shortcuts window", "Text-to-Speech"); ShortcutsShortcut { title: C_("shortcuts window", "Listen to source text"); action-name: "win.listen-src"; } ShortcutsShortcut { title: C_("shortcuts window", "Listen to translation"); action-name: "win.listen-dest"; } } ShortcutsGroup { title: C_("shortcuts window", "Navigation"); ShortcutsShortcut { title: C_("shortcuts window", "Go back in history"); action-name: "win.back"; } ShortcutsShortcut { title: C_("shortcuts window", "Go forward in history"); action-name: "win.forward"; } } ShortcutsGroup { title: C_("shortcuts window", "General"); ShortcutsShortcut { title: C_("shortcuts window", "Preferences"); action-name: "app.preferences"; } ShortcutsShortcut { title: C_("shortcut window", "Shortcuts"); action-name: "win.show-help-overlay"; } ShortcutsShortcut { title: C_("shortcuts window", "Quit"); action-name: "app.quit"; } } } } dialect-2.4.2/data/resources/style-dark.css000066400000000000000000000006001465154363000206430ustar00rootroot00000000000000 .translation-scrolled undershoot.bottom { border-bottom: 1px solid #222222; } .translation-scrolled.top-undershoot undershoot.top { border-top: 1px solid #222222; } .provider-feature-tts { color: @green_1; background-color: alpha(@green_4, .25); } .provider-feature-trans { color: @blue_1; } .provider-feature-dic { color: @yellow_2; background: alpha(#cd9309, .25); }dialect-2.4.2/data/resources/style.css000066400000000000000000000051171465154363000177340ustar00rootroot00000000000000 /* Main Window */ .translation-box { padding: 4px 12px 12px; } .translation-box.vertical { padding-bottom: 0; padding-top: 0; } .translation-side-box textview, .translation-side-box text { background: none; color: inherit; } .translation-scrolled undershoot.bottom { border-bottom: 1px solid #ededed; } .translation-scrolled.top-undershoot undershoot.top { border-top: 1px solid #ededed; } .mistakes { margin: 6px; padding-right: 12px; padding-left: 12px; padding-top: 9px; padding-bottom: 9px; background-color: mix(@accent_bg_color, @window_bg_color, 0.7); } .pronunciation { padding: 9px; } /* Lang Selector */ .search_box { background: @popover_bg_color; border-bottom: 1px solid @borders; padding: 6px; } .lang-selector list { padding: 6px; padding-top: 4px; } .lang-selector row { margin-top: 2px; } .lang-selector separator { margin: 0 6px; } /* Actionbar */ actionbar.flat > revealer > box { background: none; box-shadow: none; } /* Theme Switcher */ /* Base on gnome-text-editor */ /* https://gitlab.gnome.org/GNOME/gnome-text-editor/-/blob/main/src/style.css#L20 */ .themeswitcher { margin: 9px; } .themeswitcher checkbutton { padding: 0; min-height: 44px; min-width: 44px; padding: 1px; background-clip: content-box; border-radius: 9999px; box-shadow: inset 0 0 0 1px @borders; } .themeswitcher checkbutton.system:checked, .themeswitcher checkbutton.light:checked, .themeswitcher checkbutton.dark:checked { box-shadow: inset 0 0 0 2px @theme_selected_bg_color; } .themeswitcher checkbutton.system { background-image: linear-gradient(to bottom right, #fff 49.99%, #202020 50.01%); } .themeswitcher checkbutton.light { background-color: #fff; } .themeswitcher checkbutton.dark { background-color: #202020; } .themeswitcher checkbutton radio { -gtk-icon-source: none; border: none; background: none; box-shadow: none; min-width: 12px; min-height: 12px; transform: translate(27px, 14px); padding: 2px; } .themeswitcher checkbutton.theme-selector radio:checked { -gtk-icon-source: -gtk-icontheme("object-select-symbolic"); background-color: @theme_selected_bg_color; color: @theme_selected_fg_color; } /* Provider settings */ .provider-feature { padding: 3px 9px; border-radius: 12px; font-weight: bold; } .provider-feature:disabled { opacity: 1; filter: none; } .provider-feature-tts { color: @green_5; background-color: alpha(@green_3, .25); } .provider-feature-trans { color: @blue_4; background-color: alpha(@blue_3, .25); } .provider-feature-dic { color: #ae7b03; background: alpha(@yellow_5, .25); } dialect-2.4.2/data/resources/theme-switcher.blp000066400000000000000000000020471465154363000215100ustar00rootroot00000000000000using Gtk 4.0; template $ThemeSwitcher : Box { hexpand: true; styles [ "themeswitcher", ] Box box { hexpand: true; orientation: horizontal; spacing: 12; CheckButton system { visible: bind template.show-system; hexpand: true; halign: center; focus-on-click: false; tooltip-text: _("Follow System Style"); notify::active => $_on_color_scheme_changed(); styles [ "theme-selector", "system", ] } CheckButton light { hexpand: true; halign: center; group: system; focus-on-click: false; tooltip-text: _("Light Style"); notify::active => $_on_color_scheme_changed(); styles [ "theme-selector", "light", ] } CheckButton dark { hexpand: true; halign: center; group: system; focus-on-click: false; tooltip-text: _("Dark Style"); notify::active => $_on_color_scheme_changed(); styles [ "theme-selector", "dark", ] } } } dialect-2.4.2/data/resources/window.blp000066400000000000000000000367461465154363000201040ustar00rootroot00000000000000using Gtk 4.0; using Adw 1; menu app-menu { section { item { custom: "theme"; } } section { id: "preferences-section"; item { label: _("Show Pronunciation"); action: "app.pronunciation"; } } section { id: "help-section"; item { label: _("Preferences"); action: "app.preferences"; } item { label: _("Keyboard Shortcuts"); action: "win.show-help-overlay"; } item { label: _("About Dialect"); action: "app.about"; } } } template $DialectWindow : Adw.ApplicationWindow { default-width: 800; default-height: 300; width-request: 360; height-request: 320; focus-widget: src_text; Adw.Breakpoint { condition ("max-width: 680px") setters { actionbar.revealed: true; title_stack.visible-child-name: "label"; translator_box.orientation: vertical; } } Stack main_stack { transition-type: crossfade; StackPage { name: "loading"; child: WindowHandle { Box { orientation: vertical; spacing: 12; margin-top: 12; margin-bottom: 12; margin-start: 12; margin-end: 12; halign: center; valign: center; Spinner { spinning: true; width-request: 32; height-request: 32; } Label { wrap: true; label: _("Loading…"); styles [ "title-1", ] } } }; } StackPage { name: "error"; child: Adw.ToolbarView { [top] Adw.HeaderBar {} Adw.StatusPage error_page { vexpand: true; child: Adw.Squeezer { homogeneous: false; Box { spacing: 12; halign: center; Button { label: _("Retry"); clicked => $retry_load_translator(); styles [ "pill", "suggested-action", ] } Button { label: _("Open Preferences"); action-name: "app.preferences"; styles [ "pill", ] } } Box { spacing: 12; orientation: vertical; Button error_retry_btn { clicked => $retry_load_translator(); styles [ "pill", "suggested-action", ] child: Label { label: _("Retry"); ellipsize: end; }; } Button error_preferences_btn { action-name: "app.preferences"; styles [ "pill", ] child: Label { label: _("Open Preferences"); ellipsize: end; }; } } }; } }; } StackPage { name: "api-key"; child: Adw.ToolbarView { [top] Adw.HeaderBar {} Adw.StatusPage key_page { icon-name: "dialog-password-symbolic"; vexpand: true; child: Adw.Squeezer { homogeneous: false; Box { spacing: 12; halign: center; Button rmv_key_btn { visible: false; label: _("Remove Key and Retry"); clicked => $remove_key_and_reload(); styles [ "pill", "suggested-action", ] } Button { label: _("Open Preferences"); action-name: "app.preferences"; styles [ "pill", ] } } Box { spacing: 12; orientation: vertical; Button error_api_key_btn { visible: false; clicked => $remove_key_and_reload(); styles [ "pill", "suggested-action", ] child: Label { label: _("Remove Key and Retry"); ellipsize: end; }; } Button error_preferences2_btn { action-name: "app.preferences"; styles [ "pill", ] child: Label { label: _("Open Preferences"); ellipsize: end; }; } } }; } }; } StackPage { name: "translate"; child: Adw.ToastOverlay toast_overlay { vexpand: true; child: Adw.ToolbarView { [top] Adw.HeaderBar { centering-policy: strict; title-widget: Stack title_stack { transition-type: crossfade; hhomogeneous: false; StackPage { name: "selector"; child: Box langs_button_box { spacing: 6; $LangSelector src_lang_selector { notify::selected => $_on_src_lang_changed(); user-selection-changed => $translation(); tooltip-text: _("Change Source Language"); } Button switch_btn { action-name: "win.switch"; tooltip-text: _("Switch Languages"); icon-name: "object-flip-horizontal-symbolic"; } $LangSelector dest_lang_selector { notify::selected => $_on_dest_lang_changed(); user-selection-changed => $translation(); tooltip-text: _("Change Destination Language"); } }; } StackPage { name: "label"; child: Adw.WindowTitle { title: _("Dialect"); }; } }; Button return_btn { action-name: "win.back"; tooltip-text: _("Previous Translation"); icon-name: "go-previous-symbolic"; } Button forward_btn { action-name: "win.forward"; tooltip-text: _("Next Translation"); icon-name: "go-next-symbolic"; } [end] MenuButton menu_btn { menu-model: app-menu; tooltip-text: _("Main Menu"); icon-name: "open-menu-symbolic"; primary: true; } } Box { orientation: vertical; Box translator_box { vexpand: true; spacing: 12; homogeneous: true; styles [ "translation-box", ] Box { orientation: vertical; overflow: hidden; styles [ "card", "translation-side-box", ] ScrolledWindow { vexpand: true; $TextView src_text { left-margin: 9; right-margin: 9; top-margin: 9; bottom-margin: 9; activate => $_on_src_activated(); } styles [ "translation-scrolled" ] } Revealer src_pron_revealer { transition-type: slide_down; reveal-child: false; ScrolledWindow { Label src_pron_label { xalign: 0; wrap: true; wrap-mode: word_char; selectable: true; valign: end; styles [ "pronunciation", "dim-label", ] } styles [ "translation-scrolled", "top-undershoot" ] } } Revealer mistakes { can-focus: false; reveal-child: false; Box { can-focus: false; orientation: horizontal; spacing: 8; Image { can-focus: false; icon-name: "error-correct-symbolic"; } Label mistakes_label { can-focus: false; wrap: true; wrap-mode: word_char; activate-link => $_on_mistakes_clicked(); } styles [ "card", "mistakes" ] } } Box { Button clear_btn { action-name: "win.clear"; tooltip-text: _("Clear"); icon-name: "edit-clear-symbolic"; } Button paste_btn { action-name: "win.paste"; tooltip-text: _("Paste"); icon-name: "edit-paste-symbolic"; } Button src_voice_btn { action-name: "win.listen-src"; tooltip-text: _("Listen"); styles [ "flat", ] } Label char_counter { margin-start: 4; margin-end: 4; hexpand: true; halign: end; styles [ "dim-label", "caption-heading", "numeric" ] } Button translate_btn { label: _("Translate"); action-name: "win.translation"; styles [ "suggested-action", ] } styles [ "toolbar", ] } } Box dest_box { orientation: vertical; overflow: hidden; styles [ "card", "translation-side-box", ] ScrolledWindow { vexpand: true; $TextView dest_text { editable: false; left-margin: 9; right-margin: 9; top-margin: 9; bottom-margin: 9; } styles [ "translation-scrolled" ] } Revealer dest_pron_revealer { transition-type: slide_down; reveal-child: false; ScrolledWindow { Label dest_pron_label { xalign: 0; wrap: true; wrap-mode: word_char; selectable: true; valign: end; styles [ "pronunciation", "dim-label", ] } styles [ "translation-scrolled", "top-undershoot" ] } } Stack dest_toolbar_stack { transition-type: crossfade; StackPage { name: "default"; child: Box { Spinner trans_spinner { tooltip-text: _("Translating…"); margin-start: 8; } Image trans_warning { tooltip-text: _("Could not Translate the Text"); margin-start: 8; icon-name: "dialog-warning-symbolic"; } Button copy_btn { action-name: "win.copy"; tooltip-text: _("Copy"); icon-name: "edit-copy-symbolic"; hexpand: true; halign: end; } Button edit_btn { action-name: "win.suggest"; tooltip-text: _("Suggest Translation"); icon-name: "document-edit-symbolic"; } Button dest_voice_btn { action-name: "win.listen-dest"; tooltip-text: _("Listen"); styles [ "flat", ] } styles [ "toolbar", ] }; } StackPage { name: "edit"; child: Box { Button cancel_btn { action-name: "win.suggest-cancel"; label: _("Cancel"); hexpand: true; halign: end; } Button save_btn { action-name: "win.suggest-ok"; label: _("Save"); styles [ "suggested-action", ] } styles [ "toolbar", ] }; } } } } ActionBar actionbar { sensitive: bind langs_button_box.sensitive no-sync-create; revealed: false; styles [ "flat", ] $LangSelector src_lang_selector_m { selected: bind src_lang_selector.selected bidirectional; tooltip-text: _("Change Source Language"); user-selection-changed => $translation(); } [center] Button switch_btn2 { sensitive: bind switch_btn.sensitive no-sync-create; tooltip-text: _("Switch Languages"); action-name: "win.switch"; icon-name: "object-flip-horizontal-symbolic"; } [end] $LangSelector dest_lang_selector_m { selected: bind dest_lang_selector.selected bidirectional; tooltip-text: _("Change Destination Language"); user-selection-changed => $translation(); } } } }; }; } } EventControllerKey win_key_ctrlr { key-pressed => $_on_key_event(); } } Gtk.SizeGroup { mode: both; widgets [src_lang_selector, dest_lang_selector] } Gtk.SizeGroup { widgets [error_retry_btn, error_preferences_btn] } Gtk.SizeGroup { widgets [error_api_key_btn, error_preferences2_btn] } dialect-2.4.2/dialect.doap000066400000000000000000000027421465154363000154120ustar00rootroot00000000000000 Dialect Translate between languages Python GTK 4 Libadwaita Mufeed Ali mufeedali Rafael Mardojai CM rafaelmardojai dialect-2.4.2/dialect/000077500000000000000000000000001465154363000145405ustar00rootroot00000000000000dialect-2.4.2/dialect/__builtins__.pyi000066400000000000000000000000761465154363000177130ustar00rootroot00000000000000def _(str: str) -> str: ... def gettext(str: str) -> str: ... dialect-2.4.2/dialect/__init__.py000066400000000000000000000000001465154363000166370ustar00rootroot00000000000000dialect-2.4.2/dialect/define.in000066400000000000000000000403301465154363000163220ustar00rootroot00000000000000# Copyright 2020 gi-lom # Copyright 2020-2022 Mufeed Ali # Copyright 2020-2022 Rafael Mardojai CM # SPDX-License-Identifier: GPL-3.0-or-later APP_ID = '@APP_ID@' PROFILE = '@PROFILE@' RES_PATH = '/app/drey/Dialect' VERSION = '@VERSION@' TRANS_NUMBER = 10 # number of translations to save in history LANG_ALIASES = { 'iw': 'he', # Hebrew 'jw': 'jv', # Javanese 'mni-Mtei': 'mni', # Meiteilon (Manipuri) 'zh-CN': 'zh-Hans', 'zh-TW': 'zh-Hant', } LANGUAGES = { "aa": "Afar", "ab": "Abkhazian", "ace": "Achinese", "ach": "Acoli", "ada": "Adangme", "ady": "Adyghe", "ae": "Avestan", "aeb": "Tunisian Arabic", "af": "Afrikaans", "afh": "Afrihili", "agq": "Aghem", "ain": "Ainu", "ak": "Akan", "akk": "Akkadian", "akz": "Alabama", "ale": "Aleut", "aln": "Gheg Albanian", "alt": "Southern Altai", "am": "Amharic", "an": "Aragonese", "ang": "Old English", "ann": "Obolo", "anp": "Angika", "ar": "Arabic", "ar-001": "Modern Standard Arabic", "arc": "Aramaic", "arn": "Mapuche", "aro": "Araona", "arp": "Arapaho", "arq": "Algerian Arabic", "ars": "Najdi Arabic", "ars-alt-menu": "Arabic, Najdi", "arw": "Arawak", "ary": "Moroccan Arabic", "arz": "Egyptian Arabic", "as": "Assamese", "asa": "Asu", "ase": "American Sign Language", "ast": "Asturian", "atj": "Atikamekw", "av": "Avaric", "avk": "Kotava", "awa": "Awadhi", "ay": "Aymara", "az": "Azerbaijani", "az-alt-short": "Azeri", "ba": "Bashkir", "bal": "Baluchi", "ban": "Balinese", "bar": "Bavarian", "bas": "Basaa", "bax": "Bamun", "bbc": "Batak Toba", "bbj": "Ghomala", "be": "Belarusian", "bej": "Beja", "bem": "Bemba", "bew": "Betawi", "bez": "Bena", "bfd": "Bafut", "bfq": "Badaga", "bg": "Bulgarian", "bgc": "Haryanvi", "bgn": "Western Balochi", "bho": "Bhojpuri", "bi": "Bislama", "bik": "Bikol", "bin": "Bini", "bjn": "Banjar", "bkm": "Kom", "bla": "Siksiká", "blt": "Tai Dam", "bm": "Bambara", "bn": "Bangla", "bo": "Tibetan", "bpy": "Bishnupriya", "bqi": "Bakhtiari", "br": "Breton", "bra": "Braj", "brh": "Brahui", "brx": "Bodo", "bs": "Bosnian", "bss": "Akoose", "bua": "Buriat", "bug": "Buginese", "bum": "Bulu", "byn": "Blin", "byv": "Medumba", "ca": "Catalan", "cad": "Caddo", "car": "Carib", "cay": "Cayuga", "cch": "Atsam", "ccp": "Chakma", "ce": "Chechen", "ceb": "Cebuano", "cgg": "Chiga", "ch": "Chamorro", "chb": "Chibcha", "chg": "Chagatai", "chk": "Chuukese", "chm": "Mari", "chn": "Chinook Jargon", "cho": "Choctaw", "chp": "Chipewyan", "chr": "Cherokee", "chy": "Cheyenne", "cic": "Chickasaw", "ckb": "Central Kurdish", "ckb-alt-menu": "Kurdish, Central", "ckb-alt-variant": "Kurdish, Sorani", "clc": "Chilcotin", "co": "Corsican", "cop": "Coptic", "cps": "Capiznon", "cr": "Cree", "crg": "Michif", "crh": "Crimean Tatar", "crj": "Southern East Cree", "crk": "Plains Cree", "crl": "Northern East Cree", "crm": "Moose Cree", "crr": "Carolina Algonquian", "crs": "Seselwa Creole French", "cs": "Czech", "csb": "Kashubian", "csw": "Swampy Cree", "cu": "Church Slavic", "cv": "Chuvash", "cwd": "Woods Cree", "cy": "Welsh", "da": "Danish", "dak": "Dakota", "dar": "Dargwa", "dav": "Taita", "de": "German", "de-AT": "Austrian German", "de-CH": "Swiss High German", "del": "Delaware", "den": "Slave", "dgr": "Dogrib", "din": "Dinka", "dje": "Zarma", "doi": "Dogri", "dsb": "Lower Sorbian", "dtp": "Central Dusun", "dua": "Duala", "dum": "Middle Dutch", "dv": "Divehi", "dyo": "Jola-Fonyi", "dyu": "Dyula", "dz": "Dzongkha", "dzg": "Dazaga", "ebu": "Embu", "ee": "Ewe", "efi": "Efik", "egl": "Emilian", "egy": "Ancient Egyptian", "eka": "Ekajuk", "el": "Greek", "elx": "Elamite", "en": "English", "en-AU": "Australian English", "en-CA": "Canadian English", "en-GB": "British English", "en-GB-alt-short": "UK English", "en-US": "American English", "en-US-alt-short": "US English", "enm": "Middle English", "eo": "Esperanto", "es": "Spanish", "es-419": "Latin American Spanish", "es-ES": "European Spanish", "es-MX": "Mexican Spanish", "esu": "Central Yupik", "et": "Estonian", "eu": "Basque", "ewo": "Ewondo", "ext": "Extremaduran", "fa": "Persian", "fa-AF": "Dari", "fan": "Fang", "fat": "Fanti", "ff": "Fula", "fi": "Finnish", "fil": "Filipino", "fit": "Tornedalen Finnish", "fj": "Fijian", "fo": "Faroese", "fon": "Fon", "fr": "French", "fr-CA": "Canadian French", "fr-CH": "Swiss French", "frc": "Cajun French", "frm": "Middle French", "fro": "Old French", "frp": "Arpitan", "frr": "Northern Frisian", "frs": "Eastern Frisian", "fur": "Friulian", "fy": "Western Frisian", "ga": "Irish", "gaa": "Ga", "gag": "Gagauz", "gan": "Gan Chinese", "gay": "Gayo", "gba": "Gbaya", "gbz": "Zoroastrian Dari", "gd": "Scottish Gaelic", "gez": "Geez", "gil": "Gilbertese", "gl": "Galician", "glk": "Gilaki", "gmh": "Middle High German", "gn": "Guarani", "goh": "Old High German", "gom": "Goan Konkani", "gon": "Gondi", "gor": "Gorontalo", "got": "Gothic", "grb": "Grebo", "grc": "Ancient Greek", "gsw": "Swiss German", "gu": "Gujarati", "guc": "Wayuu", "gur": "Frafra", "guz": "Gusii", "gv": "Manx", "gwi": "Gwichʼin", "ha": "Hausa", "hai": "Haida", "hak": "Hakka Chinese", "haw": "Hawaiian", "hax": "Southern Haida", "hdn": "Northern Haida", "he": "Hebrew", "hi": "Hindi", "hi-Latn": "Hindi (Latin)", "hi-Latn-alt-variant": "Hinglish", "hif": "Fiji Hindi", "hil": "Hiligaynon", "hit": "Hittite", "hmn": "Hmong", "hnj": "Hmong Njua", "ho": "Hiri Motu", "hr": "Croatian", "hsb": "Upper Sorbian", "hsn": "Xiang Chinese", "ht": "Haitian Creole", "hu": "Hungarian", "hup": "Hupa", "hur": "Halkomelem", "hy": "Armenian", "hz": "Herero", "ia": "Interlingua", "iba": "Iban", "ibb": "Ibibio", "id": "Indonesian", "ie": "Interlingue", "ig": "Igbo", "ii": "Sichuan Yi", "ik": "Inupiaq", "ike": "Eastern Canadian Inuktitut", "ikt": "Western Canadian Inuktitut", "ilo": "Iloko", "inh": "Ingush", "io": "Ido", "is": "Icelandic", "it": "Italian", "iu": "Inuktitut", "izh": "Ingrian", "ja": "Japanese", "jam": "Jamaican Creole English", "jbo": "Lojban", "jgo": "Ngomba", "jmc": "Machame", "jpr": "Judeo-Persian", "jrb": "Judeo-Arabic", "jut": "Jutish", "jv": "Javanese", "ka": "Georgian", "kaa": "Kara-Kalpak", "kab": "Kabyle", "kac": "Kachin", "kaj": "Jju", "kam": "Kamba", "kaw": "Kawi", "kbd": "Kabardian", "kbl": "Kanembu", "kcg": "Tyap", "kde": "Makonde", "kea": "Kabuverdianu", "ken": "Kenyang", "kfo": "Koro", "kg": "Kongo", "kgp": "Kaingang", "kha": "Khasi", "kho": "Khotanese", "khq": "Koyra Chiini", "khw": "Khowar", "ki": "Kikuyu", "kiu": "Kirmanjki", "kj": "Kuanyama", "kk": "Kazakh", "kkj": "Kako", "kl": "Kalaallisut", "kln": "Kalenjin", "km": "Khmer", "kmb": "Kimbundu", "kn": "Kannada", "ko": "Korean", "koi": "Komi-Permyak", "kok": "Konkani", "kos": "Kosraean", "kpe": "Kpelle", "kr": "Kanuri", "krc": "Karachay-Balkar", "kri": "Krio", "krj": "Kinaray-a", "krl": "Karelian", "kru": "Kurukh", "ks": "Kashmiri", "ksb": "Shambala", "ksf": "Bafia", "ksh": "Colognian", "ku": "Kurdish", "kum": "Kumyk", "kut": "Kutenai", "kv": "Komi", "kw": "Cornish", "kwk": "Kwakʼwala", "ky": "Kyrgyz", "ky-alt-variant": "Kirghiz", "la": "Latin", "lad": "Ladino", "lag": "Langi", "lah": "Western Panjabi", "lam": "Lamba", "lb": "Luxembourgish", "lez": "Lezghian", "lfn": "Lingua Franca Nova", "lg": "Ganda", "li": "Limburgish", "lij": "Ligurian", "lil": "Lillooet", "liv": "Livonian", "lkt": "Lakota", "lmo": "Lombard", "ln": "Lingala", "lo": "Lao", "lol": "Mongo", "lou": "Louisiana Creole", "loz": "Lozi", "lrc": "Northern Luri", "lsm": "Saamia", "lt": "Lithuanian", "ltg": "Latgalian", "lu": "Luba-Katanga", "lua": "Luba-Lulua", "lui": "Luiseno", "lun": "Lunda", "luo": "Luo", "lus": "Mizo", "luy": "Luyia", "lv": "Latvian", "lzh": "Literary Chinese", "lzz": "Laz", "mad": "Madurese", "maf": "Mafa", "mag": "Magahi", "mai": "Maithili", "mak": "Makasar", "man": "Mandingo", "mas": "Masai", "mde": "Maba", "mdf": "Moksha", "mdr": "Mandar", "men": "Mende", "mer": "Meru", "mfe": "Morisyen", "mg": "Malagasy", "mga": "Middle Irish", "mgh": "Makhuwa-Meetto", "mgo": "Metaʼ", "mh": "Marshallese", "mi": "Māori", "mic": "Mi'kmaq", "min": "Minangkabau", "mk": "Macedonian", "ml": "Malayalam", "mn": "Mongolian", "mnc": "Manchu", "mni": "Manipuri", "moe": "Innu-aimun", "moh": "Mohawk", "mos": "Mossi", "mr": "Marathi", "mrj": "Western Mari", "ms": "Malay", "mt": "Maltese", "mua": "Mundang", "mul": "Multiple languages", "mus": "Muscogee", "mwl": "Mirandese", "mwr": "Marwari", "mwv": "Mentawai", "my": "Burmese", "my-alt-variant": "Myanmar Language", "mye": "Myene", "myv": "Erzya", "mzn": "Mazanderani", "na": "Nauru", "nan": "Min Nan Chinese", "nap": "Neapolitan", "naq": "Nama", "nb": "Norwegian Bokmål", "nd": "North Ndebele", "nds": "Low German", "nds-NL": "Low Saxon", "ne": "Nepali", "new": "Newari", "ng": "Ndonga", "nia": "Nias", "niu": "Niuean", "njo": "Ao Naga", "nl": "Dutch", "nl-BE": "Flemish", "nmg": "Kwasio", "nn": "Norwegian Nynorsk", "nnh": "Ngiemboon", "no": "Norwegian", "nog": "Nogai", "non": "Old Norse", "nov": "Novial", "nqo": "N’Ko", "nr": "South Ndebele", "nso": "Northern Sotho", "nus": "Nuer", "nv": "Navajo", "nwc": "Classical Newari", "ny": "Nyanja", "nym": "Nyamwezi", "nyn": "Nyankole", "nyo": "Nyoro", "nzi": "Nzima", "oc": "Occitan", "oj": "Ojibwa", "ojb": "Northwestern Ojibwa", "ojc": "Central Ojibwa", "ojg": "Eastern Ojibwa", "ojs": "Oji-Cree", "ojw": "Western Ojibwa", "oka": "Okanagan", "om": "Oromo", "or": "Odia", "os": "Ossetic", "osa": "Osage", "ota": "Ottoman Turkish", "pa": "Punjabi", "pag": "Pangasinan", "pal": "Pahlavi", "pam": "Pampanga", "pap": "Papiamento", "pau": "Palauan", "pcd": "Picard", "pcm": "Nigerian Pidgin", "pdc": "Pennsylvania German", "pdt": "Plautdietsch", "peo": "Old Persian", "pfl": "Palatine German", "phn": "Phoenician", "pi": "Pali", "pis": "Pijin", "pl": "Polish", "pms": "Piedmontese", "pnt": "Pontic", "pon": "Pohnpeian", "pqm": "Maliseet-Passamaquoddy", "prg": "Prussian", "pro": "Old Provençal", "ps": "Pashto", "ps-alt-variant": "Pushto", "pt": "Portuguese", "pt-BR": "Brazilian Portuguese", "pt-PT": "European Portuguese", "qu": "Quechua", "quc": "Kʼicheʼ", "qug": "Chimborazo Highland Quichua", "raj": "Rajasthani", "rap": "Rapanui", "rar": "Rarotongan", "rgn": "Romagnol", "rhg": "Rohingya", "rif": "Riffian", "rm": "Romansh", "rn": "Rundi", "ro": "Romanian", "ro-MD": "Moldavian", "rof": "Rombo", "rom": "Romany", "rtm": "Rotuman", "ru": "Russian", "rue": "Rusyn", "rug": "Roviana", "rup": "Aromanian", "rw": "Kinyarwanda", "rwk": "Rwa", "sa": "Sanskrit", "sad": "Sandawe", "sah": "Yakut", "sam": "Samaritan Aramaic", "saq": "Samburu", "sas": "Sasak", "sat": "Santali", "saz": "Saurashtra", "sba": "Ngambay", "sbp": "Sangu", "sc": "Sardinian", "scn": "Sicilian", "sco": "Scots", "sd": "Sindhi", "sdc": "Sassarese Sardinian", "sdh": "Southern Kurdish", "se": "Northern Sami", "se-alt-menu": "Sami, Northern", "see": "Seneca", "seh": "Sena", "sei": "Seri", "sel": "Selkup", "ses": "Koyraboro Senni", "sg": "Sango", "sga": "Old Irish", "sgs": "Samogitian", "sh": "Serbo-Croatian", "shi": "Tachelhit", "shn": "Shan", "shu": "Chadian Arabic", "si": "Sinhala", "sid": "Sidamo", "sk": "Slovak", "sl": "Slovenian", "slh": "Southern Lushootseed", "sli": "Lower Silesian", "sly": "Selayar", "sm": "Samoan", "sma": "Southern Sami", "sma-alt-menu": "Sami, Southern", "smj": "Lule Sami", "smj-alt-menu": "Sami, Lule", "smn": "Inari Sami", "smn-alt-menu": "Sami, Inari", "sms": "Skolt Sami", "sms-alt-menu": "Sami, Skolt", "sn": "Shona", "snk": "Soninke", "so": "Somali", "sog": "Sogdien", "sq": "Albanian", "sr": "Serbian", "sr-ME": "Montenegrin", "srn": "Sranan Tongo", "srr": "Serer", "ss": "Swati", "ssy": "Saho", "st": "Southern Sotho", "stq": "Saterland Frisian", "str": "Straits Salish", "su": "Sundanese", "suk": "Sukuma", "sus": "Susu", "sux": "Sumerian", "sv": "Swedish", "sw": "Swahili", "sw-CD": "Congo Swahili", "swb": "Comorian", "syc": "Classical Syriac", "syr": "Syriac", "szl": "Silesian", "ta": "Tamil", "tce": "Southern Tutchone", "tcy": "Tulu", "te": "Telugu", "tem": "Timne", "teo": "Teso", "ter": "Tereno", "tet": "Tetum", "tg": "Tajik", "tgx": "Tagish", "th": "Thai", "tht": "Tahltan", "ti": "Tigrinya", "tig": "Tigre", "tiv": "Tiv", "tk": "Turkmen", "tkl": "Tokelau", "tkr": "Tsakhur", "tl": "Tagalog", "tlh": "Klingon", "tli": "Tlingit", "tly": "Talysh", "tmh": "Tamashek", "tn": "Tswana", "to": "Tongan", "tog": "Nyasa Tonga", "tok": "Toki Pona", "tpi": "Tok Pisin", "tr": "Turkish", "tru": "Turoyo", "trv": "Taroko", "trw": "Torwali", "ts": "Tsonga", "tsd": "Tsakonian", "tsi": "Tsimshian", "tt": "Tatar", "ttm": "Northern Tutchone", "ttt": "Muslim Tat", "tum": "Tumbuka", "tvl": "Tuvalu", "tw": "Twi", "twq": "Tasawaq", "ty": "Tahitian", "tyv": "Tuvinian", "tzm": "Central Atlas Tamazight", "udm": "Udmurt", "ug": "Uyghur", "ug-alt-variant": "Uighur", "uga": "Ugaritic", "uk": "Ukrainian", "umb": "Umbundu", "und": "Unknown language", "ur": "Urdu", "uz": "Uzbek", "vai": "Vai", "ve": "Venda", "vec": "Venetian", "vep": "Veps", "vi": "Vietnamese", "vls": "West Flemish", "vmf": "Main-Franconian", "vo": "Volapük", "vot": "Votic", "vro": "Võro", "vun": "Vunjo", "wa": "Walloon", "wae": "Walser", "wal": "Wolaytta", "war": "Waray", "was": "Washo", "wbp": "Warlpiri", "wo": "Wolof", "wuu": "Wu Chinese", "xal": "Kalmyk", "xh": "Xhosa", "xmf": "Mingrelian", "xog": "Soga", "yao": "Yao", "yap": "Yapese", "yav": "Yangben", "ybb": "Yemba", "yi": "Yiddish", "yo": "Yoruba", "yrl": "Nheengatu", "yue": "Cantonese", "yue-alt-menu": "Chinese, Cantonese", "za": "Zhuang", "zap": "Zapotec", "zbl": "Blissymbols", "zea": "Zeelandic", "zen": "Zenaga", "zgh": "Standard Moroccan Tamazight", "zh": "Chinese", "zh-alt-long": "Mandarin Chinese", "zh-alt-menu": "Chinese, Mandarin", "zh-Hans": "Simplified Chinese", "zh-Hans-alt-long": "Simplified Mandarin Chinese", "zh-Hant": "Traditional Chinese", "zh-Hant-alt-long": "Traditional Mandarin Chinese", "zu": "Zulu", "zun": "Zuni", "zxx": "No linguistic content", "zza": "Zaza" } dialect-2.4.2/dialect/dialect.in000077500000000000000000000022071465154363000165010ustar00rootroot00000000000000#!@PYTHON@ # Copyright 2020 gi-lom # Copyright 2020 Rafael Mardojai CM # SPDX-License-Identifier: GPL-3.0-or-later import gettext import locale import os import signal import sys pkgdatadir = '@pkgdatadir@' localedir = '@localedir@' builddir = os.environ.get('MESON_BUILD_ROOT') if builddir: sys.dont_write_bytecode = True sys.path.insert(1, os.environ['MESON_SOURCE_ROOT']) data_dir = os.path.join(builddir, '@prefix@', '@datadir@') os.putenv('XDG_DATA_DIRS', '%s:%s' % (data_dir, os.getenv('XDG_DATA_DIRS', '/usr/local/share/:/usr/share/'))) sys.path.insert(1, pkgdatadir) signal.signal(signal.SIGINT, signal.SIG_DFL) langs_trans = gettext.translation('dialect-cldr-langs', localedir, fallback=True) ui_trans = gettext.translation('dialect', localedir, fallback=True) ui_trans.add_fallback(langs_trans) ui_trans.install(names=['gettext']) locale.bindtextdomain('dialect', localedir) locale.textdomain('dialect') if __name__ == '__main__': from gi.repository import Gio resource = Gio.Resource.load(os.path.join(pkgdatadir, 'dialect.gresource')) resource._register() from dialect import main sys.exit(main.main()) dialect-2.4.2/dialect/languages.py000066400000000000000000000032241465154363000170610ustar00rootroot00000000000000# Copyright 2021-2022 Mufeed Ali # Copyright 2021-2022 Rafael Mardojai CM # SPDX-License-Identifier: GPL-3.0-or-later from gi.repository import Gio, GObject from dialect.define import LANGUAGES def get_lang_name(code): name = LANGUAGES.get(code) if name: name = gettext(name) return name class LangObject(GObject.Object): __gtype_name__ = "LangObject" code = GObject.Property(type=str) name = GObject.Property(type=str) selected = GObject.Property(type=bool, default=False) def __init__(self, code, name, selected=False): super().__init__() self.code = code self.name = name self.selected = selected def __str__(self): return self.code class LanguagesListModel(GObject.GObject, Gio.ListModel): __gtype_name__ = "LanguagesListModel" def __init__(self, names_func=get_lang_name): super().__init__() self.names_func = names_func self.langs = [] def __iter__(self): return iter(self.langs) def do_get_item(self, position): return self.langs[position] def do_get_item_type(self): return LangObject def do_get_n_items(self): return len(self.langs) def set_langs(self, langs, auto=False): removed = len(self.langs) self.langs.clear() if auto: self.langs.append(LangObject("auto", _("Auto"))) for code in langs: self.langs.append(LangObject(code, self.names_func(code))) self.items_changed(0, removed, len(self.langs)) def set_selected(self, code): for item in self.langs: item.props.selected = item.code == code dialect-2.4.2/dialect/main.py000077500000000000000000000155501465154363000160470ustar00rootroot00000000000000# Copyright 2020 gi-lom # Copyright 2020-2022 Mufeed Ali # Copyright 2020-2022 Rafael Mardojai CM # SPDX-License-Identifier: GPL-3.0-or-later # Initial setup import logging import sys import gi try: gi.require_version("Gdk", "4.0") gi.require_version("Gtk", "4.0") gi.require_version("Gst", "1.0") gi.require_version("Adw", "1") gi.require_version("Secret", "1") gi.require_version("Soup", "3.0") from gi.repository import Adw, Gio, GLib, Gst, Gtk except ImportError or ValueError: logging.error("Error: GObject dependencies not met.") from dialect.define import APP_ID, RES_PATH, VERSION from dialect.preferences import DialectPreferencesDialog from dialect.settings import Settings from dialect.window import DialectWindow class Dialect(Adw.Application): def __init__(self): Adw.Application.__init__(self, application_id=APP_ID, flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE) self.set_resource_base_path(RES_PATH) # App window self.window = None # CLI self.argv = {} self._signal_handler = None # Add command line options self.add_main_option( "selection", b"n", GLib.OptionFlags.NONE, GLib.OptionArg.NONE, "Translate text from the primary clipboard", None, ) self.add_main_option("text", b"t", GLib.OptionFlags.NONE, GLib.OptionArg.STRING, "Text to translate", None) self.add_main_option("src", b"s", GLib.OptionFlags.NONE, GLib.OptionArg.STRING, "Source lang code", None) self.add_main_option("dest", b"d", GLib.OptionFlags.NONE, GLib.OptionArg.STRING, "Destination lang code", None) self.setup_actions() def do_activate(self): def on_translator_loading(_win, _pspec): if not self.window.translator_loading: # Remove signal handler if self._signal_handler: self.window.disconnect(self._signal_handler) # Process CLI args self.process_command_line() self.window = self.props.active_window if not self.window: width, height = Settings.get().window_size self.window = DialectWindow( application=self, # Translators: Do not translate the app name! title=_("Dialect"), default_height=height, default_width=width, ) # Decide when to process command line args if self.window.translator_loading: # Wait until translator is loaded self._signal_handler = self.window.connect("notify::translator-loading", on_translator_loading) else: self.process_command_line() self.window.present() def do_command_line(self, command_line): options = command_line.get_options_dict() # Save CLI args values self.argv = options.end().unpack() self.activate() return 0 def do_startup(self): Adw.Application.do_startup(self) Gst.init(None) # Init Gst def process_command_line(self): if not self.argv: return text = "" langs = {"src": None, "dest": None} selection = "selection" in self.argv if "text" in self.argv: text = self.argv["text"] if "src" in self.argv: langs["src"] = self.argv["src"] if "dest" in self.argv: langs["dest"] = self.argv["dest"] if self.window is not None: if not text and selection: self.window.translate_selection(langs["src"], langs["dest"]) elif text: self.window.translate(text, langs["src"], langs["dest"]) # Clean CLI args self.argv = {} def setup_actions(self): """Setup menu actions""" pronunciation = Gio.SimpleAction.new_stateful("pronunciation", None, Settings.get().show_pronunciation_value) pronunciation.connect("change-state", self._on_pronunciation) self.add_action(pronunciation) preferences = Gio.SimpleAction.new("preferences", None) preferences.connect("activate", self._on_preferences) self.add_action(preferences) about = Gio.SimpleAction.new("about", None) about.connect("activate", self._on_about) self.add_action(about) quit_action = Gio.SimpleAction.new("quit", None) quit_action.connect("activate", self._on_quit) self.add_action(quit_action) self.set_accels_for_action("app.pronunciation", ["P"]) self.set_accels_for_action("app.preferences", ["comma"]) self.set_accels_for_action("app.quit", ["Q"]) self.set_accels_for_action("win.back", ["Left"]) self.set_accels_for_action("win.forward", ["Right"]) self.set_accels_for_action("win.switch", ["S"]) self.set_accels_for_action("win.from", ["F"]) self.set_accels_for_action("win.to", ["T"]) self.set_accels_for_action("win.clear", ["D"]) self.set_accels_for_action("win.font-size-inc", ["plus", "KP_Add"]) self.set_accels_for_action("win.font-size-dec", ["minus", "KP_Subtract"]) self.set_accels_for_action("win.paste", ["V"]) self.set_accels_for_action("win.copy", ["C"]) self.set_accels_for_action("win.listen-dest", ["L"]) self.set_accels_for_action("win.listen-src", ["L"]) self.set_accels_for_action("win.show-help-overlay", ["question"]) def _on_pronunciation(self, action, value): """Update show pronunciation setting""" action.props.state = value Settings.get().show_pronunciation = value # Update UI if self.window.trans_src_pron is not None: self.window.src_pron_revealer.props.reveal_child = value if self.window.trans_dest_pron is not None: self.window.dest_pron_revealer.props.reveal_child = value def _on_preferences(self, _action, _param): """Show preferences window""" window = DialectPreferencesDialog(self.window) window.present(self.window) def _on_about(self, _action, _param): """Show about dialog""" builder = Gtk.Builder.new_from_resource(f"{RES_PATH}/about.ui") about = builder.get_object("about") about.props.application_icon = APP_ID about.props.version = VERSION about.props.developers = ["Mufeed Ali", "Rafael Mardojai CM http://rafaelmardojai.com", "Libretto"] about.add_link(_("Donate"), "https://opencollective.com/dialect") about.present(self.window) def _on_quit(self, _action, _param): self.quit() def main(): # Run the Application app = Dialect() return app.run(sys.argv) dialect-2.4.2/dialect/meson.build000066400000000000000000000015771465154363000167140ustar00rootroot00000000000000python = import('python') # Generate dialect bin configure_file( input: 'dialect.in', output: 'dialect', configuration: conf, install: true, install_dir: get_option('bindir') ) # Generate dialect define module configure_file( input: 'define.in', output: 'define.py', configuration: conf, install: true, install_dir: moduledir ) launcher = join_paths(meson.project_build_root(), 'dialect', meson.project_name()) run_target('run', command: [launcher] ) subdir('search_provider') # Python sources sources = [ '__init__.py', 'languages.py', 'main.py', 'preferences.py', 'session.py', 'settings.py', 'shortcuts.py', 'utils.py', 'window.py', ] # Install sources install_data(sources, install_dir: moduledir) # Install custom widgets install_subdir('widgets', install_dir: moduledir) # Install providers install_subdir('providers', install_dir: moduledir)dialect-2.4.2/dialect/preferences.py000066400000000000000000000145551465154363000174250ustar00rootroot00000000000000# Copyright 2020-2022 Mufeed Ali # Copyright 2020-2022 Rafael Mardojai CM # Copyright 2023 Libretto # SPDX-License-Identifier: GPL-3.0-or-later import os from gi.repository import Adw, Gio, Gtk from dialect.define import RES_PATH from dialect.providers import MODULES, TTS, ProviderFeature, ProvidersListModel from dialect.settings import Settings from dialect.widgets import ProviderPreferences @Gtk.Template(resource_path=f"{RES_PATH}/preferences.ui") class DialectPreferencesDialog(Adw.PreferencesDialog): __gtype_name__ = "DialectPreferencesDialog" window = NotImplemented # Child widgets live_translation = Gtk.Template.Child() search_provider = Gtk.Template.Child() translate_accel = Gtk.Template.Child() src_auto = Gtk.Template.Child() translator = Gtk.Template.Child() translator_config = Gtk.Template.Child() tts = Gtk.Template.Child() tts_config = Gtk.Template.Child() custom_default_font_size = Gtk.Template.Child() default_font_size = Gtk.Template.Child() def __init__(self, window, **kwargs): super().__init__(**kwargs) self.window = window # Bind preferences with GSettings Settings.get().bind( "live-translation", self.live_translation, "enable-expansion", Gio.SettingsBindFlags.DEFAULT ) Settings.get().bind("sp-translation", self.search_provider, "active", Gio.SettingsBindFlags.DEFAULT) Settings.get().bind("translate-accel", self.translate_accel, "selected", Gio.SettingsBindFlags.DEFAULT) Settings.get().bind("src-auto", self.src_auto, "active", Gio.SettingsBindFlags.DEFAULT) Settings.get().bind( "custom-default-font-size", self.custom_default_font_size, "enable-expansion", Gio.SettingsBindFlags.DEFAULT ) Settings.get().bind("default-font-size", self.default_font_size, "value", Gio.SettingsBindFlags.DEFAULT) self.translator_config.props.sensitive = False self.tts_config.props.sensitive = False # Setup translator chooser trans_model = ProvidersListModel("translators") with self.translator.freeze_notify(): self.translator.set_model(trans_model) self.translator.props.selected = trans_model.get_index_by_name(Settings.get().active_translator) self.translator_config.props.sensitive = self._provider_has_settings(Settings.get().active_translator) # Setup TTS chooser if len(TTS) >= 1: tts_model = ProvidersListModel("tts", True) with self.tts.freeze_notify(): self.tts.set_model(tts_model) self.tts.props.selected = tts_model.get_index_by_name(Settings.get().active_tts) self.tts_config.props.sensitive = self._provider_has_settings(Settings.get().active_tts) else: self.tts.props.visible = False # Providers Settings self.translator_config.connect("clicked", self._open_provider, "trans") self.tts_config.connect("clicked", self._open_provider, "tts") # Translator loading self.window.connect("notify::translator-loading", self._on_translator_loading) # Search Provider if os.getenv("XDG_CURRENT_DESKTOP") != "GNOME": self.search_provider.props.visible = False # Connect font size signals self.custom_default_font_size.connect("notify::enable-expansion", self._custom_default_font_size_switch) self.default_font_size.get_adjustment().connect("value-changed", self._change_default_font_size) @Gtk.Template.Callback() def is_not_true(self, _widget, boolean): """Check if boolean is not true template binding closure function """ return not boolean def _open_provider(self, _button, scope): if self.window.provider[scope] is not None: page = ProviderPreferences(scope, self, self.window) self.push_subpage(page) def _provider_has_settings(self, name): if not name: return False if ProviderFeature.INSTANCES in MODULES[name].features or ProviderFeature.API_KEY in MODULES[name].features: return True return False @Gtk.Template.Callback() def _switch_translator(self, row, _value): """Called on self.translator::notify::selected signal""" provider = self.translator.get_selected_item().name self.translator_config.props.sensitive = self._provider_has_settings(provider) if provider != Settings.get().active_translator: Settings.get().active_translator = provider @Gtk.Template.Callback() def _switch_tts(self, row, _value): """Called on self.tts::notify::selected signal""" provider = self.tts.get_selected_item().name self.tts_config.props.sensitive = self._provider_has_settings(provider) if provider != Settings.get().active_tts: Settings.get().active_tts = provider @Gtk.Template.Callback() def _provider_settings_tooltip(self, button, _pspec): if button.props.sensitive: button.props.tooltip_text = _("Edit Provider Settings") else: button.props.tooltip_text = _("No Settings for This Provider") def _on_translator_loading(self, window, _value): self.translator.props.sensitive = not window.translator_loading self.tts.props.sensitive = not window.translator_loading def _custom_default_font_size_switch(self, row, _value): """Called on self.custom_default_font_size::notify::enable-expansion signal""" enabled = row.get_enable_expansion() system_font_size = Settings.get().system_font_size if enabled: if Settings.get().default_font_size == 0: # User has never set custom size before Settings.default_font_size = system_font_size self.default_font_size.set_value(system_font_size) self.window.set_font_size(system_font_size) else: self.window.set_font_size(Settings.get().default_font_size) else: self.window.set_font_size(system_font_size) self.custom_default_font_size.set_enable_expansion(False) def _change_default_font_size(self, row): """Called on self.default_font_size.get_adjustment()::value-changed signal""" Settings.default_font_size = row.get_value() self.window.set_font_size(row.get_value()) dialect-2.4.2/dialect/providers/000077500000000000000000000000001465154363000165555ustar00rootroot00000000000000dialect-2.4.2/dialect/providers/__init__.py000066400000000000000000000054041465154363000206710ustar00rootroot00000000000000# Copyright 2021-2022 Mufeed Ali # Copyright 2021-2022 Rafael Mardojai CM # SPDX-License-Identifier: GPL-3.0-or-later import importlib import logging import pkgutil from gi.repository import Gio, GObject from dialect.providers import modules from dialect.providers.base import ( # noqa ProviderCapability, ProviderError, ProviderErrorCode, ProviderFeature, ) MODULES = {} TRANSLATORS = {} TTS = {} for _importer, modname, _ispkg in pkgutil.iter_modules(modules.__path__): try: modclass = importlib.import_module("dialect.providers.modules." + modname).Provider MODULES[modclass.name] = modclass if modclass.capabilities: if ProviderCapability.TRANSLATION in modclass.capabilities: TRANSLATORS[modclass.name] = modclass if ProviderCapability.TTS in modclass.capabilities: TTS[modclass.name] = modclass except Exception as exc: logging.warning(f"Could not load the {modname} provider: {exc}") def check_translator_availability(provider_name): if provider_name in TRANSLATORS: return True return False def get_fallback_translator_name(): if TRANSLATORS: return next(iter(TRANSLATORS)) return None class ProviderObject(GObject.Object): __gtype_name__ = "ProviderObject" def __init__(self, p_class=None): super().__init__() self.p_class = p_class @GObject.Property(type=str) def name(self): if self.p_class is not None: return self.p_class.name else: return "" @GObject.Property(type=str) def prettyname(self): if self.p_class is not None: return self.p_class.prettyname else: return _("Disabled") class ProvidersListModel(GObject.GObject, Gio.ListModel): __gtype_name__ = "ProvidersListModel" def __init__(self, p_type="", show_disabled=False): super().__init__() if p_type: # If we want to get an specific provider type types = {"translators": TRANSLATORS, "tts": TTS} providers = types.get(p_type) else: # Get all providers providers = MODULES providers = list(providers.values()) self.providers = [] for provider in providers: self.providers.append(ProviderObject(provider)) if show_disabled and self.providers: self.providers.insert(0, ProviderObject()) def do_get_item(self, position): return self.providers[position] def do_get_item_type(self): return ProviderObject def do_get_n_items(self): return len(self.providers) def get_index_by_name(self, name): for i, prov in enumerate(self.providers): if prov.name == name: return i dialect-2.4.2/dialect/providers/base.py000066400000000000000000000354471465154363000200560ustar00rootroot00000000000000# Copyright 2021-2022 Mufeed Ali # Copyright 2021-2022 Rafael Mardojai CM # SPDX-License-Identifier: GPL-3.0-or-later import io import urllib.parse from dataclasses import dataclass from enum import Enum, Flag, auto from typing import Callable, Optional from dialect.define import LANG_ALIASES from dialect.languages import get_lang_name from dialect.providers.settings import ProviderSettings class ProviderCapability(Flag): TRANSLATION = auto() """ If it provides translation """ TTS = auto() """ If it provides text-to-speech """ DEFINITIONS = auto() """ If it provides dictionary definitions """ class ProviderFeature(Flag): NONE = auto() """ Provider has no features """ INSTANCES = auto() """ If it supports changing the instance url """ API_KEY = auto() """ If the api key is supported but not necessary """ API_KEY_REQUIRED = auto() """ If the api key is required for the provider to work """ API_KEY_USAGE = auto() """ If the service reports api usage """ DETECTION = auto() """ If it supports detecting text language (Auto translation) """ MISTAKES = auto() """ If it supports showing translation mistakes """ PRONUNCIATION = auto() """ If it supports showing translation pronunciation """ SUGGESTIONS = auto() """ If it supports sending translation suggestions to the service """ class ProvideLangModel(Enum): STATIC = auto() """ The provider populate its `src_languages` and `dest_languages` properties. The `cmp_langs` method will be used to decide if one code can be translated to another. """ DYNAMIC = auto() """ The provider only populate its `src_languages` property. The `dest_langs_for` method will be used to get possible destination codes for a code. """ class ProviderErrorCode(Enum): UNEXPECTED = auto() NETWORK = auto() EMPTY = auto() API_KEY_REQUIRED = auto() API_KEY_INVALID = auto() INVALID_LANG_CODE = auto() BATCH_SIZE_EXCEEDED = auto() CHARACTERS_LIMIT_EXCEEDED = auto() SERVICE_LIMIT_REACHED = auto() TRANSLATION_FAILED = auto() TTS_FAILED = auto() class ProviderError: """Helper error handing class to be passed between callbacks""" def __init__(self, code: ProviderErrorCode, message: str = "") -> None: self.code = code # Serves for quick error matching self.message = message # More detailed error info if needed @dataclass class Translation: text: str original: tuple[str, str, str] detected: Optional[str] = None mistakes: tuple[Optional[str], Optional[str]] = (None, None) # pronunciation: tuple[Optional[str], Optional[str]] = (None, None) class BaseProvider: name = "" """ Module name for code use, like settings storing """ prettyname = "" """ Module name for UI display """ capabilities: ProviderCapability | None = None """ Provider capabilities, translation, tts, etc """ features: ProviderFeature = ProviderFeature.NONE """ Provider features """ lang_model: ProvideLangModel = ProvideLangModel.STATIC """ Translation language model """ defaults = { "instance_url": "", "api_key": "", "src_langs": ["en", "fr", "es", "de"], "dest_langs": ["fr", "es", "de", "en"], } """ Default provider settings """ def __init__(self): self.src_languages = [] """ Source languages available for translating """ self.dest_languages = [] """ Destination languages available for translating """ self.tts_languages = [] """ Languages available for TTS """ self._nonstandard_langs = {} """ Mapping of lang codes that differ with Dialect ones """ self._languages_names = {} """ Names of languages provided by the service """ self.chars_limit = -1 """ Translation char limit """ self.history: list[Translation] = [] """ Here we save the translation history """ # GSettings self.settings = ProviderSettings(self.name, self.defaults) """ Providers API methods """ def validate_instance(self, url: str, on_done: Callable[[bool], None], on_fail: Callable[[ProviderError], None]): """ Validate an instance of the provider. Args: url: The instance URL to test, only hostname and tld, e.g. libretranslate.com, localhost on_done: Called when the validation is done, argument is the result of the validation on_fail: Called when there's a fail in the validation process """ raise NotImplementedError() def validate_api_key(self, key: str, on_done: Callable[[bool], None], on_fail: Callable[[ProviderError], None]): """ Validate an API key. Args: key: The API key to validate on_done: Called when the validation is done, argument is the result of the validation on_fail: Called when there's a fail in the validation process """ raise NotImplementedError() def init_trans(self, on_done: Callable, on_fail: Callable[[ProviderError], None]): """ Initializes the provider translation capabilities. Args: on_done: Called after the provider was successfully initialized on_fail: Called after any error on initialization """ on_done() def init_tts(self, on_done: Callable, on_fail: Callable[[ProviderError], None]): """ Initializes the provider text-to-speech capabilities. Args: on_done: Called after the provider was successfully initialized on_fail: Called after any error on initialization """ on_done() def translate( self, text: str, src: str, dest: str, on_done: Callable[[Translation], None], on_fail: Callable[[ProviderError], None], ): """ Translates text in the provider. Args: text: The text to translate src: The lang code of the source text dest: The lang code to translate the text to on_done: Called after the text was successfully translated on_fail: Called after any error on translation """ raise NotImplementedError() def suggest( self, text: str, src: str, dest: str, suggestion: str, on_done: Callable[[bool], None], on_fail: Callable[[ProviderError], None], ): """ Sends a translation suggestion to the provider. Args: text: Original text without translation src: The lang code of the original text dest: The lang code of the translated text suggestion: Suggested translation for text on_done: Called after the suggestion was successfully send, argument means if it was accepted or rejected on_fail: Called after any error on the suggestion process """ raise NotImplementedError() def speech( self, text: str, language: str, on_done: Callable[[io.BytesIO], None], on_fail: Callable[[ProviderError], None], ): """ Generate speech audio from text Args: text: Text to generate speech from language: The lang code of text on_done: Called after the process successful on_fail: Called after any error on the speech process """ raise NotImplementedError() def api_char_usage( self, on_done: Callable[[int, int], None], on_fail: Callable[[ProviderError], None], ): """ Retrieves the API usage status Args: on_done: Called after the process successful, with the usage and limit as args on_fail: Called after any error on the speech process """ raise NotImplementedError() def cmp_langs(self, a: str, b: str) -> bool: """ Compare two language codes. It assumes that the codes have been normalized by `normalize_lang_code`. This method exists so providers can add additional comparison logic. Args: a: First lang to compare b: Second lang to compare """ return a == b def dest_langs_for(self, code: str) -> list[str]: """ Get the available destination languages for a source language. """ raise NotImplementedError() @property def lang_aliases(self) -> dict[str, str]: """ Mapping of Dialect/CLDR's lang codes to the provider ones. Some providers might use different lang codes from the ones used by Dialect to for example get localized language names. This dict is used by `add_lang` so lang codes can later be denormalized with `denormalize_lang`. Codes must be formatted with the criteria from normalize_lang_code, because this value would be used by `add_lang` after normalization. Check `dialect.define.LANG_ALIASES` for reference mappings. """ return {} """ Provider settings helpers and properties """ @property def instance_url(self): """Instance url saved on settings.""" return self.settings.instance_url @instance_url.setter def instance_url(self, url): self.settings.instance_url = url def reset_instance_url(self): """Resets saved instance url.""" self.instance_url = "" @property def api_key(self): """API key saved on settings.""" return self.settings.api_key @api_key.setter def api_key(self, api_key): self.settings.api_key = api_key def reset_api_key(self): """Resets saved API key.""" self.api_key = "" @property def recent_src_langs(self): """Saved recent source langs of the user.""" return self.settings.src_langs @recent_src_langs.setter def recent_src_langs(self, src_langs): self.settings.src_langs = src_langs def reset_src_langs(self): """Reset saved recent user source langs""" self.recent_src_langs = [] @property def recent_dest_langs(self): """Saved recent destination langs of the user.""" return self.settings.dest_langs @recent_dest_langs.setter def recent_dest_langs(self, dest_langs): self.settings.dest_langs = dest_langs def reset_dest_langs(self): """Reset saved recent user destination langs""" self.recent_dest_langs = [] """ General provider helpers """ @staticmethod def format_url(url: str, path: str = "", params: dict = {}, http: bool = False): """ Compose a HTTP url with the given pieces. If url is localhost, `http` is ignored and HTTP protocol is forced. Args: url: Base url, hostname and tld path: Path of the url params: Params to populate a url query http: If HTTP should be used instead of HTTPS """ if not path.startswith("/"): path = "/" + path protocol = "https://" if url.startswith("localhost:") or http: protocol = "http://" params_str = urllib.parse.urlencode(params) if params_str: params_str = "?" + params_str return protocol + url + path + params_str def normalize_lang_code(self, code: str): """ Normalice a language code to Dialect's criteria. Criteria: - Codes must be lowercase, e.g. ES => es - Codes can have a second code delimited by a hyphen, e.g. zh_CN => zh-CN - If second code is two chars long it's considered a country code and must be uppercase, e.g. zh-cn => zh-CN - If second code is four chars long it's considered a script code and must be capitalized, e.g. zh-HANS => zh-Hans This method also maps lang codes aliases using `lang_aliases` and `dialect.define.LANG_ALIASES`. Args: code: Language ISO code """ code = code.replace("_", "-").lower() # Normalize separator codes = code.split("-") if len(codes) == 2: # Code contain a script or country code if len(codes[1]) == 4: # ISO 15924 (script) codes[1] = codes[1].capitalize() elif len(codes[1]) == 2: # ISO 3166-1 (country) codes[1] = codes[1].upper() code = "-".join(codes) aliases = {**LANG_ALIASES, **self.lang_aliases} if code in aliases: code = aliases[code] return code def add_lang( self, original_code: str, name: str = None, trans_src: bool = True, trans_dest: bool = True, tts: bool = False, ): """ Add lang supported by provider after normalization. Normalized lang codes are saved for latter denormalization using `denormalize_lang`. Args: original_code: Lang code to add name: Language name to fallback in case Dialect doesn't provide one trans: Add language as supported for translation tts: Add language as supported for text-to-speech """ code = self.normalize_lang_code(original_code) # Get normalized lang code if trans_src: # Add lang to supported languages list self.src_languages.append(code) if trans_dest: self.dest_languages.append(code) if tts: # Add lang to supported TTS languages list self.tts_languages.append(code) if code != original_code and code not in self._nonstandard_langs: # Save a divergent lang code for later denormalization self._nonstandard_langs[code] = original_code if name is not None and code not in self._languages_names: # Save name provider by the service self._languages_names[code] = name def denormalize_lang(self, *codes: str) -> str | tuple[str]: """ Get denormalized lang code if available. This method will return a tuple with the same length of given codes or a str if only one code was passed. Args: *codes: Lang codes to denormalize """ if len(codes) == 1: return self._nonstandard_langs.get(codes[0], codes[0]) result = [] for code in codes: result.append(self._nonstandard_langs.get(code, code)) return tuple(result) def get_lang_name(self, code: str) -> str: """ Get a localized language name. Fallback to a name provided by the provider if available or ultimately just the code. """ name = get_lang_name(code) # Try getting translated name from Dialect if name is None: # Get name from provider if available return self._languages_names.get(code, code) return name dialect-2.4.2/dialect/providers/local.py000066400000000000000000000011511465154363000202170ustar00rootroot00000000000000# Copyright 2023 Mufeed Ali # Copyright 2023 Rafael Mardojai CM # SPDX-License-Identifier: GPL-3.0-or-later import threading from typing import Callable from dialect.providers.base import BaseProvider class LocalProvider(BaseProvider): """Base class for providers needing local threaded helpers""" def launch_thread(self, worker: Callable, *args): """ Launches a thread using Python's threading. Args: worker: Function to execute on the thread *args: Args for the worker """ threading.Thread(target=worker, args=args, daemon=True).start() dialect-2.4.2/dialect/providers/modules/000077500000000000000000000000001465154363000202255ustar00rootroot00000000000000dialect-2.4.2/dialect/providers/modules/bing.py000066400000000000000000000120661465154363000215230ustar00rootroot00000000000000# Copyright 2023 Rafael Mardojai CM # SPDX-License-Identifier: GPL-3.0-or-later import logging import re from bs4 import BeautifulSoup from dialect.providers.base import ( ProviderCapability, ProviderFeature, ProviderError, ProviderErrorCode, Translation, ) from dialect.providers.soup import SoupProvider from dialect.session import Session class Provider(SoupProvider): name = "bing" prettyname = "Bing" capabilities = ProviderCapability.TRANSLATION features = ProviderFeature.DETECTION | ProviderFeature.PRONUNCIATION defaults = { "instance_url": "", "api_key": "", "src_langs": ["en", "fr", "es", "de"], "dest_langs": ["fr", "es", "de", "en"], } _headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)", "Accept": "*/*"} def __init__(self, **kwargs): super().__init__(**kwargs) self.chars_limit = 1000 # Web UI limit # Session vars self._key = "" self._token = "" self._ig = "" self._iid = "" self._count = 1 @property def html_url(self): return self.format_url("www.bing.com", "/translator") @property def translate_url(self): params = { "isVertical": "1", "": "", "IG": self._ig, "IID": f"{self._iid}.{self._count}", } return self.format_url("www.bing.com", "/ttranslatev3", params) def init_trans(self, on_done, on_fail): def on_response(data): if data: try: soup = BeautifulSoup(data, "html.parser") # Get Langs langs = soup.find("optgroup", {"id": "t_tgtAllLang"}) for child in langs.findChildren(): if child.name == "option": self.add_lang(child["value"], child.contents[0]) # Get IID iid = soup.find("div", {"id": "rich_tta"}) self._iid = iid["data-iid"] # Decode response bytes data = data.decode("utf-8") # Look for abuse prevention data params = re.findall("var params_AbusePreventionHelper = \[(.*?)\];", data)[0] # noqa abuse_params = params.replace('"', "").split(",") self._key = abuse_params[0] self._token = abuse_params[1] # Look for IG self._ig = re.findall('IG:"(.*?)",', data)[0] on_done() except Exception as exc: error = "Failed parsing HTML from bing.com" logging.warning(error, exc) on_fail(ProviderError(ProviderErrorCode.NETWORK, error)) else: on_fail(ProviderError(ProviderErrorCode.EMPTY, "Could not get HTML from bing.com")) # Message request to get bing's website html message = self.create_message("GET", self.html_url, headers=self._headers) # Do async request self.send_and_read_and_process_response(message, on_response, on_fail, False, False) def translate(self, text, src, dest, on_done, on_fail): def on_response(data): try: data = data[0] detected = None pronunciation = None if "translations" in data: if "detectedLanguage" in data: detected = data["detectedLanguage"]["language"] if "transliteration" in data["translations"][0]: pronunciation = data["translations"][0]["transliteration"]["text"] translation = Translation( data["translations"][0]["text"], (text, src, dest), detected=detected, pronunciation=(None, pronunciation), ) on_done(translation) except Exception as exc: logging.warning(exc) on_fail(ProviderError(ProviderErrorCode.TRANSLATION_FAILED, str(exc))) # Increment requests count self._count += 1 # Form data data = { "fromLang": "auto-detect" if src == "auto" else src, "text": text, "to": dest, "token": self._token, "key": self._key, } # Request message message = self.create_message("POST", self.translate_url, data, self._headers, True) # Do async request self.send_and_read_and_process_response(message, on_response, on_fail) def check_known_errors(self, _status, data): if not data: return ProviderError(ProviderErrorCode.EMPTY, "Response is empty!") if "errorMessage" in data: error = data["errorMessage"] code = data["statusCode"] match code: case _: return ProviderError(ProviderErrorCode.UNEXPECTED, error) return None dialect-2.4.2/dialect/providers/modules/deepl.py000066400000000000000000000143441465154363000216760ustar00rootroot00000000000000# Copyright 2024 Mufeed Ali # Copyright 2024 Rafael Mardojai CM # SPDX-License-Identifier: GPL-3.0-or-later import logging from dialect.providers.base import ( ProviderCapability, ProviderFeature, ProviderErrorCode, ProviderError, Translation, ) from dialect.providers.soup import SoupProvider API_V = "v2" class Provider(SoupProvider): name = "deepl" prettyname = "DeepL" capabilities = ProviderCapability.TRANSLATION features = ( ProviderFeature.DETECTION | ProviderFeature.API_KEY | ProviderFeature.API_KEY_REQUIRED | ProviderFeature.API_KEY_USAGE ) defaults = { "instance_url": "", "api_key": "", "src_langs": ["en", "fr", "es", "de"], "dest_langs": ["fr", "es", "de", "en-US"], } _api_free = "api-free.deepl.com" _api_pro = "api.deepl.com" def __init__(self, **kwargs): super().__init__(**kwargs) self.chars_limit = 5000 # DeepL API Free keys can be identified by the suffix ":fx" self.api_url = self.__get_api_url(self.api_key) def __get_api_url(self, api_key: str) -> str: return self._api_free if api_key.endswith(":fx") else self._api_pro @property def source_lang_url(self): return self.format_url(self.api_url, f"/{API_V}/languages", {"type": "source"}) @property def target_lang_url(self): return self.format_url(self.api_url, f"/{API_V}/languages", {"type": "target"}) @property def translate_url(self): return self.format_url(self.api_url, f"/{API_V}/translate") @property def usage_url(self): return self.format_url(self.api_url, f"/{API_V}/usage") @property def headers(self): return {"Authorization": f"DeepL-Auth-Key {self.api_key}"} def init_trans(self, on_done, on_fail): def check_finished(): self._init_count -= 1 if self._init_count == 0: if self._init_error: on_fail(self._init_error) else: on_done() def on_failed(error): self._init_error = error check_finished() def on_languages_response(data, type_): try: trans_src = type_ == "src" trans_dest = type_ == "dest" for lang in data: self.add_lang(lang["language"], lang["name"], trans_src=trans_src, trans_dest=trans_dest) check_finished() except Exception as exc: print(type_) logging.warning(exc) on_failed(ProviderError(ProviderErrorCode.UNEXPECTED, str(exc))) # Keep state of multiple request self._init_count = 2 self._init_error = None # Request messages src_langs_message = self.create_message("GET", self.source_lang_url, headers=self.headers) dest_langs_message = self.create_message("GET", self.target_lang_url, headers=self.headers) # Do async requests self.send_and_read_and_process_response(src_langs_message, lambda d: on_languages_response(d, "src"), on_failed) self.send_and_read_and_process_response( dest_langs_message, lambda d: on_languages_response(d, "dest"), on_failed ) def validate_api_key(self, key, on_done, on_fail): def on_response(_data): on_done(True) api_url = self.__get_api_url(key) url = self.format_url(api_url, f"/{API_V}/languages", {"type": "source"}) # Headers headers = {"Authorization": f"DeepL-Auth-Key {key}"} # Request messages languages_message = self.create_message("GET", url, headers=headers) # Do async requests self.send_and_read_and_process_response(languages_message, on_response, on_fail) def translate(self, text, src, dest, on_done, on_fail): def on_response(data): try: translations = data.get("translations") detected = translations[0].get("detected_source_language") translation = Translation(translations[0]["text"], (text, src, dest), detected) on_done(translation) except Exception as exc: logging.warning(exc) on_fail(ProviderError(ProviderErrorCode.TRANSLATION_FAILED, str(exc))) # Request body data = { "text": [text], "target_lang": dest, } if src != "auto": data["source_lang"] = src # Request message message = self.create_message("POST", self.translate_url, data, self.headers) # Do async request self.send_and_read_and_process_response(message, on_response, on_fail) def api_char_usage(self, on_done, on_fail): def on_response(data): try: usage = data.get("character_count") limit = data.get("character_limit") on_done(usage, limit) except Exception as exc: logging.warning(exc) on_fail(ProviderError(ProviderErrorCode.UNEXPECTED, str(exc))) # Request message message = self.create_message("GET", self.usage_url, headers=self.headers) # Do async request self.send_and_read_and_process_response(message, on_response, on_fail) def cmp_langs(self, a, b): # Early return if both langs are just the same if a == b: return True # Split lang code to separate it from possible country/script code a_codes = a.split("-") b_codes = b.split("-") if a_codes[0] == b_codes[0]: # Check base codes return True return False def check_known_errors(self, status, data): message = data.get("message", "") if isinstance(data, dict) else "" match status: case 403: if not self.api_key: return ProviderError(ProviderErrorCode.API_KEY_REQUIRED, message) return ProviderError(ProviderErrorCode.API_KEY_INVALID, message) case 456: return ProviderError(ProviderErrorCode.SERVICE_LIMIT_REACHED, message) if status != 200: return ProviderError(ProviderErrorCode.UNEXPECTED, message) dialect-2.4.2/dialect/providers/modules/google.py000066400000000000000000000372041465154363000220610ustar00rootroot00000000000000# Copyright 2021 Mufeed Ali # Copyright 2021 Rafael Mardojai CM # SPDX-License-Identifier: GPL-3.0-or-later import html import json import logging import random import re from tempfile import NamedTemporaryFile from typing import List from gtts import gTTS, lang from dialect.providers.base import ( ProviderCapability, ProviderError, ProviderErrorCode, ProviderFeature, Translation, ) from dialect.providers.local import LocalProvider from dialect.providers.soup import SoupProvider RPC_ID = "MkEWBc" # Predefined URLs used to make google translate requests. TRANSLATE_RPC = "{host}/_/TranslateWebserverUi/data/batchexecute" DEFAULT_SERVICE_URLS = ( "translate.google.ac", "translate.google.ad", "translate.google.ae", "translate.google.al", "translate.google.am", "translate.google.as", "translate.google.at", "translate.google.az", "translate.google.ba", "translate.google.be", "translate.google.bf", "translate.google.bg", "translate.google.bi", "translate.google.bj", "translate.google.bs", "translate.google.bt", "translate.google.by", "translate.google.ca", "translate.google.cat", "translate.google.cc", "translate.google.cd", "translate.google.cf", "translate.google.cg", "translate.google.ch", "translate.google.ci", "translate.google.cl", "translate.google.cm", "translate.google.cn", "translate.google.co.ao", "translate.google.co.bw", "translate.google.co.ck", "translate.google.co.cr", "translate.google.co.id", "translate.google.co.il", "translate.google.co.in", "translate.google.co.jp", "translate.google.co.ke", "translate.google.co.kr", "translate.google.co.ls", "translate.google.co.ma", "translate.google.co.mz", "translate.google.co.nz", "translate.google.co.th", "translate.google.co.tz", "translate.google.co.ug", "translate.google.co.uk", "translate.google.co.uz", "translate.google.co.ve", "translate.google.co.vi", "translate.google.co.za", "translate.google.co.zm", "translate.google.co.zw", "translate.google.com.af", "translate.google.com.ag", "translate.google.com.ai", "translate.google.com.ar", "translate.google.com.au", "translate.google.com.bd", "translate.google.com.bh", "translate.google.com.bn", "translate.google.com.bo", "translate.google.com.br", "translate.google.com.bz", "translate.google.com.co", "translate.google.com.cu", "translate.google.com.cy", "translate.google.com.do", "translate.google.com.ec", "translate.google.com.eg", "translate.google.com.et", "translate.google.com.fj", "translate.google.com.gh", "translate.google.com.gi", "translate.google.com.gt", "translate.google.com.hk", "translate.google.com.jm", "translate.google.com.kh", "translate.google.com.kw", "translate.google.com.lb", "translate.google.com.ly", "translate.google.com.mm", "translate.google.com.mt", "translate.google.com.mx", "translate.google.com.my", "translate.google.com.na", "translate.google.com.ng", "translate.google.com.ni", "translate.google.com.np", "translate.google.com.om", "translate.google.com.pa", "translate.google.com.pe", "translate.google.com.pg", "translate.google.com.ph", "translate.google.com.pk", "translate.google.com.pr", "translate.google.com.py", "translate.google.com.qa", "translate.google.com.sa", "translate.google.com.sb", "translate.google.com.sg", "translate.google.com.sl", "translate.google.com.sv", "translate.google.com.tj", "translate.google.com.tr", "translate.google.com.tw", "translate.google.com.ua", "translate.google.com.uy", "translate.google.com.vc", "translate.google.com.vn", "translate.google.com", "translate.google.cv", "translate.google.cz", "translate.google.de", "translate.google.dj", "translate.google.dk", "translate.google.dm", "translate.google.dz", "translate.google.ee", "translate.google.es", "translate.google.fi", "translate.google.fm", "translate.google.fr", "translate.google.ga", "translate.google.ge", "translate.google.gg", "translate.google.gl", "translate.google.gm", "translate.google.gp", "translate.google.gr", "translate.google.gy", "translate.google.hn", "translate.google.hr", "translate.google.ht", "translate.google.hu", "translate.google.ie", "translate.google.im", "translate.google.iq", "translate.google.is", "translate.google.it", "translate.google.je", "translate.google.jo", "translate.google.kg", "translate.google.ki", "translate.google.kz", "translate.google.la", "translate.google.li", "translate.google.lk", "translate.google.lt", "translate.google.lu", "translate.google.lv", "translate.google.md", "translate.google.me", "translate.google.mg", "translate.google.mk", "translate.google.ml", "translate.google.mn", "translate.google.ms", "translate.google.mu", "translate.google.mv", "translate.google.mw", "translate.google.ne", "translate.google.nl", "translate.google.no", "translate.google.nr", "translate.google.nu", "translate.google.pl", "translate.google.pn", "translate.google.ps", "translate.google.pt", "translate.google.ro", "translate.google.rs", "translate.google.ru", "translate.google.rw", "translate.google.sc", "translate.google.se", "translate.google.sh", "translate.google.si", "translate.google.sk", "translate.google.sm", "translate.google.sn", "translate.google.so", "translate.google.sr", "translate.google.st", "translate.google.td", "translate.google.tg", "translate.google.tk", "translate.google.tl", "translate.google.tm", "translate.google.tn", "translate.google.to", "translate.google.tt", "translate.google.us", "translate.google.vg", "translate.google.vu", "translate.google.ws", ) class Provider(LocalProvider, SoupProvider): name = "google" prettyname = "Google" capabilities = ProviderCapability.TRANSLATION | ProviderCapability.TTS features = ProviderFeature.DETECTION | ProviderFeature.MISTAKES | ProviderFeature.PRONUNCIATION defaults = { "instance_url": "", "api_key": "", "src_langs": ["en", "fr", "es", "de"], "dest_langs": ["fr", "es", "de", "en"], } _service_urls = DEFAULT_SERVICE_URLS _headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)", "Referer": "https://translate.google.com", } def __init__(self, **kwargs): super().__init__(**kwargs) self.chars_limit = 2000 def init_trans(self, on_done, on_fail): languages = [ "af", "sq", "am", "ar", "hy", "az", "eu", "be", "bn", "bs", "bg", "ca", "ceb", "ny", "zh-CN", "zh-TW", "co", "hr", "cs", "da", "nl", "en", "eo", "et", "tl", "fi", "fr", "fy", "gl", "ka", "de", "el", "gu", "ht", "ha", "haw", "iw", "hi", "hmn", "hu", "is", "ig", "id", "ga", "it", "ja", "jw", "kn", "kk", "km", "rw", "ko", "ku", "ky", "lo", "la", "lv", "lt", "lb", "mk", "mg", "ms", "ml", "mt", "mi", "mr", "mn", "my", "ne", "no", "or", "ps", "fa", "pl", "pt", "pa", "ro", "ru", "sm", "gd", "sr", "st", "sn", "sd", "si", "sk", "sl", "so", "es", "su", "sw", "sv", "tg", "ta", "tt", "te", "th", "tr", "tk", "uk", "ur", "ug", "uz", "vi", "cy", "xh", "yi", "yo", "zu", ] for code in languages: self.add_lang(code) on_done() def init_tts(self, on_done, on_fail): for code in lang.tts_langs().keys(): self.add_lang(code, trans_src=False, trans_dest=False, tts=True) on_done() @staticmethod def _build_rpc_request(text: str, src: str, dest: str): return json.dumps( [ [ [ RPC_ID, json.dumps([[text, src, dest, True], [None]], separators=(",", ":")), None, "generic", ], ] ], separators=(",", ":"), ) def _pick_service_url(self): if len(self._service_urls) == 1: return self._service_urls[0] return random.choice(self._service_urls) @property def translate_url(self): url = TRANSLATE_RPC.format(host=self._pick_service_url()) + "?" params = { "rpcids": RPC_ID, "bl": "boq_translate-webserver_20201207.13_p0", "soc-app": "1", "soc-platform": "1", "soc-device": "1", "rt": "c", } return self.format_url(url, params=params) def translate(self, text, src_lang, dest_lang, on_done, on_fail): def on_response(data): try: token_found = False square_bracket_counts = [0, 0] resp = "" data = data.decode("utf-8") for line in data.split("\n"): token_found = token_found or f'"{RPC_ID}"' in line[:30] if not token_found: continue is_in_string = False for index, char in enumerate(line): if char == '"' and line[max(0, index - 1)] != "\\": is_in_string = not is_in_string if not is_in_string: if char == "[": square_bracket_counts[0] += 1 elif char == "]": square_bracket_counts[1] += 1 resp += line if square_bracket_counts[0] == square_bracket_counts[1]: break data = json.loads(resp) parsed = json.loads(data[0][2]) translated_parts = None translated = None try: translated_parts = list( map( lambda part: TranslatedPart( part[0] if len(part) > 0 else "", part[1] if len(part) >= 2 else [] ), parsed[1][0][0][5], ) ) except TypeError: translated_parts = [TranslatedPart(parsed[1][0][1][0], [parsed[1][0][0][0], parsed[1][0][1][0]])] first_iter = True translated = "" for part in translated_parts: if not part.text.isspace() and not first_iter: translated += " " if first_iter: first_iter = False translated += part.text src = None try: src = parsed[1][-1][1] except (IndexError, TypeError): pass if not src == src_lang: on_fail(ProviderError(ProviderErrorCode.TRANSLATION_FAILED, "source language mismatch")) return if src == "auto": try: if parsed[0][2] in self.src_languages: src = parsed[0][2] except (IndexError, TypeError): pass dest = None try: dest = parsed[1][-1][2] except (IndexError, TypeError): pass if not dest == dest_lang: on_fail(ProviderError(ProviderErrorCode.TRANSLATION_FAILED, "destination language mismatch")) return origin_pronunciation = None try: origin_pronunciation = parsed[0][0] except (IndexError, TypeError): pass pronunciation = None try: pronunciation = parsed[1][0][0][1] except (IndexError, TypeError): pass mistake = None try: mistake = parsed[0][1][0][0][1] # Convert to pango markup mistake = mistake.replace("", "").replace("", "") except (IndexError, TypeError): pass result = Translation( translated, (text, src, dest), src, (mistake, self._strip_html_tags(mistake)), (origin_pronunciation, pronunciation), ) on_done(result) except Exception as exc: logging.warning(exc) on_fail(ProviderError(ProviderErrorCode.TRANSLATION_FAILED, str(exc))) # Form data data = { "f.req": self._build_rpc_request(text, src_lang, dest_lang), } # Request message message = self.create_message("POST", self.translate_url, data, self._headers, True) # Do async request self.send_and_read_and_process_response(message, on_response, on_fail, False, False) def _strip_html_tags(self, text): """Strip html tags""" if text is None: return None tags_re = re.compile(r"(|<[^>]*>)") tags_removed = tags_re.sub("", text) escaped = html.escape(tags_removed) return escaped def speech(self, text, language, on_done, on_fail): def work(): try: file = NamedTemporaryFile() tts = gTTS(text, lang=language, lang_check=False) tts.write_to_fp(file) file.seek(0) on_done(file) except Exception as exc: logging.warning(exc) on_fail(ProviderError(ProviderErrorCode.TTS_FAILED, str(exc))) self.launch_thread(work) class TranslatedPart: def __init__(self, text: str, candidates: List[str]): self.text = text self.candidates = candidates def __str__(self): return self.text def __dict__(self): return { "text": self.text, "candidates": self.candidates, } dialect-2.4.2/dialect/providers/modules/libretrans.py000066400000000000000000000154011465154363000227450ustar00rootroot00000000000000# Copyright 2021-2022 Mufeed Ali # Copyright 2021-2022 Rafael Mardojai CM # SPDX-License-Identifier: GPL-3.0-or-later import logging from dialect.providers.base import ( ProviderCapability, ProviderFeature, ProviderErrorCode, ProviderError, Translation, ) from dialect.providers.soup import SoupProvider class Provider(SoupProvider): name = "libretranslate" prettyname = "LibreTranslate" capabilities = ProviderCapability.TRANSLATION features = ProviderFeature.INSTANCES | ProviderFeature.DETECTION | ProviderFeature.PRONUNCIATION defaults = { "instance_url": "lt.dialectapp.org", "api_key": "", "src_langs": ["en", "fr", "es", "de"], "dest_langs": ["fr", "es", "de", "en"], } def __init__(self, **kwargs): super().__init__(**kwargs) self.chars_limit = 0 def validate_instance(self, url, on_done, on_fail): def on_response(data): valid = False try: valid = data["info"]["title"] == "LibreTranslate" except: # noqa pass on_done(valid) # Message request to LT API spec endpoint message = self.create_message("GET", self.format_url(url, "/spec")) # Do async request self.send_and_read_and_process_response(message, on_response, on_fail, False) @property def frontend_settings_url(self): return self.format_url(self.instance_url, "/frontend/settings") @property def detect_url(self): return self.format_url(self.instance_url, "/detect") @property def lang_url(self): return self.format_url(self.instance_url, "/languages") @property def suggest_url(self): return self.format_url(self.instance_url, "/suggest") @property def translate_url(self): return self.format_url(self.instance_url, "/translate") def init_trans(self, on_done, on_fail): def check_finished(): self._init_count -= 1 if self._init_count == 0: if self._init_error: on_fail(self._init_error) else: on_done() def on_failed(error): self._init_error = error check_finished() def on_languages_response(data): try: for lang in data: self.add_lang(lang["code"], lang["name"]) check_finished() except Exception as exc: logging.warning(exc) on_failed(ProviderError(ProviderErrorCode.UNEXPECTED, str(exc))) def on_settings_response(data): try: if data.get("suggestions", False): self.features ^= ProviderFeature.SUGGESTIONS if data.get("apiKeys", False): self.features ^= ProviderFeature.API_KEY if data.get("keyRequired", False): self.features ^= ProviderFeature.API_KEY_REQUIRED self.chars_limit = data.get("charLimit", 0) check_finished() except Exception as exc: logging.warning(exc) on_failed(ProviderError(ProviderErrorCode.UNEXPECTED, str(exc))) # Keep state of multiple request self._init_count = 2 self._init_error = None # Request messages languages_message = self.create_message("GET", self.lang_url) settings_message = self.create_message("GET", self.frontend_settings_url) # Do async requests self.send_and_read_and_process_response(languages_message, on_languages_response, on_failed) self.send_and_read_and_process_response(settings_message, on_settings_response, on_failed) def validate_api_key(self, key, on_done, on_fail): def on_response(data): valid = False try: valid = "confidence" in data[0] except: # noqa pass on_done(valid) # Form data data = { "q": "hello", "api_key": key, } # Request message message = self.create_message("POST", self.detect_url, data, form=True) # Do async request self.send_and_read_and_process_response(message, on_response, on_fail) def translate(self, text, src, dest, on_done, on_fail): def on_response(data): detected = data.get("detectedLanguage", {}).get("language", None) translation = Translation(data["translatedText"], (text, src, dest), detected) on_done(translation) # Request body data = { "q": text, "source": src, "target": dest, } if self.api_key and ProviderFeature.API_KEY in self.features: data["api_key"] = self.api_key # Request message message = self.create_message("POST", self.translate_url, data) # Do async request self.send_and_read_and_process_response(message, on_response, on_fail) def suggest(self, text, src, dest, suggestion, on_done, on_fail): def on_response(data): on_done(data.get("success", False)) # Form data data = { "q": text, "source": src, "target": dest, "s": suggestion, } if self.api_key and ProviderFeature.API_KEY in self.features: data["api_key"] = self.api_key # Request message message = self.create_message("POST", self.suggest_url, data, form=True) # Do async request self.send_and_read_and_process_response(message, on_response, on_fail) def check_known_errors(self, _status, data): if not data: return ProviderError(ProviderErrorCode.EMPTY, "Response is empty!") if "error" in data: error = data["error"] if error == "Please contact the server operator to obtain an API key": return ProviderError(ProviderErrorCode.API_KEY_REQUIRED, error) elif error == "Invalid API key": return ProviderError(ProviderErrorCode.API_KEY_INVALID, error) elif "is not supported" in error: return ProviderError(ProviderErrorCode.INVALID_LANG_CODE, error) elif "exceeds text limit" in error: return ProviderError(ProviderErrorCode.BATCH_SIZE_EXCEEDED, error) elif "exceeds character limit" in error: return ProviderError(ProviderErrorCode.CHARACTERS_LIMIT_EXCEEDED, error) elif "Cannot translate text" in error or "format is not supported" in error: return ProviderError(ProviderErrorCode.TRANSLATION_FAILED, error) else: return ProviderError(ProviderErrorCode.UNEXPECTED, error) dialect-2.4.2/dialect/providers/modules/lingva.py000066400000000000000000000121141465154363000220560ustar00rootroot00000000000000# Copyright 2021 Mufeed Ali # Copyright 2021 Rafael Mardojai CM # SPDX-License-Identifier: GPL-3.0-or-later import logging from tempfile import NamedTemporaryFile from urllib.parse import quote from dialect.providers.base import ( ProviderCapability, ProviderError, ProviderErrorCode, ProviderFeature, Translation, ) from dialect.providers.soup import SoupProvider class Provider(SoupProvider): name = "lingva" prettyname = "Lingva Translate" capabilities = ProviderCapability.TRANSLATION | ProviderCapability.TTS features = ( ProviderFeature.INSTANCES | ProviderFeature.DETECTION | ProviderFeature.MISTAKES | ProviderFeature.PRONUNCIATION ) defaults = { "instance_url": "lingva.dialectapp.org", "api_key": "", "src_langs": ["en", "fr", "es", "de"], "dest_langs": ["fr", "es", "de", "en"], } def __init__(self, **kwargs): super().__init__(**kwargs) self.chars_limit = 5000 def validate_instance(self, url, on_done, on_fail): def on_response(data): valid = False try: valid = "translation" in data except: # noqa pass on_done(valid) # Lingva translation endpoint message = self.create_message("GET", self.format_url(url, "/api/v1/en/es/hello")) # Do async request self.send_and_read_and_process_response(message, on_response, on_fail, False) @property def lang_url(self): return self.format_url(self.instance_url, "/api/v1/languages/") @property def translate_url(self): return self.format_url(self.instance_url, "/api/v1/{src}/{dest}/{text}") @property def speech_url(self): return self.format_url(self.instance_url, "/api/v1/audio/{lang}/{text}") def init(self, on_done, on_fail): def on_response(data): if "languages" in data: for lang in data["languages"]: if lang["code"] != "auto": self.add_lang(lang["code"], lang["name"], tts=True) on_done() else: on_fail(ProviderError(ProviderErrorCode.UNEXPECTED, "No langs found in server.")) # Languages message request message = self.create_message("GET", self.lang_url) # Do async request self.send_and_read_and_process_response(message, on_response, on_fail) def init_trans(self, on_done, on_fail): self.init(on_done, on_fail) def init_tts(self, on_done, on_fail): self.init(on_done, on_fail) def translate(self, text, src, dest, on_done, on_fail): def on_response(data): try: detected = data.get("info", {}).get("detectedSource", None) mistakes = data.get("info", {}).get("typo", None) src_pronunciation = data.get("info", {}).get("pronunciation", {}).get("query", None) dest_pronunciation = data.get("info", {}).get("pronunciation", {}).get("translation", None) translation = Translation( data["translation"], (text, src, dest), detected, (mistakes, mistakes), (src_pronunciation, dest_pronunciation), ) on_done(translation) except Exception as exc: error = "Failed reading the translation data" logging.warning(error, exc) on_fail(ProviderError(ProviderErrorCode.TRANSLATION_FAILED, error)) # Format url query data text = quote(text, safe="") url = self.translate_url.format(text=text, src=src, dest=dest) # Request message message = self.create_message("GET", url) # Do async request self.send_and_read_and_process_response(message, on_response, on_fail) def speech(self, text, language, on_done, on_fail): def on_response(data): if "audio" in data: file = NamedTemporaryFile() audio = bytearray(data["audio"]) file.write(audio) file.seek(0) on_done(file) else: on_fail(ProviderError(ProviderErrorCode.TTS_FAILED, "No audio was found.")) # Format url query data url = self.speech_url.format(text=text, lang=language) # Request message message = self.create_message("GET", url) # Do async request self.send_and_read_and_process_response(message, on_response, on_fail) def check_known_errors(self, _status, data): """Raises a proper Exception if an error is found in the data.""" if not data: return ProviderError(ProviderErrorCode.EMPTY, "Response is empty!") if "error" in data: error = data["error"] if error == "Invalid target language" or error == "Invalid source language": return ProviderError(ProviderErrorCode.INVALID_LANG_CODE, error) else: return ProviderError(ProviderErrorCode.UNEXPECTED, error) dialect-2.4.2/dialect/providers/modules/yandex.py000066400000000000000000000101051465154363000220640ustar00rootroot00000000000000# Copyright 2023 Rafael Mardojai CM # SPDX-License-Identifier: GPL-3.0-or-later from uuid import uuid4 from dialect.providers.base import ( ProviderCapability, ProviderError, ProviderErrorCode, ProviderFeature, Translation, ) from dialect.providers.soup import SoupProvider class Provider(SoupProvider): name = "yandex" prettyname = "Yandex" capabilities = ProviderCapability.TRANSLATION features = ProviderFeature.DETECTION defaults = { "instance_url": "", "api_key": "", "src_langs": ["en", "fr", "es", "de"], "dest_langs": ["fr", "es", "de", "en"], } _headers = { "User-Agent": "ru.yandex.translate/21.15.4.21402814 (Xiaomi Redmi K20 Pro; Android 11)", } def __init__(self, **kwargs): super().__init__(**kwargs) self.chars_limit = 10000 self._uuid = str(uuid4()).replace("-", "") def init_trans(self, on_done, on_fail): languages = [ "af", "sq", "am", "ar", "hy", "az", "ba", "eu", "be", "bn", "bs", "bg", "my", "ca", "ceb", "zh", "cv", "hr", "cs", "da", "nl", "sjn", "emj", "en", "eo", "et", "fi", "fr", "gl", "ka", "de", "el", "gu", "ht", "he", "mrj", "hi", "hu", "is", "id", "ga", "it", "ja", "jv", "kn", "kk", "kazlat", "km", "ko", "ky", "lo", "la", "lv", "lt", "lb", "mk", "mg", "ms", "ml", "mt", "mi", "mr", "mhr", "mn", "ne", "no", "pap", "fa", "pl", "pt", "pa", "ro", "ru", "gd", "sr", "si", "sk", "sl", "es", "su", "sw", "sv", "tl", "tg", "ta", "tt", "te", "th", "tr", "udm", "uk", "ur", "uz", "uzbcyr", "vi", "cy", "xh", "sah", "yi", "zu", ] for code in languages: self.add_lang(code) on_done() @property def translate_url(self): path = f"/api/v1/tr.json/translate?id={self._uuid}-0-0&srv=android" return self.format_url("translate.yandex.net", path) def translate(self, text, src, dest, on_done, on_fail): def on_response(data): detected = None if "code" in data and data["code"] == 200: if "lang" in data: detected = data["lang"].split("-")[0] if "text" in data: translation = Translation(data["text"][0], (text, src, dest), detected) on_done(translation) else: on_fail(ProviderError(ProviderErrorCode.TRANSLATION_FAILED, "Translation failed")) else: error = data["message"] if "message" in data else "" on_fail(ProviderError(ProviderErrorCode.TRANSLATION_FAILED, error)) # Form data data = {"lang": dest, "text": text} if src != "auto": data["lang"] = f"{src}-{dest}" # Request message message = self.create_message("POST", self.translate_url, data, self._headers, True) # Do async request self.send_and_read_and_process_response(message, on_response, on_fail) dialect-2.4.2/dialect/providers/settings.py000066400000000000000000000054431465154363000207750ustar00rootroot00000000000000# Copyright 2024 Mufeed Ali # Copyright 2024 Rafael Mardojai CM # SPDX-License-Identifier: GPL-3.0-or-later import logging from gi.repository import Gio, GLib, Secret from dialect.define import APP_ID SECRETS_SCHEMA = Secret.Schema.new( APP_ID, Secret.SchemaFlags.NONE, { "provider": Secret.SchemaAttributeType.STRING, }, ) class ProviderSettings(Gio.Settings): """ Helper class for providers settings """ def __init__(self, name: str, defaults: dict[str, str | list[str]]): super().__init__(f"{APP_ID}.translator", f"/app/drey/Dialect/translators/{name}/") self.name = name self.defaults = defaults # set of per-provider defaults self._secret_attr = {"provider": name} @property def instance_url(self) -> str: """Instance url.""" return self.get_string("instance-url") or self.defaults["instance_url"] @instance_url.setter def instance_url(self, url: str): self.set_string("instance-url", url) @property def api_key(self) -> str: """API key.""" # Check if we have an old API KEY in GSettings for migration if gsettings := self.get_string("api-key"): self.api_key = gsettings # Save to secret self.set_string("api-key", "") # Clear GSetting return gsettings try: return Secret.password_lookup_sync(SECRETS_SCHEMA, self._secret_attr, None) or self.defaults["api_key"] except GLib.GError as exc: logging.warning(exc) return self.defaults["api_key"] @api_key.setter def api_key(self, api_key: str): try: if api_key: Secret.password_store_sync( SECRETS_SCHEMA, self._secret_attr, Secret.COLLECTION_DEFAULT, f"Dialect provider API KEY for {self.name}", api_key, None, ) else: # Remove secret Secret.password_clear_sync(SECRETS_SCHEMA, self._secret_attr, None) # Fake change in api-key setting self.emit("changed::api-key", "api-key") except GLib.GError as exc: logging.warning(exc) @property def src_langs(self) -> list[str]: """Recent source languages.""" return self.get_strv("src-langs") or self.defaults["src_langs"] @src_langs.setter def src_langs(self, src_langs: list[str]): self.set_strv("src-langs", src_langs) @property def dest_langs(self) -> list[str]: """Recent destination languages.""" return self.get_strv("dest-langs") or self.defaults["dest_langs"] @dest_langs.setter def dest_langs(self, dest_langs: list[str]): self.set_strv("dest-langs", dest_langs) dialect-2.4.2/dialect/providers/soup.py000066400000000000000000000142371465154363000201240ustar00rootroot00000000000000# Copyright 2022 Mufeed Ali # Copyright 2022 Rafael Mardojai CM # SPDX-License-Identifier: GPL-3.0-or-later import json import logging from typing import Callable from gi.repository import Gio, GLib, Soup from dialect.providers.base import BaseProvider, ProviderError, ProviderErrorCode from dialect.session import Session class SoupProvider(BaseProvider): """Base class for providers needing libsoup helpers""" def __init__(self, **kwargs): super().__init__(**kwargs) def encode_data(self, data) -> GLib.Bytes | None: """ Convert Python data to JSON and bytes. Args: data: Data to encode, anything json.dumps can handle """ data_glib_bytes = None try: data_bytes = json.dumps(data).encode("utf-8") data_glib_bytes = GLib.Bytes.new(data_bytes) except Exception as exc: logging.warning(exc) return data_glib_bytes def create_message(self, method: str, url: str, data={}, headers: dict = {}, form: bool = False) -> Soup.Message: """ Create a libsoup's message. Encodes data and adds it to the message as the request body. If form is true, data is encoded as application/x-www-form-urlencoded. Args: method: HTTP method of the message url: Url of the message data: Request body or form data headers: HTTP headers of the message form: If the data should be encoded as a form """ if form and data: form_data = Soup.form_encode_hash(data) message = Soup.Message.new_from_encoded_form(method, url, form_data) else: message = Soup.Message.new(method, url) if data and not form: data = self.encode_data(data) message.set_request_body_from_bytes("application/json", data) if headers: for name, value in headers.items(): message.get_request_headers().append(name, value) if "User-Agent" not in headers: message.get_request_headers().append("User-Agent", "Dialect App") return message def send_and_read(self, message: Soup.Message, callback: Callable[[Session, Gio.AsyncResult], None]): """ Helper method for libsoup's send_and_read_async. Useful when priority and cancellable is not needed. Args: message: Message to send callback: Callback called from send_and_read_async to finish request """ Session.get().send_and_read_async(message, 0, None, callback) def read_data(self, data: bytes) -> dict: """ Get JSON data from bytes. Args: data: Bytes to read """ return json.loads(data) if data else {} def read_response(self, session: Session, result: Gio.AsyncResult) -> dict: """ Get JSON data from session result. Finishes request from send_and_read_async and gets body dict. Args: session: Session where the request wa sent result: Result of send_and_read_async callback """ response = session.get_response(session, result) return self.read_data(response) def check_known_errors(self, status: Soup.Status, data: dict) -> None | ProviderError: """ Checks data for possible response errors and return a found error if any. This should be implemented by subclases. Args: data: Response body data """ return None def process_response( self, session: Session, result: Gio.AsyncResult, message: Soup.Message, on_continue: Callable[[dict | bytes], None], on_fail: Callable[[ProviderError], None], check_common: bool = True, json: bool = True, ): """ Helper method for the most common workflow for processing soup responses. Checks for soup errors, then checks for common errors on data and calls on_fail if any, otherwise calls on_continue where the provider will finish the process. If json is false check_common is ignored and the data isn't processed as JSON and bites are passed to on_continue. Args: session: Session where the request wa sent result: Result of send_and_read_async callback message: The message that was sent on_continue: Called after data was got successfully on_fail: Called after any error on request or in check_known_errors check_common: If response data should be checked for errors using check_known_errors json: If data should be processed as JSON using read_response """ try: if json: data = self.read_response(session, result) else: data = Session.get_response(session, result) if check_common: error = self.check_known_errors(message.get_status(), data) if error: on_fail(error) return on_continue(data) except Exception as exc: logging.warning(exc) on_fail(ProviderError(ProviderErrorCode.NETWORK, str(exc))) def send_and_read_and_process_response( self, message: Soup.Message, on_continue: Callable[[dict | bytes], None], on_fail: Callable[[ProviderError], None], check_common: bool = True, json: bool = True, ): """ Helper packaging send_and_read and process_response. Avoids providers having to deal with many callbacks. message: Message to send on_continue: Called after data was got successfully on_fail: Called after any error on request or in check_known_errors check_common: If response data should be checked for errors using check_known_errors json: If data should be processed as JSON using read_response """ def on_response(session: Session, result: Gio.AsyncResult): self.process_response(session, result, message, on_continue, on_fail, check_common, json) self.send_and_read(message, on_response) dialect-2.4.2/dialect/search_provider/000077500000000000000000000000001465154363000177175ustar00rootroot00000000000000dialect-2.4.2/dialect/search_provider/app.drey.Dialect.SearchProvider.ini000066400000000000000000000001661465154363000264300ustar00rootroot00000000000000[Shell Search Provider] DesktopId=@APP_ID@.desktop BusName=@APP_ID@.SearchProvider ObjectPath=@object_path@ Version=2 dialect-2.4.2/dialect/search_provider/app.drey.Dialect.SearchProvider.service.in000066400000000000000000000001171465154363000277120ustar00rootroot00000000000000[D-BUS Service] Name=@APP_ID@.SearchProvider Exec=@pkgdatadir@/search_provider dialect-2.4.2/dialect/search_provider/meson.build000066400000000000000000000013041465154363000220570ustar00rootroot00000000000000search_provider_dir = join_paths(get_option('prefix'), get_option('datadir'), 'gnome-shell', 'search-providers') service_dir = join_paths(get_option('prefix'), get_option('datadir'), 'dbus-1', 'services') configure_file( input: 'app.drey.Dialect.SearchProvider.ini', output: '@0@.SearchProvider.ini'.format(application_id), configuration: conf, install_dir: search_provider_dir, ) configure_file( input: 'app.drey.Dialect.SearchProvider.service.in', output: '@0@.SearchProvider.service'.format(application_id), configuration: conf, install_dir: service_dir, ) configure_file( input: 'search_provider.in', output: 'search_provider', configuration: conf, install_dir: pkgdatadir, ) dialect-2.4.2/dialect/search_provider/search_provider.in000077500000000000000000000236521465154363000234410ustar00rootroot00000000000000#!@PYTHON@ # Copyright 2020 gi-lom # Copyright 2020 Nikita Kravets # Copyright 2020-2022 Rafael Mardojai CM # Copyright 2021-2022 Mufeed Ali # Copyright 2023 Markus Göllnitz # SPDX-License-Identifier: GPL-3.0-or-later import gettext import locale import sys import gi gi.require_version("Secret", "1") gi.require_version("Soup", "3.0") from gi.repository import Gio, GLib from dialect.providers import TRANSLATORS from dialect.providers.base import ProviderErrorCode from dialect.settings import Settings CLIPBOARD_PREFIX = "copy-to-clipboard" ERROR_PREFIX = "translation-error" localedir = "@localedir@" langs_trans = gettext.translation("dialect-cldr-langs", localedir, fallback=True) ui_trans = gettext.translation("dialect", localedir, fallback=True) ui_trans.add_fallback(langs_trans) ui_trans.install(names=["gettext"]) locale.bindtextdomain("dialect", localedir) locale.textdomain("dialect") dbus_interface_description = """ """ class TranslateService: def __init__(self): self.loaded = False self.load_failed = False # Live translation enabled self.live_enabled = self.is_live_enabled() # Translations store self.translations = {} self.src_language = "auto" self.dest_language = None # Translator self._load_translator() Settings.get().connect("changed", self._on_settings_changed) Settings.get().connect("translator-changed", self._on_translator_changed) def GetInitialResultSet(self, terms, callback): """ Join separate terms in one ID line, start translation and send this line back on start of input """ def on_done(translation): self.translations[text] = translation.text callback([text, CLIPBOARD_PREFIX + text]) def on_fail(error): match error.code: case ProviderErrorCode.NETWORK: self.translations[error_id] = _("Translation failed, check for network issues") case ProviderErrorCode.API_KEY_INVALID: self.translations[error_id] = _("The provided API key is invalid") case ProviderErrorCode.API_KEY_REQUIRED: self.translations[error_id] = _("API key is required to use the service") case _: self.translations[error_id] = _("Translation failed") callback([error_id]) text = " ".join(terms) if self.live_enabled: error_id = ERROR_PREFIX + text if self.load_failed: self.translations[error_id] = _("Failed loading the translation service") callback([error_id]) elif not self.loaded: return self.GetInitialResultSet(terms) # If the two languages are the same, nothing is done if self.src_language != self.dest_language and text != "": src, dest = self.translator.denormalize_lang(self.src_language, self.dest_language) self.translator.translate(text, src, dest, on_done, on_fail) else: provider = Settings.get().active_translator callback( [ _("Translate “{text}” with {provider_name}").format( text=text, provider_name=TRANSLATORS[provider].prettyname ) ] ) def GetSubsearchResultSet(self, _previous_results, new_terms, callback): self.GetInitialResultSet(new_terms, callback) def GetResultMetas(self, ids, callback): """Send translated text""" translate_id = ids[0] if len(ids) == 1: text = translate_id if translate_id in self.translations: text = self.translations[translate_id] callback( [ { "id": GLib.Variant("s", translate_id), "name": GLib.Variant("s", text), } ] ) elif len(ids) == 2 and translate_id in self.translations and ids[1] == CLIPBOARD_PREFIX + ids[0]: text = self.translations[translate_id] lang = self.translator.get_lang_name(self.dest_language) provider = Settings.get().active_translator description = f"{lang} — {TRANSLATORS[provider].prettyname}" if self.live_enabled else "" self.translations.clear() callback( [ { "id": GLib.Variant("s", translate_id), "name": GLib.Variant("s", text), "description": GLib.Variant("s", description), }, { "id": GLib.Variant("s", ids[1]), "name": GLib.Variant("s", _("Copy")), "description": GLib.Variant("s", _("Copy translation to clipboard")), "clipboardText": GLib.Variant("s", text), }, ] ) else: # Probably never needed, just in case callback( [ dict( id=GLib.Variant("s", id), name=GLib.Variant("s", id), ) for id in ids ] ) def ActivateResult(self, result_id, terms, timestamp, callback): if not result_id.startswith(CLIPBOARD_PREFIX): self.LaunchSearch(terms, timestamp) callback((None,)) def LaunchSearch(self, terms, _timestamp): text = " ".join(terms) GLib.spawn_async_with_pipes(None, ["@BIN@", "--text", text], None, GLib.SpawnFlags.SEARCH_PATH, None) def is_live_enabled(self): return Settings.get().live_translation and Settings.get().sp_translation def _load_translator(self): def on_done(): self.loaded = True self.load_failed = False self.dest_language = self.translator.recent_dest_langs[0] self.translator.settings.connect("changed", self._on_translator_settings_changed) def on_fail(_error): self.loaded = False self.load_failed = True self.dest_language = None self.loaded = False provider = Settings.get().active_translator self.translator = TRANSLATORS[provider]() # Init translator self.translator.init_trans(on_done, on_fail) def _on_settings_changed(self, _settings, key): if key.startswith("translator-"): self._load_translator() if key == "live-translation" or key == "sp-translation": self.live_enabled = self.is_live_enabled() def _on_translator_changed(self, *args): self._load_translator() def _on_translator_settings_changed(self, _settings, key): if key == "src-langs" or key == "dest-langs": self.dest_language = self.translator.recent_dest_langs[0] else: self._load_translator() class TranslateServiceApplication(Gio.Application): def __init__(self): Gio.Application.__init__( self, application_id="@APP_ID@.SearchProvider", flags=Gio.ApplicationFlags.IS_SERVICE, inactivity_timeout=10000, ) self.service_object = TranslateService() self.search_interface = Gio.DBusNodeInfo.new_for_xml(dbus_interface_description).interfaces[0] def do_dbus_register(self, connection, object_path): try: connection.register_object( object_path=object_path, interface_info=self.search_interface, method_call_closure=self.on_dbus_method_call, ) except: self.quit() return False finally: return True def on_dbus_method_call(self, connection, sender, object_path, interface_name, method_name, parameters, invocation): def return_value(results): results = (results,) if results == (None,): results = () results_type = ( "(" + "".join( map( lambda argument_info: argument_info.signature, self.search_interface.lookup_method(method_name).out_args, ) ) + ")" ) wrapped_results = GLib.Variant(results_type, results) invocation.return_value(wrapped_results) self.release() self.hold() method = getattr(self.service_object, method_name) arguments = list(parameters.unpack()) arguments.append(return_value) method(*arguments) if __name__ == "__main__": app = TranslateServiceApplication() sys.exit(app.run()) dialect-2.4.2/dialect/session.py000066400000000000000000000045141465154363000166010ustar00rootroot00000000000000# Copyright 2021-2022 Mufeed Ali # Copyright 2021-2022 Rafael Mardojai CM # SPDX-License-Identifier: GPL-3.0-or-later from __future__ import annotations import logging from uuid import uuid4 from gi.repository import GLib, Soup class Session(Soup.Session): """ Dialect soup session handler """ instance = None errors = {} def __init__(self): Soup.Session.__init__(self) @staticmethod def new() -> Session: """Create a new instance of Session.""" s_session = Soup.Session() s_session.__class__ = Session return s_session @staticmethod def get() -> Session: """Return an active instance of Session.""" if Session.instance is None: Session.instance = Session.new() return Session.instance @staticmethod def get_response(session, result): try: response = session.send_and_read_finish(result) data = response.get_data() return data except GLib.GError as exc: raise ResponseError(exc.message) from exc def multiple(self, messages, callback=None): """Keep track of multiple async operations.""" def on_task_response(session, result, message_callback, request_id): messages.pop() try: data = Session.get_response(session, result) message_callback(data) except ResponseError as exc: logging.warning(exc) self.errors[request_id] += str(exc) + "/n" # If all tasks are done, run main callback if callback is not None and len(messages) == 0: callback(errors=self.errors[request_id]) del self.errors[request_id] request_id = uuid4() self.errors[request_id] = "" for msg in messages: # msg[0]: Soup.Message # msg[1]: message callback self.send_and_read_async(msg[0], 0, None, on_task_response, msg[1], request_id) return request_id class ResponseError(Exception): """Exception raised when response fails.""" def __init__(self, cause, message="Response has failed"): self.cause = cause self.message = message super().__init__(self.message) def __str__(self): return f"{self.message}: {self.cause}" dialect-2.4.2/dialect/settings.py000066400000000000000000000120341465154363000167520ustar00rootroot00000000000000# Copyright 2021-2022 Mufeed Ali # Copyright 2021-2022 Rafael Mardojai CM # Copyright 2023 Libretto # SPDX-License-Identifier: GPL-3.0-or-later from gi.repository import Gio, GLib, GObject from dialect.define import APP_ID from dialect.providers import ( TTS, check_translator_availability, get_fallback_translator_name, ) class Settings(Gio.Settings): """ Dialect settings handler """ __gsignals__ = { "translator-changed": (GObject.SIGNAL_RUN_FIRST, None, (str,)), "tts-changed": (GObject.SIGNAL_RUN_FIRST, None, (str,)), } instance = None def __init__(self, *args): super().__init__(*args) self._translators = self.get_child("translators") self._tts = self.get_child("tts") @staticmethod def new(): """Create a new instance of Settings.""" g_settings = Settings(APP_ID) return g_settings @staticmethod def get(): """Return an active instance of Settings.""" if Settings.instance is None: Settings.instance = Settings.new() return Settings.instance @property def translators_list(self): return self._translators.get_strv("list") @translators_list.setter def translators_list(self, translators): self._translators.set_strv("list", translators) @property def active_translator(self): value = self._translators.get_string("active") if check_translator_availability(value): return value self.active_translator = get_fallback_translator_name() return get_fallback_translator_name() @active_translator.setter def active_translator(self, translator): self._translators.set_string("active", translator) self.emit("translator-changed", translator) @property def window_size(self): value = self.get_value("window-size") return (value[0], value[1]) @window_size.setter def window_size(self, size): width, height = size self.set_value("window-size", GLib.Variant("ai", [width, height])) @property def translate_accel(self): """Return the user's preferred translation shortcut.""" value = self.translate_accel_value if value == 0: return "Return" if value == 1: return "Return" return "Return" @property def translate_accel_value(self): """Return the user's preferred translation shortcut value.""" return self.get_int("translate-accel") @property def custom_default_font_size(self): """Return whether the user wants a custom default font size.""" return self.get_boolean("custom-default-font-size") @custom_default_font_size.setter def custom_default_font_size(self, enabled): self.set_boolean("custom-default-font-size", enabled) @property def default_font_size(self): """Return the user's preferred default font size.""" return self.get_int("default-font-size") @default_font_size.setter def default_font_size(self, size): self.set_int("default-font-size", size) @property def system_font_size(self): """Return the systems's default font size.""" from gi.repository import Gtk gtk_font_name = Gtk.Settings.get_default().get_property("gtk-font-name").split(" ") try: return int(gtk_font_name[-1]) except ValueError or IndexError: return 11 @property def active_tts(self): """Return the user's preferred TTS service.""" value = self._tts.get_string("active") if value != "" and value not in TTS.keys(): value = "" self.active_tts = value return value @active_tts.setter def active_tts(self, tts): """Set the user's preferred TTS service.""" self._tts.set_string("active", tts) self.emit("tts-changed", tts) @property def color_scheme(self): return self.get_string("color-scheme") @color_scheme.setter def color_scheme(self, scheme): self.set_string("dark-mode", scheme) @property def live_translation(self): return self.get_boolean("live-translation") @live_translation.setter def live_translation(self, state): self.set_boolean("live-translation", state) @property def sp_translation(self): return self.get_boolean("sp-translation") @sp_translation.setter def sp_translation(self, state): self.set_boolean("sp-translation", state) @property def show_pronunciation(self): return self.get_boolean("show-pronunciation") @property def show_pronunciation_value(self): return self.get_value("show-pronunciation") @show_pronunciation.setter def show_pronunciation(self, state): self.set_boolean("show-pronunciation", state) @property def src_auto(self): return self.get_boolean("src-auto") @src_auto.setter def src_auto(self, state): self.set_boolean("src-auto", state) dialect-2.4.2/dialect/shortcuts.py000066400000000000000000000013761465154363000171570ustar00rootroot00000000000000# Copyright 2021-2022 Mufeed Ali # Copyright 2021-2022 Rafael Mardojai CM # SPDX-License-Identifier: GPL-3.0-or-later from gi.repository import Gtk from dialect.define import RES_PATH from dialect.settings import Settings @Gtk.Template(resource_path=f"{RES_PATH}/shortcuts.ui") class DialectShortcutsWindow(Gtk.ShortcutsWindow): __gtype_name__ = "DialectShortcutsWindow" translate_shortcut = Gtk.Template.Child() def __init__(self, **kwargs): super().__init__(**kwargs) @Gtk.Template.Callback() def _on_show(self, _data): """Called on self::show signal""" self.translate_shortcut.props.visible = not Settings.get().live_translation self.translate_shortcut.props.accelerator = Settings.get().translate_accel dialect-2.4.2/dialect/utils.py000066400000000000000000000012361465154363000162540ustar00rootroot00000000000000# Copyright 2024 Mufeed Ali # Copyright 2024 Rafael Mardojai CM # SPDX-License-Identifier: GPL-3.0-or-later def find_item_match(list1: list[str], list2: list[str]) -> str | None: """ Get the first occurrence in two lists. Args: list1: List to iterate list2: List to check against """ set_to_check = set(list2) return next((i for i in list1 if i in set_to_check), None) def first_exclude(list_: list[str], exclude: str) -> str | None: """ Get the first item that is not excluded. Args: list_: List of items exclude: Item to ignore """ return next((x for x in list_ if x != exclude), None) dialect-2.4.2/dialect/widgets/000077500000000000000000000000001465154363000162065ustar00rootroot00000000000000dialect-2.4.2/dialect/widgets/__init__.py000066400000000000000000000005721465154363000203230ustar00rootroot00000000000000# Copyright 2020-2022 Mufeed Ali # Copyright 2020-2022 Rafael Mardojai CM # SPDX-License-Identifier: GPL-3.0-or-later from dialect.widgets.lang_selector import LangSelector # noqa from dialect.widgets.provider_preferences import ProviderPreferences # noqa from dialect.widgets.textview import TextView # noqa from dialect.widgets.theme_switcher import ThemeSwitcher # noqa dialect-2.4.2/dialect/widgets/lang_selector.py000066400000000000000000000122311465154363000214000ustar00rootroot00000000000000# Copyright 2020-2022 Mufeed Ali # Copyright 2020-2022 Rafael Mardojai CM # SPDX-License-Identifier: GPL-3.0-or-later import re from gi.repository import Adw, Gdk, GObject, Gtk from dialect.define import RES_PATH @Gtk.Template(resource_path=f"{RES_PATH}/lang-selector.ui") class LangSelector(Adw.Bin): __gtype_name__ = "LangSelector" __gsignals__ = {"user-selection-changed": (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, ())} # Properties selected = GObject.Property(type=str) # Code of the selected lang # Child Widgets button = Gtk.Template.Child() label = Gtk.Template.Child() insight = Gtk.Template.Child() popover = Gtk.Template.Child() search = Gtk.Template.Child() scroll = Gtk.Template.Child() revealer = Gtk.Template.Child() recent_list = Gtk.Template.Child() separator = Gtk.Template.Child() lang_list = Gtk.Template.Child() def __init__(self, **kwargs): super().__init__(**kwargs) self.model = None self.recent_model = None # Setup search entry self.search.set_key_capture_widget(self.popover) key_events = Gtk.EventControllerKey.new() key_events.connect("key-pressed", self._on_key_pressed) self.search.add_controller(key_events) def bind_models(self, langs, recent): self.model = langs self.recent_model = recent self.recent_model.connect("items-changed", self._on_recent_changed) self.filter = Gtk.CustomFilter() self.filter.set_filter_func(self._filter_langs) sorter = Gtk.CustomSorter.new(self._sort_langs) sorted_model = Gtk.SortListModel.new(model=self.model, sorter=sorter) filter_model = Gtk.FilterListModel.new(sorted_model, self.filter) self.lang_list.bind_model(filter_model, self._create_lang_row) self.recent_list.bind_model(self.recent_model, self._create_lang_row) def set_insight(self, code): if self.selected == "auto": self.insight.props.label = f"({self._get_lang_name(code)})" def _get_lang_name(self, code): return self.model.names_func(code) def _on_recent_changed(self, _model, _position, _removed, _added): self.recent_model.set_selected(self.selected) @Gtk.Template.Callback() def _on_selected_changed(self, _self, _pspec): """Called on self::notify::selected signal""" if self.model is not None: self.model.set_selected(self.selected) if self.selected == "auto": self.label.props.label = _("Auto") else: self.label.props.label = self._get_lang_name(self.selected) self.insight.props.label = "" @Gtk.Template.Callback() def _activated(self, _list, row): """Called on self.(recent_list, lang_list)::row-activated signal""" # Close popover self.popover.popdown() # Set selected property self.selected = row.lang.code self.emit("user-selection-changed") @Gtk.Template.Callback() def _popover_show(self, _popover): """Called on self.popover::show signal""" self.search.grab_focus() @Gtk.Template.Callback() def _popover_closed(self, _popover): """Called on self.popover::closed signal""" # Reset scroll vscroll = self.scroll.get_vadjustment() vscroll.props.value = 0 # Clear search self.search.props.text = "" def _create_lang_row(self, lang): return LangRow(lang) def _filter_langs(self, item): search = self.search.get_text() return bool(re.search(search, item.name, re.IGNORECASE)) def _sort_langs(self, lang_a, lang_b, _data): a = lang_a.name.lower() b = lang_b.name.lower() return (a > b) - (a < b) @Gtk.Template.Callback() def _on_search(self, _entry): """Called on self.search::changed signal""" if self.search.props.text != "": self.revealer.props.reveal_child = False else: self.revealer.props.reveal_child = True self.filter.emit("changed", Gtk.FilterChange.DIFFERENT) @Gtk.Template.Callback() def _on_search_activate(self, _entry): """Called on self.search::activate signal""" if self.search.props.text: row = self.lang_list.get_row_at_index(0) if row: self.lang_list.emit("row-activated", row) return Gdk.EVENT_PROPAGATE def _on_key_pressed(self, _controller, keyval, _keycode, _mod): # Close popover if ESQ key is pressed in search entry if keyval == Gdk.KEY_Escape: self.popover.popdown() # Prevent search entry unfocusing when down key is pressed elif keyval == Gdk.KEY_Down: return Gdk.EVENT_STOP @Gtk.Template(resource_path=f"{RES_PATH}/lang-row.ui") class LangRow(Gtk.ListBoxRow): __gtype_name__ = "LangRow" # Widgets name = Gtk.Template.Child() selection = Gtk.Template.Child() def __init__(self, lang): super().__init__() self.lang = lang self.name.props.label = self.lang.name self.lang.bind_property("selected", self.selection, "visible", GObject.BindingFlags.SYNC_CREATE) dialect-2.4.2/dialect/widgets/provider_preferences.py000066400000000000000000000166011465154363000227770ustar00rootroot00000000000000# Copyright 2023 Mufeed Ali # Copyright 2023 Rafael Mardojai CM # SPDX-License-Identifier: GPL-3.0-or-later import re from gi.repository import Adw, GObject, Gtk from dialect.define import RES_PATH from dialect.providers import ProviderCapability, ProviderFeature @Gtk.Template(resource_path=f"{RES_PATH}/provider-preferences.ui") class ProviderPreferences(Adw.NavigationPage): __gtype_name__ = "ProviderPreferences" # Properties translation = GObject.Property(type=bool, default=False) tts = GObject.Property(type=bool, default=False) definitions = GObject.Property(type=bool, default=False) # Child widgets title = Gtk.Template.Child() page = Gtk.Template.Child() instance_entry = Gtk.Template.Child() instance_stack = Gtk.Template.Child() instance_reset = Gtk.Template.Child() instance_spinner = Gtk.Template.Child() api_key_entry = Gtk.Template.Child() api_key_stack = Gtk.Template.Child() api_key_reset = Gtk.Template.Child() api_key_spinner = Gtk.Template.Child() api_usage_group = Gtk.Template.Child() api_usage = Gtk.Template.Child() api_usage_label = Gtk.Template.Child() def __init__(self, scope, dialog, window, **kwargs): super().__init__(**kwargs) self.scope = scope self.provider = window.provider[scope] self.dialog = dialog self.window = window self.title.props.subtitle = self.provider.prettyname self.translation = ProviderCapability.TRANSLATION in self.provider.capabilities self.tts = ProviderCapability.TTS in self.provider.capabilities self.definitions = ProviderCapability.DEFINITIONS in self.provider.capabilities # Check what entries to show self._check_settings() # Load saved values self.instance_entry.props.text = self.provider.instance_url self.api_key_entry.props.text = self.provider.api_key # Main window progress self.window.connect("notify::translator-loading", self._on_translator_loading) def _check_settings(self): def on_usage(usage, limit): level = usage / limit label = _("{usage:n} of {limit:n} characters").format(usage=usage, limit=limit) self.api_usage.props.value = level self.api_usage_label.props.label = label self.api_usage_group.props.visible = True def on_usage_fail(_error): pass if self.provider: self.instance_entry.props.visible = ProviderFeature.INSTANCES in self.provider.features self.api_key_entry.props.visible = ProviderFeature.API_KEY in self.provider.features self.api_usage_group.props.visible = False if ProviderFeature.API_KEY_USAGE in self.provider.features: self.provider.api_char_usage(on_usage, on_usage_fail) @Gtk.Template.Callback() def _on_instance_apply(self, _row): """Called on self.instance_entry::apply signal""" def on_done(valid): if valid: self.provider.instance_url = self.new_instance_url self.provider.reset_src_langs() self.provider.reset_dest_langs() self.instance_entry.remove_css_class("error") self.instance_entry.props.text = self.provider.instance_url else: self.instance_entry.add_css_class("error") error_text = _("Not a valid {provider} instance") error_text = error_text.format(provider=self.provider.prettyname) toast = Adw.Toast.new(error_text) self.dialog.add_toast(toast) self.instance_entry.props.sensitive = True self.api_key_entry.props.sensitive = True self.instance_stack.props.visible_child_name = "reset" self.instance_spinner.stop() old_value = self.provider.instance_url new_value = self.instance_entry.props.text url = re.compile(r"https?://(www\.)?") self.new_instance_url = url.sub("", new_value).strip().strip("/") # Validate if self.new_instance_url != old_value: # Progress feedback self.instance_entry.props.sensitive = False self.api_key_entry.props.sensitive = False self.instance_stack.props.visible_child_name = "spinner" self.instance_spinner.start() # TODO: Use on_fail to notify network error self.provider.validate_instance(self.new_instance_url, on_done, lambda _: on_done(False)) else: self.instance_entry.remove_css_class("error") @Gtk.Template.Callback() def _on_instance_changed(self, _entry, _pspec): """Called on self.instance_entry::notify::text signal""" if self.instance_entry.props.text == self.provider.instance_url: self.instance_entry.props.show_apply_button = False elif not self.instance_entry.props.show_apply_button: self.instance_entry.props.show_apply_button = True @Gtk.Template.Callback() def _on_reset_instance(self, _button): if self.provider.instance_url != self.provider.defaults["instance_url"]: self.provider.reset_instance_url() self.instance_entry.remove_css_class("error") self.instance_entry.props.text = self.provider.instance_url @Gtk.Template.Callback() def _on_api_key_apply(self, _row): """Called on self.api_key_entry::apply signal""" def on_done(valid): if valid: self.provider.api_key = self.new_api_key self.api_key_entry.remove_css_class("error") self.api_key_entry.props.text = self.provider.api_key else: self.api_key_entry.add_css_class("error") error_text = _("Not a valid {provider} API key") error_text = error_text.format(provider=self.provider.prettyname) toast = Adw.Toast.new(error_text) self.dialog.add_toast(toast) self.instance_entry.props.sensitive = True self.api_key_entry.props.sensitive = True self.api_key_stack.props.visible_child_name = "reset" self.api_key_spinner.stop() old_value = self.provider.api_key self.new_api_key = self.api_key_entry.get_text() # Validate if self.new_api_key != old_value: # Progress feedback self.instance_entry.props.sensitive = False self.api_key_entry.props.sensitive = False self.api_key_stack.props.visible_child_name = "spinner" self.api_key_spinner.start() # TODO: Use on_fail to notify network error self.provider.validate_api_key(self.new_api_key, on_done, lambda _: on_done(False)) else: self.api_key_entry.remove_css_class("error") @Gtk.Template.Callback() def _on_reset_api_key(self, _button): """Called on self.api_key_reset::clicked signal""" if self.provider.api_key != self.provider.defaults["api_key"]: self.provider.reset_api_key() self.api_key_entry.remove_css_class("error") self.api_key_entry.props.text = self.provider.api_key def _on_translator_loading(self, window, _value): self.page.props.sensitive = not window.translator_loading if not window.translator_loading: self.provider = self.window.provider[self.scope] self._check_settings() dialect-2.4.2/dialect/widgets/textview.py000066400000000000000000000057051465154363000204460ustar00rootroot00000000000000# Copyright 2023 Mufeed Ali # Copyright 2023 Rafael Mardojai CM # Copyright 2023 Libretto # SPDX-License-Identifier: GPL-3.0-or-later from gi.repository import Gdk, GObject, Gtk from dialect.settings import Settings class TextView(Gtk.TextView): __gtype_name__ = "TextView" __gsignals__ = {"activate": (GObject.SIGNAL_RUN_FIRST, None, ())} activate_mod: bool = GObject.Property(type=bool, default=True) """If activation requieres the mod key""" def __init__(self, **kwargs): super().__init__(**kwargs) # Set word/char text wrapping self.props.wrap_mode = Gtk.WrapMode.WORD_CHAR # Key press controller key_ctrlr = Gtk.EventControllerKey() key_ctrlr.connect("key-pressed", self._on_key_pressed) self.add_controller(key_ctrlr) # Scroll controller scroll_ctrlr = Gtk.EventControllerScroll.new(Gtk.EventControllerScrollFlags.VERTICAL) scroll_ctrlr.connect("scroll", self._on_scroll) self.add_controller(scroll_ctrlr) # Custom font self._font_size = Settings.get().system_font_size self._font_css_provider = Gtk.CssProvider() # Add font CSS provider self.get_style_context().add_provider(self._font_css_provider, Gtk.STYLE_PROVIDER_PRIORITY_USER) @GObject.Property(type=int) def font_size(self) -> int: return self._font_size @font_size.setter def font_size(self, value: int): # Save value self._font_size = value # Update CSS self._font_css_provider.load_from_data(f"textview {{ font-size: { str(value) }pt; }}") def font_size_inc(self): self.font_size += 5 def font_size_dec(self): new_size = self.font_size - 5 if new_size >= 6: self.font_size = new_size def _on_key_pressed(self, _button, keyval, _keycode, state): modifiers = state & Gtk.accelerator_get_default_mod_mask() control_mask = Gdk.ModifierType.CONTROL_MASK enter_keys = (Gdk.KEY_Return, Gdk.KEY_KP_Enter) # Activate with mod key pressed if control_mask == modifiers: if keyval in enter_keys: if self.activate_mod: self.emit("activate") return Gdk.EVENT_STOP # Activate without mod key pressed elif keyval in enter_keys: if not self.activate_mod: self.emit("activate") return Gdk.EVENT_STOP return Gdk.EVENT_PROPAGATE def _on_scroll(self, ctrl: Gtk.EventControllerScroll, _dx: float, dy: float): state = ctrl.get_current_event_state() # If Control modifier is pressed if state == Gdk.ModifierType.CONTROL_MASK: if dy > 0: self.font_size_dec() else: self.font_size_inc() # Stop propagation return Gdk.EVENT_STOP # Propagate event (scrolled window, etc) return Gdk.EVENT_PROPAGATE dialect-2.4.2/dialect/widgets/theme_switcher.py000066400000000000000000000044741465154363000216030ustar00rootroot00000000000000# Copyright 2020 Manuel Genovés # Copyright 2022 Mufeed Ali # Copyright 2022 Rafael Mardojai CM # SPDX-License-Identifier: GPL-3.0-or-later # Code modified from Apostrophe # https://gitlab.gnome.org/World/apostrophe/-/blob/main/apostrophe/theme_switcher.py from gi.repository import Adw, Gio, GObject, Gtk from dialect.define import RES_PATH from dialect.settings import Settings @Gtk.Template(resource_path=f"{RES_PATH}/theme-switcher.ui") class ThemeSwitcher(Gtk.Box): __gtype_name__ = "ThemeSwitcher" # Properties show_system = GObject.property(type=bool, default=True) color_scheme = "light" # Child widgets system = Gtk.Template.Child() light = Gtk.Template.Child() dark = Gtk.Template.Child() @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.props.active = True self.style_manager.props.color_scheme = Adw.ColorScheme.PREFER_LIGHT if color_scheme == "light": self.light.props.active = True self.style_manager.props.color_scheme = Adw.ColorScheme.FORCE_LIGHT if color_scheme == "dark": self.dark.props.active = True self.style_manager.props.color_scheme = Adw.ColorScheme.FORCE_DARK def __init__(self, **kwargs): super().__init__(**kwargs) self.style_manager = Adw.StyleManager.get_default() self.color_scheme = Settings.get().color_scheme Settings.get().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): """Called on (self.system, self.light, self.dark)::notify::active signal""" if self.system.props.active: self.selected_color_scheme = "auto" if self.light.props.active: self.selected_color_scheme = "light" if self.dark.props.active: self.selected_color_scheme = "dark" dialect-2.4.2/dialect/window.py000066400000000000000000001331751465154363000164330ustar00rootroot00000000000000# Copyright 2020 gi-lom # Copyright 2020-2022 Mufeed Ali # Copyright 2020-2022 Rafael Mardojai CM # Copyright 2023 Libretto # SPDX-License-Identifier: GPL-3.0-or-later import logging from gi.repository import Adw, Gdk, Gio, GLib, GObject, Gst, Gtk from dialect.define import APP_ID, PROFILE, RES_PATH, TRANS_NUMBER from dialect.languages import LanguagesListModel from dialect.providers import ( TRANSLATORS, TTS, ProviderError, ProviderErrorCode, ProviderFeature, ) from dialect.providers.base import BaseProvider, Translation from dialect.settings import Settings from dialect.shortcuts import DialectShortcutsWindow from dialect.utils import find_item_match, first_exclude from dialect.widgets import LangSelector, TextView, ThemeSwitcher @Gtk.Template(resource_path=f"{RES_PATH}/window.ui") class DialectWindow(Adw.ApplicationWindow): __gtype_name__ = "DialectWindow" # Properties translator_loading = GObject.Property(type=bool, default=True) # Child widgets menu_btn: Gtk.MenuButton = Gtk.Template.Child() main_stack: Gtk.Stack = Gtk.Template.Child() error_page: Adw.StatusPage = Gtk.Template.Child() translator_box: Gtk.Box = Gtk.Template.Child() key_page: Adw.StatusPage = Gtk.Template.Child() rmv_key_btn: Gtk.Button = Gtk.Template.Child() error_api_key_btn: Gtk.Button = Gtk.Template.Child() title_stack: Gtk.Stack = Gtk.Template.Child() langs_button_box: Gtk.Box = Gtk.Template.Child() switch_btn: Gtk.Button = Gtk.Template.Child() src_lang_selector: LangSelector = Gtk.Template.Child() dest_lang_selector: LangSelector = Gtk.Template.Child() return_btn: Gtk.Button = Gtk.Template.Child() forward_btn: Gtk.Button = Gtk.Template.Child() src_pron_revealer: Gtk.Revealer = Gtk.Template.Child() src_pron_label: Gtk.Label = Gtk.Template.Child() mistakes: Gtk.Revealer = Gtk.Template.Child() mistakes_label: Gtk.Label = Gtk.Template.Child() char_counter: Gtk.Label = Gtk.Template.Child() src_text: TextView = Gtk.Template.Child() clear_btn: Gtk.Button = Gtk.Template.Child() paste_btn: Gtk.Button = Gtk.Template.Child() src_voice_btn: Gtk.Button = Gtk.Template.Child() translate_btn: Gtk.Button = Gtk.Template.Child() dest_box: Gtk.Box = Gtk.Template.Child() dest_pron_revealer: Gtk.Revealer = Gtk.Template.Child() dest_pron_label: Gtk.Label = Gtk.Template.Child() dest_text: TextView = Gtk.Template.Child() dest_toolbar_stack: Gtk.Stack = Gtk.Template.Child() trans_spinner: Gtk.Spinner = Gtk.Template.Child() trans_warning: Gtk.Image = Gtk.Template.Child() edit_btn: Gtk.Button = Gtk.Template.Child() copy_btn: Gtk.Button = Gtk.Template.Child() dest_voice_btn: Gtk.Button = Gtk.Template.Child() actionbar: Gtk.ActionBar = Gtk.Template.Child() src_lang_selector_m: LangSelector = Gtk.Template.Child() dest_lang_selector_m: LangSelector = Gtk.Template.Child() toast: Adw.Toast | None = None # for notification management toast_overlay: Adw.ToastOverlay = Gtk.Template.Child() win_key_ctrlr: Gtk.EventControllerKey = Gtk.Template.Child() # Providers objects provider: dict[str, BaseProvider] = {"trans": None, "tts": None} # Text to speech current_speech = {} voice_loading = False # tts loading status # Preset language values src_langs = [] dest_langs = [] current_history = 0 # for history management # Translation-related variables next_trans = {} # for ongoing translation ongoing_trans = False # for ongoing translation trans_failed = False # for monitoring connectivity issues trans_mistakes = [None, None] # "mistakes" suggestions # Pronunciations trans_src_pron = None trans_dest_pron = None # Suggestions before_suggest = None def __init__(self, **kwargs): super().__init__(**kwargs) # Application object self.app = kwargs["application"] # GStreamer playbin object and related setup self.player = Gst.ElementFactory.make("playbin", "player") bus = self.player.get_bus() bus.add_signal_watch() bus.connect("message", self.on_gst_message) # Setup window self.setup_actions() self.setup() def setup_actions(self): back = Gio.SimpleAction.new("back", None) back.props.enabled = False back.connect("activate", self.ui_return) self.add_action(back) forward_action = Gio.SimpleAction.new("forward", None) forward_action.props.enabled = False forward_action.connect("activate", self.ui_forward) self.add_action(forward_action) switch_action = Gio.SimpleAction.new("switch", None) switch_action.connect("activate", self.ui_switch) self.add_action(switch_action) from_action = Gio.SimpleAction.new("from", None) from_action.connect("activate", self.ui_from) self.add_action(from_action) to_action = Gio.SimpleAction.new("to", None) to_action.connect("activate", self.ui_to) self.add_action(to_action) clear_action = Gio.SimpleAction.new("clear", None) clear_action.props.enabled = False clear_action.connect("activate", self.ui_clear) self.add_action(clear_action) font_size_inc_action = Gio.SimpleAction.new("font-size-inc", None) font_size_inc_action.connect("activate", self.ui_font_size_inc) self.add_action(font_size_inc_action) font_size_dec_action = Gio.SimpleAction.new("font-size-dec", None) font_size_dec_action.connect("activate", self.ui_font_size_dec) self.add_action(font_size_dec_action) paste_action = Gio.SimpleAction.new("paste", None) paste_action.connect("activate", self.ui_paste) self.add_action(paste_action) copy_action = Gio.SimpleAction.new("copy", None) copy_action.props.enabled = False copy_action.connect("activate", self.ui_copy) self.add_action(copy_action) listen_dest_action = Gio.SimpleAction.new("listen-dest", None) listen_dest_action.connect("activate", self.ui_dest_voice) self.add_action(listen_dest_action) suggest_action = Gio.SimpleAction.new("suggest", None) suggest_action.props.enabled = False suggest_action.connect("activate", self.ui_suggest) self.add_action(suggest_action) suggest_ok_action = Gio.SimpleAction.new("suggest-ok", None) suggest_ok_action.connect("activate", self.ui_suggest_ok) self.add_action(suggest_ok_action) suggest_cancel_action = Gio.SimpleAction.new("suggest-cancel", None) suggest_cancel_action.connect("activate", self.ui_suggest_cancel) self.add_action(suggest_cancel_action) listen_src_action = Gio.SimpleAction.new("listen-src", None) listen_src_action.connect("activate", self.ui_src_voice) self.add_action(listen_src_action) translation_action = Gio.SimpleAction.new("translation", None) translation_action.props.enabled = False translation_action.connect("activate", self.translation) self.add_action(translation_action) def setup(self): self.set_default_icon_name(APP_ID) # Set devel style if PROFILE == "Devel": self.add_css_class("devel") # Theme Switcher theme_switcher = ThemeSwitcher() self.menu_btn.props.popover.add_child(theme_switcher, "theme") # Save settings on close self.connect("unrealize", self.save_settings) self.setup_selectors() self.setup_translation() self.set_help_overlay(DialectShortcutsWindow()) # Load translator self.load_translator() # Load text to speech self.load_tts() # Listen to active providers changes Settings.get().connect("translator-changed", self._on_active_provider_changed, "trans") Settings.get().connect("tts-changed", self._on_active_provider_changed, "tts") # Bind text views font size self.src_text.bind_property("font-size", self.dest_text, "font-size", GObject.BindingFlags.BIDIRECTIONAL) # Set initial saved text view font size if Settings.get().custom_default_font_size: font_size = Settings.get().default_font_size self.set_font_size(font_size) # Set src textview mod key requirement self.src_text.activate_mod = not bool(Settings.get().translate_accel_value) Settings.get().connect( "changed::translate-accel", lambda s, _k: self.src_text.set_property("activate_mod", not bool(s.translate_accel_value)), ) def setup_selectors(self): # Languages models self.src_lang_model = LanguagesListModel(self._lang_names_func) self.src_recent_lang_model = LanguagesListModel(self._lang_names_func) self.dest_lang_model = LanguagesListModel(self._lang_names_func) self.dest_recent_lang_model = LanguagesListModel(self._lang_names_func) # Src lang selector self.src_lang_selector.bind_models(self.src_lang_model, self.src_recent_lang_model) self.src_lang_selector_m.bind_models(self.src_lang_model, self.src_recent_lang_model) # Dest lang selector self.dest_lang_selector.bind_models(self.dest_lang_model, self.dest_recent_lang_model) self.dest_lang_selector_m.bind_models(self.dest_lang_model, self.dest_recent_lang_model) self.langs_button_box.props.homogeneous = False def _lang_names_func(self, code): return self.provider["trans"].get_lang_name(code) def setup_translation(self): # Src buffer self.src_buffer = self.src_text.props.buffer self.src_buffer.connect("changed", self.on_src_text_changed) self.src_buffer.connect("end-user-action", self.user_action_ended) # Dest buffer self.dest_buffer = self.dest_text.props.buffer self.dest_buffer.props.text = "" self.dest_buffer.connect("changed", self.on_dest_text_changed) # Translation progress spinner self.trans_spinner.hide() self.trans_warning.hide() # Voice buttons prep-work self.src_voice_warning = Gtk.Image.new_from_icon_name("dialog-warning-symbolic") self.src_voice_image = Gtk.Image.new_from_icon_name("audio-speakers-symbolic") self.src_voice_spinner = Gtk.Spinner() # For use while audio is running or still loading. self.dest_voice_warning = Gtk.Image.new_from_icon_name("dialog-warning-symbolic") self.dest_voice_image = Gtk.Image.new_from_icon_name("audio-speakers-symbolic") self.dest_voice_spinner = Gtk.Spinner() self.toggle_voice_spinner(True) def load_translator(self): def on_done(): # Mistakes support if ProviderFeature.MISTAKES not in self.provider["trans"].features: self.mistakes.props.reveal_child = False # Suggestions support self.ui_suggest_cancel(None, None) if ProviderFeature.SUGGESTIONS not in self.provider["trans"].features: self.edit_btn.props.visible = False else: self.edit_btn.props.visible = True # Pronunciation support if ProviderFeature.PRONUNCIATION not in self.provider["trans"].features: self.src_pron_revealer.props.reveal_child = False self.dest_pron_revealer.props.reveal_child = False self.app.lookup_action("pronunciation").props.enabled = False else: self.app.lookup_action("pronunciation").props.enabled = True # Update langs self.src_lang_model.set_langs(self.provider["trans"].src_languages) self.dest_lang_model.set_langs(self.provider["trans"].dest_languages) # Update selected langs set_auto = Settings.get().src_auto and ProviderFeature.DETECTION in self.provider["trans"].features src_lang = self.provider["trans"].src_languages[0] if self.src_langs and self.src_langs[0] in self.provider["trans"].src_languages: src_lang = self.src_langs[0] self.src_lang_selector.selected = "auto" if set_auto else src_lang dest_lang = self.provider["trans"].dest_languages[1] if self.dest_langs and self.dest_langs[0] in self.provider["trans"].dest_languages: dest_lang = self.dest_langs[0] self.dest_lang_selector.selected = dest_lang # Update chars limit if self.provider["trans"].chars_limit == -1: # -1 means unlimited self.char_counter.props.label = "" else: count = f"{str(self.src_buffer.get_char_count())}/{self.provider['trans'].chars_limit}" self.char_counter.props.label = count self.translator_loading = False self.check_apikey() def on_fail(error: ProviderError): self.translator_loading = False self.loading_failed(error) provider = Settings.get().active_translator # Show loading view self.main_stack.props.visible_child_name = "loading" # Translator object self.provider["trans"] = TRANSLATORS[provider]() # Get saved languages self.src_langs = self.provider["trans"].recent_src_langs self.dest_langs = self.provider["trans"].recent_dest_langs # Do provider init self.provider["trans"].init_trans(on_done, on_fail) # Connect to provider settings changes self.provider["trans"].settings.connect( "changed::instance-url", self._on_provider_changed, self.provider["trans"].name ) self.provider["trans"].settings.connect( "changed::api-key", self._on_provider_changed, self.provider["trans"].name ) def check_apikey(self): def on_done(valid): if valid: self.main_stack.props.visible_child_name = "translate" else: self.api_key_failed() def on_fail(error: ProviderError): self.loading_failed(error) if ProviderFeature.API_KEY in self.provider["trans"].features: if self.provider["trans"].api_key: self.provider["trans"].validate_api_key(self.provider["trans"].api_key, on_done, on_fail) elif ( not self.provider["trans"].api_key and ProviderFeature.API_KEY_REQUIRED in self.provider["trans"].features ): self.api_key_failed(required=True) else: self.main_stack.props.visible_child_name = "translate" else: self.main_stack.props.visible_child_name = "translate" def loading_failed(self, error: ProviderError): # Api Key error if error.code in (ProviderErrorCode.API_KEY_INVALID, ProviderErrorCode.API_KEY_REQUIRED): self.api_key_failed(error.code == ProviderErrorCode.API_KEY_REQUIRED) # Other errors else: self.main_stack.props.visible_child_name = "error" service = self.provider["trans"].prettyname url = self.provider["trans"].instance_url title = _("Failed loading the translation service") description = _("Please report this in the Dialect bug tracker if the issue persists.") if ProviderFeature.INSTANCES in self.provider["trans"].features: description = _( ( 'Failed loading "{url}", check if the instance address is correct or report in the Dialect bug tracker' " if the issue persists." ) ) description = description.format(url=url) if error.code == ProviderErrorCode.NETWORK: title = _("Couldn’t connect to the translation service") description = _("We can’t connect to the server. Please check for network issues.") if ProviderFeature.INSTANCES in self.provider["trans"].features: description = _( ( "We can’t connect to the {service} instance “{url}”.\n" "Please check for network issues or if the address is correct." ) ) description = description.format(service=service, url=url) if error.message: description = description + "\n\n" + error.message + "" self.error_page.props.title = title self.error_page.props.description = description def api_key_failed(self, required=False): if required: self.key_page.props.title = _("API key is required to use the service") self.key_page.props.description = _("Please set an API key in the preferences.") else: self.key_page.props.title = _("The provided API key is invalid") if ProviderFeature.API_KEY_REQUIRED in self.provider["trans"].features: self.key_page.props.description = _("Please set a valid API key in the preferences.") else: self.key_page.props.description = _( "Please set a valid API key or unset the API key in the preferences." ) self.rmv_key_btn.props.visible = True self.error_api_key_btn.props.visible = True self.main_stack.props.visible_child_name = "api-key" @Gtk.Template.Callback() def retry_load_translator(self, _button): self.load_translator() @Gtk.Template.Callback() def remove_key_and_reload(self, _button): self.provider["trans"].reset_api_key() self.load_translator() def load_tts(self): def on_done(): self.download_speech() def on_fail(_error: ProviderError): self.on_listen_failed() # TTS name provider = Settings.get().active_tts # Check if TTS is disabled if provider != "": self.src_voice_btn.props.visible = True self.dest_voice_btn.props.visible = True # TTS Object self.provider["tts"] = TTS[provider]() self.provider["tts"].init_tts(on_done, on_fail) # Connect to provider settings changes self.provider["tts"].settings.connect( "changed::instance-url", self._on_provider_changed, self.provider["tts"].name ) self.provider["tts"].settings.connect( "changed::api-key", self._on_provider_changed, self.provider["tts"].name ) else: self.provider["tts"] = None self.src_voice_btn.props.visible = False self.dest_voice_btn.props.visible = False def on_listen_failed(self): self.src_voice_btn.props.child = self.src_voice_warning self.src_voice_spinner.stop() self.dest_voice_btn.props.child = self.dest_voice_warning self.dest_voice_spinner.stop() tooltip_text = _("A network issue has occurred. Retry?") self.src_voice_btn.props.tooltip_text = tooltip_text self.dest_voice_btn.props.tooltip_text = tooltip_text if self.current_speech: called_from = self.current_speech["called_from"] action = { "label": _("Retry"), "name": "win.listen-src" if called_from == "src" else "win.listen-dest", } else: action = None self.send_notification(_("A network issue has occurred. Please try again."), action=action) src_text = self.src_buffer.get_text(self.src_buffer.get_start_iter(), self.src_buffer.get_end_iter(), True) dest_text = self.dest_buffer.get_text(self.dest_buffer.get_start_iter(), self.dest_buffer.get_end_iter(), True) if self.provider["tts"].tts_languages: self.lookup_action("listen-src").set_enabled( self.src_lang_selector.selected in self.provider["tts"].tts_languages and src_text != "" ) self.lookup_action("listen-dest").set_enabled( self.dest_lang_selector.selected in self.provider["tts"].tts_languages and dest_text != "" ) else: self.lookup_action("listen-src").props.enabled = src_text != "" self.lookup_action("listen-dest").props.enabled = dest_text != "" def translate(self, text, src_lang, dest_lang): """ Translates the given text from auto detected language to last used language """ # Set src lang to Auto if src_lang is None: self.src_lang_selector.selected = "auto" else: self.src_lang_selector.selected = src_lang if dest_lang is not None and dest_lang in self.provider["trans"].dest_languages: self.dest_lang_selector.selected = dest_lang self.dest_lang_selector.emit("user-selection-changed") # Set text to src buffer self.src_buffer.props.text = text # Run translation self.translation() def translate_selection(self, src_lang, dest_lang): def on_paste(clipboard, result): text = clipboard.read_text_finish(result) self.translate(text, src_lang, dest_lang) clipboard = Gdk.Display.get_default().get_primary_clipboard() clipboard.read_text_async(None, on_paste) def save_settings(self, *args, **kwargs): if not self.is_maximized(): size = self.get_default_size() Settings.get().window_size = (size.width, size.height) if self.provider["trans"] is not None: self.provider["trans"].recent_src_langs = self.src_langs self.provider["trans"].recent_dest_langs = self.dest_langs def send_notification(self, text, queue=False, action=None, timeout=5, priority=Adw.ToastPriority.NORMAL): """ Display an in-app notification. Args: text (str): The text or message of the notification. queue (bool, optional): If True, the notification will be queued. action (dict, optional): A dict containing the action to be called. """ if not queue and self.toast is not None: self.toast.dismiss() self.toast = Adw.Toast.new(text) self.toast.connect("dismissed", self._toast_dismissed) if action is not None: self.toast.props.button_label = action["label"] self.toast.props.action_name = action["name"] self.toast.props.timeout = timeout self.toast.props.priority = priority self.toast_overlay.add_toast(self.toast) def _toast_dismissed(self, toast): self.toast = None def toggle_voice_spinner(self, active=True): if active: self.lookup_action("listen-src").props.enabled = False self.src_voice_btn.props.child = self.src_voice_spinner self.src_voice_spinner.start() self.lookup_action("listen-dest").props.enabled = False self.dest_voice_btn.props.child = self.dest_voice_spinner self.dest_voice_spinner.start() else: src_text = self.src_buffer.get_text(self.src_buffer.get_start_iter(), self.src_buffer.get_end_iter(), True) self.lookup_action("listen-src").set_enabled( self.src_lang_selector.selected in self.provider["tts"].tts_languages and src_text != "" ) self.src_voice_btn.props.child = self.src_voice_image self.src_voice_spinner.stop() dest_text = self.dest_buffer.get_text( self.dest_buffer.get_start_iter(), self.dest_buffer.get_end_iter(), True ) self.lookup_action("listen-dest").set_enabled( self.dest_lang_selector.selected in self.provider["tts"].tts_languages and dest_text != "" ) self.dest_voice_btn.props.child = self.dest_voice_image self.dest_voice_spinner.stop() @Gtk.Template.Callback() def _on_src_lang_changed(self, _obj, _param): """Called on self.src_lang_selector::notify::selected signal""" code = self.src_lang_selector.selected dest_code = self.dest_lang_selector.selected src_text = self.src_buffer.get_text(self.src_buffer.get_start_iter(), self.src_buffer.get_end_iter(), True) if self.provider["trans"].cmp_langs(code, dest_code): valid = find_item_match(first_exclude(self.src_langs, dest_code), self.provider["trans"].dest_languages) if not valid: valid = first_exclude(self.provider["trans"].dest_languages, dest_code) self.dest_lang_selector.selected = valid # Disable or enable listen function. if self.provider["tts"] and Settings.get().active_tts != "": self.lookup_action("listen-src").set_enabled(code in self.provider["tts"].tts_languages and src_text != "") if code in self.provider["trans"].src_languages: # Update saved src langs list if code in self.src_langs: # Bring lang to the top self.src_langs.remove(code) elif code.lower() in self.src_langs: # Bring lang to the top self.src_langs.remove(code.lower()) elif len(self.src_langs) == 4: self.src_langs.pop() self.src_langs.insert(0, code) # Rewrite recent langs self.src_recent_lang_model.set_langs(self.src_langs, auto=True) self._check_switch_enabled() @Gtk.Template.Callback() def _on_dest_lang_changed(self, _obj, _param): """Called on self.dest_lang_selector::notify::selected signal""" code = self.dest_lang_selector.selected src_code = self.src_lang_selector.selected dest_text = self.dest_buffer.get_text(self.dest_buffer.get_start_iter(), self.dest_buffer.get_end_iter(), True) if self.provider["trans"].cmp_langs(code, src_code): valid = find_item_match(first_exclude(self.dest_langs, src_code), self.provider["trans"].src_languages) if not valid: valid = first_exclude(self.provider["trans"].src_languages, src_code) self.src_lang_selector.selected = valid # Disable or enable listen function. if self.provider["tts"] and Settings.get().active_tts != "": self.lookup_action("listen-dest").set_enabled( code in self.provider["tts"].tts_languages and dest_text != "" ) # Update saved dest langs list if code in self.dest_langs: # Bring lang to the top self.dest_langs.remove(code) elif code.lower() in self.dest_langs: # Bring lang to the top self.dest_langs.remove(code.lower()) elif len(self.src_langs) == 4: self.dest_langs.pop() self.dest_langs.insert(0, code) # Rewrite recent langs self.dest_recent_lang_model.set_langs(self.dest_langs) self._check_switch_enabled() def _check_switch_enabled(self): # Disable or enable switch function. self.lookup_action("switch").props.enabled = ( self.src_lang_selector.selected in self.provider["trans"].dest_languages and self.dest_lang_selector.selected in self.provider["trans"].src_languages ) """ User interface functions """ def ui_return(self, _action, _param): """Go back one step in history.""" if self.current_history != TRANS_NUMBER: self.current_history += 1 self.history_update() def ui_forward(self, _action, _param): """Go forward one step in history.""" if self.current_history != 0: self.current_history -= 1 self.history_update() def add_history_entry(self, translation: Translation): """Add a history entry to the history list.""" if self.current_history > 0: del self.provider["trans"].history[: self.current_history] self.current_history = 0 if len(self.provider["trans"].history) == TRANS_NUMBER: self.provider["trans"].history.pop() self.provider["trans"].history.insert(0, translation) GLib.idle_add(self.reset_return_forward_btns) def switch_all(self, src_language, dest_language, src_text, dest_text): self.src_lang_selector.selected = dest_language self.dest_lang_selector.selected = src_language self.src_buffer.props.text = dest_text self.dest_buffer.props.text = src_text self.add_history_entry(Translation(src_text, (dest_text, src_language, dest_language))) # Re-enable widgets self.langs_button_box.props.sensitive = True self.lookup_action("translation").props.enabled = self.src_buffer.get_char_count() != 0 def ui_switch(self, _action, _param): # Get variables self.langs_button_box.props.sensitive = False self.lookup_action("translation").props.enabled = False src_language = self.src_lang_selector.selected dest_language = self.dest_lang_selector.selected src_text = self.src_buffer.get_text(self.src_buffer.get_start_iter(), self.src_buffer.get_end_iter(), True) dest_text = self.dest_buffer.get_text(self.dest_buffer.get_start_iter(), self.dest_buffer.get_end_iter(), True) if src_language == "auto": return # Switch all self.switch_all(src_language, dest_language, src_text, dest_text) def ui_from(self, _action, _param): self.src_lang_selector.button.popup() def ui_to(self, _action, _param): self.dest_lang_selector.button.popup() def ui_clear(self, _action, _param): self.src_buffer.props.text = "" self.src_buffer.emit("end-user-action") def set_font_size(self, size): self.src_text.font_size = size def ui_font_size_inc(self, _action, _param): self.src_text.font_size_inc() def ui_font_size_dec(self, _action, _param): self.src_text.font_size_dec() def ui_copy(self, _action, _param): dest_text = self.dest_buffer.get_text(self.dest_buffer.get_start_iter(), self.dest_buffer.get_end_iter(), True) clipboard = Gdk.Display.get_default().get_clipboard() clipboard.set(dest_text) def ui_paste(self, _action, _param): clipboard = Gdk.Display.get_default().get_clipboard() def on_paste(_clipboard, result): text = clipboard.read_text_finish(result) if text is not None: end_iter = self.src_buffer.get_end_iter() self.src_buffer.insert(end_iter, text) self.src_buffer.emit("end-user-action") cancellable = Gio.Cancellable() clipboard.read_text_async(cancellable, on_paste) def ui_suggest(self, _action, _param): self.dest_toolbar_stack.props.visible_child_name = "edit" self.before_suggest = self.dest_buffer.get_text( self.dest_buffer.get_start_iter(), self.dest_buffer.get_end_iter(), True ) self.dest_text.props.editable = True def ui_suggest_ok(self, _action, _param): def on_done(success): self.dest_toolbar_stack.props.visible_child_name = "default" if success: self.send_notification(_("New translation has been suggested!")) else: self.send_notification(_("Suggestion failed.")) self.dest_text.props.editable = False def on_fail(error: ProviderError): self.dest_toolbar_stack.props.visible_child_name = "default" self.send_notification(_("Suggestion failed.")) self.dest_text.props.editable = False dest_text = self.dest_buffer.get_text(self.dest_buffer.get_start_iter(), self.dest_buffer.get_end_iter(), True) src, dest = self.provider["trans"].denormalize_lang( self.provider["trans"].history[self.current_history].original[1], self.provider["trans"].history[self.current_history].original[2], ) self.provider["trans"].suggest( self.provider["trans"].history[self.current_history].original[0], src, dest, dest_text, on_done, on_fail ) self.before_suggest = None def ui_suggest_cancel(self, _action, _param): self.dest_toolbar_stack.props.visible_child_name = "default" if self.before_suggest is not None: self.dest_buffer.props.text = self.before_suggest self.before_suggest = None self.dest_text.props.editable = False def ui_src_voice(self, _action, _param): src_text = self.src_buffer.get_text(self.src_buffer.get_start_iter(), self.src_buffer.get_end_iter(), True) src_language = self.src_lang_selector.selected self._pre_speech(src_text, src_language, "src") def ui_dest_voice(self, _action, _param): dest_text = self.dest_buffer.get_text(self.dest_buffer.get_start_iter(), self.dest_buffer.get_end_iter(), True) dest_language = self.dest_lang_selector.selected self._pre_speech(dest_text, dest_language, "dest") def _pre_speech(self, text, lang, called_from): if text != "": self.voice_loading = True self.toggle_voice_spinner(True) self.current_speech = {"text": text, "lang": lang, "called_from": called_from} self.download_speech() def on_gst_message(self, _bus, message): if message.type == Gst.MessageType.EOS: self.player.set_state(Gst.State.NULL) elif message.type == Gst.MessageType.ERROR: self.player.set_state(Gst.State.NULL) logging.error("Some error occurred while trying to play.") def download_speech(self): def on_done(file): try: self._play_audio(file.name) file.close() except Exception as exc: logging.error(exc) self.on_listen_failed() else: self.toggle_voice_spinner(False) finally: self.voice_loading = False self.current_speech = {} def on_fail(_error: ProviderError): self.on_listen_failed() self.toggle_voice_spinner(False) if self.current_speech: lang = self.provider["tts"].denormalize_lang(self.current_speech["lang"]) self.provider["tts"].speech(self.current_speech["text"], lang, on_done, on_fail) else: self.toggle_voice_spinner(False) self.voice_loading = False def _play_audio(self, path): uri = "file://" + path self.player.set_property("uri", uri) self.player.set_state(Gst.State.PLAYING) @Gtk.Template.Callback() def _on_key_event(self, _button, keyval, _keycode, state): """Called on self.win_key_ctrlr::key-pressed signal""" modifiers = state & Gtk.accelerator_get_default_mod_mask() shift_mask = Gdk.ModifierType.SHIFT_MASK unicode_key_val = Gdk.keyval_to_unicode(keyval) if ( GLib.unichar_isgraph(chr(unicode_key_val)) and modifiers in (shift_mask, 0) and not self.dest_text.props.editable and not self.src_text.is_focus() ): self.src_text.grab_focus() end_iter = self.src_buffer.get_end_iter() self.src_buffer.insert(end_iter, chr(unicode_key_val)) return Gdk.EVENT_STOP return Gdk.EVENT_PROPAGATE @Gtk.Template.Callback() def _on_src_activated(self, _texview): """Called on self.src_text::active signal""" if not Settings.get().live_translation: self.translation() @Gtk.Template.Callback() def _on_mistakes_clicked(self, _button, _data): """Called on self.mistakes_label::activate-link signal""" self.mistakes.props.reveal_child = False self.src_buffer.props.text = self.trans_mistakes[1] # Run translation again self.translation() return Gdk.EVENT_STOP def on_src_text_changed(self, buffer): char_count = buffer.get_char_count() # If the text is over the highest number of characters allowed, it is truncated. # This is done for avoiding exceeding the limit imposed by translation services. if self.provider["trans"].chars_limit == -1: # -1 means unlimited self.char_counter.props.label = "" else: self.char_counter.props.label = f'{str(char_count)}/{self.provider["trans"].chars_limit}' if char_count >= self.provider["trans"].chars_limit: self.send_notification(_("{} characters limit reached!").format(self.provider["trans"].chars_limit)) buffer.delete(buffer.get_iter_at_offset(self.provider["trans"].chars_limit), buffer.get_end_iter()) sensitive = char_count != 0 self.lookup_action("translation").props.enabled = sensitive self.lookup_action("clear").props.enabled = sensitive if not self.voice_loading and self.provider["tts"]: self.lookup_action("listen-src").set_enabled( self.src_lang_selector.selected in self.provider["tts"].tts_languages and sensitive ) elif not self.voice_loading and not self.provider["tts"]: self.lookup_action("listen-src").props.enabled = sensitive def on_dest_text_changed(self, buffer): sensitive = buffer.get_char_count() != 0 self.lookup_action("copy").props.enabled = sensitive self.lookup_action("suggest").set_enabled( ProviderFeature.SUGGESTIONS in self.provider["trans"].features and sensitive ) if not self.voice_loading and self.provider["tts"]: self.lookup_action("listen-dest").set_enabled( self.dest_lang_selector.selected in self.provider["tts"].tts_languages and sensitive ) elif not self.voice_loading and self.provider["tts"] is not None and not self.provider["tts"].tts_languages: self.lookup_action("listen-dest").props.enabled = sensitive def user_action_ended(self, _buffer): if Settings.get().live_translation: self.translation() # The history part def reset_return_forward_btns(self): self.lookup_action("back").props.enabled = self.current_history < len(self.provider["trans"].history) - 1 self.lookup_action("forward").props.enabled = self.current_history > 0 # Retrieve translation history def history_update(self): self.reset_return_forward_btns() translation = self.provider["trans"].history[self.current_history] self.src_lang_selector.selected = translation.original[1] self.dest_lang_selector.selected = translation.original[2] self.src_buffer.props.text = translation.original[0] self.dest_buffer.props.text = translation.text def appeared_before(self): src_language = self.src_lang_selector.selected dest_language = self.dest_lang_selector.selected src_text = self.src_buffer.get_text(self.src_buffer.get_start_iter(), self.src_buffer.get_end_iter(), True) if ( len(self.provider["trans"].history) >= self.current_history + 1 and (self.provider["trans"].history[self.current_history].original[1] == src_language or "auto") and self.provider["trans"].history[self.current_history].original[2] == dest_language and self.provider["trans"].history[self.current_history].original[0] == src_text ): return True return False @Gtk.Template.Callback() def translation(self, _action=None, _param=None): # If it's like the last translation then it's useless to continue if not self.appeared_before(): src_text = self.src_buffer.get_text(self.src_buffer.get_start_iter(), self.src_buffer.get_end_iter(), True) src_language = self.src_lang_selector.selected dest_language = self.dest_lang_selector.selected if self.ongoing_trans: self.next_trans = {"text": src_text, "src": src_language, "dest": dest_language} return if self.next_trans: src_text = self.next_trans["text"] src_language = self.next_trans["src"] dest_language = self.next_trans["dest"] self.next_trans = {} # Show feedback for start of translation. self.translation_loading() # If the two languages are the same, nothing is done if src_language != dest_language: if src_text != "": self.ongoing_trans = True src, dest = self.provider["trans"].denormalize_lang(src_language, dest_language) self.provider["trans"].translate( src_text, src, dest, self.on_translation_success, self.on_translation_fail ) else: self.trans_mistakes = (None, None) self.trans_src_pron = None self.trans_dest_pron = None self.dest_buffer.props.text = "" if not self.ongoing_trans: self.translation_finish() def on_translation_success(self, translation: Translation): self.trans_warning.props.visible = False if translation.detected and self.src_lang_selector.selected == "auto": if Settings.get().src_auto: self.src_lang_selector.set_insight(self.provider["trans"].normalize_lang_code(translation.detected)) else: self.src_lang_selector.selected = translation.detected self.dest_buffer.props.text = translation.text self.trans_mistakes = translation.mistakes self.trans_src_pron = translation.pronunciation[0] self.trans_dest_pron = translation.pronunciation[1] # Finally, translation is saved in history self.add_history_entry(translation) # Mistakes if ProviderFeature.MISTAKES in self.provider["trans"].features and not self.trans_mistakes == (None, None): self.mistakes_label.set_markup(_("Did you mean: ") + f'{self.trans_mistakes[0]}') self.mistakes.props.reveal_child = True elif self.mistakes.props.reveal_child: self.mistakes.props.reveal_child = False # Pronunciation reveal = Settings.get().show_pronunciation if ProviderFeature.PRONUNCIATION in self.provider["trans"].features: if self.trans_src_pron is not None and self.trans_mistakes == (None, None): self.src_pron_label.props.label = self.trans_src_pron self.src_pron_revealer.props.reveal_child = reveal elif self.src_pron_revealer.props.reveal_child: self.src_pron_revealer.props.reveal_child = False if self.trans_dest_pron is not None: self.dest_pron_label.props.label = self.trans_dest_pron self.dest_pron_revealer.props.reveal_child = reveal elif self.dest_pron_revealer.props.reveal_child: self.dest_pron_revealer.props.reveal_child = False self.ongoing_trans = False if self.next_trans: self.translation() else: self.translation_finish() def on_translation_fail(self, error: ProviderError): if not self.next_trans: self.translation_finish() self.trans_warning.props.visible = True self.lookup_action("copy").props.enabled = False self.lookup_action("listen-src").props.enabled = False self.lookup_action("listen-dest").props.enabled = False match error.code: case ProviderErrorCode.NETWORK: self.send_notification( _("Translation failed, check for network issues"), action={ "label": _("Retry"), "name": "win.translation", }, ) case ProviderErrorCode.API_KEY_INVALID: self.send_notification( _("The provided API key is invalid"), action={ "label": _("Retry"), "name": "win.translation", }, ) case ProviderErrorCode.API_KEY_REQUIRED: self.send_notification( _("API key is required to use the service"), action={ "label": _("Preferences"), "name": "app.preferences", }, ) case _: self.send_notification( _("Translation failed"), action={ "label": _("Retry"), "name": "win.translation", }, ) def translation_loading(self): self.trans_spinner.show() self.trans_spinner.start() self.dest_box.props.sensitive = False self.langs_button_box.props.sensitive = False def translation_finish(self): self.trans_spinner.stop() self.trans_spinner.hide() self.dest_box.props.sensitive = True self.langs_button_box.props.sensitive = True def reload_translator(self): self.translator_loading = True # Load translator self.load_translator() def _on_active_provider_changed(self, _settings, _provider, kind): self.save_settings() match kind: case "trans": self.reload_translator() case "tts": self.load_tts() def _on_provider_changed(self, _settings, _key, name): if not self.translator_loading: if name == self.provider["trans"].name: self.reload_translator() if name == self.provider["tts"].name: self.load_tts() dialect-2.4.2/meson.build000066400000000000000000000040251465154363000152760ustar00rootroot00000000000000project('dialect', version: '2.4.2', meson_version: '>= 0.59.0', default_options: [ 'warning_level=2', ], ) python = import('python') i18n = import('i18n') base_id = 'app.drey.Dialect' pkgdatadir = join_paths(get_option('prefix'), get_option('datadir'), meson.project_name()) moduledir = join_paths(pkgdatadir, 'dialect') if get_option('profile') == 'development' profile = 'Devel' vcs_tag = run_command('git', 'rev-parse', '--short', 'HEAD').stdout().strip() if vcs_tag == '' version_suffix = '-devel' else version_suffix = '-@0@'.format(vcs_tag) endif application_id = '@0@.@1@'.format(base_id, profile) object_path = '/app/drey/Dialect/Devel/SearchProvider' else profile = '' version_suffix = '' application_id = base_id object_path = '/app/drey/Dialect/SearchProvider' endif conf = configuration_data() conf.set('PYTHON', python.find_installation('python3').full_path()) conf.set('PROFILE', profile) conf.set('VERSION', meson.project_version() + version_suffix) conf.set('APP_ID', application_id) conf.set('BIN', join_paths(get_option('prefix'), get_option('bindir'), meson.project_name())) conf.set('object_path', object_path) conf.set('pkgdatadir', pkgdatadir) conf.set('datadir', get_option('datadir')) conf.set('prefix', get_option('prefix')) conf.set('localedir', join_paths(get_option('prefix'), get_option('localedir'))) message('Looking for dependencies') py_installation = python.find_installation('python3') if not py_installation.found() error('No valid python3 binary found') else message('Found python3 binary') endif dependency('glib-2.0') dependency('gobject-introspection-1.0', version: '>= 1.35.0') dependency('gstreamer-1.0', version: '>= 1.18') dependency('gtk4', version: '>= 4.6') dependency('libadwaita-1', version: '>= 1.0') dependency('libsoup-3.0') dependency('pygobject-3.0', version: '>= 3.40') subdir('data') subdir('dialect') subdir('po') gnome.post_install( gtk_update_icon_cache: true, glib_compile_schemas: true, update_desktop_database: true, ) dialect-2.4.2/meson_options.txt000066400000000000000000000002661465154363000165740ustar00rootroot00000000000000option( 'profile', type: 'combo', choices: [ 'default', 'development' ], value: 'default', description: 'The build profile. One of "default" or "development".' ) dialect-2.4.2/po/000077500000000000000000000000001465154363000135515ustar00rootroot00000000000000dialect-2.4.2/preview-2.png000066400000000000000000001103131465154363000154600ustar00rootroot00000000000000PNG  IHDRt zTXtRaw profile type exifxڥkr$+Yo@fwwYґj#UweU& p;?˥Izr=>}>ׇOλQ_#G Rcx;ʇD_ =?(_&!Ey&ꯉR|.y,_0s|޲|6 :)ƝB. p߅>gk2玙)*DF+אyʗ }q,i.<}?gɹS\qu}=#O,aKô S꼄VRay"18!F8aߣ1jL{TRW8ɕ {Nݖp^]MXydo_oo8J!e+W93,r0"˩:⚈`1/[t;)f AN , m&E,]0&$"@B*bl!H!@cqPJ\sJPI,--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eMN!7fT1bxKĄb a~8GAKb^dGфK#V{|:(CUr|F g ?$P? C%xIENDB`dialect-2.4.2/pyproject.toml000066400000000000000000000001321465154363000160430ustar00rootroot00000000000000[tool.black] line-length = 120 [tool.ruff] line-length = 120 builtins = ["_", "gettext"] dialect-2.4.2/requirements.txt000066400000000000000000000000231465154363000164120ustar00rootroot00000000000000gtts beautifulsoup4dialect-2.4.2/setup.cfg000066400000000000000000000001641465154363000147550ustar00rootroot00000000000000[flake8] max-line-length = 120 exclude = build-aux/flatpak max-complexity = 15 [pycodestyle] max-line-length = 120 dialect-2.4.2/subprojects/000077500000000000000000000000001465154363000154765ustar00rootroot00000000000000dialect-2.4.2/subprojects/blueprint-compiler.wrap000066400000000000000000000002621465154363000222050ustar00rootroot00000000000000[wrap-git] directory = blueprint-compiler url = https://gitlab.gnome.org/jwestman/blueprint-compiler.git revision = v0.4.0 depth = 1 [provide] program_names = blueprint-compiler