├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── ISSUE_TEMPLATE.md ├── LICENSE ├── README.md ├── build_zip.sh ├── new_dialogs_preview.png ├── night_mode ├── __init__.py ├── actions_and_settings.py ├── color_map.py ├── config.py ├── css_class.py ├── gui.py ├── icons.py ├── internals.py ├── languages.py ├── locale │ ├── de │ │ └── LC_MESSAGES │ │ │ └── Anki-Night-Mode.mo │ ├── hy │ │ └── LC_MESSAGES │ │ │ └── Anki-Night-Mode.mo │ ├── pl │ │ └── LC_MESSAGES │ │ │ └── Anki-Night-Mode.mo │ └── sv │ │ └── LC_MESSAGES │ │ └── Anki-Night-Mode.mo ├── menu.py ├── mode.py ├── night_mode.py ├── selector.py ├── stylers.py └── styles.py ├── preview.png ├── run_tests.sh └── tests ├── test_decorators.py └── test_styler.py /.gitignore: -------------------------------------------------------------------------------- 1 | anki_root 2 | anki_testing 3 | 4 | # Byte-compiled / optimized / DLL files 5 | __pycache__/ 6 | *.py[cod] 7 | *$py.class 8 | 9 | # Release file 10 | night_mode.zip 11 | 12 | # C extensions 13 | *.so 14 | 15 | # Distribution / packaging 16 | .Python 17 | build/ 18 | develop-eggs/ 19 | dist/ 20 | downloads/ 21 | eggs/ 22 | .eggs/ 23 | lib/ 24 | lib64/ 25 | parts/ 26 | sdist/ 27 | var/ 28 | wheels/ 29 | *.egg-info/ 30 | .installed.cfg 31 | *.egg 32 | MANIFEST 33 | 34 | # PyInstaller 35 | # Usually these files are written by a python script from a template 36 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 37 | *.manifest 38 | *.spec 39 | 40 | # Installer logs 41 | pip-log.txt 42 | pip-delete-this-directory.txt 43 | 44 | # Unit test / coverage reports 45 | htmlcov/ 46 | .tox/ 47 | .coverage 48 | .coverage.* 49 | .cache 50 | nosetests.xml 51 | coverage.xml 52 | *.cover 53 | .hypothesis/ 54 | 55 | # Translations 56 | *.mo 57 | *.pot 58 | 59 | # Django stuff: 60 | *.log 61 | local_settings.py 62 | 63 | # Flask stuff: 64 | instance/ 65 | .webassets-cache 66 | 67 | # Scrapy stuff: 68 | .scrapy 69 | 70 | # Sphinx documentation 71 | docs/_build/ 72 | 73 | # PyBuilder 74 | target/ 75 | 76 | # Jupyter Notebook 77 | .ipynb_checkpoints 78 | 79 | # pyenv 80 | .python-version 81 | 82 | # celery beat schedule file 83 | celerybeat-schedule 84 | 85 | # SageMath parsed files 86 | *.sage.py 87 | 88 | # Environments 89 | .env 90 | .venv 91 | env/ 92 | venv/ 93 | ENV/ 94 | env.bak/ 95 | venv.bak/ 96 | 97 | # Spyder project settings 98 | .spyderproject 99 | .spyproject 100 | 101 | # Rope project settings 102 | .ropeproject 103 | 104 | # mkdocs documentation 105 | /site 106 | 107 | # mypy 108 | .mypy_cache/ 109 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | sudo: required 3 | 4 | python: 5 | - 3.6 6 | 7 | install: 8 | - git clone https://github.com/krassowski/anki_testing 9 | - source anki_testing/setup.sh 10 | 11 | script: 12 | - bash run_tests.sh 13 | 14 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ### 2.3.3 2 | *January 29, 2020* 3 | - Fix compatibility with other add-ons (thanks to @lovac42) 4 | 5 | ### 2.3.2 6 | *January 25, 2020* 7 | - Fix the "sidebar not resizing" bug (thanks to @lovac42) 8 | - Fix the profile switching bug (thanks to @lovac42) 9 | 10 | ### 2.3.1 11 | *January 18, 2020* 12 | - Fix/improve the browser's sidebar compatibility issues related to the 2.1.17 release (thanks to @lovac42) 13 | 14 | ### 2.3.0 15 | *January 12, 2020* 16 | - Delay loading to allow for compatibility with @lovac42's (and potentially others) add-ons (thanks to @lovac42) 17 | - Adapt styling of the browser's sidebar to the changes introduced in Anki 2.1.17 (thanks to @zjosua) 18 | 19 | ### 2.2.4 20 | *April 20, 2019* 21 | - Improve styling to eliminate the white rectangle around buttons in the editor in night mode (introduced by Anki 2.1.8) 22 | 23 | ### 2.2.3 24 | *October 24, 2018* 25 | - Apply night_mode class to Overview and DeckBrowser for future compatibility with Review Heatmap 0.7 26 | - Improve the white background workaround to handle text including bold elements 27 | 28 | ### 2.2.2 29 | *September 26, 2018* 30 | - Add German translation (by Is) 31 | - Improve the workaround eliminating white backgrounds after using "backspace", "delete", or pasting 32 | 33 | ### 2.2.1 34 | *September 26, 2018* 35 | - Add Swedish translation (by Jeremias) 36 | - Fix jumping cursor when deleting the last letter in the edit field 37 | 38 | ### 2.2.0 39 | *September 25, 2018* 40 | - Add Armenian (by Arman High) and Polish translations #47 41 | - Workaround a bug causing white background to appear after deleting a new line #27 42 | - Ensure that text in HTML/Latex edit windows are readable #44 43 | 44 | ### 2.1.9 45 | *August 11, 2018* 46 | - Invert icons in sidebar of browser #28 47 | - Improve dark scrollbars appearance on Windows 48 | - Make it possible to use arrow-down icon in browser on Windows again 49 | - Improve horizontal splitter styling in browser 50 | 51 | ### 2.1.8 52 | *August 8, 2018* 53 | - Add dark styling of scrollbars #35 54 | - Improve styling of CardLayout (card types) modal window 55 | - Fix night_mode CSS class being overwritten on question side by the new, fancy Anki fade-in transition logic #41 56 | 57 | ### 2.1.7 58 | *June 12, 2018* 59 | - Allow to selectively disable reviewer card's styling in the "Choose what to style" dialog #38 60 | - Sort stylers in the "Choose what to style" dialog alphabetically 61 | - Add "check all / uncheck all" to in "Choose what to style" dialog 62 | - Fix night_mode CSS class being applied regardless of night mode state #37 63 | 64 | ### 2.1.6 65 | *February 21, 2018* 66 | - Improve visibility of items in table in browser #28 (thanks nathanmalloy!) 67 | - Provide potential workaround for Qt bug causing Chinese text to be rendered black when selected 68 | 69 | ### 2.1.5 70 | *January 21, 2017* 71 | - Allow to selectively disable parts of the add-on #26, #25 72 | 73 | ### 2.1.4 74 | *January 20, 2017* 75 | - Add styling to "Statistics" window (when "enable in dialogs" is on) #9 76 | 77 | ### 2.1.3 78 | *January 15, 2017* 79 | - Add compatibility with 2.1 beta 31 (which changed progress dialogs interface) 80 | 81 | 82 | ### 2.1.2 83 | *September 23, 2017* 84 | - Use night mode colors for synchronization/backup progress pop-up dialogs. 85 | - Minor fix: make selected rows in card browser use night mode colors again. 86 | 87 | Please note that the new options are only available in addon when running Anki 2.1.x 88 | 89 | ### 2.1 90 | *September 22, 2017* 91 | - new option: "Automatic mode" (suggested by p2635: #22) - allows to set times at which the nigh mode should be automatically turned on and off. 92 | - new option: "Customise colors on cards" - defining custom color mappings just got easier with a new dedicated dialog window - no need to modify source files anymore! 93 | 94 | Please note that the new options are only available in addon when running Anki 2.1.x 95 | 96 | ### 2.0 97 | *September 19, 2017* 98 | - new, rewritten addon, compatible with Anki 2.1.x Beta 13+. 99 | 100 | ### 1.2.3 101 | *September 6, 2017* 102 | - bug fix: make text over difficulty buttons easier to read 103 | 104 | ### 1.2.2 105 | *August 3, 2017* 106 | - bug fix for Anki 2.1 beta 6 107 | 108 | ### 1.2.1 109 | *August 3, 2017* 110 | - support for Anki 2.1 beta 6 111 | 112 | ### 1.2.0 113 | *March 6, 2017* 114 | - initial support for Anki 2.1 (thanks to b50) 115 | - new option: "Force transparent latex" - assures that latex generation has '-bg transparent' option included. 116 | - compatibility with Again Hard Good Easy wide big buttons (thanks ankitest) 117 | 118 | ### 1.1.4 119 | *March 4, 2016* 120 | - added display of visual indication when a button is focused 121 | - small improvements in the code 122 | 123 | ### 1.1.3 124 | *January 29, 2016* 125 | - added rule for styling deck's (collapsed/expanded) indicator (+/-) 126 | 127 | ### 1.1.2 128 | *December 16, 2015* 129 | - improved "invert" function compatibility with different systems 130 | - increased links visibility on cards in Night Mode - general performance improvements, especially in card editor (you may notice changes if you are using "enable in dialogs" option) 131 | - small code cleanings 132 | 133 | ### 1.1.0 134 | *November 1, 2015* 135 | 136 | Improvements: 137 | - better styling of browser window, 138 | - lighter colors for filtered decks and decks descriptions in Night Mode, 139 | - some code refinements, allowing easy customization of constants which are not available to edit in GUI. 140 | 141 | ### 1.0.8 142 | *July 8, 2015* 143 | 144 | New features: 145 | - whole browser window is now styled, 146 | - card information window is also styled. 147 | Bugfixes: 148 | - Rare bug: TypeError: cannot concatenate 'str' and 'function' objects should be gone. 149 | 150 | ### 1.0.6 151 | *June 5, 2015* 152 | 153 | ![Dialogs preview](https://raw.githubusercontent.com/krassowski/Anki-Night-Mode/master/new_dialogs_preview.png) 154 | 155 | New features: 156 | - "add card" and "edit current card" are now styled too (if the option "Enable in dialogs" is selected in menu) 157 | - there is the class name "night_mode" when the night_mode is active (like in AnkiDroid) 158 | Bugfixes: 159 | - workaround for Qt error with styling function (at now night mode can be switched only outside dialogs) 160 | 161 | ### 1.0.2 162 | *April 10, 201* 163 | - Added: dark skin for all menus in Night Mode 164 | 165 | ### 1.0.1 166 | *April 8, 2015* 167 | - Improvement: lighter color of clozes forced in stylesheets for better readability 168 | -------------------------------------------------------------------------------- /ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | #### Problem description 2 | 3 | *Describe problem concisely in here* 4 | 5 | #### Checklist 6 | 7 | *Please put x inside brackets if following sentences apply to you:* 8 | 9 | - [ ] I verified that I use the lastest add-on version, 10 | - [ ] I verified that I use the lastest Anki version, 11 | - [ ] I tried to disable other add-ons to find the culprit, 12 | - [ ] I checked if anyone reported this problem before, as well as Known issues section on add-ons page, 13 | - [ ] My issue is solved when holding shift while starting Anki. 14 | 15 | #### Information about your Anki Setup 16 | 17 |
18 | 19 | *Please open Anki, go to Help → About, look-up two lines, starting with `Version:` and `Qt` and copy-paste them below:* 20 | 21 | ``` 22 | Version: 23 | Qt: 24 | ``` 25 | 26 | *Please got to Night Mode → About now and copy-paste the first line from the pop-up window below:* 27 | 28 | ``` 29 | Night Mode x.x.x 30 | ``` 31 | 32 | *Please fill in your OS details (Linux/Mac/Windows):* 33 | 34 | ``` 35 | OS: 36 | ``` 37 | 38 | 39 | *If you have a compatibility problem with a specific add-on or add-ons, please paste the add-on page links below:* 40 | - [Other add-on name](https://) 41 |
42 | 43 | #### Backtrace (if any) 44 | 45 |
46 | 47 | *If you had an error which resulted in producing exception with a backtrace, please paste the backtrace below:* 48 | 49 | ```python" 50 | [paste your backtrace in here if you got any; otherwise feel free to remove this part] 51 | ``` 52 | 53 |
54 | -------------------------------------------------------------------------------- /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 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 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 | {project} Copyright (C) {year} {fullname} 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 | 676 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Anki-Night-Mode 2 | [![Build Status](https://travis-ci.org/krassowski/Anki-Night-Mode.svg?branch=master)](https://travis-ci.org/krassowski/Anki-Night-Mode) [![Code Climate](https://codeclimate.com/github/krassowski/Anki-Night-Mode/badges/gpa.svg)](https://codeclimate.com/github/krassowski/Anki-Night-Mode) 3 | 4 | This plugin adds a functionality of night mode, similar to the one implemented in AnkiDroid app. 5 | 6 | ## Archiving note 7 | 8 | Recent versions of Anki (2.1.20+) introduced built-in Night Mode support. While it does not have all the features that this add-on offered, it causes fewer conflicts and does not require a never-ending maintenance burden due to the limited add-ons API and breaking changes in the interfaces. You are advised to upgrade Anki and use the built-in night mode instead of this add-on; please report any missing features to the Anki authors. 9 | 10 | To prevent user confusion this repository has been archived but you are welcome to install the old versions as legacy support, or to contact the author (who still uses Anki) if you wish to port this add-on to a newer version ([see this issue](https://github.com/krassowski/Anki-Night-Mode/issues/101#issuecomment-626913211)). 11 | 12 | It was fun 5 years; many thanks to all contributors listed [here](https://github.com/krassowski/Anki-Night-Mode/blob/master/night_mode/night_mode.py#L25-L38) and [there](https://github.com/krassowski/Anki-Night-Mode/graphs/contributors) and to all of you: friendly users who encouraged developement and maintenance. 13 | 14 | ### How it works? 15 | 16 | It adds a "view" menu entity with options like: 17 | - Automatic (i.e. at specified time) or manual switching of the night mode 18 | - Inverting colors of images or latex formulas 19 | - Defining custom color substitution rules 20 | 21 | It provides shortcut ctrl+n to quickly switch mode and color picker to adjust some of color parameters. 22 | 23 | After enabling the night mode, the add-on changes colors of menubar, toolbar, bottombars and content windows. Take a look at a screenshot at the bottom of this page to see an example. 24 | 25 | ### Compatibility 26 | 27 | The add-on supports Anki in 2.1 version. While there is an older version of the add-on written for Anki 2.0, it is no longer supported as Anki 2.0 uses [well oudated and unsecure](https://github.com/krassowski/Anki-Night-Mode/issues/79#issuecomment-517806633) technology which lead to a large number of [difficult do diagnose issues](https://github.com/krassowski/Anki-Night-Mode/issues?utf8=✓&q=+label%3Aold-version+). 28 | 29 | ### How can I get it? 30 | 31 | #### Automatic install 32 | 33 | You can download this add-on from within the Anki app. 34 | From menu select: `Tools >> Add-ons >> Browse && Install...` and type the following code: 35 | 36 | ```python 37 | 1496166067 38 | ``` 39 | 40 | after clicking `ok` the add-on will be downloaded and installed. You neeed to restart Anki to enable changes. 41 | 42 | To switch into the night mode you can use ctrl+n shortcut, or use one of the new options in the menu: `View >> Night Mode >> ...`. 43 | 44 | #### Manual installation 45 | 46 | For the most recent updates and additions you may want to install a newer version of this addon manually. 47 | Follow this steps: 48 | 49 | 1. Get the newest version of `night_mode` directory from GitHub 50 | 2. Run Anki, from menu select `Tools >> Add-ons >> Open Add-ons Folder...` to open add-ons directory 51 | 4. Copy downloaded directory into the directory opened in the previous step 52 | 5. Restart Anki and enjoy the latest features! 53 | 54 | #### After installation 55 | 56 | Please, leave any feedback on [Anki webpage](https://ankiweb.net/shared/info/1496166067) or let me know of any issues here, on GitHub. 57 | 58 | ### Preview 59 | 60 | ![Preview](https://raw.githubusercontent.com/krassowski/Anki-Night-Mode/master/preview.png) 61 | 62 | 63 | ### Tags color in the edit window 64 | 65 | The Mac OS users might experience an issue with the tags colors in the edit window. There are couple of workarounds proposed for this, one of which is disabling the edit widow styling and another (proposed [here](https://github.com/krassowski/Anki-Night-Mode/issues/59#issuecomment-517092923)) depends on a new functionality of Mojave system: 66 | 67 | - close Anki 68 | - paste the following command in the Terminal: 69 | ```bash 70 | defaults write net.ankiweb.dtop NSRequiresAquaSystemAppearance -bool no 71 | ``` 72 | - restart Anki 73 | 74 | The application (including title bar) should be styled dark now and the tags box contrast problem should be resolved. Please let us know if it worked for you [here](https://github.com/krassowski/Anki-Night-Mode/issues/59). 75 | 76 | 77 | ### For developers & translators 78 | 79 | Feel free to contribute, send bug reports or feature requests :) 80 | 81 | If you can help translate the add-on to your language, please join us [at POEditor](https://poeditor.com/join/project/0waBVUY8oC). 82 | 83 | 84 | #### Custom CSS in night mode 85 | 86 | You may use `night_mode` class, to overwrite some of the CSS rules; sometimes usage of `important!` directive or catch-all selector (`*`) will be needed to enforce you own styling. Examples: 87 | 88 | #### Change color of every piece of text: 89 | 90 | ```css 91 | .night_mode * { 92 | color: red; 93 | } 94 | ``` 95 | 96 | #### Change card background 97 | 98 | ```css 99 | .night_mode.card { 100 | background: red !important; 101 | } 102 | ``` 103 | 104 | #### Specifically replace a background of an element 105 | 106 | given the HTML of your card: 107 | 108 | ```html 109 |
Normal text highlighted text
110 | ``` 111 | 112 | ```css 113 | .night_mode span[style="background-color: rgb(240, 244, 198);"] { 114 | background-color: red!important; 115 | } 116 | ``` 117 | 118 | #### Change the color of a cloze 119 | 120 | ```css 121 | .night_mode .cloze { 122 | color: red!important; 123 | } 124 | ``` 125 | 126 | ### Add-ons compatibility 127 | 128 | Add-ons which are known to work well with the night mode: 129 | - [Anki-TouchScreen](https://github.com/krassowski/Anki-TouchScreen) 130 | - [Anki-Zoom](https://github.com/krassowski/Anki-Zoom) 131 | 132 | If you add-on works well Night Mode, please feel free to add your add-on on to the list above by editing this file (proposing a change)! 133 | -------------------------------------------------------------------------------- /build_zip.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | cd night_mode 3 | zip -r night_mode.zip * -x __pycache__/* -x __pycache__/ 4 | cp night_mode.zip .. 5 | -------------------------------------------------------------------------------- /new_dialogs_preview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/krassowski/Anki-Night-Mode/b7bd89878ed3b1deeea92549059670c6be5e8614/new_dialogs_preview.png -------------------------------------------------------------------------------- /night_mode/__init__.py: -------------------------------------------------------------------------------- 1 | from aqt import mw 2 | from anki.hooks import addHook 3 | 4 | 5 | #addons should selectively load before or after a delay of 666 6 | NM_RESERVED_DELAY = 666 7 | 8 | night_mode = None 9 | 10 | def delayedLoader(): 11 | """ 12 | Delays loading of NM to avoid addon conflicts. 13 | """ 14 | global night_mode 15 | from .night_mode import NightMode 16 | night_mode = NightMode() 17 | night_mode.load() 18 | 19 | def onProfileLoaded(): 20 | if not night_mode: 21 | mw.progress.timer( 22 | NM_RESERVED_DELAY, delayedLoader, False 23 | ) 24 | else: 25 | night_mode.load() 26 | 27 | addHook('profileLoaded', onProfileLoaded) 28 | -------------------------------------------------------------------------------- /night_mode/actions_and_settings.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | 3 | from PyQt5.QtCore import QTimer 4 | from PyQt5.QtGui import QColor 5 | from PyQt5.QtWidgets import QColorDialog 6 | 7 | from .internals import Setting, MenuAction, alert 8 | from .color_map import ColorMapWindow 9 | from .mode import ModeWindow 10 | from .selector import StylersSelectorWindow 11 | 12 | 13 | class UserColorMap(Setting, MenuAction): 14 | value = {'#000000': 'white'} 15 | window = None 16 | label = 'Customise colors on cards' 17 | 18 | def action(self): 19 | from aqt import mw as main_window 20 | if not self.window: 21 | # self.value is mutable, any modifications done by ColorMapWindow 22 | # will be done on the value of this singleton class object 23 | self.window = ColorMapWindow( 24 | main_window, 25 | self.value, 26 | on_update=self.on_colors_changed 27 | ) 28 | self.window.show() 29 | 30 | def on_colors_changed(self): 31 | self.app.refresh() 32 | 33 | 34 | class InvertImage(Setting, MenuAction): 35 | """Toggles image inversion. 36 | 37 | To learn how images are inverted check also append_to_styles(). 38 | """ 39 | 40 | # setting 41 | value = False 42 | 43 | # menu action 44 | label = '&Invert images' 45 | checkable = True 46 | 47 | def action(self): 48 | self.value = not self.value 49 | self.app.refresh() 50 | 51 | 52 | class InvertLatex(Setting, MenuAction): 53 | """Toggles latex inversion. 54 | 55 | Latex formulas are nothing more than images with class "latex". 56 | To learn how formulas are inverted check also append_to_styles(). 57 | """ 58 | value = False 59 | label = 'Invert &latex' 60 | checkable = True 61 | 62 | def action(self): 63 | self.value = not self.value 64 | self.app.refresh() 65 | 66 | 67 | class TransparentLatex(Setting, MenuAction): 68 | """Toggles transparent latex generation. 69 | 70 | See make_latex_transparent() for details. 71 | """ 72 | value = False 73 | label = 'Force transparent latex' 74 | checkable = True 75 | 76 | def action(self): 77 | self.value = not self.value 78 | if self.value: 79 | self.make_latex_transparent() 80 | 81 | def make_latex_transparent(self): 82 | """Overwrite latex generation commands to use transparent images. 83 | 84 | Already generated latex images won't be affected; 85 | delete those manually from your media folder in order 86 | to regenerate images in transparent version. 87 | """ 88 | 89 | commands = self.get_commands() 90 | 91 | for command in commands: 92 | command[1] = [ 93 | "dvipng", 94 | "-D", "200", 95 | "-T", "tight", 96 | "-bg", "Transparent", 97 | "-z", "9", # use maximal PNG compression 98 | "tmp.dvi", 99 | "-o", "tmp.png" 100 | ] 101 | 102 | @staticmethod 103 | def get_commands(): 104 | from anki.latex import pngCommands 105 | from anki.latex import svgCommands 106 | commands = [] 107 | commands.extend([pngCommands, svgCommands]) 108 | return commands 109 | 110 | def on_load(self): 111 | if self.value: 112 | self.make_latex_transparent() 113 | 114 | 115 | class ColorAction(Setting, MenuAction): 116 | 117 | def action(self): 118 | qt_color_old = QColor(self.value) 119 | qt_color = QColorDialog.getColor(qt_color_old) 120 | 121 | if qt_color.isValid(): 122 | self.value = qt_color.name() 123 | self.app.refresh() 124 | 125 | 126 | class TextColor(ColorAction): 127 | """ 128 | Open color picker and set chosen color to text (in content) 129 | """ 130 | name = 'color_t' 131 | value = '#ffffff' 132 | label = 'Set &text color' 133 | 134 | 135 | class BackgroundColor(ColorAction): 136 | """ 137 | Open color picker and set chosen color to background (of content) 138 | """ 139 | name = 'color_b' 140 | value = '#272828' 141 | label = 'Set &background color' 142 | 143 | 144 | class AuxiliaryBackgroundColor(ColorAction): 145 | """ 146 | Open color picker and set chosen color to auxiliary background (of content) 147 | """ 148 | name = 'color_s' 149 | value = '#373838' 150 | label = 'Set &auxiliary background color' 151 | 152 | 153 | # TODO: include in menu 154 | class ActiveBackgroundColor(ColorAction): 155 | """ 156 | Open color picker and set chosen color to auxiliary background (of content) 157 | """ 158 | name = 'color_a' 159 | value = '#443477' 160 | label = 'Set active color' 161 | 162 | 163 | class ResetColors(MenuAction): 164 | """Reset colors""" 165 | label = '&Reset background and text colors' 166 | 167 | def action(self): 168 | self.app.config.color_b.reset() 169 | self.app.config.color_t.reset() 170 | self.app.refresh() 171 | 172 | 173 | class About(MenuAction): 174 | """Show "about" window""" 175 | label = '&About...' 176 | 177 | def action(self): 178 | self.app.about() 179 | 180 | 181 | class EnableInDialogs(Setting, MenuAction): 182 | """Switch for night mode in dialogs""" 183 | value = True 184 | label = 'Enable in &dialogs' 185 | checkable = True 186 | 187 | def action(self): 188 | self.value = not self.value 189 | 190 | 191 | class StyleScrollBars(Setting, MenuAction): 192 | value = True 193 | label = 'Dark Scroll Bars' 194 | checkable = True 195 | 196 | def action(self): 197 | self.value = not self.value 198 | self.app.refresh() 199 | 200 | 201 | class ModeSettings(Setting, MenuAction): 202 | value = { 203 | 'mode': 'manual', 204 | 'start_at': '21:30', 205 | 'end_at': '07:30' 206 | } 207 | window = None 208 | label = 'Start automatically' 209 | checkable = True 210 | 211 | @property 212 | def is_checked(self): 213 | return self.mode == 'auto' 214 | 215 | @property 216 | def mode(self): 217 | return self.value['mode'] 218 | 219 | def action(self): 220 | from aqt import mw as main_window 221 | 222 | if not self.window: 223 | # self.value is mutable, any modifications done by ColorMapWindow 224 | # will be done on the value of this singleton class object 225 | self.window = ModeWindow( 226 | main_window, 227 | self.value, 228 | on_update=self.update 229 | ) 230 | self.window.show() 231 | self.app.update_menu() 232 | 233 | def update(self): 234 | self.app.refresh() 235 | 236 | @property 237 | def is_active(self): 238 | current_time = datetime.now().time() 239 | start = self.time('start_at') 240 | end = self.time('end_at') 241 | if end > start: 242 | return start <= current_time <= end 243 | else: 244 | return start <= current_time or current_time <= end 245 | 246 | def time(self, which): 247 | return datetime.strptime(self.value[which], '%H:%M').time() 248 | 249 | 250 | class EnableNightMode(Setting, MenuAction): 251 | """Switch night mode""" 252 | value = False 253 | label = '&Enable night mode' 254 | shortcut = 'Ctrl+n' 255 | checkable = True 256 | 257 | require = { 258 | ModeSettings, 259 | # 'StateSettings' (circular dependency) 260 | } 261 | 262 | def action(self): 263 | self.value = not self.value 264 | 265 | if self.mode_settings.mode != 'manual': 266 | alert( 267 | 'Automatic Night Mode has been disabled. ' 268 | '(You pressed "ctrl+n" or switched a toggle in the menu). ' 269 | 'Now you can toggle Night Mode manually ' 270 | 'or re-enable the Automatic Night Mode in the menu. ' 271 | ) 272 | self.mode_settings.value['mode'] = 'manual' 273 | 274 | success = self.app.refresh() 275 | 276 | if not success: 277 | self.value = not self.value 278 | 279 | self.app.config.state_on.update_state() 280 | 281 | 282 | class StateSetting(Setting): 283 | """Stores the last state of application. 284 | 285 | The state after start-up is determined programmatically; 286 | the value set during configuration loading will be ignored. 287 | """ 288 | name = 'state_on' 289 | state = None 290 | 291 | require = { 292 | ModeSettings, 293 | EnableNightMode 294 | } 295 | 296 | @property 297 | def value(self): 298 | if self.mode_settings.mode == 'manual': 299 | return self.enable_night_mode.value 300 | else: 301 | return self.mode_settings.is_active 302 | 303 | @value.setter 304 | def value(self, value): 305 | pass 306 | 307 | def __init__(self, *args, **kwargs): 308 | super().__init__(*args, **kwargs) 309 | # check the state every 60 seconds 310 | # (maybe a bit suboptimal, but the most reliable) 311 | from aqt import mw as main_window 312 | self.timer = QTimer(main_window) 313 | self.timer.setInterval(60 * 100) # 1000 milliseconds 314 | self.timer.timeout.connect(self.maybe_enable_maybe_disable) 315 | 316 | def on_load(self): 317 | if self.value: 318 | self.app.on() 319 | 320 | self.update_state() 321 | self.timer.start() 322 | 323 | def on_save(self): 324 | self.timer.stop() 325 | 326 | def maybe_enable_maybe_disable(self): 327 | if self.value != self.state: 328 | self.app.refresh() 329 | self.update_state() 330 | 331 | def update_state(self): 332 | self.state = self.value 333 | 334 | 335 | class DisabledStylers(Setting, MenuAction): 336 | 337 | value = set() 338 | window = None 339 | label = 'Choose what to style' 340 | 341 | def action(self): 342 | from aqt import mw as main_window 343 | 344 | if not self.window: 345 | self.window = StylersSelectorWindow( 346 | main_window, 347 | self.value, 348 | self.app.styles.stylers, 349 | on_update=self.update 350 | ) 351 | self.window.show() 352 | 353 | def update(self): 354 | self.app.refresh(reload=True) 355 | -------------------------------------------------------------------------------- /night_mode/color_map.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtCore import Qt, pyqtSlot as slot 2 | from PyQt5.QtGui import QColor 3 | from PyQt5.QtWidgets import QWidget, QLabel, QGridLayout, QPushButton, QColorDialog, QHBoxLayout, QVBoxLayout 4 | 5 | from .internals import alert 6 | from .gui import create_button, remove_layout, AddonDialog 7 | from .languages import _ 8 | 9 | 10 | class ColorSwatch(QPushButton): 11 | 12 | def __init__(self, parent, color=None, on_color_change=None, name='Color', verify_colors=False): 13 | """ 14 | 15 | Args: 16 | parent: a parent Qt instance 17 | color: the color name or hexadecimal code (in form of a string) 18 | on_color_change: a function or method taking old color and a new one 19 | verify_colors: should the parent be asked if the color is acceptable? 20 | to verify a color parent.is_acceptable(color) will be invoked 21 | """ 22 | QPushButton.__init__(self, color, parent) 23 | self.verify_colors = verify_colors 24 | self.parent = parent 25 | self.color = color 26 | self.name = name 27 | self.callback = on_color_change 28 | 29 | if color: 30 | self.set_color(color) 31 | else: 32 | self.setText(_('(Not specified)')) 33 | 34 | self.clicked.connect(self.pick_color) 35 | 36 | def set_color(self, color): 37 | self.color = color 38 | self.setText(color) 39 | self.setStyleSheet(f'background-color: {self.color}; color: {self.text_color}') 40 | 41 | @property 42 | def text_color(self): 43 | return 'black' if self.qt_color.lightness() > 127 else 'white' 44 | 45 | @property 46 | def qt_color(self): 47 | return QColor(self.color) 48 | 49 | @slot() 50 | def pick_color(self, qt_color=None): 51 | if not qt_color: 52 | qt_color = self.qt_color 53 | 54 | old_color = self.color 55 | qt_color = QColorDialog.getColor( 56 | qt_color, 57 | parent=self, 58 | title=_('Select %s') % _(self.name) 59 | ) 60 | 61 | if qt_color.isValid(): 62 | color = qt_color.name() 63 | if self.verify_colors and not self.parent.is_acceptable(color): 64 | alert(_('This color (%s) is already mapped. Please select a different one.') % color) 65 | return self.pick_color(qt_color=qt_color) 66 | 67 | self.set_color(color) 68 | self.callback(old_color, self.color) 69 | 70 | 71 | class ColorMapping(QWidget): 72 | 73 | def __init__(self, parent, normal_color, night_color): 74 | """ 75 | 76 | Args: 77 | parent: ColorMapWindow instance 78 | normal_color: name or code of code to use in normal mode 79 | night_color: name or code of code to use in night mode 80 | """ 81 | QWidget.__init__(self, parent) 82 | self.parent = parent 83 | self.normal = ColorSwatch(self, normal_color, self.update_normal, 'Normal Mode Color', verify_colors=True) 84 | self.night = ColorSwatch(self, night_color, self.update_night, 'Night Mode Color') 85 | self.grid = QGridLayout() 86 | self.fill_layout() 87 | self.setLayout(self.grid) 88 | 89 | def fill_layout(self): 90 | remove = create_button('Remove', self.remove) 91 | grid = self.grid 92 | grid.addWidget(self.normal, 0, 1, 1, 3) 93 | arrow = QLabel('→') 94 | arrow.setAlignment(Qt.AlignCenter) 95 | grid.addWidget(arrow, 0, 4) 96 | grid.addWidget(self.night, 0, 5, 1, 3) 97 | grid.addWidget(remove, 0, 8) 98 | 99 | @slot() 100 | def remove(self): 101 | self.parent.update(self.normal.color, None, None) 102 | remove_layout(self.grid) 103 | self.parent.mappings.removeWidget(self) 104 | self.deleteLater() 105 | 106 | def update_normal(self, old, new): 107 | night = self.night.color 108 | self.parent.update(old, new, night) 109 | 110 | def update_night(self, old, new): 111 | normal = self.normal.color 112 | self.parent.update(normal, normal, new) 113 | 114 | def is_acceptable(self, color): 115 | return self.parent.is_acceptable(color) 116 | 117 | 118 | class ColorMapWindow(AddonDialog): 119 | 120 | def __init__(self, parent, color_map, title='Customise colors swapping', on_update=None): 121 | super().__init__(self, parent, Qt.Window) 122 | self.on_update = on_update 123 | self.color_map = color_map 124 | 125 | self.init_ui(title) 126 | 127 | def init_ui(self, title): 128 | self.setWindowTitle(_(title)) 129 | 130 | btn_add_mapping = create_button('+ Add colors mapping', self.on_add) 131 | btn_close = create_button('Close', self.close) 132 | 133 | buttons = QHBoxLayout() 134 | 135 | buttons.addWidget(btn_close) 136 | buttons.addWidget(btn_add_mapping) 137 | buttons.setAlignment(Qt.AlignBottom) 138 | 139 | body = QVBoxLayout() 140 | body.setAlignment(Qt.AlignTop) 141 | 142 | header = QLabel(_( 143 | 'Specify how particular colors on your cards ' 144 | 'should be swapped when the night mode is on.' 145 | )) 146 | header.setAlignment(Qt.AlignCenter) 147 | 148 | mappings = QVBoxLayout() 149 | mappings.setAlignment(Qt.AlignTop) 150 | 151 | for normal_color, night_color in self.color_map.items(): 152 | mapping = ColorMapping(self, normal_color, night_color) 153 | mappings.addWidget(mapping) 154 | 155 | self.mappings = mappings 156 | 157 | body.addWidget(header) 158 | body.addLayout(mappings) 159 | body.addStretch(1) 160 | body.addLayout(buttons) 161 | self.setLayout(body) 162 | 163 | self.setGeometry(300, 300, 350, 300) 164 | self.show() 165 | 166 | @slot() 167 | def on_add(self): 168 | mapping = ColorMapping(self, None, None) 169 | self.mappings.addWidget(mapping) 170 | mapping.normal.pick_color() 171 | mapping.night.pick_color() 172 | 173 | def is_acceptable(self, color): 174 | return color not in self.color_map 175 | 176 | def update(self, old_key, new_key, new_value): 177 | if old_key: 178 | del self.color_map[old_key] 179 | if new_key: 180 | self.color_map[new_key] = new_value 181 | if self.on_update: 182 | self.on_update() 183 | -------------------------------------------------------------------------------- /night_mode/config.py: -------------------------------------------------------------------------------- 1 | from aqt import mw 2 | from .internals import Setting 3 | 4 | 5 | class Config: 6 | 7 | def __init__(self, app, prefix=''): 8 | self.app = app 9 | self.prefix = prefix 10 | self.settings = {} 11 | 12 | # has to be separately from __init__ to avoid circular reference 13 | def init_settings(self): 14 | for setting_class in Setting.members: 15 | setting = setting_class(self.app) 16 | self.settings[setting.name] = setting 17 | 18 | def __getattr__(self, attr): 19 | return self.settings[attr] 20 | 21 | def stored_name(self, name): 22 | return self.prefix + name 23 | 24 | def load(self): 25 | for name, setting in self.settings.items(): 26 | key = self.stored_name(name) 27 | value = mw.pm.profile.get(key, setting.default_value) 28 | 29 | setting.value = value 30 | 31 | for setting in self.settings.values(): 32 | setting.on_load() 33 | 34 | def save(self): 35 | """ 36 | Saves configurable variables into profile, so they can 37 | be used to restore previous state after Anki restart. 38 | """ 39 | for name, setting in self.settings.items(): 40 | key = self.stored_name(name) 41 | mw.pm.profile[key] = setting.value 42 | 43 | for setting in self.settings.values(): 44 | setting.on_save() 45 | 46 | 47 | class ConfigValueGetter: 48 | 49 | def __init__(self, config): 50 | self.config = config 51 | 52 | def __getattr__(self, attr): 53 | setting = getattr(self.config, attr) 54 | return setting.value 55 | -------------------------------------------------------------------------------- /night_mode/css_class.py: -------------------------------------------------------------------------------- 1 | def inject_css_class(state: bool, html: str): 2 | if state: 3 | javascript = """ 4 | function add_night_mode_class(){ 5 | current_classes = document.body.className; 6 | if(current_classes.indexOf("night_mode") == -1) 7 | { 8 | document.body.className += " night_mode"; 9 | } 10 | } 11 | // explanation of setTimeout use: 12 | // callback defined in _showQuestion of reviewer.js would otherwise overwrite 13 | // the newly set body class; in order to prevent that the function execution 14 | // is being placed on the end of execution queue (hence time = 0) 15 | setTimeout(add_night_mode_class, 0) 16 | """ 17 | else: 18 | javascript = """ 19 | function remove_night_mode_class(){ 20 | current_classes = document.body.className; 21 | if(current_classes.indexOf("night_mode") != -1) 22 | { 23 | document.body.className = current_classes.replace("night_mode",""); 24 | } 25 | } 26 | setTimeout(remove_night_mode_class, 0) 27 | """ 28 | # script on the beginning of the HTML so it will always be 29 | # before any user-defined, potentially malformed HTML 30 | html = f"" + html 31 | return html 32 | -------------------------------------------------------------------------------- /night_mode/gui.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtWidgets import QPushButton, QDialog 2 | 3 | from .languages import _ 4 | 5 | 6 | class AddonDialog(QDialog): 7 | def __init__(self, *args, **kwargs): 8 | QDialog.__init__(*args, **kwargs) 9 | 10 | 11 | def create_button(name, callback=None): 12 | button = QPushButton(_(name)) 13 | if callback: 14 | button.clicked.connect(callback) 15 | return button 16 | 17 | 18 | def iterate_widgets(layout): 19 | for i in reversed(range(layout.count())): 20 | yield layout.itemAt(i).widget() 21 | 22 | 23 | def remove_layout(layout): 24 | for widget in iterate_widgets(layout): 25 | layout.removeWidget(widget) 26 | widget.deleteLater() 27 | 28 | -------------------------------------------------------------------------------- /night_mode/icons.py: -------------------------------------------------------------------------------- 1 | from os import makedirs 2 | from os.path import isfile, dirname, abspath, join 3 | from PyQt5.QtGui import QIcon, QPixmap 4 | from PyQt5.QtWidgets import QStyle 5 | 6 | 7 | def inverted_icon(icon, width=32, height=32, as_image=False): 8 | pixmap = icon.pixmap(width, height) 9 | image = pixmap.toImage() 10 | image.invertPixels() 11 | if as_image: 12 | return image 13 | new_icon = QIcon(QPixmap.fromImage(image)) 14 | return new_icon 15 | 16 | 17 | class Icons: 18 | 19 | paths = {} 20 | 21 | def __init__(self, mw): 22 | 23 | add_on_path = dirname(abspath(__file__)) 24 | add_on_resources = join(add_on_path, 'user_files') 25 | icons_path = join(add_on_resources, 'icons') 26 | makedirs(icons_path, exist_ok=True) 27 | 28 | icon_path = join(icons_path, 'arrow.png') 29 | 30 | if not isfile(icon_path): 31 | down_arrow_icon = mw.style().standardIcon(QStyle.SP_ArrowDown) 32 | image = inverted_icon(down_arrow_icon, width=16, height=16, as_image=True) 33 | image.save(icon_path) 34 | 35 | arrow_path = icon_path.replace('\\', '/') 36 | 37 | where_to_look_for_arrow_icon = [ 38 | '/usr/share/icons/Adwaita/scalable/actions/pan-down-symbolic.svg', 39 | '/usr/share/icons/gnome/scalable/actions/go-down-symbolic.svg', 40 | '/usr/share/icons/ubuntu-mobile/actions/scalable/dropdown-menu.svg', 41 | '/usr/share/icons/Humanity/actions/16/down.svg', 42 | '/usr/share/icons/Humanity/actions/16/go-down.svg', 43 | '/usr/share/icons/Humanity/actions/16/stock_down.svg', 44 | '/usr/share/icons/nuvola/16x16/actions/arrow-down.png', 45 | '/usr/share/icons/default.kde4/16x16/actions/arrow-down.png' 46 | ] 47 | 48 | for path in where_to_look_for_arrow_icon: 49 | if isfile(path): 50 | arrow_path = path 51 | break 52 | 53 | self.paths['arrow'] = arrow_path 54 | 55 | @property 56 | def arrow(self): 57 | return self.paths['arrow'] 58 | -------------------------------------------------------------------------------- /night_mode/internals.py: -------------------------------------------------------------------------------- 1 | import re 2 | from PyQt5 import QtCore 3 | from abc import abstractmethod, ABCMeta 4 | from inspect import isclass 5 | from types import MethodType 6 | 7 | from anki.hooks import wrap 8 | from anki.lang import _ 9 | from aqt.utils import showWarning 10 | 11 | 12 | try: 13 | from_utf8 = QtCore.QString.fromUtf8 14 | except AttributeError: 15 | from_utf8 = lambda s: s 16 | 17 | 18 | def alert(info): 19 | showWarning(_(info)) 20 | 21 | 22 | class PropertyDescriptor: 23 | def __init__(self, value=None): 24 | self.value = value 25 | 26 | def __get__(self, obj, obj_type): 27 | return self.value(obj) 28 | 29 | def __set__(self, obj, value): 30 | self.value = value 31 | 32 | 33 | class css(PropertyDescriptor): 34 | is_css = True 35 | 36 | 37 | def abstract_property(func): 38 | return property(abstractmethod(func)) 39 | 40 | 41 | def snake_case(camel_case): 42 | return re.sub('(?!^)([A-Z]+)', r'_\1', camel_case).lower() 43 | 44 | 45 | class AbstractRegisteringType(ABCMeta): 46 | 47 | def __init__(cls, name, bases, attributes): 48 | super().__init__(name, bases, attributes) 49 | 50 | if not hasattr(cls, 'members'): 51 | cls.members = set() 52 | 53 | cls.members.add(cls) 54 | cls.members -= set(bases) 55 | 56 | 57 | class SnakeNameMixin: 58 | 59 | @property 60 | def name(self): 61 | """Nice looking internal identifier.""" 62 | 63 | return snake_case( 64 | self.__class__.__name__ 65 | if hasattr(self, '__class__') 66 | else self.__name__ 67 | ) 68 | 69 | 70 | class MenuAction(SnakeNameMixin, metaclass=AbstractRegisteringType): 71 | 72 | def __init__(self, app): 73 | self.app = app 74 | 75 | @abstract_property 76 | def label(self): 77 | """Text to be shown on menu entry. 78 | 79 | Use ampersand ('&') to set that the following 80 | character as a menu shortcut for this action. 81 | 82 | Use double ampersand ('&&') to display '&'. 83 | """ 84 | pass 85 | 86 | @property 87 | def checkable(self): 88 | """Add 'checked' sign to menu item when active""" 89 | return False 90 | 91 | @property 92 | def shortcut(self): 93 | """Global shortcut for this menu action. 94 | 95 | The shortcut should be given as a string, like: 96 | shortcut = 'Ctrl+n' 97 | """ 98 | return None 99 | 100 | @abstractmethod 101 | def action(self): 102 | """Callback for menu entry clicking/selection""" 103 | pass 104 | 105 | @property 106 | def is_checked(self): 107 | """Should the menu item be checked (assuming that checkable is True)""" 108 | return bool(self.value) 109 | 110 | 111 | def singleton_creator(old_creator): 112 | def one_to_rule_them_all(cls, *args, **kwargs): 113 | if not cls.instance: 114 | cls.instance = old_creator(cls) 115 | return cls.instance 116 | return one_to_rule_them_all 117 | 118 | 119 | class SingletonMetaclass(AbstractRegisteringType): 120 | 121 | def __init__(cls, name, bases, attributes): 122 | super().__init__(name, bases, attributes) 123 | 124 | # singleton 125 | cls.instance = None 126 | old_creator = cls.__new__ 127 | cls.__new__ = singleton_creator(old_creator) 128 | 129 | 130 | class RequiringMixin: 131 | 132 | require = set() 133 | dependencies = {} 134 | 135 | def __init__(self, app): 136 | for requirement in self.require: 137 | instance = requirement(app) 138 | key = instance.name 139 | self.dependencies[key] = instance 140 | 141 | def __getattr__(self, attr): 142 | if attr in self.dependencies: 143 | return self.dependencies[attr] 144 | 145 | 146 | class Setting(RequiringMixin, SnakeNameMixin, metaclass=SingletonMetaclass): 147 | 148 | def __init__(self, app): 149 | RequiringMixin.__init__(self, app) 150 | self.default_value = self.value 151 | self.app = app 152 | 153 | @abstract_property 154 | def value(self): 155 | """Default value of a setting""" 156 | pass 157 | 158 | def on_load(self): 159 | """Callback called after loading of initial value""" 160 | pass 161 | 162 | def on_save(self): 163 | pass 164 | 165 | def reset(self): 166 | if hasattr(self, 'default_value'): 167 | self.value = self.default_value 168 | 169 | 170 | def decorate_or_call(operator): 171 | def outer_decorator(method_or_value): 172 | if callable(method_or_value): 173 | method = method_or_value 174 | 175 | def decorated(*args, **kwargs): 176 | return operator(method(*args, **kwargs)) 177 | return decorated 178 | else: 179 | return operator(method_or_value) 180 | return outer_decorator 181 | 182 | 183 | @decorate_or_call 184 | def style_tag(some_css): 185 | return '' 186 | 187 | 188 | @decorate_or_call 189 | def percent_escaped(text): 190 | return text.replace('%', '%%') 191 | 192 | 193 | class StylerMetaclass(AbstractRegisteringType): 194 | """ 195 | Makes classes: singletons, work with: 196 | wraps, 197 | appends_in_night_mode, 198 | replaces_in_night_mode 199 | decorators 200 | """ 201 | 202 | def __init__(cls, name, bases, attributes): 203 | super().__init__(name, bases, attributes) 204 | 205 | # singleton 206 | cls.instance = None 207 | old_creator = cls.__new__ 208 | cls.__new__ = singleton_creator(old_creator) 209 | 210 | # additions and replacements 211 | cls.additions = {} 212 | cls.replacements = {} 213 | 214 | target = attributes.get('target', None) 215 | 216 | def callback_maker(wrapper): 217 | def raw_new(*args, **kwargs): 218 | return wrapper(cls.instance, *args, **kwargs) 219 | return raw_new 220 | 221 | for key, attr in attributes.items(): 222 | 223 | if key == 'init': 224 | key = '__init__' 225 | if hasattr(attr, 'wraps'): 226 | 227 | if not target: 228 | raise Exception(f'Asked to wrap "{key}" but target of {name} not defined') 229 | 230 | original = getattr(target, key) 231 | 232 | if type(original) is MethodType: 233 | original = original.__func__ 234 | 235 | new = wrap(original, callback_maker(attr), attr.position) 236 | 237 | # for classes, just add the new function, it will be bound later, 238 | # but instances need some more work: we need to bind! 239 | if not isclass(target): 240 | new = MethodType(new, target) 241 | 242 | cls.replacements[key] = new 243 | 244 | if hasattr(attr, 'appends_in_night_mode'): 245 | if not target: 246 | raise Exception(f'Asked to replace "{key}" but target of {name} not defined') 247 | cls.additions[key] = attr 248 | if hasattr(attr, 'replaces_in_night_mode'): 249 | if not target: 250 | raise Exception(f'Asked to replace "{key}" but target of {name} not defined') 251 | cls.replacements[key] = attr 252 | 253 | # TODO: invoke and cache css? 254 | if hasattr(attr, 'is_css'): 255 | pass 256 | 257 | 258 | def wraps(method=None, position='after'): 259 | """Decorator for methods extending Anki QT methods. 260 | 261 | Args: 262 | method: a function method to be wrapped 263 | position: after, before or around 264 | """ 265 | 266 | if not method: 267 | def wraps_inner(func): 268 | return wraps(method=func, position=position) 269 | return wraps_inner 270 | 271 | method.wraps = True 272 | method.position = position 273 | 274 | return method 275 | 276 | 277 | class appends_in_night_mode(PropertyDescriptor): 278 | appends_in_night_mode = True 279 | 280 | 281 | class replaces_in_night_mode(PropertyDescriptor): 282 | replaces_in_night_mode = True 283 | 284 | 285 | def move_args_to_kwargs(original_function, args, kwargs): 286 | args = list(args) 287 | 288 | import inspect 289 | 290 | signature = inspect.signature(original_function) 291 | i = 0 292 | for name, parameter in signature.parameters.items(): 293 | if i >= len(args): 294 | break 295 | if parameter.default is not inspect._empty: 296 | value = args.pop(i) 297 | kwargs[name] = value 298 | else: 299 | i += 1 300 | return args, kwargs 301 | -------------------------------------------------------------------------------- /night_mode/languages.py: -------------------------------------------------------------------------------- 1 | import gettext 2 | from os import path 3 | 4 | from anki.lang import getLang, _ as fallback_translation 5 | 6 | lang = getLang() 7 | this_dir = path.dirname(path.abspath(__file__)) 8 | locale_dir = path.join(this_dir, 'locale') 9 | trans = gettext.translation('Anki-Night-Mode', locale_dir, languages=[lang], fallback=True) 10 | # See: http://www.loc.gov/standards/iso639-2/php/code_list.php for language codes 11 | 12 | 13 | def _(text): 14 | try: 15 | return trans.gettext(text) 16 | except Exception as e: 17 | print(e) 18 | return fallback_translation(text) 19 | -------------------------------------------------------------------------------- /night_mode/locale/de/LC_MESSAGES/Anki-Night-Mode.mo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/krassowski/Anki-Night-Mode/b7bd89878ed3b1deeea92549059670c6be5e8614/night_mode/locale/de/LC_MESSAGES/Anki-Night-Mode.mo -------------------------------------------------------------------------------- /night_mode/locale/hy/LC_MESSAGES/Anki-Night-Mode.mo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/krassowski/Anki-Night-Mode/b7bd89878ed3b1deeea92549059670c6be5e8614/night_mode/locale/hy/LC_MESSAGES/Anki-Night-Mode.mo -------------------------------------------------------------------------------- /night_mode/locale/pl/LC_MESSAGES/Anki-Night-Mode.mo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/krassowski/Anki-Night-Mode/b7bd89878ed3b1deeea92549059670c6be5e8614/night_mode/locale/pl/LC_MESSAGES/Anki-Night-Mode.mo -------------------------------------------------------------------------------- /night_mode/locale/sv/LC_MESSAGES/Anki-Night-Mode.mo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/krassowski/Anki-Night-Mode/b7bd89878ed3b1deeea92549059670c6be5e8614/night_mode/locale/sv/LC_MESSAGES/Anki-Night-Mode.mo -------------------------------------------------------------------------------- /night_mode/menu.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtGui import QKeySequence 2 | from PyQt5.QtWidgets import QAction, QMenu 3 | 4 | from aqt import mw 5 | 6 | from .languages import _ 7 | 8 | 9 | def get_or_create_menu(attribute_name, label): 10 | 11 | if not hasattr(mw, attribute_name): 12 | menu = QMenu(_(label), mw) 13 | setattr(mw, attribute_name, menu) 14 | 15 | mw.form.menubar.insertMenu( 16 | mw.form.menuTools.menuAction(), 17 | menu 18 | ) 19 | else: 20 | menu = getattr(mw, attribute_name) 21 | menu.setTitle(_(label)) 22 | 23 | return menu 24 | 25 | 26 | class Menu: 27 | 28 | actions = { 29 | # action name => action 30 | } 31 | 32 | connections = { 33 | # action => callback 34 | } 35 | 36 | def __init__(self, app, menu_name, layout, attach_to=None): 37 | self.menu = QMenu(_(menu_name), mw) 38 | 39 | if attach_to: 40 | attach_to.addMenu(self.menu) 41 | 42 | layout = [ 43 | entry(app) if hasattr(entry, 'action') else entry 44 | for entry in layout 45 | ] 46 | 47 | self.raw_actions = { 48 | entry.name: entry 49 | for entry in layout 50 | if hasattr(entry, 'action') 51 | } 52 | 53 | for action in self.raw_actions.values(): 54 | 55 | self.create_action( 56 | action.name, 57 | _(action.label), 58 | action.action, 59 | checkable=action.checkable, 60 | shortcut=action.shortcut 61 | ) 62 | 63 | self.setup_layout(layout) 64 | self.setup_connections() 65 | 66 | def create_action(self, name, text, callback, checkable=False, shortcut=None): 67 | action = QAction(_(text), mw, checkable=checkable) 68 | 69 | if shortcut: 70 | toggle = QKeySequence(shortcut) 71 | action.setShortcut(toggle) 72 | 73 | if name in self.actions: 74 | message = 'Action {0} already exists'.format(name) 75 | raise Exception(message) 76 | 77 | self.actions[name] = action 78 | self.connections[action] = callback 79 | 80 | def set_checked(self, name, value=True): 81 | self.actions[name].setChecked(value) 82 | 83 | def setup_layout(self, layout): 84 | for entry in layout: 85 | if entry == '-': 86 | self.menu.addSeparator() 87 | else: 88 | action = self.actions[entry.name] 89 | self.menu.addAction(action) 90 | 91 | def setup_connections(self): 92 | for menu_entry, connection in self.connections.items(): 93 | self.connect(menu_entry, connection) 94 | 95 | def connect(self, action, callback): 96 | action.triggered.connect(callback) 97 | 98 | def update_checkboxes(self, settings): 99 | for name, setting in settings.items(): 100 | if name in self.actions and self.raw_actions[name].checkable: 101 | self.set_checked(name, setting.is_checked) 102 | -------------------------------------------------------------------------------- /night_mode/mode.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtCore import Qt, pyqtSlot as slot, QTime 2 | from PyQt5.QtWidgets import QWidget, QLabel, QGridLayout, QHBoxLayout, QVBoxLayout, QTimeEdit 3 | 4 | from .gui import create_button, AddonDialog, iterate_widgets 5 | 6 | 7 | class TimeEdit(QWidget): 8 | 9 | def __init__(self, parent, initial_time, label, on_update=lambda x: x): 10 | """ 11 | 12 | Args: 13 | parent: ColorMapWindow instance 14 | """ 15 | QWidget.__init__(self, parent) 16 | self.parent = parent 17 | self.on_update = on_update 18 | self.label = QLabel(label) 19 | self.qt_time = QTime.fromString(initial_time) 20 | self.time_edit = QTimeEdit(self.qt_time) 21 | self.time_edit.timeChanged.connect(self.update) 22 | self.grid = QGridLayout() 23 | self.fill_layout() 24 | self.setLayout(self.grid) 25 | 26 | @property 27 | def time(self): 28 | return self.qt_time.toPyTime().strftime('%H:%M') 29 | 30 | def fill_layout(self): 31 | grid = self.grid 32 | grid.addWidget(self.label, 0, 0) 33 | grid.addWidget(self.time_edit, 1, 0) 34 | 35 | @slot() 36 | def update(self): 37 | self.qt_time = self.time_edit.time() 38 | self.on_update(self.time) 39 | 40 | def update_constraint(self, min_time, max_time): 41 | pass 42 | 43 | 44 | class ModeWindow(AddonDialog): 45 | 46 | def __init__(self, parent, settings, title='Manage Night Mode', on_update=lambda x: x): 47 | super().__init__(self, parent, Qt.Window) 48 | self.on_update = on_update 49 | self.settings = settings 50 | 51 | self.init_ui(title) 52 | 53 | def init_ui(self, title): 54 | self.setWindowTitle(title) 55 | 56 | btn_close = create_button('Close', self.close) 57 | 58 | buttons = QHBoxLayout() 59 | 60 | buttons.addWidget(btn_close) 61 | buttons.setAlignment(Qt.AlignBottom) 62 | 63 | body = QVBoxLayout() 64 | body.setAlignment(Qt.AlignTop) 65 | 66 | header = QLabel( 67 | 'If you choose an automatic (scheduled) mode ' 68 | 'the "ctrl+n" shortcut and menu checkbox for ' 69 | 'quick toggle will switch between the manual ' 70 | 'and automatic mode (when used for the first ' 71 | 'time).' 72 | ) 73 | header.setWordWrap(True) 74 | 75 | mode_switches = QHBoxLayout() 76 | mode_switches.addWidget(QLabel('Mode:')) 77 | self.manual = create_button('Manual', self.on_set_manual) 78 | self.auto = create_button('Automatic', self.on_set_automatic) 79 | mode_switches.addWidget(self.manual) 80 | mode_switches.addWidget(self.auto) 81 | 82 | time_controls = QHBoxLayout() 83 | time_controls.setAlignment(Qt.AlignTop) 84 | 85 | start_at = TimeEdit(self, self.settings['start_at'], 'From', self.start_update) 86 | end_at = TimeEdit(self, self.settings['end_at'], 'To', self.end_update) 87 | time_controls.addWidget(start_at) 88 | time_controls.addWidget(end_at) 89 | 90 | self.time_controls = time_controls 91 | 92 | self.set_mode(self.settings['mode'], False) 93 | 94 | body.addWidget(header) 95 | body.addStretch(1) 96 | body.addLayout(mode_switches) 97 | body.addLayout(time_controls) 98 | body.addStretch(1) 99 | body.addLayout(buttons) 100 | self.setLayout(body) 101 | 102 | self.setGeometry(300, 300, 470, 255) 103 | self.show() 104 | 105 | def start_update(self, time): 106 | self.set_time('start_at', time) 107 | 108 | def end_update(self, time): 109 | self.set_time('end_at', time) 110 | 111 | def set_time(self, which, time): 112 | self.settings[which] = time 113 | self.on_update() 114 | 115 | @slot() 116 | def on_set_manual(self): 117 | self.set_mode('manual') 118 | 119 | @slot() 120 | def on_set_automatic(self): 121 | self.set_mode('auto') 122 | 123 | def switch_buttons(self, auto): 124 | self.auto.setEnabled(not auto) 125 | self.manual.setEnabled(auto) 126 | self.auto.setChecked(auto) 127 | self.manual.setChecked(not auto) 128 | 129 | def set_mode(self, mode, run_callback=True): 130 | auto = mode == 'auto' 131 | self.settings['mode'] = mode 132 | # time controls are needed only in the 'auto' mode 133 | for widget in iterate_widgets(self.time_controls): 134 | widget.setEnabled(auto) 135 | self.switch_buttons(auto) 136 | if run_callback: 137 | self.on_update() 138 | -------------------------------------------------------------------------------- /night_mode/night_mode.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright: Michal Krassowski 3 | # License: GNU GPL, version 3 or later; http://www.gnu.org/copyleft/gpl.html 4 | """ 5 | This plugin adds the function of night mode, similar that one implemented in AnkiDroid. 6 | 7 | It adds a "view" menu entity (if it doesn't exist) with options like: 8 | 9 | switching night mode 10 | inverting colors of images or latex formulas 11 | modifying some of the colors 12 | 13 | It provides shortcut ctrl+n to quickly switch mode and color picker to adjust some of color parameters. 14 | 15 | After enabling night mode, add-on changes colors of menubar, toolbar, bottombars and content windows. 16 | 17 | If you want to contribute visit GitHub page: https://github.com/krassowski/Anki-Night-Mode 18 | Also, feel free to send me bug reports or feature requests. 19 | 20 | Copyright: Michal Krassowski 21 | License: GNU GPL, version 3 or later; http://www.gnu.org/copyleft/gpl.html except when stated otherwise. 22 | 23 | Special thanks to contributors: [github nickname (reason)] 24 | 25 | - b50 (initial compatibility with 2.1), 26 | - ankitest (compatibility with 1508882486), 27 | - omega3 (useful bug reports and suggestions) 28 | - colchizin 29 | - JulyMorning 30 | - nathanmalloy 31 | - rathsky 32 | - zjosua 33 | - lovac42 34 | 35 | And translators: 36 | - Arman High (Armenian) 37 | - Jeremias (Swedish) 38 | - Is (German) 39 | """ 40 | import traceback 41 | 42 | from anki.hooks import addHook, runHook 43 | from aqt import appVersion 44 | from aqt import mw 45 | 46 | from PyQt5.QtWidgets import QMessageBox 47 | 48 | from .actions_and_settings import * 49 | from .internals import alert 50 | from .config import Config, ConfigValueGetter 51 | from .css_class import inject_css_class 52 | from .icons import Icons 53 | from .menu import get_or_create_menu, Menu 54 | from .stylers import Styler 55 | from .styles import Style, MessageBoxStyle 56 | 57 | __addon_name__ = 'Night Mode' 58 | __version__ = '2.3.3' 59 | __anki_version__ = '2.1' 60 | 61 | 62 | if not appVersion.startswith(__anki_version__): 63 | print( 64 | ( 65 | 'Unsupported version of Anki. ' 66 | 'Anki-Night-Mode 2.0 requires %s to work properly. ' 67 | 'For older versions of Anki use Night-Mode 1.x' 68 | ) % __anki_version__ 69 | ) 70 | 71 | 72 | # Add here you color replacements mapping - old: new, comma separated 73 | 74 | 75 | class StylingManager: 76 | def __init__(self, app): 77 | self.styles = Style.members 78 | self.stylers = [ 79 | styler(app) 80 | for styler in Styler.members 81 | ] 82 | self.config = ConfigValueGetter(app.config) 83 | 84 | @property 85 | def active_stylers(self): 86 | return [ 87 | styler 88 | for styler in self.stylers 89 | if styler.name not in self.config.disabled_stylers 90 | ] 91 | 92 | def replace(self): 93 | for styler in self.active_stylers: 94 | styler.replace_attributes() 95 | 96 | def restore(self): 97 | for styler in self.stylers: 98 | styler.restore_attributes() 99 | 100 | 101 | class NightMode: 102 | 103 | menu_layout = [ 104 | EnableNightMode, 105 | EnableInDialogs, 106 | '-', 107 | InvertImage, 108 | InvertLatex, 109 | TransparentLatex, 110 | '-', 111 | BackgroundColor, 112 | TextColor, 113 | ResetColors, 114 | '-', 115 | ModeSettings, 116 | UserColorMap, 117 | DisabledStylers, 118 | StyleScrollBars, 119 | '-', 120 | About 121 | ] 122 | 123 | def __init__(self): 124 | self.profile_loaded = False 125 | self.config = Config(self, prefix='nm_') 126 | self.config.init_settings() 127 | self.icons = Icons(mw) 128 | self.styles = StylingManager(self) 129 | 130 | view_menu = get_or_create_menu('addon_view_menu', '&View') 131 | self.menu = Menu( 132 | self, 133 | '&Night Mode', 134 | self.menu_layout, 135 | attach_to=view_menu 136 | ) 137 | 138 | addHook('unloadProfile', self.save) 139 | 140 | # Disabled, uses delay in __init__.py 141 | # addHook('profileLoaded', self.load) 142 | 143 | addHook('prepareQA', self.night_class_injection) 144 | 145 | addHook('loadNote', self.background_bug_workaround) 146 | 147 | def load(self): 148 | """ 149 | Load configuration from profile, set states of checkable menu objects 150 | and turn on night mode if it were enabled on previous session. 151 | """ 152 | self.config.load() 153 | self.profile_loaded = True 154 | 155 | self.refresh() 156 | self.update_menu() 157 | 158 | runHook("night_mode_config_loaded", self.config) 159 | 160 | def update_menu(self): 161 | self.menu.update_checkboxes(self.config.settings) 162 | 163 | def save(self): 164 | self.config.save() 165 | 166 | def on(self): 167 | """Turn on night mode.""" 168 | self.styles.replace() 169 | runHook("night_mode_state_changed", True) 170 | 171 | def off(self): 172 | """Turn off night mode.""" 173 | self.styles.restore() 174 | runHook("night_mode_state_changed", False) 175 | 176 | def refresh(self, reload=False): 177 | """ 178 | Refresh display by re-enabling night or normal mode, 179 | regenerate customizable css strings. 180 | """ 181 | state = self.config.state_on.value 182 | 183 | if not self.profile_loaded: 184 | alert(ERROR_NO_PROFILE) 185 | return 186 | 187 | try: 188 | if state: 189 | if reload: 190 | self.off() 191 | self.on() 192 | else: 193 | self.off() 194 | except Exception: 195 | alert(ERROR_SWITCH % traceback.format_exc()) 196 | return 197 | 198 | # Reload current screen. 199 | if mw.state == 'review': 200 | mw.moveToState('overview') 201 | mw.moveToState('review') 202 | if mw.state == 'deckBrowser': 203 | mw.deckBrowser.refresh() 204 | if mw.state == 'overview': 205 | mw.overview.refresh() 206 | 207 | # Redraw toolbar (should be always visible). 208 | mw.toolbar.draw() 209 | self.update_menu() 210 | return True 211 | 212 | def about(self): 213 | about_box = self.message_box() 214 | about_box.setText(__addon_name__ + ' ' + __version__ + __doc__) 215 | about_box.setGeometry(300, 300, 250, 150) 216 | about_box.setWindowTitle('About ' + __addon_name__ + ' ' + __version__) 217 | 218 | about_box.exec_() 219 | 220 | def message_box(self): 221 | box = QMessageBox() 222 | if self.config.state_on.value: 223 | box_style = MessageBoxStyle(self) 224 | box.setStyleSheet(box_style.style) 225 | return box 226 | 227 | def night_class_injection(self, html, card, context): 228 | html = inject_css_class(self.config.state_on.value, html) 229 | return html 230 | 231 | def background_bug_workaround(self, editor): 232 | 233 | if self.config.state_on.value: 234 | javascript = """ 235 | (function bg_bug_workaround() 236 | { 237 | function getTextNodeAtPosition(root, index){ 238 | // Copyright notice: 239 | // 240 | // following function is based on a function created by Pery Mimon: 241 | // https://stackoverflow.com/a/38479462 242 | // and is distributed under CC-BY SA 3.0 license terms: 243 | // https://creativecommons.org/licenses/by-sa/3.0/ 244 | 245 | var lastNode = null; 246 | var lastIndex = null 247 | 248 | var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT,function next(elem) { 249 | if(index >= elem.textContent.length){ 250 | lastIndex = index 251 | index -= elem.textContent.length; 252 | lastNode = elem; 253 | return NodeFilter.FILTER_REJECT 254 | } 255 | return NodeFilter.FILTER_ACCEPT; 256 | }); 257 | var c = treeWalker.nextNode(); 258 | return { 259 | node: c ? c : lastNode, 260 | position: c ? index : lastIndex 261 | }; 262 | } 263 | 264 | var regex = /<(span|strong) style="background-color: rgb\(255, 255, 255\);">(.*?)<\/(span|strong)>/gm 265 | 266 | function background_workaround_callback(raw_field) 267 | { 268 | function get_rid_of_background(){ 269 | var field = $(raw_field) 270 | var html = field.html() 271 | 272 | if(html.search(regex) == -1) 273 | return 274 | 275 | var selection = window.getSelection() 276 | var range = selection.getRangeAt(0) 277 | range.setStart(raw_field, 0) 278 | var len = range.toString().length 279 | 280 | field.html(html.replace(regex, '<$1>$2')) 281 | 282 | var range = new Range() 283 | var pos = getTextNodeAtPosition(raw_field, len) 284 | 285 | range.setStart(pos.node, pos.position) 286 | 287 | selection.removeAllRanges() 288 | selection.addRange(range) 289 | } 290 | return get_rid_of_background 291 | } 292 | 293 | var field = $('.field') 294 | 295 | field.on('keydown', function(e){ 296 | var raw_field = this 297 | var get_rid_of_background = background_workaround_callback(raw_field) 298 | 299 | if(e.which === 8 || e.which == 46){ 300 | window.setTimeout(get_rid_of_background, 0) 301 | } 302 | }) 303 | 304 | field.on('paste', function(){ 305 | var raw_field = this 306 | var get_rid_of_background = background_workaround_callback(raw_field) 307 | 308 | window.setTimeout(get_rid_of_background, 100) 309 | }) 310 | 311 | })() 312 | """ 313 | else: 314 | javascript = '' 315 | 316 | editor.web.eval(javascript) 317 | 318 | 319 | ERROR_NO_PROFILE = """Switching night mode failed: The profile is not loaded yet. 320 | Probably it's a bug of Anki or you tried to switch mode to quickly.""" 321 | 322 | ERROR_SWITCH = """Switching night mode failed: Something went really really wrong. 323 | Contact add-on author to get help. 324 | 325 | Please provide following traceback when reporting the issue: 326 | %s 327 | """ 328 | -------------------------------------------------------------------------------- /night_mode/selector.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtCore import Qt 2 | from PyQt5.QtWidgets import QLabel, QHBoxLayout, QVBoxLayout, QCheckBox 3 | 4 | from .gui import create_button, AddonDialog 5 | from .languages import _ 6 | 7 | 8 | class StylerCheckButton(QCheckBox): 9 | 10 | def __init__(self, parent, styler): 11 | QCheckBox.__init__(self, _(styler.friendly_name), parent) 12 | self.styler = styler 13 | if styler.is_active: 14 | self.toggle() 15 | self.stateChanged.connect(self.switch_state) 16 | self.parent = parent 17 | 18 | def switch_state(self, state): 19 | self.parent.update(self.styler, state) 20 | 21 | 22 | class StylersSelectorWindow(AddonDialog): 23 | 24 | def __init__(self, parent, disabled_stylers: set, all_stylers, title=_('Choose what to style'), on_update=None): 25 | super().__init__(self, parent, Qt.Window) 26 | self.on_update = on_update 27 | self.disabled_stylers = disabled_stylers 28 | self.all_stylers = all_stylers 29 | 30 | self.stylers_checkboxes = [] 31 | self.stylers_layout = None 32 | self.init_ui(title) 33 | 34 | def init_ui(self, title): 35 | self.setWindowTitle(title) 36 | 37 | btn_close = create_button('Close', self.close) 38 | 39 | buttons = QHBoxLayout() 40 | 41 | buttons.addWidget(btn_close) 42 | buttons.setAlignment(Qt.AlignBottom) 43 | 44 | body = QVBoxLayout() 45 | body.setAlignment(Qt.AlignTop) 46 | 47 | header = QLabel(_( 48 | 'Select which parts of Anki should be displayed ' 49 | 'in eye-friendly, dark colors.\n\n' 50 | 'To disable all dialog windows, ' 51 | 'use the "Enable in dialogs" switch which is available in menu.' 52 | )) 53 | header.setAlignment(Qt.AlignCenter) 54 | 55 | stylers = QVBoxLayout() 56 | stylers.setAlignment(Qt.AlignTop) 57 | 58 | for styler in sorted(self.all_stylers, key=lambda s: s.name): 59 | styler_checkbox = StylerCheckButton(self, styler) 60 | self.stylers_checkboxes.append(styler_checkbox) 61 | stylers.addWidget(styler_checkbox) 62 | 63 | self.stylers_layout = stylers 64 | 65 | checked_boxes = sum(1 for checkbox in self.stylers_checkboxes if checkbox.isChecked()) 66 | check_all = QCheckBox(_('Check/uncheck all'), self) 67 | check_all.setChecked(checked_boxes > len(self.stylers_checkboxes) / 2) 68 | check_all.stateChanged.connect(self.check_uncheck_all) 69 | 70 | body.addWidget(header) 71 | body.addWidget(check_all) 72 | body.addLayout(stylers) 73 | body.addStretch(1) 74 | body.addLayout(buttons) 75 | self.setLayout(body) 76 | 77 | self.setGeometry(300, 300, 350, 300) 78 | self.show() 79 | 80 | def check_uncheck_all(self, state): 81 | for checkbox in self.stylers_checkboxes: 82 | checkbox.setChecked(state) 83 | 84 | def update(self, styler, value): 85 | if value: 86 | self.disabled_stylers.remove(styler.name) 87 | else: 88 | self.disabled_stylers.add(styler.name) 89 | 90 | if self.on_update: 91 | self.on_update() 92 | -------------------------------------------------------------------------------- /night_mode/stylers.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtCore import Qt 2 | from PyQt5 import QtWidgets 3 | 4 | import aqt 5 | from anki.stats import CollectionStats 6 | from aqt import mw, editor, QPixmap 7 | from aqt.addcards import AddCards 8 | from aqt.browser import Browser 9 | from aqt.clayout import CardLayout 10 | from aqt.editcurrent import EditCurrent 11 | from aqt.editor import Editor 12 | from aqt.progress import ProgressManager 13 | from aqt.stats import DeckStats 14 | from .gui import AddonDialog, iterate_widgets 15 | 16 | from .config import ConfigValueGetter 17 | from .css_class import inject_css_class 18 | from .internals import percent_escaped, move_args_to_kwargs, from_utf8, PropertyDescriptor 19 | from .internals import style_tag, wraps, appends_in_night_mode, replaces_in_night_mode, css 20 | from .styles import SharedStyles, ButtonsStyle, ImageStyle, DeckStyle, LatexStyle, DialogStyle 21 | from .internals import SnakeNameMixin, StylerMetaclass, abstract_property 22 | from .internals import RequiringMixin 23 | 24 | 25 | class Styler(RequiringMixin, SnakeNameMixin, metaclass=StylerMetaclass): 26 | 27 | def __init__(self, app): 28 | RequiringMixin.__init__(self, app) 29 | self.app = app 30 | self.config = ConfigValueGetter(app.config) 31 | self.original_attributes = {} 32 | 33 | @abstract_property 34 | def target(self): 35 | return None 36 | 37 | @property 38 | def is_active(self): 39 | return self.name not in self.config.disabled_stylers 40 | 41 | @property 42 | def friendly_name(self): 43 | name = self.name.replace('_styler', '') 44 | return name.replace('_', ' ').title() 45 | 46 | def get_or_create_original(self, key): 47 | if key not in self.original_attributes: 48 | original = getattr(self.target, key) 49 | self.original_attributes[key] = original 50 | else: 51 | original = self.original_attributes[key] 52 | 53 | return original 54 | 55 | def replace_attributes(self): 56 | try: 57 | for key, addition in self.additions.items(): 58 | original = self.get_or_create_original(key) 59 | setattr(self.target, key, original + addition.value(self)) 60 | 61 | for key, replacement in self.replacements.items(): 62 | self.get_or_create_original(key) 63 | 64 | if isinstance(replacement, PropertyDescriptor): 65 | replacement = replacement.value(self) 66 | 67 | setattr(self.target, key, replacement) 68 | 69 | except (AttributeError, TypeError): 70 | print('Failed to inject style to:', self.target, key, self.name) 71 | raise 72 | 73 | def restore_attributes(self): 74 | for key, original in self.original_attributes.items(): 75 | setattr(self.target, key, original) 76 | 77 | 78 | class ToolbarStyler(Styler): 79 | 80 | target = mw.toolbar 81 | require = { 82 | SharedStyles 83 | } 84 | 85 | @appends_in_night_mode 86 | @style_tag 87 | @percent_escaped 88 | def _body(self): 89 | return self.shared.top 90 | 91 | 92 | class StyleSetter: 93 | 94 | def __init__(self, target): 95 | self.target = target 96 | 97 | @property 98 | def css(self): 99 | return self.target.styleSheet() 100 | 101 | @css.setter 102 | def css(self, value): 103 | self.target.setStyleSheet(value) 104 | 105 | 106 | class MenuStyler(Styler): 107 | target = StyleSetter(mw) 108 | 109 | @appends_in_night_mode 110 | def css(self): 111 | return self.shared.menu 112 | 113 | 114 | class ReviewerStyler(Styler): 115 | 116 | target = mw.reviewer 117 | require = { 118 | SharedStyles, 119 | ButtonsStyle 120 | } 121 | 122 | @wraps(position='around') 123 | def _bottomHTML(self, reviewer, _old): 124 | return _old(reviewer) + style_tag(percent_escaped(self.bottom_css)) 125 | 126 | @property 127 | def bottom_css(self): 128 | return self.buttons.html + self.shared.colors_replacer + """ 129 | body, #outer 130 | { 131 | background:-webkit-gradient(linear, left top, left bottom, from(#333), to(#222)); 132 | border-top-color:#222 133 | } 134 | .stattxt 135 | { 136 | color:#ccc 137 | } 138 | /* Make the color above "Again" "Hard" "Easy" and so on buttons readable */ 139 | .nobold 140 | { 141 | color:#ddd 142 | } 143 | """ 144 | 145 | 146 | class ReviewerCards(Styler): 147 | 148 | target = mw.reviewer 149 | require = { 150 | LatexStyle, 151 | ImageStyle 152 | } 153 | 154 | # TODO: it can be implemented with a nice decorator 155 | @wraps(position='around') 156 | def revHtml(self, reviewer, _old): 157 | return _old(reviewer) + style_tag(percent_escaped(self.body)) 158 | 159 | @css 160 | def body(self): 161 | # Invert images and latex if needed 162 | 163 | css_body = """ 164 | .card input 165 | { 166 | background-color:black!important; 167 | border-color:#444!important; 168 | color:#eee!important 169 | } 170 | .card input::selection 171 | { 172 | color: """ + self.config.color_t + """; 173 | background: #0864d4 174 | } 175 | .typeGood 176 | { 177 | color:black; 178 | background:#57a957 179 | } 180 | .typeBad 181 | { 182 | color:black; 183 | background:#c43c35 184 | } 185 | .typeMissed 186 | { 187 | color:black; 188 | background:#ccc 189 | } 190 | #answer 191 | { 192 | height:0; 193 | border:0; 194 | border-bottom: 2px solid #333; 195 | border-top: 2px solid black 196 | } 197 | img#star 198 | { 199 | -webkit-filter:invert(0%)!important 200 | } 201 | .cloze 202 | { 203 | color:#5566ee!important 204 | } 205 | a 206 | { 207 | color:#0099CC 208 | } 209 | """ 210 | 211 | card_color = """ 212 | .card{ 213 | color:""" + self.config.color_t + """!important; 214 | } 215 | """ 216 | 217 | css = css_body + card_color + self.shared.user_color_map + self.shared.body_colors 218 | 219 | if self.config.invert_image: 220 | css += self.image.invert 221 | if self.config.invert_latex: 222 | css += self.latex.invert 223 | 224 | return css 225 | 226 | 227 | class DeckBrowserStyler(Styler): 228 | 229 | target = mw.deckBrowser 230 | require = { 231 | SharedStyles, 232 | DeckStyle 233 | } 234 | 235 | @appends_in_night_mode 236 | def _body(self): 237 | styles_html = style_tag(percent_escaped(self.deck.style + self.shared.body_colors)) 238 | return inject_css_class(True, styles_html) 239 | 240 | 241 | class DeckBrowserBottomStyler(Styler): 242 | 243 | target = mw.deckBrowser.bottom 244 | require = { 245 | DeckStyle 246 | } 247 | 248 | @appends_in_night_mode 249 | def _centerBody(self): 250 | styles_html = style_tag(percent_escaped(self.deck.bottom)) 251 | return inject_css_class(True, styles_html) 252 | 253 | 254 | class OverviewStyler(Styler): 255 | 256 | target = mw.overview 257 | require = { 258 | SharedStyles, 259 | ButtonsStyle 260 | } 261 | 262 | @appends_in_night_mode 263 | def _body(self): 264 | styles_html = style_tag(percent_escaped(self.css)) 265 | return inject_css_class(True, styles_html) 266 | 267 | @css 268 | def css(self): 269 | return f""" 270 | {self.buttons.html} 271 | {self.shared.colors_replacer} 272 | {self.shared.body_colors} 273 | .descfont 274 | {{ 275 | color: {self.config.color_t} 276 | }} 277 | """ 278 | 279 | 280 | class OverviewBottomStyler(Styler): 281 | 282 | target = mw.overview.bottom 283 | require = { 284 | DeckStyle 285 | } 286 | 287 | @appends_in_night_mode 288 | @style_tag 289 | @percent_escaped 290 | def _centerBody(self): 291 | return self.deck.bottom 292 | 293 | 294 | class AnkiWebViewStyler(Styler): 295 | 296 | target = mw.web 297 | require = { 298 | SharedStyles, 299 | ButtonsStyle 300 | } 301 | 302 | @wraps(position='around') 303 | def stdHtml(self, web, *args, **kwargs): 304 | old = kwargs.pop('_old') 305 | 306 | args, kwargs = move_args_to_kwargs(old, [web] + list(args), kwargs) 307 | 308 | kwargs['head'] = kwargs.get('head', '') + style_tag(self.waiting_screen) 309 | 310 | return old(web, *args[1:], **kwargs) 311 | 312 | @css 313 | def waiting_screen(self): 314 | return self.buttons.html + self.shared.body_colors 315 | 316 | 317 | class BrowserPackageStyler(Styler): 318 | 319 | target = aqt.browser 320 | 321 | @replaces_in_night_mode 322 | def COLOUR_MARKED(self): 323 | return '#735083' 324 | 325 | @replaces_in_night_mode 326 | def COLOUR_SUSPENDED(self): 327 | return '#777750' 328 | 329 | 330 | class BrowserStyler(Styler): 331 | 332 | target = Browser 333 | require = { 334 | SharedStyles, 335 | ButtonsStyle, 336 | } 337 | 338 | @wraps 339 | def init(self, browser, mw): 340 | 341 | if self.config.enable_in_dialogs: 342 | 343 | basic_css = browser.styleSheet() 344 | global_style = '#' + browser.form.centralwidget.objectName() + '{' + self.shared.colors + '}' 345 | browser.setStyleSheet(self.shared.menu + self.style + basic_css + global_style) 346 | 347 | browser.form.tableView.setStyleSheet(self.table) 348 | browser.form.tableView.horizontalHeader().setStyleSheet(self.table_header) 349 | 350 | browser.form.searchEdit.setStyleSheet(self.search_box) 351 | browser.form.searchEdit.setSizeAdjustPolicy(QtWidgets.QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLength) 352 | 353 | browser.form.searchButton.setStyleSheet(self.buttons.qt) 354 | browser.form.previewButton.setStyleSheet(self.buttons.qt) 355 | 356 | # TODO: test this 357 | #@wraps 358 | def _renderPreview(self, browser, cardChanged=False): 359 | if browser._previewWindow: 360 | self.app.take_care_of_night_class(web_object=browser._previewWeb) 361 | 362 | 363 | @wraps(position='around') 364 | def buildTree(self, browser, _old): 365 | root = _old(browser) 366 | if root: # For Anki 2.1.17++ 367 | return root 368 | # --------------------------- 369 | # For Anki 2.1.15-- 370 | root = browser.sidebarTree 371 | for item in root.findItems('', Qt.MatchContains | Qt.MatchRecursive): 372 | icon = item.icon(0) 373 | pixmap = icon.pixmap(32, 32) 374 | image = pixmap.toImage() 375 | image.invertPixels() 376 | new_icon = aqt.QIcon(QPixmap.fromImage(image)) 377 | item.setIcon(0, new_icon) 378 | 379 | @wraps 380 | def setupSidebar(self, browser): 381 | browser.sidebarTree.setStyleSheet(self.style) 382 | 383 | @wraps(position='around') 384 | def _cardInfoData(self, browser, _old): 385 | 386 | rep, cs = _old(browser) 387 | 388 | if self.config.enable_in_dialogs: 389 | rep += style_tag(""" 390 | * 391 | { 392 | """ + self.shared.colors + """ 393 | } 394 | div 395 | { 396 | border-color:#fff!important 397 | } 398 | """ + self.shared.colors_replacer + """ 399 | """) 400 | return rep, cs 401 | 402 | @css 403 | def style(self): 404 | return """ 405 | QSplitter::handle 406 | { 407 | /* handled below as QWidget */ 408 | } 409 | #""" + from_utf8("widget") + """, QTreeView 410 | { 411 | """ + self.shared.colors + """ 412 | } 413 | QTreeView::item:selected:active, QTreeView::branch:selected:active 414 | { 415 | color: """ + self.config.color_t + """; 416 | background-color:""" + self.config.color_a + """ 417 | } 418 | QTreeView::item:selected:!active, QTreeView::branch:selected:!active 419 | { 420 | color: """ + self.config.color_t + """; 421 | background-color:""" + self.config.color_a + """ 422 | } 423 | """ + ( 424 | """ 425 | /* make the splitter light-dark (match all widgets as selecting with QSplitter does not work) */ 426 | QWidget{ 427 | background-color: """ + self.config.color_s + """; 428 | color: """ + self.config.color_t + """; 429 | } 430 | /* make sure that no other important widgets - like tags box - are light-dark */ 431 | QGroupBox{ 432 | background-color: """ + self.config.color_b + """; 433 | } 434 | """ 435 | if self.config.style_scroll_bars else 436 | '' 437 | ) 438 | 439 | @css 440 | def table(self): 441 | return f""" 442 | QTableView 443 | {{ 444 | selection-color: {self.config.color_t}; 445 | alternate-background-color: {self.config.color_s}; 446 | gridline-color: {self.config.color_s}; 447 | {self.shared.colors} 448 | selection-background-color: {self.config.color_a} 449 | }} 450 | """ 451 | 452 | @css 453 | def table_header(self): 454 | return """ 455 | QHeaderView, QHeaderView::section 456 | { 457 | """ + self.shared.colors + """ 458 | border:1px solid """ + self.config.color_s + """ 459 | } 460 | """ 461 | 462 | @css 463 | def search_box(self): 464 | return """ 465 | QComboBox 466 | { 467 | border:1px solid """ + self.config.color_s + """; 468 | border-radius:3px; 469 | padding:0px 4px; 470 | """ + self.shared.colors + """ 471 | } 472 | 473 | QComboBox:!editable 474 | { 475 | background:""" + self.config.color_a + """ 476 | } 477 | 478 | QComboBox QAbstractItemView 479 | { 480 | border:1px solid #111; 481 | """ + self.shared.colors + """ 482 | background:#444 483 | } 484 | 485 | QComboBox::drop-down, QComboBox::drop-down:editable 486 | { 487 | """ + self.shared.colors + """ 488 | width:24px; 489 | border-left:1px solid #444; 490 | border-top-right-radius:3px; 491 | border-bottom-right-radius:3px; 492 | background:qlineargradient(x1: 0.0, y1: 0.0, x2: 0.0, y2: 1.0, radius: 1, stop: 0.03 #3D4850, stop: 0.04 #313d45, stop: 1 #232B30); 493 | } 494 | 495 | QComboBox::down-arrow 496 | { 497 | top:1px; 498 | image: url('""" + self.app.icons.arrow + """') 499 | } 500 | """ 501 | 502 | 503 | try: # Requires anki 2.1.17++ 504 | from aqt.browser import SidebarModel 505 | 506 | class SidebarModelStyler(Styler): 507 | 508 | target = SidebarModel 509 | 510 | @wraps 511 | def init(self, *args, **kwargs): 512 | self.inverted = [] # Prevent auto invert of icon colors. 513 | 514 | @wraps(position='around') 515 | def iconFromRef(self, sidebar_model, iconRef, _old): 516 | icon = _old(sidebar_model, iconRef) 517 | try: 518 | if icon and iconRef not in self.inverted: 519 | pixmap = icon.pixmap(32, 32) 520 | image = pixmap.toImage() 521 | image.invertPixels() 522 | icon = aqt.QIcon(QPixmap.fromImage(image)) 523 | 524 | self.inverted.append(iconRef) 525 | sidebar_model.iconCache[iconRef] = icon 526 | except TypeError: 527 | pass 528 | return icon 529 | except ImportError: 530 | pass 531 | 532 | 533 | class AddCardsStyler(Styler): 534 | 535 | target = AddCards 536 | require = { 537 | SharedStyles, 538 | ButtonsStyle, 539 | } 540 | 541 | @wraps 542 | def init(self, add_cards, mw): 543 | if self.config.enable_in_dialogs: 544 | 545 | # style add/history button 546 | add_cards.form.buttonBox.setStyleSheet(self.buttons.qt) 547 | 548 | self.set_style_to_objects_inside(add_cards.form.horizontalLayout, self.buttons.qt) 549 | 550 | # style the single line which has some bright color 551 | add_cards.form.line.setStyleSheet('#' + from_utf8('line') + '{border: 0px solid #333}') 552 | 553 | add_cards.form.fieldsArea.setAutoFillBackground(False) 554 | 555 | @staticmethod 556 | def set_style_to_objects_inside(layout, style): 557 | for widget in iterate_widgets(layout): 558 | widget.setStyleSheet(style) 559 | 560 | 561 | class EditCurrentStyler(Styler): 562 | 563 | target = EditCurrent 564 | require = { 565 | ButtonsStyle, 566 | } 567 | 568 | @wraps 569 | def init(self, edit_current, mw): 570 | if self.config.enable_in_dialogs: 571 | # style close button 572 | edit_current.form.buttonBox.setStyleSheet(self.buttons.qt) 573 | 574 | 575 | class ProgressStyler(Styler): 576 | 577 | target = None 578 | require = { 579 | SharedStyles, 580 | DialogStyle, 581 | ButtonsStyle 582 | } 583 | 584 | def init(self, progress, *args, **kwargs): 585 | if self.config.enable_in_dialogs: 586 | progress.setStyleSheet(self.buttons.qt + self.dialog.style) 587 | 588 | 589 | if hasattr(ProgressManager, 'ProgressNoCancel'): 590 | # before beta 31 591 | class LegacyProgressStyler(Styler): 592 | 593 | target = None 594 | require = { 595 | SharedStyles, 596 | DialogStyle, 597 | ButtonsStyle 598 | } 599 | 600 | def init(self, progress, label='', *args, **kwargs): 601 | if self.config.enable_in_dialogs: 602 | # Set label and its styles explicitly (otherwise styling does not work) 603 | label = aqt.QLabel(label) 604 | progress.setLabel(label) 605 | label.setAlignment(Qt.AlignCenter) 606 | label.setStyleSheet(self.dialog.style) 607 | 608 | progress.setStyleSheet(self.buttons.qt + self.dialog.style) 609 | 610 | class ProgressNoCancel(Styler): 611 | 612 | target = ProgressManager.ProgressNoCancel 613 | require = {LegacyProgressStyler} 614 | 615 | # so this bit is required to enable init wrapping of Qt objects 616 | def init(cls, label='', *args, **kwargs): 617 | aqt.QProgressDialog.__init__(cls, label, *args, **kwargs) 618 | 619 | target.__init__ = init 620 | 621 | @wraps 622 | def init(self, progress, *args, **kwargs): 623 | self.legacy_progress_styler.init(progress, *args, **kwargs) 624 | 625 | 626 | class ProgressCancelable(Styler): 627 | 628 | target = ProgressManager.ProgressCancellable 629 | require = {LegacyProgressStyler} 630 | 631 | @wraps 632 | def init(self, progress, *args, **kwargs): 633 | self.legacy_progress_styler.init(progress, *args, **kwargs) 634 | 635 | else: 636 | # beta 31 or newer 637 | 638 | class ProgressDialog(Styler): 639 | 640 | target = ProgressManager.ProgressDialog 641 | require = {ProgressStyler} 642 | 643 | @wraps 644 | def init(self, progress, *args, **kwargs): 645 | self.progress_styler.init(progress, *args, **kwargs) 646 | 647 | 648 | class StatsWindowStyler(Styler): 649 | 650 | target = DeckStats 651 | 652 | require = { 653 | DialogStyle, 654 | ButtonsStyle 655 | } 656 | 657 | @wraps 658 | def init(self, stats, *args, **kwargs): 659 | if self.config.enable_in_dialogs: 660 | stats.setStyleSheet(self.buttons.qt + self.dialog.style) 661 | 662 | 663 | class StatsReportStyler(Styler): 664 | 665 | target = CollectionStats 666 | 667 | require = { 668 | SharedStyles, 669 | DialogStyle 670 | } 671 | 672 | @appends_in_night_mode 673 | @style_tag 674 | @percent_escaped 675 | def css(self): 676 | return ( 677 | self.shared.user_color_map + self.shared.body_colors + """ 678 | body{background-image: none} 679 | """ 680 | ) 681 | 682 | 683 | class EditorStyler(Styler): 684 | 685 | target = Editor 686 | 687 | require = { 688 | SharedStyles, 689 | DialogStyle, 690 | ButtonsStyle 691 | } 692 | 693 | # TODO: this would make more sense if we add some styling to .editor-btn 694 | def _addButton(self, editor, icon, command, *args, **kwargs): 695 | original_function = kwargs.pop('_old') 696 | button = original_function(editor, icon, command, *args, **kwargs) 697 | return button.replace('