├── .flake8 ├── .github └── workflows │ └── ci.yml ├── .gitignore ├── .gitmodules ├── .pre-commit-config.yaml ├── .pylintrc ├── README.md ├── addon.json ├── ankiweb.html ├── pyproject.toml ├── requirements.txt ├── screenshots ├── Back.jpg ├── Front.jpg ├── configuration.png ├── main_features.gif ├── main_features.mp4 ├── main_features_note.png └── one_by_one.mp4 ├── scripts └── run.sh └── src └── enhanced_cloze ├── LICENSE ├── __init__.py ├── ankiaddonconfig ├── .gitignore ├── LICENSE ├── README.md ├── __init__.py ├── errors.py ├── manager.py ├── mypy.ini └── window.py ├── compat.py ├── config.json ├── config.py ├── constants.py ├── editor.py ├── manifest.json ├── menu.py ├── model.py ├── note_type ├── Enhanced_Cloze_Back_Side.html ├── Enhanced_Cloze_CSS.css ├── Enhanced_Cloze_Front_Side.html └── model.py ├── patches.py ├── resources └── _jquery.min.js └── setup_jquery.py /.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | max-line-length = 120 3 | ignore = E722, E203, W503 4 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: tests 2 | 3 | on: 4 | push: 5 | branches: 6 | - "master" 7 | pull_request: 8 | 9 | jobs: 10 | test: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/setup-python@v4 14 | with: 15 | python-version: "3.9" 16 | 17 | - name: Checkout add-on repo 18 | uses: actions/checkout@v3 19 | 20 | - name: Install deps 21 | run: | 22 | python -m pip install -r ./requirements.txt 23 | 24 | - name: Run pre-commit 25 | run: pre-commit run --all-files 26 | 27 | - name: Run mypy 28 | run: mypy 29 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *code-workspace 2 | 3 | meta.json 4 | 5 | *.pyc 6 | __pycache__/ 7 | src/*/__pycache__/ 8 | 9 | *.ankiaddon 10 | 11 | .env/ 12 | .venv/ 13 | env/ 14 | venv/ 15 | build/ 16 | tools/ 17 | profile/ 18 | 19 | .vscode/ 20 | .idea/ 21 | 22 | .directory 23 | 24 | *___bak_* 25 | *___note* 26 | 27 | .gitignore 28 | checksums.csv 29 | 30 | old/* 31 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "anki_"] 2 | path = anki 3 | url = https://github.com/ankitects/anki 4 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | exclude: "(src/anking_notetypes/note_types)|(src/enhanced_cloze/ankiaddonconfig)" 2 | repos: 3 | - repo: https://github.com/pre-commit/pre-commit-hooks 4 | rev: v4.1.0 5 | hooks: 6 | - id: trailing-whitespace 7 | - id: end-of-file-fixer 8 | - id: check-yaml 9 | 10 | - repo: https://github.com/psf/black 11 | rev: 22.3.0 12 | hooks: 13 | - id: black 14 | 15 | - repo: https://github.com/pycqa/isort 16 | rev: 5.12.0 17 | hooks: 18 | - id: isort 19 | args: ["--diff"] 20 | 21 | - repo: https://github.com/pycqa/flake8 22 | rev: 4.0.1 23 | hooks: 24 | - id: flake8 25 | 26 | - repo: https://github.com/pycqa/pylint 27 | rev: v2.14.0 28 | hooks: 29 | - id: pylint 30 | language: python 31 | types: [python] 32 | additional_dependencies: [aqt] 33 | args: 34 | [ 35 | "-rn", # Only display messages 36 | "-sn", # Don't display the score 37 | ] 38 | -------------------------------------------------------------------------------- /.pylintrc: -------------------------------------------------------------------------------- 1 | [MESSAGES CONTROL] 2 | disable= 3 | C, # convention 4 | R, # refactoring 5 | bare-except, 6 | unnecessary-lambda, 7 | raise-missing-from, 8 | unspecified-encoding, 9 | redefined-outer-name, 10 | redefined-builtin, 11 | attribute-defined-outside-init, 12 | 13 | 14 | [TYPECHECK] 15 | ignored-modules=aqt.qt 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Enhanced cloze 2.1 2 | This add-on allows to improve clozes usage. See the [AnkiWeb page](https://ankiweb.net/shared/info/1990296174) for more details. 3 | 4 | 5 | ## Links, licence and credits 6 | 7 | Key |Value 8 | -----------------|------------------------------------------------------------------- 9 | Version 2.0 by | [https://github.com/luzhe610/anki-enhanced-cloze](luzhe610) 10 | Ported to 2.1 by | Arthur Milchior 11 | Based on | Anki code by Damien Elmes 12 | License | GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html 13 | Support luzhe610 | https://www.paypal.me/LuZhe610 14 | Support Arthur | [![Ko-fi](https://ko-fi.com/img/Kofi_Logo_Blue.svg)](Ko-fi.com/arthurmilchior) or [![Patreon](http://www.milchior.fr/patreon.png)](https://www.patreon.com/bePatron?u=146206) 15 | -------------------------------------------------------------------------------- /addon.json: -------------------------------------------------------------------------------- 1 | { 2 | "display_name": "Enhanced Cloze", 3 | "module_name": "enhanced_cloze", 4 | "repo_name": "anki-enhanced-cloze", 5 | "ankiweb_id": "1990296174", 6 | "author": "RisingOrange", 7 | "conflicts": [], 8 | "targets": [ 9 | "anki21" 10 | ] 11 | } 12 | -------------------------------------------------------------------------------- /ankiweb.html: -------------------------------------------------------------------------------- 1 | Cloze notes are very powerful for spaced repetition softwares like Anki. This add-on along with the attached note type 2 | aims to improve Anki's mechanism of displaying clozes and offers great features for better user interaction. 3 | 4 | The name of the note type the add-on uses is "Enhanced Cloze 2.1 v2". 5 | 6 | Preview 7 | 8 | 9 | 10 | 11 | Improved Mechanism of Displaying Clozes 12 | - Take card1 for example. 13 | - All c1 clozes (called "genuine clozes") will be red. 14 | - All other clozes (called "pseudo clozes" for this card), eg. c2, c3 will be blue. 15 | - On the front of the card, all clozes (genuine or pseudo) will be shown as their hint (if one exists) or empty. 16 | - You can show the answer of every cloze (genuine or pseudo) by clicking it. 17 | - This means you can think about a genuize cloze and check the answer one by one without getting hints from pseudo-clozes and genuine clozes after it. 18 | 19 | Handy Keyboard And Touchscreen Shortcut 20 | You can... 21 | - uncover genuine clozes one by one using the keyboard shortcut [J] (conifgurable) or by touching the left border of the card. 22 | - uncover pseudo clozes one by one using the keyboard shortcut [N] (conifgurable) or by touching the right border of the card 23 | - toggle all genuine clozes using the keyboard shortcut [Shift+J] (conifgurable) border. 24 | - toggle all pseudo clozes using the keyboard shortcut [Shift+N] (conifgurable) border. 25 | - This makes uncovering clozes super convenient, no matter whether it's on a computer using the keyboard or on a mobile phone. 26 | - You can edit the shortcut keys in the config (Tools -> Enhanced Cloze -> Config) 27 | 28 | Auto Scroll To The Relevant Cloze 29 | - The card will scroll to the first genuine cloze at the very beginning. 30 | - When you use shortcut to uncover clozes one by one, if the next cloze is out of view (common situation on mobile phones with small screen), the card will automatically scroll to it. This makes for a super fluent experience of answering cards. The behaviour can be turned off (Tools -> Enhanced Cloze -> Config). 31 | 32 | Can Be Used In No-Cloze Basic Mode 33 | - It is also Ok to go without clozes using this note type. (Note: Creating such notes only works on Anki Desktop, not on mobile!) Just type the question in the Content field and the answer in the Note field. The Note field will be hidden on the front of the card and shown on the back of the card, just like with the Basic note type. 34 | - Anki won't warn you that no clozes are found. 35 | 36 | "Normal" clozes 37 | - If you want a cloze to alway be displayed when it's a pseudo cloze, prepend the answer with a #-sign like this: {{c1::#some text}}. 38 | 39 | Usage 40 | - Select the "Enhanced Cloze 2.1 v2" note type in the editor 41 | - Write down anything in the Content field, whether with clozes like {{c1::abc}} or not, the add-on will process the note intelligently. 42 | - For you information, you can create clozes with increasing numbers like {{c1::aa}} {{c2::bb}} with Ctrl+Shift+C and clozes with the same number like {{c1::aa}} {{c1::bb}}. 43 | - I'd recommend you to group several closely related pieces of information to use the same cloze number and review them together on a card for convenience; use different cloze numbers to turn you informative note into several cards to maximize review efficiency. 44 | - When you have the Edit Field During Review (Cloze) add-on installed, Ctrl+Click fields to edit them. 45 | 46 | Configuration 47 | 48 | 49 | 50 | To open this dialog, select Tools -> Enhanced Cloze -> Config. 51 | If the underline options do not work, try using "Reset Enhanced Clozes css to default" from the Tools menu of the main 52 | window. 53 | 54 | Credits 55 | The 2022-02-04 - update was inspired by TRIAEIOU's Flexible Cloze add-on 56 | This add-on is a fork of https://github.com/ijgnd/anki-enhanced-cloze by ijgnd 57 | Previous version of the add-on by Arthur Milchior: https://github.com/Arthur-Milchior/anki-enhanced-cloze 58 | Previous version of the add-on by LuZhe610: https://ankiweb.net/shared/info/873439973 59 | Thanks to BlueGreenMagick for creating the ankiaddonconfig package used in this add-on. 60 | 61 | Problems, Bugs, Errors, Improvements 62 | If you have an idea for an improvement or encounter a problem please create an issue on Github. 63 | 64 | Support my work 65 | If this add-on is useful to you please consider buying me a coffee: 66 | 67 | 68 | 69 | Changelog 70 | 2023-09-10: Toggling clozes on mobile is less finicky now. Fixed config values not getting read into config properly. 71 | Fixed note type changes not always getting synced to AnkiWeb. 72 | 73 | 2023-08-27: Fix for note type not working when reviewing on AnkiWeb 74 | 75 | 2023-07-26: Added config dialog (Tools -> Enhanced Cloze -> Config) 76 | 77 | 2023-07-25: Added option to swap left and right border actions 78 | 79 | 2023-04-26: Fix basic-mode clozes on AnkiDroid on Anki >= 2.1.61 80 | 81 | 2022-11-15: Fix incompatibility with CrowdAnki 82 | 83 | 2022-07-21: Changes to actions in the Tools menu. 84 | 85 | 2022-07-19: Fixed the Extra field. To get the fixed note type you have to go to Tools -> "Reset Enhanced Cloze note 86 | type to default" on the main Anki window 87 | 88 | 2022-07-15: Added option to reveal pseudo-clozes by default 89 | 90 | 2022-04-22: Added compatibility with Edit Field 91 | During Review (Cloze) add-on, added option to not underline revealed clozes 92 | 93 | 2022-03-18: Fixes for iOS, other fixes 94 | 95 | 2022-03-15: Added option to disable hints for pseudo clozes (showHintsForPseudoClozes on the front card template) 96 | 97 | 2022-03-15: Added option to reset note type to default version (it's in the main window in the Tools menu) 98 | 99 | 2022-02-09: Added option to disable scroll animation (animateScroll = false). Force a full sync to get the new version 100 | 101 | to your mobile device (Preferences -> Network -> Check "On next sync force changes in one direction") 102 | 103 | 2022-02-09: Shortcuts now reveal only one cloze even if multiple clozes have the same id 104 | 105 | 2022-02-04: Big update: Adding/Editing on mobile works now, removed unnecessary fields (Thanks to TRIAEIOU for showing how to do this), added shortcuts, some fixes 106 | 107 | 2022-01-28: Update for Anki 2.1.50 108 | 109 | 2021-10-20: Fixed incompatibility with Field during 110 | Review (Cloze) (cards work now, but you still can't edit them during review) 111 | 112 | 2021-10-15: Fixed images not working in the Content field (again, because the first fix was not complete) 113 | 114 | 2021-9-31: Fixed touches not working properly on iOS devices 115 | 116 | 2021-9-22: Fixed mathjax not working inside of clozes 117 | 118 | 2021-9-16: Fixed images not working in first field 119 | 120 | 2021-9-14: Fixed incompatibility with Popup-dictionary 121 | 122 | 2021-9-08: Fixed no-cloze-mode on Ankidroid (force sync collection from desktop to phone to make it work) + clozes start 123 | at 1 when using the shortcut in the editor 124 | 125 | 2021-8-28: Add-on doesn't overwrite changes of the note type now (you can add new fields, just don't delete the existing 126 | ones) 127 | 128 | 2021-8-26: You can now have 50 clozes on one note if you want to (before this update the limit was 20) 129 | 130 | 2021-8-19: Added backwards compatibility down to Anki 2.1.28 131 | 132 | 2021-8-18: Fixed no cloze mode 133 | 134 | 2021-8-17: Fixed "type in the answer" message showing up on mobile, Fixed "show one cloze" hotkey action 135 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.mypy] 2 | files=[ 3 | "src/enhanced_cloze", 4 | ] 5 | no_strict_optional = true 6 | check_untyped_defs = true 7 | 8 | [[tool.mypy.overrides]] 9 | module = "enhanced_cloze.ankiaddonconfig.*" 10 | ignore_errors = true 11 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | aqt==2.1.65 2 | black==23.7.0 3 | mypy==1.4.1 4 | mypy-extensions==1.0.0 5 | pre-commit==3.3.3 6 | pylint==2.17.4 7 | PyQt6==6.5.2 8 | PyQt6-Qt6==6.5.2 9 | PyQt6-sip==13.5.2 10 | PyQt6-WebEngine==6.5.0 11 | PyQt6-WebEngine-Qt6==6.5.2 12 | -------------------------------------------------------------------------------- /screenshots/Back.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RisingOrange/anki-enhanced-cloze/f6cf396ebe2729f9d214021db4d67d1de4b9a283/screenshots/Back.jpg -------------------------------------------------------------------------------- /screenshots/Front.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RisingOrange/anki-enhanced-cloze/f6cf396ebe2729f9d214021db4d67d1de4b9a283/screenshots/Front.jpg -------------------------------------------------------------------------------- /screenshots/configuration.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RisingOrange/anki-enhanced-cloze/f6cf396ebe2729f9d214021db4d67d1de4b9a283/screenshots/configuration.png -------------------------------------------------------------------------------- /screenshots/main_features.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RisingOrange/anki-enhanced-cloze/f6cf396ebe2729f9d214021db4d67d1de4b9a283/screenshots/main_features.gif -------------------------------------------------------------------------------- /screenshots/main_features.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RisingOrange/anki-enhanced-cloze/f6cf396ebe2729f9d214021db4d67d1de4b9a283/screenshots/main_features.mp4 -------------------------------------------------------------------------------- /screenshots/main_features_note.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RisingOrange/anki-enhanced-cloze/f6cf396ebe2729f9d214021db4d67d1de4b9a283/screenshots/main_features_note.png -------------------------------------------------------------------------------- /screenshots/one_by_one.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RisingOrange/anki-enhanced-cloze/f6cf396ebe2729f9d214021db4d67d1de4b9a283/screenshots/one_by_one.mp4 -------------------------------------------------------------------------------- /scripts/run.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | declare DIR="$(cd "$(dirname "$0")/.." && pwd -P)" 3 | set -e 4 | 5 | # cd "$DIR"; 6 | # git submodule update --init 7 | 8 | cd "$DIR/anki"; 9 | ANKI_BASE="$DIR/profile" "$DIR/anki/tools/ts-run" 10 | -------------------------------------------------------------------------------- /src/enhanced_cloze/LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /src/enhanced_cloze/__init__.py: -------------------------------------------------------------------------------- 1 | from aqt.gui_hooks import profile_did_open 2 | 3 | from .compat import add_compatibility_aliases 4 | from .config import setup_config 5 | from .editor import setup_editor 6 | from .setup_jquery import setup_maybe_add_jquery_to_media_folder 7 | from .menu import setup_enhanced_cloze_menu 8 | from .model import setup_maybe_update_model_on_startup 9 | from .patches import setup_prevent_warnings_about_clozes 10 | 11 | profile_did_open.append(add_compatibility_aliases) 12 | 13 | setup_config() 14 | setup_maybe_add_jquery_to_media_folder() 15 | setup_maybe_update_model_on_startup() 16 | setup_editor() 17 | setup_enhanced_cloze_menu() 18 | setup_prevent_warnings_about_clozes() 19 | -------------------------------------------------------------------------------- /src/enhanced_cloze/ankiaddonconfig/.gitignore: -------------------------------------------------------------------------------- 1 | # JS related 2 | node_modules 3 | 4 | # Byte-compiled / optimized / DLL files 5 | __pycache__/ 6 | *.py[cod] 7 | *$py.class 8 | 9 | # C extensions 10 | *.so 11 | 12 | # Distribution / packaging 13 | .Python 14 | build/ 15 | develop-eggs/ 16 | dist/ 17 | downloads/ 18 | eggs/ 19 | .eggs/ 20 | lib/ 21 | lib64/ 22 | parts/ 23 | sdist/ 24 | var/ 25 | wheels/ 26 | *.egg-info/ 27 | .installed.cfg 28 | *.egg 29 | MANIFEST 30 | 31 | # PyInstaller 32 | # Usually these files are written by a python script from a template 33 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 34 | *.manifest 35 | *.spec 36 | 37 | # Installer logs 38 | pip-log.txt 39 | pip-delete-this-directory.txt 40 | 41 | # Unit test / coverage reports 42 | htmlcov/ 43 | .tox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | 53 | # Translations 54 | *.mo 55 | *.pot 56 | 57 | # Django stuff: 58 | *.log 59 | local_settings.py 60 | db.sqlite3 61 | 62 | # Flask stuff: 63 | instance/ 64 | .webassets-cache 65 | 66 | # Scrapy stuff: 67 | .scrapy 68 | 69 | # Sphinx documentation 70 | docs/_build/ 71 | 72 | # PyBuilder 73 | target/ 74 | 75 | # Jupyter Notebook 76 | .ipynb_checkpoints 77 | 78 | # pyenv 79 | .python-version 80 | 81 | # celery beat schedule file 82 | celerybeat-schedule 83 | 84 | # SageMath parsed files 85 | *.sage.py 86 | 87 | # Environments 88 | .env 89 | .venv 90 | env/ 91 | venv/ 92 | ENV/ 93 | env.bak/ 94 | venv.bak/ 95 | 96 | # Spyder project settings 97 | .spyderproject 98 | .spyproject 99 | 100 | # Rope project settings 101 | .ropeproject 102 | 103 | # mkdocs documentation 104 | /site 105 | 106 | # mypy 107 | .mypy_cache/ 108 | *~ 109 | -------------------------------------------------------------------------------- /src/enhanced_cloze/ankiaddonconfig/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Yoonchae Lee 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/enhanced_cloze/ankiaddonconfig/README.md: -------------------------------------------------------------------------------- 1 | # ankiaddonconfig 2 | 3 | This package was born out of a desire to make creating a gui config window as painless as possible. You can also use it as a shorthand to manage the config as well. To use this package, download(clone) the repo and put it in your addon. 4 | Used in my add-ons [Edit Field During Review (Cloze)](https://github.com/BlueGreenMagick/Edit-Field-During-Review-Cloze/), [Review Hotmouse](https://github.com/BlueGreenMagick/Review-Hotmouse), [ReColor](https://github.com/AnKingMed/AnkiRecolor) and other private add-ons. 5 | 6 | ## Creating a custom config window 7 | 8 | ```python 9 | from .ankiaddonconfig import ConfigManager, ConfigWindow 10 | 11 | conf = ConfigManager() 12 | 13 | def general_tab(conf_window: ConfigWindow) -> None: 14 | tab = conf_window.add_tab("General") 15 | tab.text("Addon Config") 16 | tab.checkbox("use_fruit", "Should this addon use a fruit?") 17 | 18 | fruit_labels = ["Apples", "Pears", "Grapes"] # Shown to the user in the config window 19 | fruit_values = ["apple", "pear", "grape"] # Actual value the json config will have 20 | tab.dropdown("fruit", fruit_labels, fruit_values) 21 | 22 | tab.color_input("apple.color", "Color of the apple:") 23 | 24 | # This adds a stretchable blank space. 25 | # If you are not sure what this does, 26 | # Try resizing the config window without this line 27 | tab.stretch() 28 | 29 | conf.use_custom_window() 30 | conf.add_config_tab(general_tab) 31 | ``` 32 | 33 | When the user opens the config window, a ConfigWindow object is created. Then before it is shown, every function you registered with `conf.add_config_tab` is run. 34 | 35 | Each widget is linked to a single config entry. When the user interacts with a widget and saves it, its corresponding config entry is modified and saved in the ConfigManager real-time. The config entry key that it will be linked to is passed as the first argument to the input widget. When you have a dictionary inside your config, you can link a config widget to one of its value using `"dict_name.dict_key"`. The config that ConfigManager stores will be saved to `meta.json` if 'Save' is clicked and discarded if 'Cancel' is clicked. 36 | 37 | Each ConfigManager instance stores its own config separately. And its configs are synced with `meta.json` only when `load()` and `save()` is called. This is intended so the config value changing while the add-on is running will not cause unanticipated errors. You should only call `conf.load()` when it is safe to do so. With that in mind, it is recommended to use separate ConfigManager instances for your config window. 38 | 39 | 40 | ## Add to your project 41 | 42 | To download ankiaddonconfig to your project: 43 | ```sh 44 | git remote add ankiaddonconfig 45 | git subtree add --prefix ankiaddonconfig master --squash 46 | ``` 47 | 48 | If you want to pull new changes in ankiaddonconfig: 49 | ```sh 50 | git subtree pull --prefix ankiaddonconfig master --squash 51 | ``` 52 | 53 | ## Compatibility 54 | 55 | This library is compatible from Anki v2.1.0+. And atleast python v3.6. 56 | It should also remain compatible with newer Anki versions for a long time. 57 | 58 | ## Basic Documentation 59 | ### Methods in ConfigLayout 60 | When you call `ConfigWindow.add_tab(name)`, you get a ConfigLayout object. 61 | Creating the widgets is done in ConfigLayout. All the below methods are methods of the ConfigLayout. 62 | 63 | 64 | List of all inputs. 65 | 66 | ```python 67 | def checkbox(self, key: str, description: str = "") -> QCheckBox: 68 | assert isinstance(conf[key], bool) 69 | def dropdown(self, key: str, labels: list, values: list, description: Optional[str] = None) -> QComboBox: 70 | assert conf[key] in values 71 | def text_input(self, key: str, description: Optional[str] = None) -> QLineEdit: 72 | assert isinstance(conf[key], str) 73 | def number_input(self, key: str, description: Optional[str] = None, 74 | minimum: int = 0, maximum: int = 99, step: int = 1, 75 | decimal: bool = False, precision: int = 2) -> QSpinBox | QDoubleSpinBox: 76 | if decimal: 77 | assert isinstance(conf[key], int | bool) 78 | else: 79 | assert isinstance(conf[key], int) 80 | def color_input(self, key: str, description: Optional[str] = None) -> QPushButton: 81 | assert conf[key] is 'a hex color string like "#000", "#000000" that QColor can understand' 82 | def path_input(self, key: str, description: Optional[str] = None, get_directory: bool = False, filter="Any files (*)") 83 | -> Tuple[QLineEdit, QPushButton]: 84 | assert isinstance(conf[key], str) 85 | ``` 86 | 87 | Commonly used methods: 88 | ```python 89 | def text(self, text: str, bold: bool = False, html: bool = False, size: int = 0, multiline: bool = False) -> QLabel: 90 | # Text label. `size`: font size 91 | def space(self, space: int = 1) -> None: 92 | # Space between widgets 93 | def stretch(self, factor: int = 0) -> None: 94 | # Stretch spacing for when window resizes 95 | def hlayout(self) -> ConfigLayout: 96 | # Left to right ConfigLayout 97 | def vlayout(self) -> ConfigLayout: 98 | # Top to bottom ConfigLayout 99 | ``` 100 | 101 | ### Using ConfigManager 102 | ```python 103 | from .ankiaddon import ConfigManager 104 | conf = ConfigManager() 105 | 106 | fruit = conf["fruit"] 107 | 108 | conf["fruit"] = "apple" 109 | conf.save() # Save conf to disk 110 | ``` 111 | 112 | If you have a dictionary in your config, you can also do this: 113 | ```python 114 | value = conf.get("apple.color", "#ff0000") # conf["apple.color"] will raise KeyError if it doesn't exist 115 | conf["apple.color"] = "#ffff00" 116 | 117 | apple_color = conf.pop("apple.color") 118 | del conf["apple.size"] 119 | ``` 120 | 121 | Other features: 122 | ```python 123 | conf.load() # discards current config and loads config from disk. 124 | conf.get_default("fruit") # returns the value set in config.json 125 | conf.to_json() # returns a json copy of the config 126 | conf.clone() # returns a deepcopy of the config dictionary 127 | ``` 128 | 129 | ## Contributing 130 | 131 | Please run mypy and black before creating a pull request. You may need to run `python -m pip install aqt PyQt5-stubs` for mypy checks to work. 132 | ``` 133 | python -m mypy . 134 | python -m black . 135 | ``` 136 | 137 | -------------------------------------------------------------------------------- /src/enhanced_cloze/ankiaddonconfig/__init__.py: -------------------------------------------------------------------------------- 1 | from .manager import ConfigManager 2 | from .window import ConfigWindow, ConfigLayout 3 | -------------------------------------------------------------------------------- /src/enhanced_cloze/ankiaddonconfig/errors.py: -------------------------------------------------------------------------------- 1 | from typing import Any 2 | 3 | 4 | class InvalidConfigValueError(Exception): 5 | def __init__(self, key: str, expected: str, value: Any): 6 | self.key = key 7 | self.expected = expected 8 | self.value = value 9 | 10 | def __str__(self) -> str: 11 | return f"For config: {self.key}\nexpected value is: {self.expected}\nbut instead encountered: {self.value}" 12 | -------------------------------------------------------------------------------- /src/enhanced_cloze/ankiaddonconfig/manager.py: -------------------------------------------------------------------------------- 1 | import json 2 | import copy 3 | from typing import Any, Callable, Dict, Iterator, List, Optional 4 | 5 | from aqt import mw 6 | from aqt.qt import * 7 | 8 | from .window import ConfigWindow 9 | 10 | 11 | class ConfigManager: 12 | def __init__(self) -> None: 13 | self.config_window: Optional[ConfigWindow] = None 14 | self.window_open_hook: List[Callable[[ConfigWindow], None]] = [] 15 | self._config: Dict 16 | addon_dir = __name__.split(".")[0] 17 | self.addon_dir = addon_dir 18 | try: 19 | self.addon_name = mw.addonManager.addon_meta(addon_dir).human_name() 20 | except: 21 | self.addon_name = mw.addonManager.addonName(addon_dir) 22 | self._default = mw.addonManager.addonConfigDefaults(addon_dir) 23 | self.load() 24 | 25 | def load(self) -> None: 26 | "Loads config from disk" 27 | self._config = mw.addonManager.getConfig(self.addon_dir) 28 | 29 | def save(self) -> None: 30 | "Writes its config data to disk." 31 | mw.addonManager.writeConfig(self.addon_dir, self._config) 32 | 33 | def load_defaults(self) -> None: 34 | "call .save() afterwards to restore defaults." 35 | self._config = copy.deepcopy(self._default) 36 | 37 | def to_json(self) -> str: 38 | return json.dumps(self._config) 39 | 40 | def get_from_dict(self, dict_obj: dict, key: str) -> Any: 41 | "Raises KeyError if config doesn't exist" 42 | levels = key.split(".") 43 | return_val = dict_obj 44 | for level in levels: 45 | if isinstance(return_val, list): 46 | level = int(level) 47 | return_val = return_val[level] 48 | return copy.deepcopy(return_val) 49 | 50 | def copy(self) -> Dict: 51 | return copy.deepcopy(self._config) 52 | 53 | def get(self, key: str, default: Any = None) -> Any: 54 | "Returns default or None if config dones't exist" 55 | try: 56 | return self.get_from_dict(self._config, key) 57 | except KeyError: 58 | return default 59 | 60 | def get_default(self, key: str) -> Any: 61 | return self.get_from_dict(self._default, key) 62 | 63 | def set(self, key: str, value: Any) -> None: 64 | levels = key.split(".") 65 | conf_obj = self._config 66 | for i in range(len(levels) - 1): 67 | level = levels[i] 68 | if isinstance(conf_obj, list): 69 | level = int(level) 70 | try: 71 | conf_obj = conf_obj[level] 72 | except KeyError: 73 | conf_obj[level] = {} 74 | conf_obj = conf_obj[level] 75 | level = levels[-1] 76 | if isinstance(conf_obj, list): 77 | level = int(level) 78 | conf_obj[level] = value 79 | 80 | def pop(self, key: str) -> Any: 81 | levels = key.split(".") 82 | conf_obj = self._config 83 | for i in range(len(levels) - 1): 84 | level = levels[i] 85 | if isinstance(conf_obj, list): 86 | level = int(level) 87 | try: 88 | conf_obj = conf_obj[level] 89 | except KeyError: 90 | return None 91 | level = levels[-1] 92 | if isinstance(conf_obj, list): 93 | level = int(level) 94 | return conf_obj.pop(level) 95 | 96 | def __getitem__(self, key: str) -> Any: 97 | return self.get(key) 98 | 99 | def __setitem__(self, key: str, value: Any) -> None: 100 | "This function only modifies the internal config data. Call conf.save() to actually write to disk" 101 | self.set(key, value) 102 | 103 | def __iter__(self) -> Iterator: 104 | return iter(self._config) 105 | 106 | def __delitem__(self, key: str) -> Any: 107 | self.pop(key) 108 | 109 | def __contains__(self, key: str) -> bool: 110 | try: 111 | self.get_from_dict(self._config, key) 112 | return True 113 | except KeyError: 114 | return False 115 | 116 | # Config Window 117 | 118 | def open_config(self) -> bool: 119 | config_window = ConfigWindow(self) 120 | self.config_window = config_window 121 | for fn in self.window_open_hook: 122 | fn(config_window) 123 | config_window.on_open() 124 | config_window.exec() 125 | return True 126 | 127 | def use_custom_window(self) -> None: 128 | mw.addonManager.setConfigAction(self.addon_dir, self.open_config) 129 | 130 | def on_window_open(self, fn: Callable[["ConfigWindow"], None]) -> None: 131 | self.window_open_hook.append(fn) 132 | 133 | add_config_tab = on_window_open 134 | -------------------------------------------------------------------------------- /src/enhanced_cloze/ankiaddonconfig/mypy.ini: -------------------------------------------------------------------------------- 1 | [mypy] 2 | no_strict_optional = True 3 | disallow_untyped_defs = True -------------------------------------------------------------------------------- /src/enhanced_cloze/ankiaddonconfig/window.py: -------------------------------------------------------------------------------- 1 | from typing import Callable, List, Tuple, TYPE_CHECKING, Optional 2 | from pathlib import Path 3 | 4 | import aqt.addons 5 | from aqt import mw 6 | from aqt.qt import * 7 | from aqt.utils import tooltip, showText, saveGeom, restoreGeom 8 | 9 | from .errors import InvalidConfigValueError 10 | 11 | if TYPE_CHECKING: 12 | from .manager import ConfigManager 13 | 14 | QT6 = QT_VERSION_STR.split(".")[0] == "6" 15 | 16 | 17 | class ConfigWindow(QDialog): 18 | def __init__(self, conf: "ConfigManager") -> None: 19 | QDialog.__init__(self, mw, Qt.WindowType.Window) # type: ignore 20 | self.conf = conf 21 | self.mgr = mw.addonManager 22 | self.widget_updates: List[Callable[[], None]] = [] 23 | self.should_save_hook: List[Callable[[], bool]] = [] 24 | self._on_save_hook: List[Callable[[], None]] = [] 25 | self._on_close_hook: List[Callable[[], None]] = [] 26 | self.geom_key = f"addonconfig-{conf.addon_name}" 27 | 28 | self.setWindowTitle(f"Config for {conf.addon_name}") 29 | self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose) 30 | self.setup() 31 | 32 | def setup(self) -> None: 33 | self.outer_layout = ConfigLayout(self, QBoxLayout.Direction.TopToBottom) 34 | self.main_layout = ConfigLayout(self, QBoxLayout.Direction.TopToBottom) 35 | self.btn_layout = ConfigLayout(self, QBoxLayout.Direction.LeftToRight) 36 | self.outer_layout.addLayout(self.main_layout) 37 | self.outer_layout.addLayout(self.btn_layout) 38 | self.setLayout(self.outer_layout) 39 | 40 | self.main_tab = QTabWidget() 41 | main_tab = self.main_tab 42 | main_tab.setFocusPolicy(Qt.FocusPolicy.StrongFocus) 43 | self.main_layout.addWidget(main_tab) 44 | self.setup_buttons(self.btn_layout) 45 | 46 | def setup_buttons(self, btn_box: "ConfigLayout") -> None: 47 | self.advanced_btn = QPushButton("Advanced") 48 | self.advanced_btn.clicked.connect(self.on_advanced) 49 | btn_box.addWidget(self.advanced_btn) 50 | 51 | self.reset_btn = QPushButton("Restore Defaults") 52 | self.reset_btn.clicked.connect(self.on_reset) 53 | btn_box.addWidget(self.reset_btn) 54 | 55 | btn_box.addStretch(1) 56 | 57 | self.cancel_btn = QPushButton("Cancel") 58 | self.cancel_btn.clicked.connect(self.on_cancel) 59 | btn_box.addWidget(self.cancel_btn) 60 | 61 | self.save_btn = QPushButton("Save") 62 | self.save_btn.setDefault(True) 63 | self.save_btn.setShortcut("Ctrl+Return") 64 | self.save_btn.clicked.connect(self.on_save) 65 | btn_box.addWidget(self.save_btn) 66 | 67 | def update_widgets(self) -> None: 68 | try: 69 | for widget_update in self.widget_updates: 70 | widget_update() 71 | except Exception as e: 72 | advanced = self.advanced_window() 73 | dial, bbox = showText( 74 | "Invalid Config. Please fix the following issue in the advanced config editor. \n\n" 75 | + str(e), 76 | title="Invalid Config", 77 | parent=advanced, 78 | run=False, 79 | ) 80 | button = QPushButton("Quit Config") 81 | bbox.addButton(button, QDialogButtonBox.ButtonRole.DestructiveRole) 82 | bbox.button(QDialogButtonBox.StandardButton.Close).setDefault(True) 83 | 84 | def quit() -> None: 85 | self.widget_updates = [] 86 | dial.close() 87 | advanced.reject() 88 | self.close() 89 | 90 | button.clicked.connect(quit) 91 | dial.setModal(True) 92 | dial.show() 93 | 94 | def on_open(self) -> None: 95 | self.update_widgets() 96 | restoreGeom(self, self.geom_key) 97 | 98 | def on_save(self) -> None: 99 | for hook in self.should_save_hook: 100 | if not hook(): 101 | return 102 | for hook in self._on_save_hook: 103 | hook() 104 | self.conf.save() 105 | self.close() 106 | 107 | def on_cancel(self) -> None: 108 | self.close() 109 | 110 | def on_reset(self) -> None: 111 | self.conf.load_defaults() 112 | self.update_widgets() 113 | tooltip("Press save to save changes") 114 | 115 | def on_advanced(self) -> None: 116 | self.advanced_window() 117 | 118 | def advanced_window(self) -> aqt.addons.ConfigEditor: 119 | def on_finish(result: int) -> None: 120 | self.conf.load() 121 | self.update_widgets() 122 | 123 | diag = aqt.addons.ConfigEditor( 124 | self, self.conf.addon_dir, self.conf._config # type: ignore 125 | ) 126 | diag.finished.connect(on_finish) 127 | diag.show() 128 | return diag 129 | 130 | def closeEvent(self, evt: QCloseEvent) -> None: 131 | # Discard the contents when clicked cancel, 132 | # and also in case the window was clicked without clicking any of the buttons 133 | for hook in self._on_close_hook: 134 | hook() 135 | self.conf.load() 136 | saveGeom(self, self.geom_key) 137 | evt.accept() 138 | 139 | # Add Widgets 140 | 141 | def add_tab(self, name: str) -> "ConfigLayout": 142 | tab = QWidget(self) 143 | layout = ConfigLayout(self, QBoxLayout.Direction.TopToBottom) 144 | tab.setLayout(layout) 145 | self.main_tab.addTab(tab, name) 146 | return layout 147 | 148 | def execute_on_save(self, hook: Callable[[], None]) -> None: 149 | self._on_save_hook.append(hook) 150 | 151 | def execute_on_close(self, hook: Callable[[], None]) -> None: 152 | self._on_close_hook.append(hook) 153 | 154 | def set_footer( 155 | self, 156 | text: str, 157 | html: bool = False, 158 | size: int = 0, 159 | multiline: bool = False, 160 | tooltip: Optional[str] = None, 161 | ) -> QLabel: 162 | footer = QLabel(text) 163 | if html: 164 | footer.setTextFormat(Qt.TextFormat.RichText) 165 | footer.setOpenExternalLinks(True) 166 | else: 167 | footer.setTextFormat(Qt.TextFormat.PlainText) 168 | if size: 169 | font = QFont() 170 | font.setPixelSize(size) 171 | footer.setFont(font) 172 | if multiline: 173 | footer.setWordWrap(True) 174 | if tooltip is not None: 175 | footer.setToolTip(tooltip) 176 | 177 | self.main_layout.addWidget(footer) 178 | return footer 179 | 180 | 181 | class ConfigLayout(QBoxLayout): 182 | def __init__(self, conf_window: ConfigWindow, direction: QBoxLayout.Direction): 183 | QBoxLayout.__init__(self, direction) 184 | self.conf = conf_window.conf 185 | self.config_window = conf_window 186 | self.widget_updates = conf_window.widget_updates 187 | 188 | # Config Input Widgets 189 | 190 | def checkbox( 191 | self, key: str, description: Optional[str] = None, tooltip: Optional[str] = None 192 | ) -> QCheckBox: 193 | "For boolean config" 194 | checkbox = QCheckBox() 195 | if description is not None: 196 | checkbox.setText(description) 197 | if tooltip is not None: 198 | checkbox.setToolTip(tooltip) 199 | 200 | def update() -> None: 201 | value = self.conf.get(key) 202 | if not isinstance(value, bool): 203 | raise InvalidConfigValueError(key, "boolean", value) 204 | checkbox.setChecked(value) 205 | 206 | self.widget_updates.append(update) 207 | 208 | checkbox.stateChanged.connect( 209 | lambda s: self.conf.set( 210 | key, 211 | s == (Qt.CheckState.Checked.value if QT6 else Qt.CheckState.Checked), 212 | ) 213 | ) 214 | self.addWidget(checkbox) 215 | return checkbox 216 | 217 | def dropdown( 218 | self, 219 | key: str, 220 | labels: list, 221 | values: list, 222 | description: Optional[str] = None, 223 | tooltip: Optional[str] = None, 224 | ) -> QComboBox: 225 | combobox = QComboBox() 226 | combobox.insertItems(0, labels) 227 | if tooltip is not None: 228 | combobox.setToolTip(tooltip) 229 | 230 | def update() -> None: 231 | conf = self.conf 232 | try: 233 | val = conf.get(key) 234 | index = values.index(val) 235 | except ValueError: 236 | raise InvalidConfigValueError( 237 | key, "any value in list " + str(values), val 238 | ) 239 | combobox.setCurrentIndex(index) 240 | 241 | self.widget_updates.append(update) 242 | 243 | combobox.currentTextChanged.connect(lambda text: self.conf.set(key, text)) 244 | 245 | if description is not None: 246 | row = self.hlayout() 247 | row.text(description, tooltip=tooltip) 248 | row.space(7) 249 | row.addWidget(combobox) 250 | row.stretch() 251 | else: 252 | self.addWidget(combobox) 253 | 254 | return combobox 255 | 256 | def text_input( 257 | self, key: str, description: Optional[str] = None, tooltip: Optional[str] = None 258 | ) -> QLineEdit: 259 | "For string config" 260 | line_edit = QLineEdit() 261 | if tooltip is not None: 262 | line_edit.setToolTip(tooltip) 263 | 264 | def update() -> None: 265 | val = self.conf.get(key) 266 | if not isinstance(val, str): 267 | raise InvalidConfigValueError(key, "string", val) 268 | line_edit.setText(val) 269 | line_edit.setCursorPosition(0) 270 | 271 | self.widget_updates.append(update) 272 | 273 | line_edit.textChanged.connect(lambda text: self.conf.set(key, text)) 274 | 275 | if description is not None: 276 | row = self.hlayout() 277 | row.text(description, tooltip=tooltip) 278 | row.space(7) 279 | row.addWidget(line_edit) 280 | else: 281 | self.addWidget(line_edit) 282 | return line_edit 283 | 284 | def number_input( 285 | self, 286 | key: str, 287 | description: Optional[str] = None, 288 | tooltip: Optional[str] = None, 289 | minimum: int = 0, 290 | maximum: int = 99, 291 | step: int = 1, 292 | decimal: bool = False, 293 | precision: int = 2, 294 | ) -> Union[QDoubleSpinBox, QSpinBox]: 295 | "For integer config" 296 | spin_box: Union[QDoubleSpinBox, QSpinBox] 297 | if decimal: 298 | spin_box = QDoubleSpinBox() 299 | spin_box.setDecimals(precision) 300 | else: 301 | spin_box = QSpinBox() 302 | if tooltip is not None: 303 | spin_box.setToolTip(tooltip) 304 | spin_box.setMinimum(minimum) 305 | spin_box.setMaximum(maximum) 306 | spin_box.setSingleStep(step) 307 | 308 | def update() -> None: 309 | val = self.conf.get(key) 310 | if not decimal and not isinstance(val, int): 311 | raise InvalidConfigValueError(key, "integer number", val) 312 | if decimal and not isinstance(val, (int, float)): 313 | raise InvalidConfigValueError(key, "number", val) 314 | if minimum is not None and val < minimum: 315 | raise InvalidConfigValueError( 316 | key, f"integer number greater or equal to {minimum}", val 317 | ) 318 | if maximum is not None and val > maximum: 319 | raise InvalidConfigValueError( 320 | key, f"integer number lesser or equal to {maximum}", val 321 | ) 322 | spin_box.setValue(val) 323 | 324 | self.widget_updates.append(update) 325 | 326 | spin_box.valueChanged.connect(lambda val: self.conf.set(key, val)) 327 | 328 | if description is not None: 329 | row = self.hlayout() 330 | row.text(description, tooltip=tooltip) 331 | row.space(7) 332 | row.addWidget(spin_box) 333 | row.stretch() 334 | else: 335 | self.addWidget(spin_box) 336 | return spin_box 337 | 338 | def color_input( 339 | self, 340 | key: str, 341 | description: Optional[str] = None, 342 | tooltip: Optional[str] = None, 343 | opacity: bool = False, 344 | ) -> QPushButton: 345 | """For hex color config. 346 | If opacity is true, allows changing opacity. Note that color is stored in RGBA format, not ARGB. 347 | When creating using the RGBA in Qt, you need to change it to ARGB format first. 348 | """ 349 | color: QColor 350 | button = QPushButton() 351 | button.setFixedWidth(25) 352 | button.setFixedHeight(25) 353 | button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor)) 354 | if tooltip is not None: 355 | button.setToolTip(tooltip) 356 | 357 | def set_color(rgb: str) -> None: 358 | nonlocal color 359 | if len(rgb) == 9: 360 | rgb = "#" + rgb[7:] + rgb[1:7] # RGBA to ARGB 361 | 362 | button.setStyleSheet( 363 | 'QPushButton{ background-color: "%s"; border: none; border-radius: 3px}' 364 | % rgb # QT bug? CSS accepts ARGB instead of RGBA. 365 | ) 366 | color = QColor() 367 | color.setNamedColor(rgb) # Accepts #RGB, #RRGGBB or #AARRGGBB 368 | if not color.isValid(): 369 | raise InvalidConfigValueError(key, "rgb hex color string", rgb) 370 | 371 | def update() -> None: 372 | value = self.conf.get(key) 373 | set_color(value) 374 | 375 | def save(color: QColor) -> None: 376 | if opacity: 377 | rgb = color.name(QColor.NameFormat.HexArgb) 378 | rgb = "#" + rgb[3:] + rgb[1:3] # ARGB to RGBA 379 | else: 380 | rgb = color.name() 381 | self.conf.set(key, rgb) 382 | set_color(rgb) 383 | 384 | def open_color_dialog() -> None: 385 | color_dialog = QColorDialog(self.config_window) 386 | if opacity: 387 | color_dialog.setOptions(QColorDialog.ShowAlphaChannel) 388 | color_dialog.setCurrentColor(color) 389 | color_dialog.colorSelected.connect(lambda c: save(c)) 390 | color_dialog.exec() 391 | 392 | self.widget_updates.append(update) 393 | 394 | button.clicked.connect(lambda _: open_color_dialog()) 395 | 396 | if description is not None: 397 | row = self.hlayout() 398 | row.text(description, tooltip=tooltip) 399 | row.space(7) 400 | row.addWidget(button) 401 | row.stretch() 402 | else: 403 | self.addWidget(button) 404 | 405 | return button 406 | 407 | def path_input( 408 | self, 409 | key: str, 410 | description: Optional[str] = None, 411 | tooltip: Optional[str] = None, 412 | get_directory: bool = False, 413 | filter: str = "Any files (*)", 414 | ) -> Tuple[QLineEdit, QPushButton]: 415 | "For path string config" 416 | 417 | row = self.hlayout() 418 | if description is not None: 419 | row.text(description, tooltip=tooltip) 420 | row.space(7) 421 | line_edit = QLineEdit() 422 | line_edit.setReadOnly(True) 423 | row.addWidget(line_edit) 424 | button = QPushButton("Browse") 425 | row.addWidget(button) 426 | if tooltip is not None: 427 | line_edit.setToolTip(tooltip) 428 | 429 | def update() -> None: 430 | val = self.conf.get(key) 431 | if not isinstance(val, str): 432 | raise InvalidConfigValueError(key, "string file path", val) 433 | line_edit.setText(val) 434 | 435 | def get_path() -> None: 436 | val = self.conf.get(key) 437 | parent_dir = str(Path(val).parent) 438 | 439 | if get_directory: 440 | path = QFileDialog.getExistingDirectory( 441 | self.config_window, directory=parent_dir 442 | ) 443 | else: 444 | path = QFileDialog.getOpenFileName( 445 | self.config_window, directory=parent_dir, filter=filter 446 | )[0] 447 | if path: # is None if cancelled 448 | self.conf.set(key, path) 449 | update() 450 | 451 | self.widget_updates.append(update) 452 | button.clicked.connect(get_path) 453 | 454 | return (line_edit, button) 455 | 456 | def shortcut_edit( 457 | self, key, description: Optional[str] = None, tooltip: Optional[str] = None 458 | ) -> Tuple[QKeySequenceEdit, QPushButton]: 459 | edit = QKeySequenceEdit() 460 | 461 | if description is not None: 462 | row = self.hlayout() 463 | row.text(description, tooltip=tooltip) 464 | 465 | def update(): 466 | val = self.conf.get(key) 467 | if not isinstance(val, str): 468 | raise InvalidConfigValueError(key, "str", val) 469 | val = val.replace(" ", "") 470 | edit.setKeySequence(val) 471 | 472 | self.widget_updates.append(update) 473 | 474 | edit.keySequenceChanged.connect( # type: ignore 475 | lambda s: self.conf.set(key, edit.keySequence().toString()) 476 | ) 477 | 478 | self.addWidget(edit) 479 | 480 | def on_shortcut_clear_btn_click(): 481 | edit.clear() 482 | 483 | shortcut_clear_btn = QPushButton("Clear") 484 | shortcut_clear_btn.setSizePolicy( 485 | QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed 486 | ) 487 | shortcut_clear_btn.clicked.connect(on_shortcut_clear_btn_click) # type: ignore 488 | 489 | layout = QHBoxLayout() 490 | layout.addWidget(edit) 491 | layout.addWidget(shortcut_clear_btn) 492 | 493 | self.addLayout(layout) 494 | return edit, shortcut_clear_btn 495 | 496 | # Layout widgets 497 | 498 | def text( 499 | self, 500 | text: str, 501 | bold: bool = False, 502 | html: bool = False, 503 | size: int = 0, 504 | multiline: bool = False, 505 | tooltip: Optional[str] = None, 506 | ) -> QLabel: 507 | label_widget = QLabel(text) 508 | label_widget.setTextInteractionFlags( 509 | Qt.TextInteractionFlag.TextBrowserInteraction 510 | ) 511 | if html: 512 | label_widget.setTextFormat(Qt.TextFormat.RichText) 513 | label_widget.setOpenExternalLinks(True) 514 | else: 515 | label_widget.setTextFormat(Qt.TextFormat.PlainText) 516 | if bold or size: 517 | font = QFont() 518 | if bold: 519 | font.setBold(True) 520 | if size: 521 | font.setPixelSize(size) 522 | label_widget.setFont(font) 523 | if multiline: 524 | label_widget.setWordWrap(True) 525 | if tooltip is not None: 526 | label_widget.setToolTip(tooltip) 527 | 528 | self.addWidget(label_widget) 529 | return label_widget 530 | 531 | def text_button( 532 | self, 533 | text: str, 534 | tooltip: str = "", 535 | on_click: Optional[Callable] = None, 536 | color: str = "", 537 | size: int = 0, 538 | url: str = "/", 539 | ) -> QLabel: 540 | """A QLabel that behaves like a button. 541 | 542 | on_click is provided 1 argument: 'url'. 543 | """ 544 | css = "text-decoration: none;" 545 | if color: 546 | css += f" color: {color};" 547 | if size: 548 | css += f" font-size: {size}px;" 549 | label = QLabel(f'{text}') 550 | label.setTextFormat(Qt.TextFormat.RichText) 551 | if tooltip: 552 | label.setToolTip(tooltip) 553 | if on_click: 554 | label.linkActivated.connect(on_click) 555 | 556 | self.addWidget(label) 557 | return label 558 | 559 | def _separator(self, direction: QFrame.Shape) -> QFrame: 560 | """direction should be either QFrame.HLine or QFrame.VLine""" 561 | line = QFrame() 562 | line.setLineWidth(0) 563 | line.setFrameShape(direction) 564 | line.setFrameShadow(QFrame.Shadow.Plain) 565 | self.addWidget(line) 566 | return line 567 | 568 | def hseparator(self) -> QFrame: 569 | return self._separator(QFrame.Shape.HLine) 570 | 571 | def vseparator(self) -> QFrame: 572 | return self._separator(QFrame.Shape.VLine) 573 | 574 | def _container(self, direction: QBoxLayout.Direction) -> "ConfigLayout": 575 | """Adds (empty) QWidget > ConfigLayout. 576 | 577 | You can access its parent widget using ConfigLayout.parentWidget() 578 | """ 579 | container = QWidget() 580 | inner_layout = ConfigLayout(self.config_window, direction) 581 | container.setLayout(inner_layout) 582 | self.addWidget(container) 583 | return inner_layout 584 | 585 | def hcontainer(self) -> "ConfigLayout": 586 | """Adds (empty) QWidget > ConfigLayout.""" 587 | return self._container(QBoxLayout.Direction.RightToLeft) 588 | 589 | def vcontainer(self) -> "ConfigLayout": 590 | """Adds (empty) QWidget > ConfigLayout.""" 591 | return self._container(QBoxLayout.Direction.TopToBottom) 592 | 593 | def _layout(self, direction: QBoxLayout.Direction) -> "ConfigLayout": 594 | layout = ConfigLayout(self.config_window, direction) 595 | self.addLayout(layout) 596 | return layout 597 | 598 | def hlayout(self) -> "ConfigLayout": 599 | return self._layout(QBoxLayout.Direction.LeftToRight) 600 | 601 | def vlayout(self) -> "ConfigLayout": 602 | return self._layout(QBoxLayout.Direction.TopToBottom) 603 | 604 | def space(self, space: int = 1) -> None: 605 | self.addSpacing(space) 606 | 607 | def stretch(self, factor: int = 0) -> None: 608 | self.addStretch(factor) 609 | 610 | def _scroll_layout( 611 | self, 612 | hsizepolicy: QSizePolicy.Policy, 613 | vsizepolicy: QSizePolicy.Policy, 614 | hscrollbarpolicy: Qt.ScrollBarPolicy, 615 | vscrollbarpolicy: Qt.ScrollBarPolicy, 616 | ) -> "ConfigLayout": 617 | """Adds QScrollArea > QWidget*2 > ConfigLayout, returns the layout.""" 618 | # QScrollArea seems to automatically add a child widget. 619 | layout = ConfigLayout(self.config_window, QBoxLayout.Direction.TopToBottom) 620 | inner_widget = QWidget() 621 | inner_widget.setLayout(layout) 622 | scroll = QScrollArea() 623 | scroll.setWidgetResizable(True) 624 | scroll.setFrameShape(QFrame.Shape.NoFrame) 625 | scroll.setWidget(inner_widget) 626 | scroll.setSizePolicy(hsizepolicy, vsizepolicy) 627 | scroll.setHorizontalScrollBarPolicy(hscrollbarpolicy) 628 | scroll.setVerticalScrollBarPolicy(vscrollbarpolicy) 629 | self.addWidget(scroll) 630 | return layout 631 | 632 | def hscroll_layout(self, always: bool = False) -> "ConfigLayout": 633 | """Adds QScrollArea > QWidget*2 > ConfigLayout, returns the layout.""" 634 | scroll = ( 635 | Qt.ScrollBarPolicy.ScrollBarAlwaysOn 636 | if always 637 | else Qt.ScrollBarPolicy.ScrollBarAsNeeded 638 | ) 639 | return self._scroll_layout( 640 | QSizePolicy.Policy.Expanding, 641 | QSizePolicy.Policy.Minimum, 642 | scroll, 643 | Qt.ScrollBarPolicy.ScrollBarAlwaysOff, 644 | ) 645 | 646 | def vscroll_layout(self, always: bool = False) -> "ConfigLayout": 647 | """Adds QScrollArea > QWidget*2 > ConfigLayout, returns the layout.""" 648 | scroll = ( 649 | Qt.ScrollBarPolicy.ScrollBarAlwaysOn 650 | if always 651 | else Qt.ScrollBarPolicy.ScrollBarAsNeeded 652 | ) 653 | return self._scroll_layout( 654 | QSizePolicy.Policy.Minimum, 655 | QSizePolicy.Policy.Expanding, 656 | Qt.ScrollBarPolicy.ScrollBarAlwaysOff, 657 | scroll, 658 | ) 659 | 660 | def scroll_layout( 661 | self, 662 | horizontal: bool = True, 663 | vertical: bool = True, 664 | ) -> "ConfigLayout": 665 | """Legacy. Adds QScrollArea > QWidget*2 > ConfigLayout, returns the layout.""" 666 | return self._scroll_layout( 667 | QSizePolicy.Policy.Expanding if horizontal else QSizePolicy.Policy.Minimum, 668 | QSizePolicy.Policy.Expanding if vertical else QSizePolicy.Minimum, 669 | Qt.ScrollBarPolicy.ScrollBarAsNeeded, 670 | Qt.ScrollBarPolicy.ScrollBarAsNeeded, 671 | ) 672 | -------------------------------------------------------------------------------- /src/enhanced_cloze/compat.py: -------------------------------------------------------------------------------- 1 | import aqt 2 | from anki import notes 3 | 4 | 5 | def add_compatibility_aliases() -> None: 6 | add_compatibility_alias( 7 | notes.Note, 8 | "note_type", 9 | "model", 10 | ) 11 | add_compatibility_alias(aqt.mw.col.models, "by_name", "byName") 12 | add_compatibility_alias(aqt.mw.col.models, "field_names", "fieldNames") 13 | add_compatibility_alias(aqt.mw.col.models, "field_map", "fieldMap") 14 | add_compatibility_alias(aqt.editor.Editor, "call_after_note_saved", "saveNow") 15 | add_compatibility_alias(aqt.mw.col, "get_note", "getNote") 16 | add_compatibility_alias(aqt.mw.col, "find_notes", "findNotes") 17 | 18 | 19 | def add_compatibility_alias(namespace, new_name: str, old_name: str) -> bool: 20 | if new_name not in dir(namespace): 21 | setattr(namespace, new_name, getattr(namespace, old_name)) 22 | return True 23 | 24 | return False 25 | -------------------------------------------------------------------------------- /src/enhanced_cloze/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "scrollToClozeOnToggle": true, 3 | "animateScroll": true, 4 | "showHintsForPseudoClozes": true, 5 | "underlineRevealedPseudoClozes": false, 6 | "underlineRevealedGenuineClozes": true, 7 | "revealPseudoClozesByDefault": false, 8 | "revealNextGenuineClozeShortcut": "J", 9 | "revealAllGenuineClozesShortcut": "Shift+J", 10 | "revealNextPseudoClozeShortcut": "N", 11 | "revealAllPseudoClozesShortcut": "Shift+N", 12 | "swapLeftAndRightBorderActions": false 13 | } 14 | -------------------------------------------------------------------------------- /src/enhanced_cloze/config.py: -------------------------------------------------------------------------------- 1 | from .ankiaddonconfig import ConfigManager, ConfigWindow 2 | 3 | conf = ConfigManager() 4 | 5 | 6 | def setup_config(): 7 | conf.use_custom_window() 8 | conf.on_window_open(_on_config_window_open) 9 | conf.add_config_tab(_general_tab) 10 | 11 | 12 | def _on_config_window_open(conf_window: ConfigWindow) -> None: 13 | """Ankiaddonconfig is used here in a non-standard way for configuring the note type options. 14 | The options don't really need to be saved in the config and they are overwritten with the values on the model when 15 | the config window is opened. 16 | """ 17 | from .model import ( 18 | config_values_from_model, 19 | add_or_update_model, 20 | update_model_options_with_config_values, 21 | ) 22 | 23 | # Create the model if it doesn't exist 24 | add_or_update_model() 25 | 26 | # Load the config values from the model 27 | d = config_values_from_model() 28 | for key in d: 29 | conf.set(key, d[key]) 30 | 31 | # Update the model when the config is saved 32 | conf_window.execute_on_save(update_model_options_with_config_values) 33 | 34 | 35 | def _general_tab(conf_window: ConfigWindow) -> None: 36 | tab = conf_window.add_tab("General") 37 | 38 | tab.text("Shorcuts", bold=True) 39 | tab.shortcut_edit( 40 | "revealNextGenuineClozeShortcut", "Shortcut to reveal next genuine cloze" 41 | ) 42 | tab.shortcut_edit( 43 | "revealAllGenuineClozesShortcut", "Shortcut to reveal all genuine clozes" 44 | ) 45 | tab.shortcut_edit( 46 | "revealNextPseudoClozeShortcut", "Shortcut to reveal next pseudo cloze" 47 | ) 48 | tab.shortcut_edit( 49 | "revealAllPseudoClozesShortcut", "Shortcut to reveal all pseudo clozes" 50 | ) 51 | tab.hseparator() 52 | tab.space(8) 53 | 54 | tab.text("Border Actions", bold=True) 55 | tab.checkbox("swapLeftAndRightBorderActions", "Swap left and right border actions") 56 | tab.hseparator() 57 | tab.space(8) 58 | 59 | tab.text("Cloze Style", bold=True) 60 | tab.checkbox("underlineRevealedPseudoClozes", "Underline revealed pseudo clozes") 61 | tab.checkbox("underlineRevealedGenuineClozes", "Underline revealed genuine clozes") 62 | tab.hseparator() 63 | tab.space(8) 64 | 65 | tab.text("Cloze Behavior", bold=True) 66 | tab.checkbox("showHintsForPseudoClozes", "Show hints for pseudo clozes") 67 | tab.checkbox("revealPseudoClozesByDefault", "Reveal pseudo clozes by default") 68 | tab.hseparator() 69 | tab.space(8) 70 | 71 | tab.text("Auto Scroll to relevant cloze", bold=True) 72 | tab.checkbox("scrollToClozeOnToggle", "Scroll to cloze on toggle") 73 | tab.checkbox("animateScroll", "Animate scrolling") 74 | 75 | tab.stretch() 76 | -------------------------------------------------------------------------------- /src/enhanced_cloze/constants.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | 3 | from anki.buildinfo import version as anki_version 4 | 5 | MODEL_NAME = "Enhanced Cloze 2.1 v2" 6 | ANKI_VERSION_TUPLE = tuple(int(i) for i in anki_version.split(".")) 7 | NOTE_TYPE_DIR = Path(__file__).parent / "note_type" 8 | 9 | 10 | UPDATE_MSG = f"""\ 11 | Do you want to update the {MODEL_NAME} note type?

\ 12 | The changes include: 13 |
    14 |
  • Adding and editing notes on mobile works now (except for adding notes without clozes)
  • 15 |
  • New shortcuts for reavaling clozes (configurable): 16 |
      17 |
    • J - Reveal Next Genuine Cloze
    • 18 |
    • Shift+J - Toggle All Genuine Clozes
    • 19 |
    • N - Reveal Next Pseudo Cloze
    • 20 |
    • Shift+N - Toggle All Pseudo Clozes
    • 21 |
    22 |
  • A new option to disable scrolling to a cloze when it is revealed
  • 23 |
  • All Cloze1, Cloze2, ... fields except for Cloze99 are not longer necessary and were removed \ 24 | (also the data field)
  • 25 |
  • Some fixes
  • 26 |
27 | 28 | This will require a full sync to AnkiWeb (if you use synchronization).

29 | 30 | If you have made changes to the note type and don\'t want to loose them you can duplicate the note type first \ 31 | (Tools->Manage Note Types->Add). 32 |

33 | If you don't want to update you can get the previous version of the add-on from \ 34 | here. 35 |

36 | Note: If you choose "No" this notice will show up the next time you open Anki.""" 37 | -------------------------------------------------------------------------------- /src/enhanced_cloze/editor.py: -------------------------------------------------------------------------------- 1 | import re 2 | from typing import Callable, List, Tuple 3 | 4 | from anki.hooks import note_will_flush 5 | from anki.notes import Note 6 | from aqt.editor import Editor 7 | from aqt.gui_hooks import editor_did_init_shortcuts 8 | from aqt.qt import Qt 9 | 10 | from .constants import ANKI_VERSION_TUPLE, MODEL_NAME 11 | 12 | 13 | # this is needed so the no-cloze mode works 14 | def maybe_fill_in_or_remove_cloze99(note: Note) -> None: 15 | def in_use_clozes(): 16 | cloze_start_regex = r"{{c\d+::" 17 | cloze_start_matches = re.findall(cloze_start_regex, note["Content"]) 18 | return [int(re.sub(r"\D", "", x)) for x in set(cloze_start_matches)] 19 | 20 | if note and note.note_type()["name"] == MODEL_NAME: 21 | if in_use_clozes(): 22 | note["Cloze99"] = "" 23 | else: 24 | note["Cloze99"] = "{{c1::.}}" 25 | 26 | 27 | def make_cloze_shortcut_start_at_cloze1(shortcuts: List[Tuple], editor: Editor) -> None: 28 | original_onCloze = Editor.onCloze 29 | 30 | # code adapted from original onCloze and _onCloze 31 | def myOnCloze(self) -> None: 32 | if self.note.note_type()["name"] == MODEL_NAME: 33 | self.call_after_note_saved(lambda: _myOnCloze(editor), keepFocus=True) 34 | else: 35 | original_onCloze(self) 36 | 37 | def _myOnCloze(self) -> None: 38 | # find the highest existing cloze 39 | highest = 0 40 | val = self.note["Content"] 41 | m = re.findall(r"\{\{c(\d+)::", val) 42 | if m: 43 | highest = max(highest, sorted([int(x) for x in m])[-1]) 44 | # reuse last? 45 | if not self.mw.app.keyboardModifiers() & Qt.KeyboardModifier.AltModifier: 46 | highest += 1 47 | # must start at 1 48 | highest = max(1, highest) 49 | self.web.eval("wrap('{{c%d::', '}}');" % highest) 50 | 51 | replace_shortcut(shortcuts, "Ctrl+Shift+C", lambda: myOnCloze(editor)) 52 | replace_shortcut(shortcuts, "Ctrl+Shift+Alt+C", lambda: myOnCloze(editor)) 53 | 54 | 55 | def replace_shortcut( 56 | shortcuts: List[Tuple], 57 | key_combination: str, 58 | func: Callable[[], None], 59 | ) -> None: 60 | existing = next((x for x in shortcuts if x[0] == key_combination), None) 61 | if existing is not None: 62 | shortcuts.remove(existing) 63 | shortcuts.append((key_combination, func)) 64 | 65 | 66 | def setup_editor() -> None: 67 | note_will_flush.append(maybe_fill_in_or_remove_cloze99) 68 | if ANKI_VERSION_TUPLE < (2, 1, 50): 69 | editor_did_init_shortcuts.append(make_cloze_shortcut_start_at_cloze1) 70 | -------------------------------------------------------------------------------- /src/enhanced_cloze/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "package":"1990296174", 3 | "name": "Enhanced cloze, 2.1" 4 | } 5 | -------------------------------------------------------------------------------- /src/enhanced_cloze/menu.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # License: GNU GPL, version 3 or later; http://www.gnu.org/licenses/gpl.html 3 | # Copyright: Ankitects Pty Ltd and contributors 4 | # 2017- LuZhe610 5 | # 2019 Arthur Milchior 6 | # 2019 Hyun Woo Park (phu54321@naver.com) 7 | # 2021 Jakub Fidler 8 | # (for the included js see the top of these files) 9 | 10 | 11 | from aqt import mw 12 | from aqt.gui_hooks import main_window_did_init 13 | from aqt.qt import QMenu 14 | from aqt.utils import askUser, tooltip 15 | 16 | from .config import conf 17 | from .constants import MODEL_NAME 18 | from .model import add_or_update_model, enhanced_cloze 19 | 20 | 21 | def setup_enhanced_cloze_menu() -> None: 22 | def on_main_window_did_init(): 23 | menu: QMenu = mw.form.menuTools 24 | submenu = menu.addMenu("Enhanced Cloze") 25 | add_config_action_to_menu(submenu) 26 | add_reset_notetype_action_to_menu(submenu) 27 | add_reset_css_action_to_menu(submenu) 28 | 29 | main_window_did_init.append(on_main_window_did_init) 30 | 31 | 32 | def add_config_action_to_menu(menu: QMenu) -> None: 33 | action = menu.addAction("Config") 34 | action.triggered.connect(conf.open_config) 35 | 36 | 37 | def add_reset_notetype_action_to_menu(menu: QMenu) -> None: 38 | action = menu.addAction("Reset Enhanced Cloze note type") 39 | 40 | def on_triggered(): 41 | if not askUser( 42 | "This will reset the Enhanced Cloze note type to its default version.\n\n" 43 | "Note: After doing this the next you time you synchronize Anki will require a full sync to AnkiWeb.\n\n" 44 | "Continue?", 45 | ): 46 | return 47 | 48 | current_model = mw.col.models.by_name(MODEL_NAME) 49 | if not current_model: 50 | add_or_update_model() 51 | return 52 | 53 | default_model = enhanced_cloze() 54 | default_model["id"] = current_model["id"] 55 | default_model["usn"] = -1 # triggers full sync 56 | mw.col.models.update_dict(default_model) 57 | tooltip("Successfully reset Enhanced Cloze note type.") 58 | 59 | action.triggered.connect(on_triggered) 60 | 61 | 62 | def add_reset_css_action_to_menu(menu: QMenu) -> None: 63 | action = menu.addAction("Reset Enhanced Cloze note type styling (css)") 64 | 65 | def on_triggered() -> None: 66 | if not askUser( 67 | "This will reset the styling (css) of the Enhanced Cloze note type to its default version.\n\nContinue?" 68 | ): 69 | return 70 | 71 | current_model = mw.col.models.by_name(MODEL_NAME) 72 | if not current_model: 73 | add_or_update_model() 74 | return 75 | 76 | current_model["css"] = enhanced_cloze()["css"] 77 | mw.col.models.update_dict(current_model) 78 | tooltip("Successfully reset Enhanced Cloze note type styling.") 79 | 80 | action.triggered.connect(on_triggered) 81 | -------------------------------------------------------------------------------- /src/enhanced_cloze/model.py: -------------------------------------------------------------------------------- 1 | import re 2 | from copy import deepcopy 3 | from typing import Dict, Optional, Tuple, Union 4 | 5 | from aqt import mw 6 | from aqt.gui_hooks import profile_did_open, sync_did_finish 7 | from aqt.utils import askUser 8 | 9 | from .config import conf 10 | from .constants import MODEL_NAME, NOTE_TYPE_DIR, UPDATE_MSG 11 | from .note_type.model import enhancedModel 12 | 13 | try: 14 | from aqt.models import NotetypeDict # pylint: disable = unused-import 15 | except: # noqa 16 | pass 17 | 18 | from .compat import add_compatibility_aliases 19 | 20 | 21 | def setup_maybe_update_model_on_startup() -> None: 22 | def on_profile_did_open(): 23 | add_compatibility_aliases() 24 | 25 | if not mw.can_auto_sync(): 26 | add_or_update_model() 27 | else: 28 | # add the function to the sync_did_finish hook 29 | # and remove it from the hook after sync 30 | # so it only gets called on the auto sync on opening Anki 31 | def fn(): 32 | add_or_update_model() 33 | sync_did_finish.remove(fn) 34 | 35 | sync_did_finish.append(fn) 36 | 37 | profile_did_open.append(on_profile_did_open) 38 | 39 | 40 | def _new_version_available() -> bool: 41 | return current_version() is None or current_version() < incoming_version() 42 | 43 | 44 | def current_version() -> Optional[Tuple[int, ...]]: 45 | return version(mw.col.models.by_name(MODEL_NAME)) 46 | 47 | 48 | def incoming_version() -> Optional[Tuple[int, ...]]: 49 | return version(enhanced_cloze()) 50 | 51 | 52 | def version(note_type: "NotetypeDict") -> Optional[Tuple[int, ...]]: 53 | front = note_type["tmpls"][0]["qfmt"] 54 | m = re.match("", front) 55 | if not m: 56 | return None 57 | 58 | return tuple(map(int, m.group(1).split("."))) 59 | 60 | 61 | def set_version(front: str, version: Tuple[int, ...]) -> str: 62 | return re.sub( 63 | "", 64 | f"", 65 | front, 66 | ) 67 | 68 | 69 | def add_or_update_model() -> None: 70 | model = mw.col.models.by_name(MODEL_NAME) 71 | if not model: 72 | mw.col.models.add(enhanced_cloze()) 73 | return 74 | 75 | if not _new_version_available(): 76 | return 77 | 78 | if current_version() is None: 79 | update_from_unnamed_version() 80 | return 81 | 82 | # for the front template, update the code part, the version number and the config on the front template, 83 | # keep the rest as it is so that users can customize the other parts of the template 84 | seperator = "" 85 | cur_front = model["tmpls"][0]["qfmt"] 86 | incoming_front = enhanced_cloze()["tmpls"][0]["qfmt"] 87 | 88 | cur_sep_m = re.search(seperator, cur_front) 89 | incoming_sep_m = re.search(seperator, incoming_front) 90 | if not cur_sep_m: 91 | print("Could not find seperator comment, replacing whole front template") 92 | model["tmpls"][0]["qfmt"] = incoming_front 93 | else: 94 | cur_before_sep = cur_front[: cur_sep_m.start()] 95 | incoming_after_sep = incoming_front[incoming_sep_m.end() :] 96 | new_front = f"{cur_before_sep}{seperator}{incoming_after_sep}" 97 | new_front = set_version(new_front, incoming_version()) 98 | new_front = maybe_add_config_option( 99 | new_front, 100 | "animateScroll", 101 | "var animateScroll = true", 102 | "scrollToClozeOnToggle", 103 | ) 104 | new_front = maybe_add_config_option( 105 | new_front, 106 | "showHintsForPseudoClozes", 107 | "var showHintsForPseudoClozes = true", 108 | "animateScroll", 109 | ) 110 | new_front = maybe_add_config_option( 111 | new_front, 112 | "underlineRevealedPseudoClozes", 113 | "var underlineRevealedPseudoClozes = true", 114 | "showHintsForPseudoClozes", 115 | ) 116 | new_front = maybe_add_config_option( 117 | new_front, 118 | "underlineRevealedGenuineClozes", 119 | "var underlineRevealedGenuineClozes = true", 120 | "underlineRevealedPseudoClozes", 121 | ) 122 | new_front = maybe_add_config_option( 123 | new_front, 124 | "revealPseudoClozesByDefault", 125 | "var revealPseudoClozesByDefault = false", 126 | "underlineRevealedGenuineClozes", 127 | ) 128 | new_front = maybe_add_config_option( 129 | new_front, 130 | "swapLeftAndRightBorderActions", 131 | "var swapLeftAndRightBorderActions = false", 132 | "revealPseudoClozesByDefault", 133 | ) 134 | model["tmpls"][0]["qfmt"] = new_front 135 | 136 | # update the back template 137 | model["tmpls"][0]["afmt"] = enhanced_cloze()["tmpls"][0]["afmt"] 138 | 139 | mw.col.models.update_dict(model) 140 | 141 | 142 | def maybe_add_config_option( 143 | front: str, option_name: str, line_to_be_added: str, previous_option_name: str 144 | ) -> str: 145 | # hacky way to add options to the CONFIG, the CONFIG being the section of the front template 146 | # before the comment 147 | # the text in to be added will be added after previous_option where previous_option 148 | # is the name of a configuration variable 149 | 150 | assert option_name in line_to_be_added 151 | 152 | config_m = re.search(r"([\w\W]*?)", front) 153 | config_str = config_m.group(1) 154 | 155 | if option_name in config_str: 156 | return front 157 | 158 | new_config_str = re.sub( 159 | f"(?<=\n)(.*)(var +{previous_option_name}.+)\n", 160 | rf"\1\2\n\1{line_to_be_added}\n", 161 | config_str, 162 | ) 163 | result = f"{new_config_str}{front[len(config_str) :]}" 164 | return result 165 | 166 | 167 | def update_from_unnamed_version() -> None: 168 | if not askUser( 169 | title="Enhanced Cloze", 170 | text=UPDATE_MSG, 171 | defaultno=True, 172 | ): 173 | return 174 | 175 | mm = mw.col.models 176 | model = mm.by_name(MODEL_NAME) 177 | 178 | def remove_field_if_exists(field_name, model): 179 | if field_name in mm.field_names(model): 180 | mm.remove_field(model, mm.field_map(model)[field_name][1]) 181 | 182 | fields_to_remove = [f"Cloze{i}" for i in range(1, 51)] 183 | fields_to_remove.extend( 184 | [ 185 | "data", 186 | "In-use Clozes", 187 | ] 188 | ) 189 | 190 | for field in fields_to_remove: 191 | remove_field_if_exists(field, model) 192 | 193 | load_enhanced_cloze(model) 194 | mm.update(model) 195 | 196 | 197 | def enhanced_cloze() -> "NotetypeDict": 198 | result = deepcopy(enhancedModel) 199 | load_enhanced_cloze(result) 200 | return result 201 | 202 | 203 | def load_enhanced_cloze(note_type: "NotetypeDict") -> None: 204 | front_path = NOTE_TYPE_DIR / "Enhanced_Cloze_Front_Side.html" 205 | css_path = NOTE_TYPE_DIR / "Enhanced_Cloze_CSS.css" 206 | back_path = NOTE_TYPE_DIR / "Enhanced_Cloze_Back_Side.html" 207 | 208 | with open(front_path) as f: 209 | front = f.read() 210 | with open(back_path) as f: 211 | back = f.read() 212 | with open(css_path) as f: 213 | styling = f.read() 214 | 215 | note_type["tmpls"][0]["qfmt"] = front 216 | note_type["tmpls"][0]["afmt"] = back 217 | note_type["css"] = styling 218 | 219 | 220 | def update_model_options_with_config_values() -> None: 221 | # Create a string with the config variables and their values as javascript variables 222 | conf_lines = [] 223 | for key in conf: 224 | value = conf[key] 225 | if isinstance(value, str): 226 | value = f'"{value}"' 227 | elif isinstance(value, bool): 228 | value = "true" if value else "false" 229 | conf_lines.append(f"var {key}={value}") 230 | conf_str = "\n".join(conf_lines) 231 | 232 | # Update the front template with the config variables 233 | model = mw.col.models.by_name(MODEL_NAME) 234 | front = model["tmpls"][0]["qfmt"] 235 | front = re.sub( 236 | r"(?=\n)", 237 | f"", 238 | front, 239 | ) 240 | assert conf_str in front, "Could not update note type options" 241 | model["tmpls"][0]["qfmt"] = front 242 | 243 | mw.col.models.update_dict(model) 244 | 245 | 246 | def config_values_from_model() -> Dict[str, Union[str, bool]]: 247 | """Get the config values from the javascript variables on the model's front template""" 248 | front = mw.col.models.by_name(MODEL_NAME)["tmpls"][0]["qfmt"] 249 | config_m = re.search(r"([\w\W]*?)", front) 250 | config_str = config_m.group(1) 251 | config_lines = config_str.split("\n") 252 | config_lines = [ 253 | stripped_line 254 | for line in config_lines 255 | if (stripped_line := line.strip()).startswith("var") 256 | ] 257 | result = {} 258 | for line in config_lines: 259 | m = re.match(r"var +(.+?) *= *(.+)", line) 260 | if not m: 261 | continue 262 | key, value = m.groups() 263 | if value == "true": 264 | value = True 265 | elif value == "false": 266 | value = False 267 | elif value.startswith('"') and value.endswith('"'): 268 | value = value[1:-1] 269 | result[key] = value 270 | 271 | return result 272 | -------------------------------------------------------------------------------- /src/enhanced_cloze/note_type/Enhanced_Cloze_Back_Side.html: -------------------------------------------------------------------------------- 1 | {{FrontSide}} 2 | 3 | {{cloze:Content}} 4 | 19 | -------------------------------------------------------------------------------- /src/enhanced_cloze/note_type/Enhanced_Cloze_CSS.css: -------------------------------------------------------------------------------- 1 | #card-body { 2 | font: 17px/1.65em 'Avenir Next'; 3 | text-align: justify; 4 | margin-top: 50px; 5 | margin-bottom: 60px; 6 | } 7 | 8 | .content { 9 | padding-left: 0.5em; 10 | border-left: 4px solid transparent; 11 | } 12 | 13 | .header { 14 | font: bold 17px/1.5em; 15 | padding-left: 0.5em; 16 | } 17 | 18 | .header-red { 19 | border-left: 4px solid #db4437; 20 | color: #db4437; 21 | } 22 | 23 | .header-green { 24 | border-left: 4px solid #0f9d58; 25 | color: #0f9d58; 26 | } 27 | 28 | .header-blue { 29 | border-left: 4px solid #4285f4; 30 | color: #4285f4; 31 | } 32 | 33 | .header-yellow { 34 | border-left: 4px solid #f4b400; 35 | color: #f4b400; 36 | } 37 | 38 | .genuine-cloze[show-state="hint"] { 39 | border-bottom: 2px solid #ff5c82; 40 | background-color: #ff96af; 41 | } 42 | 43 | .pseudo-cloze[show-state="hint"] { 44 | border-bottom: 2px solid #4285f4; 45 | background-color: #87b1ff; 46 | } 47 | 48 | #show-one-cloze-left, 49 | #show-one-cloze-right, 50 | #no-more-cloze { 51 | height: 100%; 52 | width: 30px; 53 | position: fixed; 54 | z-index: 9; 55 | top: 0; 56 | background-color: transparent; 57 | } 58 | 59 | #show-one-cloze-left { 60 | left: 0; 61 | } 62 | 63 | #show-one-cloze-right { 64 | right: 0; 65 | } 66 | 67 | #no-more-cloze { 68 | width: 10px; 69 | background-color: #db4437; 70 | left: 0; 71 | display: none; 72 | } 73 | 74 | #show-all-pseudo-clozes { 75 | height: 20px; 76 | width: 100%; 77 | position: fixed; 78 | z-index: 9; 79 | top: 0; 80 | left: 0; 81 | background-color: transparent; 82 | } 83 | 84 | .mobile ol, 85 | .mobile ul, 86 | .mobile li { 87 | margin-left: -0.5em; 88 | } 89 | 90 | .mobile li { 91 | margin: 0.1em, inherit; 92 | } 93 | 94 | table { 95 | border-collapse: collapse; 96 | margin: 0.5em; 97 | } 98 | 99 | thead tr, 100 | tfoot tr { 101 | border-top: 2px solid #0f9d58; 102 | border-bottom: 2px solid #0f9d58; 103 | } 104 | 105 | td, 106 | th { 107 | border: 1px solid #0f9d58; 108 | padding: 0.3em 0.5em; 109 | } 110 | 111 | hr { 112 | border-top: 1px solid #aaaaaa; 113 | width: 100%; 114 | margin: 0; 115 | padding: 0; 116 | } 117 | 118 | pre { 119 | border-left: 2px solid #0f9d58; 120 | padding-left: 10px; 121 | } 122 | 123 | code, 124 | kbd, 125 | var, 126 | samp, 127 | tt { 128 | background-color: #fdf3d6; 129 | } 130 | 131 | .disable-select { 132 | -webkit-touch-callout: none; 133 | user-select: none; 134 | } 135 | -------------------------------------------------------------------------------- /src/enhanced_cloze/note_type/Enhanced_Cloze_Front_Side.html: -------------------------------------------------------------------------------- 1 | 2 | 15 | 16 | 17 |
18 |
19 | 20 | 21 |
22 |
23 |
24 |
25 |
26 |

27 |
28 | {{#Note}} 29 |
30 |
31 | Note 32 |
33 | 36 |
37 |
38 |

39 | {{/Note}} 40 | 41 | {{#Mnemonics}} 42 |
43 |
44 | Mnemonics 45 |
46 | 49 |
50 |
51 |

52 | {{/Mnemonics}} 53 | 54 | 55 | {{#Extra}} 56 |
57 |
58 | Extra 59 |
60 | 63 |
64 |
65 |

66 | {{/Extra}} 67 | 68 | 69 |
70 |
71 | Information 72 |
73 | 74 | 86 |
87 |
88 | 89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 | 97 | 98 | 99 | 100 | 101 | 102 | {{cloze:Content}} 103 | 104 | 105 | {{cloze:Cloze99}} 106 | 107 | 606 | -------------------------------------------------------------------------------- /src/enhanced_cloze/note_type/model.py: -------------------------------------------------------------------------------- 1 | enhancedModel = { 2 | "vers": [], 3 | "name": "Enhanced Cloze 2.1 v2", 4 | "tags": [], 5 | "did": 1, 6 | "usn": -1, 7 | "flds": [ 8 | { 9 | "name": "Content", 10 | "media": [], 11 | "sticky": False, 12 | "rtl": False, 13 | "ord": 0, 14 | "font": "Arial", 15 | "size": 20, 16 | }, 17 | { 18 | "name": "Note", 19 | "media": [], 20 | "sticky": False, 21 | "rtl": False, 22 | "ord": 1, 23 | "font": "Arial", 24 | "size": 20, 25 | }, 26 | { 27 | "name": "Mnemonics", 28 | "media": [], 29 | "sticky": False, 30 | "rtl": False, 31 | "ord": 2, 32 | "font": "Arial", 33 | "size": 20, 34 | }, 35 | { 36 | "name": "Extra", 37 | "media": [], 38 | "sticky": False, 39 | "rtl": False, 40 | "ord": 3, 41 | "font": "Arial", 42 | "size": 20, 43 | }, 44 | { 45 | "name": "Cloze99", 46 | "media": [], 47 | "sticky": True, 48 | "rtl": False, 49 | "ord": 4, 50 | "font": "Arial", 51 | "size": 1, 52 | }, 53 | ], 54 | "sortf": 0, 55 | "tmpls": [ 56 | { 57 | "name": "Enhanced Cloze", 58 | "qfmt": "", 59 | "did": None, 60 | "bafmt": "", 61 | "afmt": "", 62 | "ord": 0, 63 | "bqfmt": "", 64 | } 65 | ], 66 | "mod": 1560146886, 67 | "latexPost": "\\end{document}", 68 | "type": 1, 69 | "id": 0, 70 | "css": "", 71 | "latexPre": """\\documentclass[12pt]{article} 72 | \\special{papersize=3in,5in} 73 | \\usepackage[utf8]{inputenc} 74 | \\usepackage{amssymb,amsmath} 75 | \\pagestyle{empty} 76 | \\setlength{\\parindent}{0in} 77 | \\begin{document} 78 | """, 79 | } 80 | -------------------------------------------------------------------------------- /src/enhanced_cloze/patches.py: -------------------------------------------------------------------------------- 1 | from anki.notes import Note 2 | from aqt import mw 3 | from aqt.editor import Editor 4 | from aqt.gui_hooks import add_cards_will_add_note 5 | from aqt.utils import tr 6 | 7 | from .constants import ANKI_VERSION_TUPLE, MODEL_NAME 8 | 9 | 10 | def setup_prevent_warnings_about_clozes() -> None: 11 | if ANKI_VERSION_TUPLE == (2, 1, 26): 12 | from anki.models import ModelManager 13 | 14 | original_availableClozeOrds = ( 15 | ModelManager._availClozeOrds # pylint: disable=protected-access 16 | ) 17 | 18 | def new_availClozeOrds(self, m, flds: str, allowEmpty: bool = True): 19 | if m["name"] != MODEL_NAME: 20 | return original_availableClozeOrds(self, m, flds, allowEmpty) 21 | 22 | # the exact value is not important, it has to be an non-empty array 23 | return [0] 24 | 25 | ModelManager._availClozeOrds = ( # type: ignore # pylint: disable=protected-access 26 | new_availClozeOrds 27 | ) 28 | elif ANKI_VERSION_TUPLE < (2, 1, 45): 29 | original_cloze_numbers_in_fields = Note.cloze_numbers_in_fields 30 | 31 | def new_cloze_numbers_in_fields(self): 32 | if self.note_type()["name"] != MODEL_NAME: 33 | return original_cloze_numbers_in_fields(self) 34 | 35 | # the exact value is not important, it has to be an non-empty array 36 | return [0] 37 | 38 | Note.cloze_numbers_in_fields = ( # type: ignore # pylint: disable=protected-access 39 | new_cloze_numbers_in_fields 40 | ) 41 | else: 42 | from anki.notes import NoteFieldsCheckResult 43 | 44 | original_update_duplicate_display = ( 45 | Editor._update_duplicate_display # pylint: disable=protected-access 46 | ) 47 | 48 | def _update_duplicate_display_ignore_cloze_problems_for_enh_clozes( 49 | self, result 50 | ) -> None: 51 | if self.note.note_type()["name"] == MODEL_NAME: 52 | if result == NoteFieldsCheckResult.NOTETYPE_NOT_CLOZE: 53 | result = NoteFieldsCheckResult.NORMAL 54 | if result == NoteFieldsCheckResult.FIELD_NOT_CLOZE: 55 | result = NoteFieldsCheckResult.NORMAL 56 | original_update_duplicate_display(self, result) 57 | 58 | Editor._update_duplicate_display = ( # type: ignore # pylint: disable=protected-access 59 | _update_duplicate_display_ignore_cloze_problems_for_enh_clozes 60 | ) 61 | 62 | def ignore_some_cloze_problems_for_enh_clozes(problem, note): 63 | if note.note_type()["name"] != MODEL_NAME: 64 | return problem 65 | 66 | if problem == tr.adding_cloze_outside_cloze_notetype(): 67 | return None 68 | elif problem == tr.adding_cloze_outside_cloze_field(): 69 | return None 70 | else: 71 | return problem 72 | 73 | add_cards_will_add_note.append(ignore_some_cloze_problems_for_enh_clozes) 74 | 75 | # the warning about no clozes in the field will still show up in version lower 2.1.45 76 | original_fields_check = Note.fields_check 77 | 78 | def new_fields_check(self): 79 | result = original_fields_check(self) 80 | 81 | if mw.col.models.get(self.mid)["name"] != MODEL_NAME: 82 | return result 83 | 84 | if result == NoteFieldsCheckResult.MISSING_CLOZE: 85 | return None 86 | else: 87 | return result 88 | 89 | Note.fields_check = new_fields_check # type: ignore 90 | -------------------------------------------------------------------------------- /src/enhanced_cloze/setup_jquery.py: -------------------------------------------------------------------------------- 1 | import shutil 2 | 3 | from aqt.gui_hooks import profile_did_open 4 | 5 | from pathlib import Path 6 | import aqt 7 | 8 | 9 | # Name of the jQuery file in the resources folder. 10 | # This has to be the same filename as the card template uses. 11 | # The underscore in the front prevents Anki from cleaning up the file when Check Media is run. 12 | JQUERY_FILE_NAME = "_jquery.min.js" 13 | JQUERY_PATH = Path(__file__).parent / "resources" / JQUERY_FILE_NAME 14 | 15 | 16 | def setup_maybe_add_jquery_to_media_folder() -> None: 17 | profile_did_open.append(_maybe_add_jquery_to_media_folder) 18 | 19 | 20 | def _maybe_add_jquery_to_media_folder() -> None: 21 | media_folder = Path(aqt.mw.col.media.dir()) 22 | media_folder_jquery_path = media_folder / JQUERY_FILE_NAME 23 | if not media_folder_jquery_path.exists(): 24 | shutil.copy(JQUERY_PATH, media_folder_jquery_path) 25 | --------------------------------------------------------------------------------