├── LICENSE ├── README.md ├── __init__.py ├── _config.yml ├── bettereditor.py ├── calltips.py ├── completionmodel.py ├── customclasses.py ├── dependencies.py ├── docs ├── black.gif ├── jedi.gif ├── resource_browser.png ├── settings_dialog.png ├── syntax_check.png └── toggle.gif ├── i18n ├── BetterEditor_en.ts ├── BetterEditor_fr.ts └── update_translations.py ├── icon.png ├── icons ├── about.svg ├── clear.svg ├── file-1.svg ├── folder.svg ├── icon.svg ├── symbol-class.svg ├── symbol-enumerator.svg ├── symbol-key.svg ├── symbol-keyword.svg ├── symbol-method.svg ├── symbol-misc.svg ├── symbol-namespace.svg ├── symbol-variable.svg └── wizard.svg ├── indicatorsutils.py ├── metadata.txt ├── monkeypatch.py ├── pb_tool.cfg ├── resourcebrowser.ui ├── resourcebrowserimpl.py ├── resources.qrc ├── settingsdialog.ui ├── settingsdialogimpl.py └── tests └── test_monkeypatch.py /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | > **Warning** 2 | > 3 | > This plugin is **OBSOLETE** and is not guaranteed to work beyond QGIS 3.10. 4 | > 5 | > Some of its features will eventually be merged to QGIS: 6 | > - ToggleComment (https://github.com/qgis/QGIS/pull/50341): 3.30 7 | > - Smart brackets (https://github.com/qgis/QGIS/pull/51391): 3.30 8 | > - Fix altgr shortcut (https://github.com/qgis/QGIS/pull/51420): 3.30 9 | > - Save / Run / Tab shortcuts (https://github.com/qgis/QGIS/pull/51913): 3.30 10 | > - Format code (https://github.com/qgis/QGIS/pull/51733): 3.32 11 | > - IPython-style system commands (https://github.com/qgis/QGIS/pull/51919): 3.32 12 | > - Jedi features (autocompletion, calltips, goto): TBD 13 | 14 | 15 | Better Editor (QGIS plugin) 16 | === 17 | ![Icon](./icon.png) 18 | 19 | This plugin improves the embedded Python editor with several useful features. 20 | 21 | - Smart autocompletion and call tips with Jedi 22 | ![jedi](./docs/jedi.gif) 23 | 24 | - Replace comment / uncomment action with a single well-behaved Toggle comment action (`Ctrl+:`) 25 | 26 | ![toggleComment](./docs/toggle.gif) 27 | - Format code with [black formatter](https://github.com/psf/black) (`Ctrl+Alt+F` or Format on save) 28 | 29 | ![formatCode](./docs/black.gif) 30 | - Better handling of `[{('""')}]` : automatic insertion and deletion 31 | - Goto definition: press F12 or F2 will go to the definition of the word under the cursor (works only within the script) 32 | - Insert icon from QGIS resources: useful for quick prototyping 33 | - Tweak some QGIS shortcuts which prevented user from entering `}` and `|` in the console when keyboard used AZERTY (French) layout 34 | - Pressing Ctrl+S and Ctrl+Shift+S triggers file save when editor has focus 35 | - Pressing Ctrl+R triggers script run 36 | - Tab navigation with `Ctrl+PgDown` and `Ctrl+PgUp` 37 | - Multiple syntax error check with [jedi](https://github.com/davidhalter/jedi). 38 | 39 | ![syntax check](./docs/syntax_check.png) 40 | Original, simple check (QGIS) and multi check (Jedi) 41 | 42 | Settings dialog 43 | --- 44 | 45 | ![Settings dialog](./docs/settings_dialog.png) 46 | - Hide default QGIS comment & uncomment actions 47 | - Set the max line length (will be used by the ruler, and black) 48 | - Set the autocompletion threshold (Autocompletion is not triggered for words shorther than the threshold) 49 | - Format on save applies black before saving file 50 | - Configure the ruler 51 | - Change the default folding indicator (QGIS default is `Plain`) 52 | 53 | 54 | 55 | Resource browser 56 | --- 57 | ![Resource browser](./docs/resource_browser.png) 58 | 59 | 60 | The resource browser allow to search through the embedded .qrc files to look for images to use as icon. 61 | 62 | 63 | *Copyright © 2020 Yoann Quenach de Quivillic* 64 | 65 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | /*************************************************************************** 4 | Better Editor 5 | A QGIS plugin which improves the embedded python editor 6 | 7 | ------------------- 8 | begin : 2020-06-15 9 | git sha : $Format:%H$ 10 | copyright : (C) 2020 Yoann Quenach de Quivillic 11 | email : yoann.quenach@gmail.com 12 | ***************************************************************************/ 13 | 14 | /*************************************************************************** 15 | * * 16 | * This program is free software; you can redistribute it and/or modify * 17 | * it under the terms of the GNU General Public License as published by * 18 | * the Free Software Foundation; either version 2 of the License, or * 19 | * (at your option) any later version. * 20 | * * 21 | ***************************************************************************/ 22 | This script initializes the plugin, making it known to QGIS. 23 | """ 24 | 25 | 26 | # noinspection PyPep8Naming 27 | def classFactory(iface): # pylint: disable=invalid-name 28 | """ 29 | :param iface: A QGIS interface instance. 30 | :type iface: QgsInterface 31 | """ 32 | # 33 | from .bettereditor import BetterEditor 34 | 35 | return BetterEditor(iface) 36 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-slate -------------------------------------------------------------------------------- /bettereditor.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | /*************************************************************************** 4 | Better Editor 5 | A QGIS plugin which improves the embedded python editor 6 | 7 | ------------------- 8 | begin : 2020-06-15 9 | git sha : $Format:%H$ 10 | copyright : (C) 2020 Yoann Quenach de Quivillic 11 | email : yoann.quenach@gmail.com 12 | ***************************************************************************/ 13 | 14 | /*************************************************************************** 15 | * * 16 | * This program is free software; you can redistribute it and/or modify * 17 | * it under the terms of the GNU General Public License as published by * 18 | * the Free Software Foundation; either version 2 of the License, or * 19 | * (at your option) any later version. * 20 | * * 21 | ***************************************************************************/ 22 | """ 23 | import os 24 | import sys 25 | import configparser 26 | 27 | 28 | from PyQt5.QtCore import QSettings, QTranslator, QCoreApplication, Qt, QTimer 29 | from PyQt5.QtGui import QIcon, QColor 30 | from PyQt5.QtWidgets import ( 31 | QAction, 32 | QMessageBox, 33 | QWidget, 34 | QToolBar, 35 | QShortcut, 36 | QCompleter, 37 | ) 38 | from PyQt5.Qsci import QsciScintilla 39 | 40 | from qgis.core import QgsApplication 41 | 42 | from console.console import PythonConsole 43 | from console.console_editor import Editor, EditorTabWidget, EditorTab 44 | from processing.script.ScriptEdit import ScriptEdit 45 | from processing.script.ScriptEditorDialog import ScriptEditorDialog 46 | 47 | 48 | from .dependencies import ( 49 | import_or_install, 50 | check_pip, 51 | check_minimum_version, 52 | install, 53 | check_module, 54 | ) 55 | from .customclasses import ( 56 | MonkeyEditorTab, 57 | MonkeyEditor, 58 | MonkeyScriptEditor, 59 | MonkeyScriptEditorDialog, 60 | ) 61 | from .settingsdialogimpl import SettingsDialog 62 | from .indicatorsutils import define_indicators, clear_all_indicators, MARKER_NUMBER 63 | from .completionmodel import CompletionModel 64 | from .calltips import CallTips 65 | from .monkeypatch import patch, unpatch 66 | from .resources import * 67 | 68 | 69 | class BetterEditor: 70 | """QGIS Plugin Implementation.""" 71 | 72 | def __init__(self, iface): 73 | """Constructor. 74 | 75 | :param iface: An interface instance that will be passed to this class 76 | which provides the hook by which you can manipulate the QGIS 77 | application at run time. 78 | :type iface: QgsInterface 79 | """ 80 | # Save reference to the QGIS interface 81 | self.iface = iface 82 | # initialize plugin directory 83 | self.plugin_dir = os.path.dirname(__file__) 84 | # initialize locale 85 | locale = QSettings().value("locale/userLocale")[0:2] 86 | locale_path = os.path.join(self.plugin_dir, "i18n", "BetterEditor_{}.qm".format(locale)) 87 | 88 | if os.path.exists(locale_path): 89 | self.translator = QTranslator() 90 | self.translator.load(locale_path) 91 | QCoreApplication.installTranslator(self.translator) 92 | 93 | # Init settings 94 | self.settings = QSettings() 95 | self.settings.beginGroup("plugins/bettereditor") 96 | 97 | # noinspection PyMethodMayBeStatic 98 | def tr(self, message): 99 | """Get the translation for a string using Qt translation API. 100 | 101 | We implement this ourselves since we do not inherit QObject. 102 | 103 | :param message: String for translation. 104 | :type message: str, QString 105 | 106 | :returns: Translated version of message. 107 | :rtype: QString 108 | """ 109 | # noinspection PyTypeChecker,PyArgumentList,PyCallByClass 110 | return QCoreApplication.translate("BetterEditor", message) 111 | 112 | def initGui(self): 113 | """Create the menu entries and toolbar icons inside the QGIS GUI.""" 114 | 115 | # Create settings dialog 116 | self.settings_dialog = SettingsDialog(self.settings, self.iface.mainWindow()) 117 | self.settings_dialog.settingsChanged.connect(self.on_settings_changed) 118 | 119 | # Show Python console to trigger its creation 120 | self.python_console = self.iface.mainWindow().findChild(PythonConsole) 121 | if not self.python_console: 122 | self.iface.actionShowPythonDialog().trigger() 123 | self.python_console = self.iface.mainWindow().findChild(PythonConsole) 124 | self.python_console.hide() 125 | self.iface.actionShowPythonDialog().setChecked(False) 126 | 127 | self.about_action = QAction( 128 | QIcon(":/plugins/bettereditor/icons/about.svg"), 129 | self.tr("About"), 130 | parent=self.iface.mainWindow(), 131 | ) 132 | self.about_action.triggered.connect(self.show_about) 133 | 134 | self.settings_action = QAction( 135 | QIcon(":/images/themes/default/console/iconSettingsConsole.svg"), 136 | self.tr("Settings"), 137 | parent=self.iface.mainWindow(), 138 | ) 139 | self.settings_action.triggered.connect(self.show_settings) 140 | 141 | self.plugin_menu = self.iface.pluginMenu().addMenu( 142 | QIcon(":/plugins/bettereditor/icons/icon.svg"), "Better Editor" 143 | ) 144 | self.plugin_menu.addAction(self.about_action) 145 | self.plugin_menu.addAction(self.settings_action) 146 | self.toolbar = self.python_console.findChild(QToolBar) 147 | self.tab_widget = self.python_console.findChild(EditorTabWidget) 148 | 149 | # Connect current 150 | self.tab_widget.currentChanged.connect(self.customize_current_editor) 151 | 152 | # Tweak zoom shortcuts to prevent them from interfering 153 | # when typing '|' and '}' with an AZERTY (French) keyboard layout 154 | action_zoom_in = self.iface.mainWindow().findChild(QAction, "mActionZoomIn") 155 | action_zoom_out = self.iface.mainWindow().findChild(QAction, "mActionZoomOut") 156 | action_zoom_in.setShortcut("") 157 | action_zoom_out.setShortcut("") 158 | 159 | self.iface.initializationCompleted.connect(self.on_initialization_completed) 160 | for shortcut_name in ( 161 | "ZoomInToCanvas", 162 | "ZoomInToCanvas2", 163 | "ZoomIn2", 164 | "ZoomOutOfCanvas", 165 | ): 166 | shortcut = self.iface.mainWindow().findChild(QShortcut, shortcut_name) 167 | if shortcut: 168 | shortcut.setParent(self.iface.mapCanvas()) 169 | shortcut.setContext(Qt.WidgetWithChildrenShortcut) 170 | self.zoom_out_shortcut = QShortcut("Ctrl+Alt+-", self.iface.mapCanvas()) 171 | self.zoom_out_shortcut.setObjectName("MyZoomOut") 172 | self.zoom_out_shortcut.setContext(Qt.WidgetWithChildrenShortcut) 173 | self.zoom_out_shortcut.activated.connect(action_zoom_out.trigger) 174 | 175 | # Customize buttons tooltips 176 | save_button = self.python_console.widget().saveFileButton 177 | saveas_button = self.python_console.widget().saveAsFileButton 178 | run_button = self.python_console.widget().runScriptEditorButton 179 | 180 | save_button.setToolTip(f"{save_button.text()} (Ctrl+S)") 181 | saveas_button.setToolTip(f"{saveas_button.text()} (Ctrl+Shift+S)") 182 | run_button.setToolTip(f"{run_button.text()} (Ctrl+R)") 183 | 184 | # Create our own toggle comment action 185 | separator = self.toolbar.addSeparator() 186 | separator = separator.setObjectName("separator") 187 | self.toggle_comment_action = self.toolbar.addAction( 188 | QIcon(":/images/themes/default/console/iconCommentEditorConsole.svg"), 189 | self.tr("Toggle Comment"), 190 | ) 191 | self.toggle_comment_action.setObjectName("toggleComment") 192 | self.toggle_comment_action.triggered.connect(self.toggle_comment) 193 | self.toggle_comment_action.setShortcut("Ctrl+:") 194 | self.toggle_comment_action.setToolTip( 195 | f"{self.toggle_comment_action.text()} ({self.toggle_comment_action.shortcut().toString()})" 196 | ) 197 | 198 | # Check that submodules are installed 199 | self.black = None 200 | self.jedi = None 201 | self.check_dependencies() 202 | 203 | # Add format action 204 | self.format_action = self.toolbar.addAction( 205 | QIcon(r":/plugins/bettereditor/icons/wizard.svg"), self.tr("Format file") 206 | ) 207 | self.format_action.setObjectName("format") 208 | self.format_action.setShortcut("Ctrl+Alt+F") 209 | self.format_action.triggered.connect(self.format_file) 210 | self.format_action.setToolTip( 211 | f"{self.format_action.text()} ({self.format_action.shortcut().toString()})" 212 | ) 213 | if not self.black: 214 | self.format_action.setEnabled(False) 215 | 216 | self.project = None 217 | if self.jedi: 218 | self.project = self.jedi.Project("", sys_path=sys.path, load_unsafe_extensions=True, smart_sys_path=False) 219 | 220 | patch(Editor, MonkeyEditor) 221 | patch(EditorTab, MonkeyEditorTab) 222 | patch(ScriptEdit, MonkeyScriptEditor) 223 | patch(ScriptEditorDialog, MonkeyScriptEditorDialog) 224 | ScriptEdit.project = self.project 225 | ScriptEdit.settings = self.settings 226 | 227 | self.oldAutoCloseBracketEditor = QSettings().value("pythonConsole/autoCloseBracketEditor", False, bool) 228 | QSettings().setValue("pythonConsole/autoCloseBracketEditor", False) 229 | 230 | # Add insert icon from ressource action 231 | self.insert_resource_action = self.toolbar.addAction( 232 | QIcon(":/images/themes/default/propertyicons/diagram.svg"), 233 | self.tr("Insert resource path"), 234 | ) 235 | self.insert_resource_action.setObjectName("insertResource") 236 | self.insert_resource_action.triggered.connect(self.insert_resource) 237 | self.insert_resource_action.setToolTip(f"{self.insert_resource_action.text()}") 238 | 239 | # Add next / previous tab shortcuts 240 | self.next_tab_shortcut = QShortcut("Ctrl+PgDown", self.python_console) 241 | self.next_tab_shortcut.setObjectName("NextTab") 242 | self.next_tab_shortcut.activated.connect(self.go_to_next_tab) 243 | 244 | self.previous_tab_shortcut = QShortcut("Ctrl+PgUp", self.python_console) 245 | self.previous_tab_shortcut.setObjectName("PreviousTab") 246 | self.previous_tab_shortcut.activated.connect(self.go_to_previous_tab) 247 | 248 | self.on_settings_changed() 249 | 250 | if not self.black or not self.jedi: 251 | if not check_pip(): 252 | 253 | QMessageBox.warning( 254 | self.iface.mainWindow(), 255 | self.tr("Error"), 256 | self.tr( 257 | "Pip is not installed. Try to get it, then restart QGIS, or manually install black and jedi" 258 | ), 259 | ) 260 | 261 | else: 262 | if not self.black: 263 | QMessageBox.warning( 264 | self.iface.mainWindow(), 265 | self.tr("Error"), 266 | self.tr( 267 | "Unable to load black. Formatting will be disabled. You could try to manually install black with pip" 268 | ), 269 | ) 270 | 271 | if not self.jedi: 272 | 273 | # If check_module return true, an obsolete version was loaded, ad user was already informed 274 | if not check_module("jedi"): 275 | QMessageBox.warning( 276 | self.iface.mainWindow(), 277 | self.tr("Error"), 278 | self.tr( 279 | "Unable to load jedi. Multi syntax error check will be disabled. You could try to manually install jedi with pip" 280 | ), 281 | ) 282 | 283 | def check_dependencies(self): 284 | install("packaging") 285 | self.black, _ = import_or_install("black") 286 | self.jedi, jedi_version = import_or_install("jedi") 287 | 288 | # JEDI 0.17 is required 289 | if not check_minimum_version(jedi_version, "0.17"): 290 | res = QMessageBox.question( 291 | self.iface.mainWindow(), 292 | self.tr("Information"), 293 | self.tr( 294 | "jedi version is {0} and BetterEditor needs {1}. Do you want to upgrade jedi?
Warning: it could cause old code relying on the obsolete jedi to stop working correctly." 295 | ).format(jedi_version, "0.17"), 296 | QMessageBox.Yes | QMessageBox.No, 297 | ) 298 | 299 | if res == QMessageBox.Yes: 300 | install("jedi", True) 301 | QMessageBox.information( 302 | self.iface.mainWindow(), 303 | self.tr("Information"), 304 | self.tr("Jedi was upgraded. You need to restart QGIS to fully use BetterEditor"), 305 | ) 306 | 307 | self.jedi = None 308 | 309 | def on_initialization_completed(self): 310 | """ Called after QGIS has completed its initialization """ 311 | 312 | # Shortcuts are created after plugins 313 | for shortcut_name in ( 314 | "ZoomInToCanvas", 315 | "ZoomInToCanvas2", 316 | "ZoomIn2", 317 | "ZoomOutOfCanvas", 318 | ): 319 | shortcut = self.iface.mainWindow().findChild(QShortcut, shortcut_name) 320 | if shortcut: 321 | shortcut.setParent(self.iface.mapCanvas()) 322 | shortcut.setContext(Qt.WidgetWithChildrenShortcut) 323 | 324 | def unload(self): 325 | """Removes the plugin menu item and icon from QGIS GUI.""" 326 | 327 | # Delete Settings dialog 328 | self.settings_dialog.deleteLater() 329 | 330 | # Remove buttons tooltips 331 | save_button = self.python_console.widget().saveFileButton 332 | saveas_button = self.python_console.widget().saveAsFileButton 333 | run_button = self.python_console.widget().runScriptEditorButton 334 | 335 | save_button.setToolTip(save_button.text()) 336 | saveas_button.setToolTip(saveas_button.text()) 337 | run_button.setToolTip(run_button.text()) 338 | 339 | # Show comment actions 340 | self.set_old_comments_action_visible(True) 341 | 342 | # Remove custom actions 343 | for action_name in ("separator", "toggleComment", "format", "insertResource"): 344 | action = self.toolbar.findChild(QAction, action_name) 345 | if action: 346 | action.deleteLater() 347 | 348 | # Remove Next tab / previous tab shortcuts 349 | for shortcut in (self.next_tab_shortcut, self.previous_tab_shortcut): 350 | shortcut.activated.disconnect() 351 | shortcut.setEnabled(False) 352 | shortcut.deleteLater() 353 | 354 | # Reenable zoom shortcuts & actions 355 | for shortcut_name in ( 356 | "ZoomInToCanvas", 357 | "ZoomInToCanvas2", 358 | "ZoomIn2", 359 | "ZoomOutOfCanvas", 360 | ): 361 | shortcut = self.iface.mainWindow().findChild(QShortcut, shortcut_name) 362 | if shortcut: 363 | shortcut.setParent(self.iface.mainWindow()) 364 | shortcut.setContext(Qt.ApplicationShortcut) 365 | 366 | self.iface.mainWindow().findChild(QAction, "mActionZoomIn").setShortcut("Ctrl+Alt++") 367 | self.iface.mainWindow().findChild(QAction, "mActionZoomOut").setShortcut("Ctrl+Alt+-") 368 | 369 | self.zoom_out_shortcut.activated.disconnect() 370 | self.zoom_out_shortcut.setEnabled(False) 371 | self.zoom_out_shortcut.deleteLater() 372 | 373 | self.tab_widget.currentChanged.disconnect(self.customize_current_editor) 374 | for editor in self.python_console.findChildren(Editor): 375 | clear_all_indicators(editor) 376 | self.restore_editor(editor) 377 | 378 | # Revert MonkeyPatch 379 | unpatch(Editor) 380 | unpatch(EditorTab) 381 | unpatch(ScriptEdit) 382 | unpatch(ScriptEditorDialog) 383 | 384 | del ScriptEdit.project 385 | del ScriptEdit.settings 386 | 387 | # Remove menu from plugins menu 388 | self.iface.pluginMenu().removeAction(self.plugin_menu.menuAction()) 389 | 390 | # Reactivate old autoCloseBracketEditor 391 | QSettings().setValue("pythonConsole/autoCloseBracketEditor", self.oldAutoCloseBracketEditor) 392 | 393 | def current_editor(self) -> Editor: 394 | if not self.tab_widget.currentWidget(): 395 | return None 396 | return self.tab_widget.currentWidget().findChild(Editor) 397 | 398 | def toggle_comment(self): 399 | self.current_editor().toggle_comment() 400 | 401 | def format_file(self): 402 | self.current_editor().format_file() 403 | 404 | def insert_resource(self): 405 | self.current_editor().insert_resource() 406 | 407 | def go_to_next_tab(self): 408 | self.tab_widget.setCurrentIndex((self.tab_widget.currentIndex() + 1) % self.tab_widget.count()) 409 | 410 | def go_to_previous_tab(self): 411 | self.tab_widget.setCurrentIndex((self.tab_widget.currentIndex() - 1) % self.tab_widget.count()) 412 | 413 | def show_about(self): 414 | 415 | # Used to display plugin icon in the about message box 416 | bogus = QWidget(self.iface.mainWindow()) 417 | bogus.setWindowIcon(QIcon(":/plugins/bettereditor/icons/icon.svg")) 418 | 419 | cfg = configparser.ConfigParser() 420 | cfg.read(os.path.join(os.path.dirname(__file__), "metadata.txt")) 421 | version = cfg.get("general", "version") 422 | 423 | QMessageBox.about( 424 | bogus, 425 | self.tr("About Better Editor"), 426 | "Version {0}

" 427 | "{1} : GitHub
" 428 | "{2} : GitHub
" 429 | "{3} : GitHub".format( 430 | version, 431 | self.tr("Source code"), 432 | self.tr("Report issues"), 433 | self.tr("Documentation"), 434 | ), 435 | ) 436 | 437 | bogus.deleteLater() 438 | 439 | def set_old_comments_action_visible(self, value): 440 | self.toolbar.actions()[13].setVisible(value) 441 | self.toolbar.actions()[14].setVisible(value) 442 | self.toolbar.actions()[15].setVisible(value) 443 | 444 | def show_settings(self): 445 | 446 | self.settings_dialog.show() 447 | self.settings_dialog.raise_() 448 | 449 | def on_settings_changed(self): 450 | 451 | # Hide / Show old comment actions 452 | self.set_old_comments_action_visible(not self.settings.value("hide_old_comment_actions", True, bool)) 453 | 454 | for editor in self.python_console.findChildren(Editor): 455 | self.customize_editor(editor) 456 | 457 | def customize_current_editor(self): 458 | return self.customize_editor() 459 | 460 | def customize_editor(self, editor: Editor = None): 461 | if editor is None: 462 | editor = self.current_editor() 463 | 464 | if editor is None: 465 | return 466 | editor.project = self.project 467 | 468 | # Disable shortcuts 469 | for shortcut in editor.findChildren(QShortcut): 470 | shortcut.setEnabled(False) 471 | 472 | editor.set_completer(QCompleter(editor)) 473 | editor.completer.setModel(CompletionModel([], editor)) 474 | editor.callTips = CallTips(editor) 475 | editor.callTipsTimer = QTimer(editor) 476 | editor.callTipsTimer.setSingleShot(True) 477 | editor.callTipsTimer.setInterval(500) 478 | editor.callTipsTimer.timeout.connect(editor.update_calltips) 479 | 480 | editor.setCallTipsStyle(QsciScintilla.CallTipsNone) 481 | editor.setAutoCompletionSource(QsciScintilla.AcsNone) 482 | editor.setFolding(self.settings.value("folding_style", QsciScintilla.BoxedTreeFoldStyle, int)) 483 | 484 | # Add a small margin after the indicator (if folding is not Plain or None) 485 | if editor.folding() > 1: 486 | editor.setMarginWidth(3, "0") 487 | else: 488 | editor.setMarginWidth(3, "") 489 | 490 | if self.settings.value("ruler_visible", True, bool): 491 | editor.setEdgeMode(QsciScintilla.EdgeLine) 492 | editor.setEdgeColumn(self.settings.value("max_line_length", 88, int)) 493 | editor.setEdgeColor(self.settings.value("ruler_color", QColor("#00aaff"), QColor)) 494 | else: 495 | editor.setEdgeMode(QsciScintilla.EdgeNone) 496 | 497 | # Change syntax error marker 498 | define_indicators(editor) 499 | 500 | editor.cursorPositionChanged.connect(editor.on_position_changed) 501 | 502 | def restore_editor(self, editor: Editor): 503 | editor.cursorPositionChanged.disconnect(editor.on_position_changed) 504 | editor.setFolding(QsciScintilla.PlainFoldStyle) 505 | editor.setEdgeMode(QsciScintilla.EdgeLine) 506 | editor.setEdgeColumn(80) 507 | editor.setMarginWidth(3, "") 508 | editor.setEdgeColor(QSettings().value("pythonConsole/edgeColorEditor", QColor("#efefef"), QColor)) 509 | 510 | # Disable shortcuts 511 | for shortcut in editor.findChildren(QShortcut): 512 | shortcut.setEnabled(True) 513 | 514 | editor.markerDefine( 515 | QgsApplication.getThemePixmap("console/iconSyntaxErrorConsole.svg"), 516 | MARKER_NUMBER, 517 | ) 518 | 519 | editor.setAnnotationDisplay(QsciScintilla.AnnotationBoxed) 520 | editor.setCallTipsStyle(QsciScintilla.CallTipsNoContext) 521 | editor.setAutoCompletionSource(QsciScintilla.AcsAll) 522 | 523 | editor.callTips.deleteLater() 524 | del editor.callTips 525 | editor.callTipsTimer.deleteLater() 526 | del editor.callTipsTimer 527 | editor.completer.deleteLater() 528 | del editor.completer 529 | del editor.project 530 | -------------------------------------------------------------------------------- /calltips.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtWidgets import QFrame, QVBoxLayout, QLabel, QTextEdit 2 | from PyQt5.QtGui import QColor, QPalette 3 | from PyQt5.QtCore import Qt, QPoint 4 | 5 | SCROLL_STYLESHEET = """ 6 | QScrollBar:vertical { 7 | border: None; 8 | width: 8px; 9 | background: #eee; 10 | margin: 0 0 0 0; 11 | } 12 | QScrollBar::handle { 13 | background: #aaa; 14 | } 15 | QScrollBar::handle:hover { 16 | background: #888; 17 | } 18 | QScrollBar::add-line { 19 | border: None; 20 | } 21 | QScrollBar::sub-line { 22 | border: None; 23 | } 24 | """ 25 | 26 | 27 | class CallTips(QFrame): 28 | def __init__(self, parent): 29 | super().__init__(parent) 30 | self.setFrameStyle(QFrame.StyledPanel) 31 | layout = QVBoxLayout(self) 32 | layout.setContentsMargins(2, 2, 2, 2) 33 | palette = self.palette() 34 | palette.setColor(QPalette.Window, QColor("#fff")) 35 | self.setPalette(palette) 36 | self.setWindowFlags(Qt.ToolTip) 37 | 38 | self.line = QFrame(self) 39 | self.line.setFrameShape(QFrame.HLine) 40 | self.line.setFrameShadow(QFrame.Sunken) 41 | 42 | self.title_label = QLabel() 43 | self.title_label.setMinimumWidth(300) 44 | self.title_label.setFont(parent.font()) 45 | self.docstring_textedit = QTextEdit(self) 46 | self.docstring_textedit.setReadOnly(True) 47 | self.docstring_textedit.setFont(parent.font()) 48 | 49 | palette = self.docstring_textedit.palette() 50 | palette.setColor(QPalette.WindowText, QColor("#888")) 51 | palette.setColor(QPalette.Text, QColor("#888")) 52 | self.docstring_textedit.setPalette(palette) 53 | self.docstring_textedit.setFrameShape(QFrame.NoFrame) 54 | self.docstring_textedit.document().setDocumentMargin(0) 55 | self.title_label.setPalette(palette) 56 | 57 | layout.setSpacing(2) 58 | layout.addWidget(self.title_label) 59 | layout.addWidget(self.line) 60 | layout.addWidget(self.docstring_textedit) 61 | layout.setSizeConstraint(QVBoxLayout.SetFixedSize) 62 | 63 | @staticmethod 64 | def signature_to_string(signature): 65 | name = signature.name 66 | params = [] 67 | for i, param in enumerate(signature.params): 68 | try: 69 | type_hint = param.get_type_hint() 70 | except TypeError: 71 | type_hint = None 72 | 73 | if signature.index == i: 74 | if type_hint: 75 | params.append( 76 | f'{param.name}: {type_hint}' 77 | ) 78 | else: 79 | params.append( 80 | f'{param.name}' 81 | ) 82 | 83 | else: 84 | if type_hint: 85 | params.append(f"{param.name}: {type_hint}") 86 | else: 87 | params.append(param.name) 88 | html = f'{name}({", ".join(params)})' 89 | 90 | docstring = "" 91 | if signature.docstring(True, True): 92 | docstring = signature.docstring(True, True).replace("\n", "
") 93 | 94 | return html, docstring 95 | 96 | def show_signatures(self, signatures, pos: QPoint): 97 | signature = signatures[0] 98 | 99 | text, docstring = self.signature_to_string(signature) 100 | 101 | self.title_label.setText(text) 102 | if not docstring: 103 | self.docstring_textedit.hide() 104 | self.line.hide() 105 | else: 106 | self.docstring_textedit.show() 107 | self.line.show() 108 | self.docstring_textedit.setHtml(docstring) 109 | self.docstring_textedit.document().adjustSize() 110 | height = self.docstring_textedit.document().size().height() 111 | self.docstring_textedit.setFixedHeight(min(150, height)) 112 | 113 | point = self.parent().mapToGlobal( 114 | QPoint(pos.x(), pos.y() - self.sizeHint().height() - 2) 115 | ) 116 | self.show() 117 | self.move(point.x(), point.y()) 118 | 119 | self.docstring_textedit.setStyleSheet(SCROLL_STYLESHEET) 120 | -------------------------------------------------------------------------------- /completionmodel.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtCore import QModelIndex, Qt, QAbstractListModel 2 | from PyQt5.QtGui import QIcon 3 | 4 | 5 | class CompletionModel(QAbstractListModel): 6 | def __init__(self, completions=None, parent=None): 7 | super().__init__(parent) 8 | if not completions: 9 | self.completions = [] 10 | else: 11 | self.completions = completions 12 | 13 | def rowCount(self, index=QModelIndex()): 14 | return len(self.completions) 15 | 16 | def setCompletions(self, completions): 17 | self.beginResetModel() 18 | self.completions = completions 19 | self.endResetModel() 20 | 21 | def data(self, index, role=Qt.DisplayRole): 22 | 23 | if not index.isValid(): 24 | return 25 | 26 | completion = self.completions[index.row()] 27 | 28 | if completion.type == "path" and completion.name.endswith("\\"): 29 | name = f"{completion.name[:-1]}/" 30 | else: 31 | name = completion.name 32 | 33 | if role == Qt.DisplayRole: 34 | return name 35 | elif role == Qt.EditRole: 36 | return name 37 | elif role == Qt.DecorationRole: 38 | if completion.type == "class": 39 | return QIcon(":/plugins/bettereditor/icons/symbol-class.svg") 40 | elif completion.type == "keyword": 41 | return QIcon(":/plugins/bettereditor/icons/symbol-keyword.svg") 42 | elif completion.type == "function": 43 | return QIcon(":/plugins/bettereditor/icons/symbol-namespace.svg") 44 | elif completion.type == "path": 45 | if name.endswith("/"): 46 | return QIcon(":/plugins/bettereditor/icons/folder.svg") 47 | else: 48 | return QIcon(":/plugins/bettereditor/icons/file-1.svg") 49 | elif completion.type == "statement": 50 | return QIcon(":/plugins/bettereditor/icons/symbol-enumerator.svg") 51 | elif completion.type == "param": 52 | return QIcon(":/plugins/bettereditor/icons/symbol-variable.svg") 53 | elif completion.type == "name": 54 | return QIcon(":/plugins/bettereditor/icons/symbol-key.svg") 55 | else: 56 | return QIcon(":/plugins/bettereditor/icons/symbol-method.svg") 57 | -------------------------------------------------------------------------------- /customclasses.py: -------------------------------------------------------------------------------- 1 | # pylint: disable=no-member 2 | 3 | import os 4 | import subprocess 5 | import tempfile 6 | import tokenize 7 | from io import BytesIO 8 | 9 | from PyQt5.QtCore import ( 10 | QSettings, 11 | Qt, 12 | QPoint, 13 | QRect, 14 | QSize, 15 | QEvent, 16 | QTimer, 17 | QCoreApplication, 18 | ) 19 | from PyQt5.QtGui import QPalette, QColor, QKeySequence, QIcon 20 | from PyQt5.QtWidgets import QDialog, QCompleter, QListView, QShortcut 21 | from PyQt5.Qsci import QsciScintilla 22 | 23 | from qgis.utils import iface 24 | 25 | from .dependencies import check_module 26 | from .monkeypatch import unpatched 27 | from .resourcebrowserimpl import ResourceBrowser 28 | from .indicatorsutils import define_indicators, check_syntax 29 | from .completionmodel import CompletionModel 30 | from .calltips import CallTips 31 | 32 | 33 | def tr(message): 34 | return QCoreApplication.translate("BetterEditor", message) 35 | 36 | 37 | class MonkeyEditorTab: 38 | def save(self, filename=""): 39 | editor = self.newEditor 40 | settings = QSettings() 41 | settings.beginGroup("plugins/bettereditor") 42 | if settings.value("format_on_save", True, bool): 43 | editor.format_file() 44 | return unpatched().save(filename) 45 | 46 | 47 | class MonkeyEditor: 48 | def syntaxCheck(self, filename=None, fromContextMenu=True): 49 | if not check_module("jedi", "0.17"): 50 | return unpatched().syntaxCheck(filename, fromContextMenu) 51 | return check_syntax(self, filename, fromContextMenu) 52 | 53 | def format_file(self): 54 | 55 | if not check_module("black"): 56 | return 57 | 58 | # Check there's no syntax errors before calling black 59 | if not self.syntaxCheck(): 60 | return 61 | 62 | old_pos = self.getCursorPosition() 63 | old_scroll_value = self.verticalScrollBar().value() 64 | 65 | myfile = tempfile.mkstemp(".py") 66 | filepath = myfile[1] 67 | os.close(myfile[0]) 68 | with open(filepath, "w") as out: 69 | out.write(self.text().replace("\r\n", "\n")) 70 | 71 | settings = QSettings() 72 | settings.beginGroup("plugins/bettereditor") 73 | line_length = settings.value("max_line_length", 88, int) 74 | 75 | cmd = ["python3", "-m", "black", filepath, "-l", str(line_length)] 76 | # Prevents the call to black from spawning an console on Windows. 77 | try: 78 | completed_process = subprocess.run( 79 | cmd, check=False, creationflags=subprocess.CREATE_NO_WINDOW 80 | ) 81 | except (AttributeError, TypeError): 82 | completed_process = subprocess.run(cmd, check=False) 83 | 84 | if completed_process.returncode == 0: 85 | with open(filepath) as out: 86 | content = out.read() 87 | self.beginUndoAction() 88 | self.selectAll() 89 | self.removeSelectedText() 90 | self.insert(content) 91 | self.setCursorPosition(*old_pos) 92 | self.verticalScrollBar().setValue(old_scroll_value) 93 | self.endUndoAction() 94 | 95 | os.remove(filepath) 96 | 97 | def toggle_comment(self): 98 | 99 | self.beginUndoAction() 100 | if self.hasSelectedText(): 101 | start_line, start_pos, end_line, end_pos = self.getSelection() 102 | else: 103 | start_line, start_pos = self.getCursorPosition() 104 | end_line, end_pos = start_line, start_pos 105 | 106 | # Special case, only empty lines 107 | if not any(self.text(line).strip() for line in range(start_line, end_line + 1)): 108 | return 109 | 110 | all_commented = all( 111 | self.text(line).strip().startswith("#") 112 | for line in range(start_line, end_line + 1) 113 | if self.text(line).strip() 114 | ) 115 | min_indentation = min( 116 | self.indentation(line) 117 | for line in range(start_line, end_line + 1) 118 | if self.text(line).strip() 119 | ) 120 | 121 | for line in range(start_line, end_line + 1): 122 | # Empty line 123 | if not self.text(line).strip(): 124 | continue 125 | 126 | delta = 0 127 | 128 | if not all_commented: 129 | self.insertAt("# ", line, min_indentation) 130 | delta = -2 131 | else: 132 | if not self.text(line).strip().startswith("#"): 133 | continue 134 | if self.text(line).strip().startswith("# "): 135 | delta = 2 136 | else: 137 | delta = 1 138 | 139 | self.setSelection( 140 | line, self.indentation(line), line, self.indentation(line) + delta, 141 | ) 142 | self.removeSelectedText() 143 | 144 | self.endUndoAction() 145 | 146 | self.setSelection(start_line, start_pos - delta, end_line, end_pos - delta) 147 | 148 | def insert_resource(self): 149 | dialog = ResourceBrowser(iface.mainWindow()) 150 | res = dialog.exec() 151 | if res == QDialog.Accepted: 152 | 153 | line, offset = self.getCursorPosition() 154 | old_selection = self.getSelection() 155 | if old_selection == (-1, -1, -1, -1): 156 | selection = (line, offset - 1, line, offset + 1) 157 | else: 158 | selection = ( 159 | old_selection[0], 160 | old_selection[1] - 1, 161 | old_selection[2], 162 | old_selection[3] + 1, 163 | ) 164 | 165 | self.setSelection(*selection) 166 | selected_text = self.selectedText() 167 | 168 | if selected_text and not ( 169 | selected_text[-1] == selected_text[0] 170 | and selected_text[-1] in ("'", '"') 171 | ): 172 | self.setSelection(*old_selection) 173 | if old_selection == (-1, -1, -1, -1): 174 | self.setCursorPosition(line, offset) 175 | self.removeSelectedText() 176 | ressource_path = f'"{dialog.icon}"' 177 | self.insert(ressource_path) 178 | 179 | line, offset = self.getCursorPosition() 180 | self.setCursorPosition(line, offset + len(ressource_path)) 181 | 182 | def event(self, e): 183 | if e.type() in (QEvent.FocusOut, QEvent.MouseButtonPress): 184 | if hasattr(self, "callTips"): 185 | self.callTips.hide() 186 | if e.type() == QEvent.ShortcutOverride: 187 | 188 | ctrl = bool(e.modifiers() & Qt.ControlModifier) 189 | shift = bool(e.modifiers() & Qt.ShiftModifier) 190 | alt = bool(e.modifiers() & Qt.AltModifier) 191 | 192 | # Override Save, SavesAs and Run 193 | if ( 194 | e.matches(QKeySequence.Save) 195 | or (ctrl and shift and e.key() == Qt.Key_S) 196 | or (ctrl and e.key() == Qt.Key_R) 197 | or (ctrl and alt and e.key() == Qt.Key_F) 198 | or (e.key() == Qt.Key_F12) 199 | or (e.key() == Qt.Key_F2) 200 | ): 201 | e.accept() 202 | return True 203 | 204 | return unpatched().event(e) 205 | 206 | def keyPressEvent(self, e): 207 | 208 | ctrl = bool(e.modifiers() & Qt.ControlModifier) 209 | shift = bool(e.modifiers() & Qt.ShiftModifier) 210 | alt = bool(e.modifiers() & Qt.AltModifier) 211 | 212 | # Ctrl+S: Save 213 | if e.matches(QKeySequence.Save): 214 | self.save() 215 | return 216 | 217 | # Ctrl+Shift+As: Save As 218 | if ctrl and shift and e.key() == Qt.Key_S: 219 | self.saveAs() 220 | return 221 | 222 | # Ctrl+R: Run Script 223 | if ctrl and e.key() == Qt.Key_R: 224 | self.runScriptCode() 225 | return 226 | 227 | # Ctrl+: Toggle comment 228 | if ctrl and e.key() == Qt.Key_Colon: 229 | self.toggle_comment() 230 | return 231 | 232 | # Ctrl+Alt+F: Format 233 | if ctrl and alt and e.key() == Qt.Key_F: 234 | self.format_file() 235 | return 236 | 237 | # F12 or F2: Go to definition 238 | if e.key() in (Qt.Key_F12, Qt.Key_F2): 239 | self.goto() 240 | return 241 | 242 | # Ctrl+Space: Autocomplete 243 | if ctrl and e.key() == Qt.Key_Space: 244 | self.update_calltips() 245 | char = self.character_before_cursor() 246 | if char.isidentifier() or char in (r"\/."): 247 | self.autocomplete() 248 | return 249 | 250 | # If press escape and call tips widget is shown, hide it 251 | 252 | if ( 253 | e.key() == Qt.Key_Escape 254 | and hasattr(self, "callTips") 255 | and self.callTips.isVisible() 256 | ): 257 | self.callTips.hide() 258 | 259 | # If completer popup is visible, discard those events 260 | if self.completer.popup().isVisible(): 261 | # The following keys are forwarded by the completer to the widget 262 | if e.key() in ( 263 | Qt.Key_Enter, 264 | Qt.Key_Return, 265 | Qt.Key_Escape, 266 | Qt.Key_Tab, 267 | Qt.Key_Backtab, 268 | ): 269 | e.ignore() 270 | return # let the completer do default behavior 271 | 272 | # Handle closing and opening 273 | last_char = self.character_before_cursor() 274 | next_char = self.character_after_cursor() 275 | line, column = self.getCursorPosition() 276 | 277 | openings = "([{'\"" 278 | closings = ")]}'\"" 279 | pairs = list(zip(openings, closings)) 280 | 281 | if not self.hasSelectedText(): 282 | if e.key() == Qt.Key_Backspace: 283 | pair = (last_char, next_char) 284 | if pair in pairs: 285 | self.setSelection(line, column - 1, line, column + 1) 286 | self.removeSelectedText() 287 | return 288 | 289 | if e.text() and e.text() in closings and next_char == e.text(): 290 | self.setSelection(line, column, line, column + 1) 291 | self.removeSelectedText() 292 | 293 | elif self.code_context() and e.text() and e.text() in openings: 294 | # Allow to enter """ and ''' 295 | if not (e.text() in "'\"" and last_char == e.text()): 296 | i = openings.index(e.text()) 297 | self.insert("".join(pairs[i])) 298 | self.setCursorPosition(line, column + 1) 299 | 300 | if e.text() == "(": 301 | self.callTipsTimer.start() 302 | return 303 | 304 | elif e.text() and e.text() in openings: 305 | i = openings.index(e.text()) 306 | start_line, start_pos, end_line, end_pos = self.getSelection() 307 | 308 | # Multi line quotes 309 | if start_line != end_line and e.text() in "'\"": 310 | self.replaceSelectedText( 311 | f"{openings[i]*3}{self.selectedText()}{closings[i]*3}" 312 | ) 313 | self.setSelection(start_line, start_pos + 3, end_line, end_pos + 3) 314 | else: 315 | self.replaceSelectedText( 316 | f"{openings[i]}{self.selectedText()}{closings[i]}" 317 | ) 318 | self.setSelection(start_line, start_pos + 1, end_line, end_pos + 1) 319 | return 320 | 321 | # Let QSciScintilla handle the keyboard event 322 | unpatched().keyPressEvent(e) 323 | prefix = self.text_under_cursor() 324 | 325 | if e.text() == "(": 326 | self.callTipsTimer.start() 327 | 328 | if e.text() == ".": 329 | self.autocomplete() 330 | return 331 | 332 | # end of word 333 | eow = "~!@#$%^&*()+{}|:\"<>?,/;'[]\\-= " 334 | 335 | if last_char in eow: 336 | self.completer.popup().hide() 337 | return 338 | 339 | if prefix != self.completer.completionPrefix(): 340 | self.completer.setCompletionPrefix(prefix) 341 | 342 | settings = QSettings() 343 | settings.beginGroup("plugins/bettereditor") 344 | threshold = settings.value("autocomplete_threshold", 4, int) 345 | # Jedi completion model is already accurate 346 | if self.completer.modelprefix and prefix.lower().startswith( 347 | self.completer.modelprefix.lower() 348 | ): 349 | 350 | # No more suggested completion: hide popup 351 | if self.completer.completionModel().rowCount() == 0: 352 | self.completer.popup().hide() 353 | return 354 | # Else, show popup select the first suggestion 355 | else: 356 | self.completer.popup().setCurrentIndex( 357 | self.completer.completionModel().index(0, 0) 358 | ) 359 | self.completer.popup().show() 360 | return 361 | 362 | # Jedi completion model must be updated 363 | elif len(prefix) >= threshold and e.text() and e.text().isidentifier(): 364 | self.autocomplete() 365 | else: 366 | self.completer.popup().hide() 367 | 368 | def code_context(self): 369 | """ Return true if current position is not inside a string or a comment """ 370 | line, column = self.getCursorPosition() 371 | inside_string = False 372 | single_quote = False 373 | double_quote = False 374 | triple_single_quote = False 375 | triple_double_quote = False 376 | 377 | pos = self.positionFromLineIndex(line, 0) 378 | for i in range(column): 379 | char = self.text(pos + i, pos + i + 1) 380 | if not inside_string: 381 | if char == "#": 382 | return False 383 | if char == "'": 384 | if self.text(pos + i - 2, pos + i + 1) == "'''": 385 | triple_single_quote = True 386 | inside_string = True 387 | 388 | inside_string = True 389 | single_quote = True 390 | if char == '"': 391 | if self.text(pos + i - 2, pos + i + 1) == '"""': 392 | triple_double_quote = True 393 | inside_string = True 394 | inside_string = True 395 | double_quote = True 396 | else: 397 | if char == "'": 398 | if single_quote: 399 | inside_string = False 400 | single_quote = False 401 | if triple_single_quote: 402 | if self.text(pos + i - 2, pos + i + 1) == "'''": 403 | inside_string = False 404 | triple_single_quote = False 405 | 406 | if char == '"': 407 | if double_quote: 408 | inside_string = False 409 | double_quote = False 410 | if triple_double_quote: 411 | if self.text(pos + i - 2, pos + i + 1) == '"""': 412 | inside_string = False 413 | triple_double_quote = False 414 | 415 | return not inside_string 416 | 417 | def save(self): 418 | self.parent.save() 419 | 420 | def saveAs(self): 421 | self.parent.tw.saveAs() 422 | 423 | def on_position_changed(self): 424 | if hasattr(self, "callTips") and self.callTips.isVisible(): 425 | self.callTipsTimer.start() 426 | 427 | def insert_completion(self, completion): 428 | line, column = self.getCursorPosition() 429 | self.setSelection( 430 | line, column - len(self.completer.completionPrefix()), line, column 431 | ) 432 | self.replaceSelectedText(completion) 433 | if completion.endswith("/"): 434 | self.autocomplete() 435 | 436 | def character_before_cursor(self): 437 | pos = self.positionFromLineIndex(*self.getCursorPosition()) 438 | return self.text(pos - 1, pos) 439 | 440 | def character_after_cursor(self): 441 | pos = self.positionFromLineIndex(*self.getCursorPosition()) 442 | return self.text(pos, pos + 1) 443 | 444 | def text_under_cursor(self): 445 | line, column = self.getCursorPosition() 446 | return self.wordAtLineIndex(line, column) 447 | 448 | def set_completer(self, completer): 449 | if hasattr(self, "completer") and self.completer: 450 | self.completer.disconnect() 451 | 452 | self.completer = completer 453 | self.completer.modelprefix = "" 454 | self.completer.setWidget(self) 455 | self.completer.setCompletionMode(QCompleter.PopupCompletion) 456 | self.completer.setModelSorting(QCompleter.CaseInsensitivelySortedModel) 457 | self.completer.setCaseSensitivity(Qt.CaseInsensitive) 458 | self.completer.activated[str].connect(self.insert_completion) 459 | 460 | def update_calltips(self): 461 | if not check_module("jedi", "0.17"): 462 | return 463 | import jedi 464 | 465 | line, column = self.getCursorPosition() 466 | 467 | # Simulate QGIS python default imports 468 | init_lines = [ 469 | "from qgis.core import *", 470 | "from qgis.gui import *", 471 | "from qgis.utils import iface", 472 | "from PyQt5.QtCore import *", 473 | "from PyQt5.QtWidgets import *", 474 | "from PyQt5.QtGui import *", 475 | "iface: QgisInterface = iface", 476 | ] 477 | init_text = "\n".join(init_lines) + "\n" 478 | script = jedi.Interpreter( 479 | code=init_text + self.text(), namespaces=(globals(), locals()) 480 | ) 481 | try: 482 | res = script.get_signatures(line + 1 + len(init_lines), column) 483 | except TypeError: 484 | res = None 485 | if not res: 486 | self.callTips.hide() 487 | return 488 | 489 | bracket_line, bracket_column = res[0].bracket_start 490 | pos = self.positionFromLineIndex( 491 | bracket_line - 1 - len(init_lines), bracket_column 492 | ) 493 | x = self.SendScintilla(QsciScintilla.SCI_POINTXFROMPOSITION, 0, pos) 494 | y = self.SendScintilla(QsciScintilla.SCI_POINTYFROMPOSITION, 0, pos) 495 | 496 | self.callTips.show_signatures(res, QPoint(x, y)) 497 | 498 | def goto(self): 499 | if not check_module("jedi", "0.17"): 500 | return 501 | import jedi 502 | 503 | line, column = self.getCursorPosition() 504 | script = jedi.Script(code=self.text(), project=self.project) 505 | names = script.goto(line + 1, column) 506 | if not names: 507 | return 508 | definition_pos = names[0].get_definition_start_position() 509 | if definition_pos: 510 | line = definition_pos[0] - 1 511 | column = definition_pos[1] 512 | self.setCursorPosition(line, column) 513 | 514 | def get_words(self): 515 | tokens = tokenize.tokenize(BytesIO(self.text().encode("utf-8")).readline) 516 | names = {token.string for token in tokens if token.type == 1} 517 | return names 518 | 519 | def word_completions(self): 520 | return sorted( 521 | ( 522 | WordCompletion(word) 523 | for word in self.get_words() 524 | if word != self.text_under_cursor() 525 | ), 526 | key=lambda x: x.name.lower(), 527 | ) 528 | 529 | def autocomplete(self): 530 | if not check_module("jedi", "0.17"): 531 | return 532 | import jedi 533 | 534 | line, column = self.getCursorPosition() 535 | 536 | # Simulate QGIS python default imports 537 | init_lines = [ 538 | "from qgis.core import *", 539 | "from qgis.gui import *", 540 | "from qgis.utils import iface", 541 | "from PyQt5.QtCore import *", 542 | "from PyQt5.QtWidgets import *", 543 | "from PyQt5.QtGui import *", 544 | "iface: QgisInterface = iface", 545 | ] 546 | 547 | init_text = "\n".join(init_lines) + "\n" 548 | script = jedi.Script(code=init_text + self.text(), project=self.project) 549 | completions = script.complete(line + 1 + len(init_lines), column) 550 | 551 | prefix = self.text_under_cursor() 552 | self.completer.modelprefix = prefix 553 | 554 | if not completions and prefix: 555 | completions = self.word_completions() 556 | 557 | if not completions: 558 | self.completer.popup().hide() 559 | self.completer.model().setCompletions([]) 560 | return 561 | 562 | self.completer.model().setCompletions(completions) 563 | self.completer.setCompletionPrefix(prefix) 564 | 565 | pos = self.positionFromLineIndex(line, column - len(prefix)) 566 | x = self.SendScintilla(QsciScintilla.SCI_POINTXFROMPOSITION, 0, pos) 567 | y = self.SendScintilla(QsciScintilla.SCI_POINTYFROMPOSITION, 0, pos) 568 | line_height = self.SendScintilla(QsciScintilla.SCI_TEXTHEIGHT, line) 569 | 570 | content_rect = QRect(0, 0, 450, 300) 571 | content_rect.setWidth( 572 | self.completer.popup().sizeHintForColumn(0) 573 | + self.completer.popup().verticalScrollBar().sizeHint().width() 574 | + 30 575 | ) 576 | self.completer.complete(content_rect) 577 | self.completer.popup().setFont(self.font()) 578 | self.completer.popup().move(self.mapToGlobal(QPoint(x, y + line_height + 2))) 579 | 580 | self.completer.popup().setCurrentIndex( 581 | self.completer.completionModel().index(0, 0) 582 | ) 583 | self.completer.popup().setUniformItemSizes(True) 584 | self.completer.popup().setLayoutMode(QListView.Batched) 585 | self.completer.popup().setIconSize(QSize(16, 16)) 586 | 587 | p = self.completer.popup().palette() 588 | p.setColor(QPalette.Highlight, QColor("#ccddff")) 589 | p.setColor(QPalette.HighlightedText, QColor("black")) 590 | self.completer.popup().setPalette(p) 591 | 592 | 593 | class MonkeyScriptEditor(MonkeyEditor): 594 | def customize(self): 595 | # Disable shortcuts 596 | for shortcut in self.findChildren(QShortcut): 597 | shortcut.setEnabled(False) 598 | self.bufferMarkerLine = [] 599 | self.set_completer(QCompleter(self)) 600 | self.completer.setModel(CompletionModel([], self)) 601 | self.callTips = CallTips(self) 602 | self.callTipsTimer = QTimer(self) 603 | self.callTipsTimer.setSingleShot(True) 604 | self.callTipsTimer.setInterval(500) 605 | self.callTipsTimer.timeout.connect(self.update_calltips) 606 | 607 | self.setCallTipsStyle(QsciScintilla.CallTipsNone) 608 | self.setAutoCompletionSource(QsciScintilla.AcsNone) 609 | self.setFolding( 610 | self.settings.value("folding_style", QsciScintilla.BoxedTreeFoldStyle, int) 611 | ) 612 | 613 | # Add a small margin after the indicator (if folding is not Plain or None) 614 | if self.folding() > 1: 615 | self.setMarginWidth(3, "0") 616 | else: 617 | self.setMarginWidth(3, "") 618 | 619 | if self.settings.value("ruler_visible", True, bool): 620 | self.setEdgeMode(QsciScintilla.EdgeLine) 621 | self.setEdgeColumn(self.settings.value("max_line_length", 88, int)) 622 | self.setEdgeColor( 623 | self.settings.value("ruler_color", QColor("#00aaff"), QColor) 624 | ) 625 | else: 626 | self.setEdgeMode(QsciScintilla.EdgeNone) 627 | 628 | # Change syntax error marker 629 | define_indicators(self) 630 | 631 | self.cursorPositionChanged.connect(self.on_position_changed) 632 | 633 | def call_parent_method(self, name, *args, **kwargs): 634 | """ Follow the parent hierarchy to find a method named and call it""" 635 | temp = self.parent() 636 | while temp: 637 | if hasattr(temp, name): 638 | return getattr(temp, name)(*args, **kwargs) 639 | temp = temp.parent() 640 | 641 | def save(self): 642 | """ Will be called when Ctrl+S is pressed (see keyPressEvent)""" 643 | self.call_parent_method("save") 644 | 645 | def saveAs(self): 646 | """ Will be called when Ctrl+Shift+S is pressed (see keyPressEvent)""" 647 | self.call_parent_method("saveAs") 648 | 649 | def runScriptCode(self): 650 | """ Will be called when Ctrl+R is pressed (see keyPressEvent)""" 651 | self.call_parent_method("runAlgorithm") 652 | 653 | 654 | class MonkeyScriptEditorDialog: 655 | def show(self): 656 | """ Customize the dialog and its editor before actualy showing it """ 657 | self.customize() 658 | unpatched().show() 659 | 660 | def customize(self): 661 | """ Some init needed by BetterEditor""" 662 | 663 | # Already patched : do nothing 664 | if hasattr(self.editor, "completer"): 665 | return 666 | 667 | # Patch the Editor (QsciScintilla) 668 | self.editor.customize() 669 | 670 | # Add toggle comment and format actions 671 | self.toolBar.addSeparator() 672 | self.toggle_comment_action = self.toolBar.addAction( 673 | QIcon(":/images/themes/default/console/iconCommentEditorConsole.svg"), 674 | tr("Toggle Comment"), 675 | ) 676 | self.toggle_comment_action.setObjectName("toggleComment") 677 | self.toggle_comment_action.triggered.connect(self.editor.toggle_comment) 678 | self.toggle_comment_action.setShortcut("Ctrl+:") 679 | self.toggle_comment_action.setToolTip( 680 | f"{self.toggle_comment_action.text()} ({self.toggle_comment_action.shortcut().toString()})" 681 | ) 682 | self.toolBar.addAction(self.toggle_comment_action) 683 | 684 | if check_module("black"): 685 | self.format_action = self.toolBar.addAction( 686 | QIcon(":/plugins/bettereditor/icons/wizard.svg"), tr("Format file") 687 | ) 688 | self.format_action.setObjectName("format") 689 | self.format_action.setShortcut("Ctrl+Alt+F") 690 | self.format_action.triggered.connect(self.editor.format_file) 691 | self.format_action.setToolTip( 692 | f"{self.format_action.text()} ({self.format_action.shortcut().toString()})" 693 | ) 694 | 695 | def saveScript(self, saveAs: bool): 696 | """ Format file before saving """ 697 | settings = QSettings() 698 | settings.beginGroup("plugins/bettereditor") 699 | if settings.value("format_on_save", True, bool): 700 | self.editor.format_file() 701 | unpatched().saveScript(saveAs) 702 | 703 | def runAlgorithm(self): 704 | """ Check syntax before calling the actual method """ 705 | if self.editor.syntaxCheck(): 706 | unpatched().runAlgorithm() 707 | 708 | 709 | class WordCompletion: 710 | """ Stub to an actual Jedi Completion. Used in word_completions""" 711 | 712 | def __init__(self, name): 713 | self.name = name 714 | self.type = "name" 715 | -------------------------------------------------------------------------------- /dependencies.py: -------------------------------------------------------------------------------- 1 | """ 2 | Wrapper on Pip to install required python modules 3 | """ 4 | 5 | import subprocess 6 | import importlib 7 | 8 | 9 | def check_module(module, min_version=""): 10 | try: 11 | m = importlib.import_module(module) 12 | if min_version and not check_minimum_version(m.__version__, min_version): 13 | return False 14 | except ModuleNotFoundError: 15 | return False 16 | return True 17 | 18 | 19 | def check_pip(): 20 | return check_module("pip") 21 | 22 | 23 | def check_minimum_version(module_version, min_version): 24 | try: 25 | from packaging import version 26 | 27 | return version.parse(module_version) >= version.parse(min_version) 28 | except ModuleNotFoundError: 29 | return module_version >= min_version 30 | 31 | 32 | def install(dep, upgrade=False): 33 | module = None 34 | module_version = "" 35 | 36 | if not check_pip(): 37 | return module, module_version 38 | 39 | cmd = ["python3", "-m", "pip", "install", dep, "--user"] 40 | if upgrade: 41 | cmd.append("--upgrade") 42 | 43 | # Prevents the call to pip from spawning an console on Windows. 44 | try: 45 | subprocess.run(cmd, check=False, creationflags=subprocess.CREATE_NO_WINDOW) 46 | except (AttributeError, TypeError): 47 | subprocess.run(cmd, check=False) 48 | 49 | # Even if process failed, try to import module 50 | try: 51 | module = importlib.import_module(dep) 52 | module_version = module.__version__ 53 | except ModuleNotFoundError: 54 | pass 55 | 56 | return module, module_version 57 | 58 | 59 | def import_or_install(dep): 60 | try: 61 | module = importlib.import_module(dep) 62 | return module, module.__version__ 63 | except ModuleNotFoundError: 64 | return install(dep) 65 | -------------------------------------------------------------------------------- /docs/black.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YoannQDQ/qgis-better-editor/d12c610375446f63d0886178dc65fde6c38cf87b/docs/black.gif -------------------------------------------------------------------------------- /docs/jedi.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YoannQDQ/qgis-better-editor/d12c610375446f63d0886178dc65fde6c38cf87b/docs/jedi.gif -------------------------------------------------------------------------------- /docs/resource_browser.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YoannQDQ/qgis-better-editor/d12c610375446f63d0886178dc65fde6c38cf87b/docs/resource_browser.png -------------------------------------------------------------------------------- /docs/settings_dialog.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YoannQDQ/qgis-better-editor/d12c610375446f63d0886178dc65fde6c38cf87b/docs/settings_dialog.png -------------------------------------------------------------------------------- /docs/syntax_check.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YoannQDQ/qgis-better-editor/d12c610375446f63d0886178dc65fde6c38cf87b/docs/syntax_check.png -------------------------------------------------------------------------------- /docs/toggle.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YoannQDQ/qgis-better-editor/d12c610375446f63d0886178dc65fde6c38cf87b/docs/toggle.gif -------------------------------------------------------------------------------- /i18n/BetterEditor_en.ts: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | @default 6 | 7 | 8 | Toggle Comment 9 | Toggle Comment 10 | 11 | 12 | 13 | Format file 14 | Format file 15 | 16 | 17 | 18 | BetterEditor 19 | 20 | 21 | About 22 | About 23 | 24 | 25 | 26 | Settings 27 | Settings 28 | 29 | 30 | 31 | Toggle Comment 32 | Toggle Comment 33 | 34 | 35 | 36 | Format file 37 | Format file 38 | 39 | 40 | 41 | Insert resource path 42 | Insert resource path 43 | 44 | 45 | 46 | About Better Editor 47 | About Better Editor 48 | 49 | 50 | 51 | Source code 52 | Source code 53 | 54 | 55 | 56 | Documentation 57 | Documentation 58 | 59 | 60 | 61 | Report issues 62 | Report issues 63 | 64 | 65 | 66 | Error 67 | Error 68 | 69 | 70 | 71 | Pip is not installed. Try to get it, then restart QGIS, or manually install <b>black</b> and <b>jedi</b> 72 | Pip is not installed. Try to get it, then restart QGIS, or manually install <b>black</b> and <b>jedi</b> 73 | 74 | 75 | 76 | Unable to load <b>black</b>. Formatting will be disabled. You could try to manually install <b>black</b> with pip 77 | Unable to load <b>black</b>. Formatting will be disabled. You could try to manually install <b>black</b> with pip 78 | 79 | 80 | 81 | Unable to load <b>jedi</b>. Multi syntax error check will be disabled. You could try to manually install <b>jedi</b> with pip 82 | Unable to load <b>jedi</b>. Multi syntax error check will be disabled. You could try to manually install <b>jedi</b> with pip 83 | 84 | 85 | 86 | Information 87 | Information 88 | 89 | 90 | 91 | <b>jedi</b> version is {0} and BetterEditor needs {1}. Do you want to upgrade <b>jedi</b>?<br><b>Warning:</b> it could cause old code relying on the obsolete <b>jedi</b> to stop working correctly. 92 | <b>jedi</b> version is {0} and BetterEditor needs {1}. Do you want to upgrade <b>jedi</b>?<br><b>Warning:</b> it could cause old code relying on the obsolete <b>jedi</b> to stop working correctly. 93 | 94 | 95 | 96 | Jedi was upgraded. You need to restart QGIS to fully use BetterEditor 97 | Jedi was upgraded. You need to restart QGIS to fully use BetterEditor 98 | 99 | 100 | 101 | ResourceBrowser 102 | 103 | 104 | Resource Browser 105 | Resource Browser 106 | 107 | 108 | 109 | Filter 110 | Filter 111 | 112 | 113 | 114 | Ok 115 | Ok 116 | 117 | 118 | 119 | Cancel 120 | Cancel 121 | 122 | 123 | 124 | Copy resource path to clipboard 125 | Copy resource path to clipboard 126 | 127 | 128 | 129 | SettingsDialog 130 | 131 | 132 | Hide old comment actions 133 | Hide old comment actions 134 | 135 | 136 | 137 | Max line length (black) 138 | Max line length (black) 139 | 140 | 141 | 142 | Folding indicator style 143 | Folding indicator style 144 | 145 | 146 | 147 | Show ruler 148 | Show ruler 149 | 150 | 151 | 152 | Ruler color 153 | Ruler color 154 | 155 | 156 | 157 | Restore default values 158 | Restore default values 159 | 160 | 161 | 162 | None 163 | None 164 | 165 | 166 | 167 | Plain 168 | Plain 169 | 170 | 171 | 172 | Circled 173 | Circled 174 | 175 | 176 | 177 | Boxed 178 | Boxed 179 | 180 | 181 | 182 | Better Editor Settings 183 | Better Editor Settings 184 | 185 | 186 | 187 | Format on save 188 | Format on save 189 | 190 | 191 | 192 | Autocomplete threshold 193 | Autocomplete threshold 194 | 195 | 196 | 197 | Ok 198 | Ok 199 | 200 | 201 | 202 | -------------------------------------------------------------------------------- /i18n/BetterEditor_fr.ts: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | @default 6 | 7 | 8 | Toggle Comment 9 | Commenter / Décommenter 10 | 11 | 12 | 13 | Format file 14 | Formater le fichier 15 | 16 | 17 | 18 | BetterEditor 19 | 20 | 21 | About 22 | À propos 23 | 24 | 25 | 26 | Settings 27 | Paramètres 28 | 29 | 30 | 31 | Toggle Comment 32 | Commenter / Décommenter 33 | 34 | 35 | 36 | Format file 37 | Formater le fichier 38 | 39 | 40 | 41 | Insert resource path 42 | Insérer un chemin vers une ressource 43 | 44 | 45 | 46 | About Better Editor 47 | À propos de Better Editor 48 | 49 | 50 | 51 | Source code 52 | Code source 53 | 54 | 55 | 56 | Documentation 57 | Documentation 58 | 59 | 60 | 61 | Report issues 62 | Signaler un problème 63 | 64 | 65 | 66 | Error 67 | Erreur 68 | 69 | 70 | 71 | Pip is not installed. Try to get it, then restart QGIS, or manually install <b>black</b> and <b>jedi</b> 72 | Pip n'est pas installé. Installez le avant de rédémarrrer QGIS, ou installez manuellement <b>black</b> et <b>jedi</b> 73 | 74 | 75 | 76 | Unable to load <b>black</b>. Formatting will be disabled. You could try to manually install <b>black</b> with pip 77 | Impossible de charger <b>black</b>.Le formattage sera désactivé. Vous pouvez essayer d'installer <b>black</b> manuellement avec pip 78 | 79 | 80 | 81 | Unable to load <b>jedi</b>. Multi syntax error check will be disabled. You could try to manually install <b>jedi</b> with pip 82 | Impossible de charger <b>jedi</b>.La vérification multiple d'erreurs de syntaxe sera désactivée. Vous pouvez essayer d'installer <b>jedi</b> manuellement avec pip 83 | 84 | 85 | 86 | Information 87 | Information 88 | 89 | 90 | 91 | <b>jedi</b> version is {0} and BetterEditor needs {1}. Do you want to upgrade <b>jedi</b>?<br><b>Warning:</b> it could cause old code relying on the obsolete <b>jedi</b> to stop working correctly. 92 | La version de <b>jedi</b> installée est {0} et BetterEditor nécessite jedi >= {1}. Voulez-vous mettre à jour <b>jedi</b> ?<br><b>Avertissement :</b> si du code existant utilise l' ancienne version de jedi, il pourrait cesser de fonctionner correctement. 93 | 94 | 95 | 96 | Jedi was upgraded. You need to restart QGIS to fully use BetterEditor 97 | Jedi a été mis à jour. Redémarrez QGIS pour utiliser toutes les fonctionnalités de BetterEditor 98 | 99 | 100 | 101 | ResourceBrowser 102 | 103 | 104 | Resource Browser 105 | Explorateur de ressources 106 | 107 | 108 | 109 | Filter 110 | Filtre 111 | 112 | 113 | 114 | Ok 115 | Ok 116 | 117 | 118 | 119 | Cancel 120 | Annuler 121 | 122 | 123 | 124 | Copy resource path to clipboard 125 | Copier le chemin de la ressource dans le presse-papier 126 | 127 | 128 | 129 | SettingsDialog 130 | 131 | 132 | Hide old comment actions 133 | Masquer les actions commenter et décommenter 134 | 135 | 136 | 137 | Max line length (black) 138 | Longueur de ligne max (black) 139 | 140 | 141 | 142 | Folding indicator style 143 | Style de l'indicateur de repliement 144 | 145 | 146 | 147 | Show ruler 148 | Monter la règle 149 | 150 | 151 | 152 | Ruler color 153 | Couleur de la règle 154 | 155 | 156 | 157 | Restore default values 158 | Restaurer les valeurs par défaut 159 | 160 | 161 | 162 | None 163 | Aucun 164 | 165 | 166 | 167 | Plain 168 | Simple 169 | 170 | 171 | 172 | Circled 173 | Cercle 174 | 175 | 176 | 177 | Boxed 178 | Carré 179 | 180 | 181 | 182 | Better Editor Settings 183 | Paramètres de Better Editor 184 | 185 | 186 | 187 | Format on save 188 | Formater à l'enregistrement 189 | 190 | 191 | 192 | Autocomplete threshold 193 | Seuil d'autocomplétion 194 | 195 | 196 | 197 | Ok 198 | Ok 199 | 200 | 201 | 202 | -------------------------------------------------------------------------------- /i18n/update_translations.py: -------------------------------------------------------------------------------- 1 | """ Scan plugin folder for translations""" 2 | import os 3 | import contextlib 4 | 5 | from pathlib import Path 6 | 7 | 8 | @contextlib.contextmanager 9 | def working_directory(path): 10 | """Changes working directory and returns to previous on exit.""" 11 | prev_cwd = Path.cwd() 12 | os.chdir(path) 13 | try: 14 | yield 15 | finally: 16 | os.chdir(prev_cwd) 17 | 18 | 19 | if __name__ == "__main__": 20 | with working_directory(Path(__file__).parent): 21 | PATHS = [] 22 | for path in Path("..").rglob("*.py"): 23 | PATHS.append(f'"{path}"') 24 | 25 | os.system( 26 | f"pylupdate5 -verbose -noobsolete {' '.join(PATHS)} -ts ./BetterEditor_fr.ts ./BetterEditor_en.ts" 27 | ) 28 | -------------------------------------------------------------------------------- /icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YoannQDQ/qgis-better-editor/d12c610375446f63d0886178dc65fde6c38cf87b/icon.png -------------------------------------------------------------------------------- /icons/about.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 22 | 24 | 31 | 34 | 38 | 39 | 47 | 51 | 56 | 57 | 59 | 63 | 67 | 68 | 70 | 74 | 78 | 79 | 87 | 95 | 102 | 106 | 110 | 111 | 119 | 127 | 134 | 137 | 141 | 142 | 144 | 147 | 151 | 152 | 160 | 168 | 175 | 179 | 182 | 186 | 187 | 188 | 204 | 206 | 207 | 209 | image/svg+xml 210 | 212 | 213 | 214 | 215 | Python 216 | script 217 | programing language 218 | 219 | 220 | 222 | 223 | 224 | Vinicius Depizzol 225 | 226 | 227 | vdepizzol@gmail.com 228 | 229 | 230 | Paper sheet by Jakub Steiner <http://jimmac.musichall.cz> 231 | 232 | 233 | 2007-02-16 234 | 235 | 237 | 239 | 241 | 243 | 245 | 247 | 249 | 250 | 251 | 252 | 254 | 256 | 260 | 268 | 277 | 285 | 286 | 287 | 288 | 292 | 300 | 308 | 309 | 311 | 319 | 328 | 335 | 340 | 350 | 360 | 370 | 380 | 390 | 400 | 410 | 420 | 430 | 440 | 450 | 460 | 470 | 480 | 490 | 491 | 492 | 495 | 503 | 506 | 512 | 515 | 521 | 526 | 527 | 532 | 533 | 534 | 537 | 545 | 550 | i 561 | 562 | 563 | -------------------------------------------------------------------------------- /icons/clear.svg: -------------------------------------------------------------------------------- 1 | 2 | 18 | 20 | 21 | 23 | image/svg+xml 24 | 26 | 27 | 28 | 29 | 30 | 32 | 52 | 55 | 60 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /icons/file-1.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /icons/folder.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /icons/icon.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 22 | 24 | 31 | 34 | 38 | 39 | 47 | 51 | 56 | 57 | 59 | 63 | 67 | 68 | 70 | 74 | 78 | 79 | 87 | 95 | 102 | 106 | 110 | 111 | 119 | 127 | 134 | 137 | 141 | 142 | 144 | 147 | 151 | 152 | 160 | 168 | 175 | 179 | 182 | 186 | 187 | 188 | 204 | 206 | 207 | 209 | image/svg+xml 210 | 212 | Python script 213 | 214 | 215 | Python 216 | script 217 | programing language 218 | 219 | 220 | 222 | 223 | 224 | Vinicius Depizzol 225 | 226 | 227 | vdepizzol@gmail.com 228 | 229 | 230 | Paper sheet by Jakub Steiner <http://jimmac.musichall.cz> 231 | 232 | 233 | 2007-02-16 234 | 235 | 237 | 239 | 241 | 243 | 245 | 247 | 249 | 250 | 251 | 252 | 254 | 256 | 260 | 268 | 277 | 285 | 286 | 287 | 288 | 292 | 300 | 308 | 309 | 311 | 319 | 328 | 335 | 340 | 350 | 360 | 370 | 380 | 390 | 400 | 410 | 420 | 430 | 440 | 450 | 460 | 470 | 480 | 490 | 491 | 492 | 495 | 503 | 506 | 512 | 515 | 521 | 526 | 527 | 532 | 533 | 534 | 535 | -------------------------------------------------------------------------------- /icons/symbol-class.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /icons/symbol-enumerator.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /icons/symbol-key.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /icons/symbol-keyword.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /icons/symbol-method.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /icons/symbol-misc.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /icons/symbol-namespace.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /icons/symbol-variable.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /icons/wizard.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | image/svg+xml 44 | 46 | 48 | 50 | 51 | 52 | 56 | 61 | 65 | 69 | 74 | 96 | 97 | 98 | 100 | 101 | 103 | 104 | 106 | 107 | 109 | 110 | 112 | 113 | 115 | 116 | 118 | 119 | 121 | 122 | 124 | 125 | 127 | 128 | 130 | 131 | 133 | 134 | 136 | 137 | 139 | 140 | 142 | 143 | -------------------------------------------------------------------------------- /indicatorsutils.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtCore import Qt, QSettings, QSize 2 | from PyQt5.Qsci import QsciScintilla, QsciStyle 3 | from PyQt5.QtGui import QColor, QPixmap, QFont 4 | 5 | from console.console_editor import Editor 6 | from .dependencies import check_module 7 | 8 | 9 | SYNTAX_ERROR_STYLE = 100 10 | MARKER_NUMBER = 6 11 | 12 | 13 | def check_syntax(editor, *args, **kwargs): 14 | 15 | if not check_module("jedi", "0.17"): 16 | return 17 | 18 | import jedi 19 | 20 | s = jedi.Script(code=editor.text()) 21 | errors = s.get_syntax_errors() 22 | 23 | editor.markerDeleteAll() 24 | editor.clearAnnotations() 25 | clear_all_indicators(editor) 26 | 27 | if not errors: 28 | return True 29 | 30 | for error in errors: 31 | eline = error.line - 1 32 | ecolumn = error.column 33 | edescr = error._parso_error.message 34 | syntax_error(editor, eline, ecolumn, error.until_line - 1, error.until_column) 35 | editor.markerAdd(eline, MARKER_NUMBER) 36 | editor.annotate(eline, edescr, editor.style_annotation) 37 | editor.setCursorPosition(eline, ecolumn - 1) 38 | editor.ensureLineVisible(eline) 39 | return False 40 | 41 | 42 | def define_indicators(editor): 43 | 44 | # Create annotation style 45 | load_font = QSettings().value("pythonConsole/fontfamilytextEditor", "Monospace") 46 | editor.style_annotation = QsciStyle( 47 | SYNTAX_ERROR_STYLE, 48 | "Annotation", 49 | QColor("#ff0000"), 50 | QColor("#ffdddd"), 51 | QFont(load_font, 8, -1, False), 52 | True, 53 | ) 54 | 55 | editor.markerDefine( 56 | QPixmap(":/plugins/bettereditor/icons/clear.svg").scaled( 57 | QSize(16, 16), Qt.KeepAspectRatio, Qt.SmoothTransformation 58 | ), 59 | MARKER_NUMBER, 60 | ) 61 | editor.setAnnotationDisplay(QsciScintilla.AnnotationStandard) 62 | 63 | editor.indicatorDefine(QsciScintilla.TriangleCharacterIndicator, 20) 64 | editor.setIndicatorForegroundColor(QColor("red"), 20) 65 | editor.indicatorDefine(QsciScintilla.SquiggleLowIndicator, 21) 66 | editor.setIndicatorForegroundColor(QColor("red"), 21) 67 | 68 | 69 | def indicator(editor, line, col, nb_chars, style=0, value=99): 70 | editor.SendScintilla(QsciScintilla.SCI_SETINDICATORCURRENT, style) 71 | editor.SendScintilla(QsciScintilla.SCI_SETINDICATORVALUE, value) 72 | start_pos = editor.positionFromLineIndex(line, col) 73 | editor.SendScintilla(QsciScintilla.SCI_INDICATORFILLRANGE, start_pos, nb_chars) 74 | 75 | 76 | def clear_indicator(editor, line, col, nb_chars, style=0): 77 | editor.SendScintilla(QsciScintilla.SCI_SETINDICATORCURRENT, style) 78 | start_pos = editor.positionFromLineIndex(line, col) 79 | editor.SendScintilla(QsciScintilla.SCI_INDICATORCLEARRANGE, start_pos, nb_chars) 80 | 81 | 82 | def clear_indicator_from_file(editor, style=2): 83 | editor.SendScintilla(QsciScintilla.SCI_SETINDICATORCURRENT, style) 84 | editor.SendScintilla(QsciScintilla.SCI_INDICATORCLEARRANGE, 0, len(editor.text())) 85 | 86 | 87 | def clear_all_indicators(editor): 88 | for i in range(32): 89 | clear_indicator_from_file(editor, i) 90 | 91 | 92 | def syntax_error(editor, start_line, start_column, end_line, end_column): 93 | start_pos = editor.positionFromLineIndex(start_line, start_column) 94 | end_pos = editor.positionFromLineIndex(end_line, end_column) 95 | indicator(editor, start_line, start_column, end_pos - start_pos, 20) 96 | indicator(editor, start_line, start_column + 1, end_pos - start_pos - 1, 21) 97 | -------------------------------------------------------------------------------- /metadata.txt: -------------------------------------------------------------------------------- 1 | [general] 2 | name=Better Editor 3 | qgisMinimumVersion=3.0 4 | description=Improve the embedded python editor 5 | version=1.5.0 6 | author=Yoann Quenach de Quivillic 7 | email=yoann.quenach@gmail.com 8 | about=Tweak the default python editor 9 | Add toggle comment, code formatting (using black), smart autocomplete (using jedi), tab navigation and more 10 | 11 | hasProcessingProvider=no 12 | 13 | changelog=1.5.0 2020-07-23 14 | * Smart opening and closing of [{("''")}] 15 | * Goto definition (press F2 or F12) 16 | 1.4.0 2020-07-22 17 | * Better Editor features now also available in the Processing Script Editor 18 | 1.3.0 2020-07-18 19 | * Add smart autocomplete using Jedi 20 | 1.2.0 2020-06-23 21 | * Update Jedi if an obsolete version is installed 22 | * Add format on save option 23 | 1.1.2 2020-06-21 24 | * Fix Linux compatibility 25 | 1.1.1 2020-06-18 26 | * Fix crash in case subprocess.CREATE_NO_WINDOW is not defined 27 | 1.1.0 2020-06-18 28 | * Add multiple syntax check 29 | 1.0.0 2020-06-16 30 | * First version 31 | 32 | homepage=https://github.com/YoannQDQ/qgis-better-editor 33 | tracker=https://github.com/YoannQDQ/qgis-better-editor/issues 34 | repository=https://github.com/YoannQDQ/qgis-better-editor 35 | 36 | icon=icon.png 37 | experimental=False 38 | tags=python,editor,comment,autocomplete 39 | deprecated=False 40 | 41 | # Since QGIS 3.8, a comma separated list of plugins to be installed 42 | # (or upgraded) can be specified. 43 | # Check the documentation for more information. 44 | # plugin_dependencies= 45 | 46 | # If the plugin can run on QGIS Server. 47 | server=False 48 | 49 | -------------------------------------------------------------------------------- /monkeypatch.py: -------------------------------------------------------------------------------- 1 | """ 2 | MonkeyPatching tools 3 | 4 | - The Patcher class allow to patch a single instance or a whole class 5 | - unpatched() is an helper which works kind of like super() 6 | - monkey is a context manager which unpatches the class/instance on exit 7 | - decorator allow to patch a class 8 | """ 9 | 10 | import inspect 11 | import types 12 | import contextlib 13 | from functools import wraps 14 | 15 | 16 | PRIVATE_KEY_PREFIX = "monkey" 17 | MONKEY_DICT_NAME = "_originals" 18 | 19 | 20 | class MissingValue: 21 | pass 22 | 23 | 24 | def patch(patched_object, monkey_class, repatch=False): 25 | 26 | if hasattr(patched_object, MONKEY_DICT_NAME): 27 | if not repatch: 28 | return 29 | else: 30 | setattr(patched_object, MONKEY_DICT_NAME, {}) 31 | 32 | original_dict = getattr(patched_object, MONKEY_DICT_NAME) 33 | class_patch = inspect.isclass(patched_object) 34 | 35 | for method_name, method in inspect.getmembers( 36 | monkey_class, predicate=inspect.isfunction 37 | ): 38 | original_method = getattr(patched_object, method_name, MissingValue) 39 | 40 | if method_name.startswith("__"): 41 | key_name = PRIVATE_KEY_PREFIX + method_name 42 | else: 43 | key_name = method_name 44 | 45 | original_dict.setdefault(key_name, original_method) 46 | 47 | if not class_patch: 48 | method = types.MethodType(method, patched_object) 49 | setattr(patched_object, method_name, method) 50 | 51 | for method_name, method in inspect.getmembers( 52 | monkey_class, predicate=inspect.isfunction 53 | ): 54 | original_method = getattr(patched_object, method_name, MissingValue) 55 | 56 | if method_name.startswith("__"): 57 | key_name = PRIVATE_KEY_PREFIX + method_name 58 | else: 59 | key_name = method_name 60 | 61 | original_dict.setdefault(key_name, original_method) 62 | 63 | if not class_patch: 64 | method = types.MethodType(method, patched_object) 65 | setattr(patched_object, method_name, method) 66 | 67 | 68 | def unpatch(obj): 69 | original_dict = getattr(obj, MONKEY_DICT_NAME, None) 70 | if original_dict is None: 71 | return 72 | 73 | for method_name, method in original_dict.items(): 74 | if method_name.startswith(PRIVATE_KEY_PREFIX + "__"): 75 | method_name = method_name[: len(PRIVATE_KEY_PREFIX)] 76 | if method is MissingValue: 77 | delattr(obj, method_name) 78 | else: 79 | setattr(obj, method_name, method) 80 | 81 | delattr(obj, MONKEY_DICT_NAME) 82 | 83 | 84 | def unpatched(): 85 | """ Helper function to call original methods in Monkey Class definition. 86 | Acts kind of like like super() with child/parent classes""" 87 | frame = inspect.stack()[1][0] 88 | arginfo = inspect.getargvalues(frame) 89 | self = arginfo.locals[arginfo.args[0]] 90 | 91 | class Wrapper: 92 | def __init__(self, patched_instance): 93 | self.patched_instance = patched_instance 94 | 95 | def __getattr__(self, attrname): 96 | original_dict = getattr(self.patched_instance, MONKEY_DICT_NAME, {}) 97 | if attrname in original_dict: 98 | func = original_dict[attrname] 99 | # Patched instance 100 | if inspect.ismethod(func): 101 | return func 102 | # Patched class 103 | else: 104 | return types.MethodType( 105 | original_dict[attrname], self.patched_instance, 106 | ) 107 | return getattr(self.patched_instance, attrname) 108 | 109 | return Wrapper(self) 110 | 111 | 112 | @contextlib.contextmanager 113 | def monkey(patched_object, monkey_cls): 114 | """Changes working directory and returns to previous on exit.""" 115 | patch(patched_object, monkey_cls) 116 | try: 117 | yield 118 | finally: 119 | unpatch(patched_object) 120 | 121 | 122 | def decorator(patched_cls, monkey_cls): 123 | """ Monkey patch decorator factory """ 124 | 125 | def inner_decorator(func): 126 | @wraps(func) 127 | def wrapper(*args, **kwargs): 128 | with monkey(patched_cls, monkey_cls): 129 | return func(*args, **kwargs) 130 | 131 | return wrapper 132 | 133 | return inner_decorator 134 | 135 | 136 | class Patcher: 137 | """ Monkey Patcher. Applies a Monkey Class on a single instance or a whole class """ 138 | 139 | def __init__( 140 | self, patched_object, monkey_class, patch_now=True, unpatch_on_delete=True 141 | ): 142 | self.class_patch = inspect.isclass(patched_object) 143 | self.patched_object = patched_object 144 | self.monkey_class = monkey_class 145 | self.unpatch_on_delete = unpatch_on_delete 146 | if patch_now: 147 | self.patch() 148 | 149 | def __del__(self): 150 | if self.unpatch_on_delete: 151 | self.unpatch() 152 | 153 | def patch(self): 154 | patch(self.patched_object, self.monkey_class) 155 | 156 | def unpatch(self): 157 | unpatch(self.patched_object) 158 | -------------------------------------------------------------------------------- /pb_tool.cfg: -------------------------------------------------------------------------------- 1 | #/*************************************************************************** 2 | # Better Editor 3 | # 4 | # Configuration file for plugin builder tool (pb_tool) 5 | # Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/ 6 | # ------------------- 7 | # begin : 2020-05-09 8 | # copyright : (C) 2020 by Yoann Quenach de Quivillic 9 | # email : yoann.quenach@gmail.com 10 | # ***************************************************************************/ 11 | # 12 | #/*************************************************************************** 13 | # * * 14 | # * This program is free software; you can redistribute it and/or modify * 15 | # * it under the terms of the GNU General Public License as published by * 16 | # * the Free Software Foundation; either version 2 of the License, or * 17 | # * (at your option) any later version. * 18 | # * * 19 | # ***************************************************************************/ 20 | # 21 | # 22 | # You can install pb_tool using: 23 | # pip install http://geoapt.net/files/pb_tool.zip 24 | # 25 | # Consider doing your development (and install of pb_tool) in a virtualenv. 26 | # 27 | # For details on setting up and using pb_tool, see: 28 | # http://g-sherman.github.io/plugin_build_tool/ 29 | # 30 | # Issues and pull requests here: 31 | # https://github.com/g-sherman/plugin_build_tool: 32 | # 33 | # Sane defaults for your plugin generated by the Plugin Builder are 34 | # already set below. 35 | # 36 | # As you add Python source files and UI files to your plugin, add 37 | # them to the appropriate [files] section below. 38 | 39 | [plugin] 40 | # Name of the plugin. This is the name of the directory that will 41 | # be created in .qgis2/python/plugins 42 | name: bettereditor 43 | 44 | # Full path to where you want your plugin directory copied. If empty, 45 | # the QGIS default path will be used. Don't include the plugin name in 46 | # the path. 47 | plugin_path: 48 | 49 | [files] 50 | # Python files that should be deployed with the plugin 51 | python_files: 52 | __init__.py 53 | bettereditor.py 54 | resourcebrowserimpl.py 55 | settingsdialogimpl.py 56 | dependencies.py 57 | indicatorsutils.py 58 | monkeypatch.py 59 | customclasses.py 60 | calltips.py 61 | completionmodel.py 62 | 63 | # The main dialog file that is loaded (not compiled) 64 | main_dialog: 65 | 66 | # Other ui files for dialogs you create (these will be compiled) 67 | compiled_ui_files: resourcebrowser.ui settingsdialog.ui 68 | 69 | # Resource file(s) that will be compiled 70 | resource_files: resources.qrc 71 | 72 | # Other files required for the plugin 73 | extras: metadata.txt icon.png 74 | 75 | # Other directories to be deployed with the plugin. 76 | # These must be subdirectories under the plugin directory 77 | extra_dirs: i18n 78 | 79 | # ISO code(s) for any locales (translations), separated by spaces. 80 | # Corresponding .ts files must exist in the i18n directory 81 | locales: BetterEditor_en BetterEditor_fr 82 | 83 | [help] 84 | # the built help directory that should be deployed with the plugin 85 | dir: help/build/html 86 | # the name of the directory to target in the deployed plugin 87 | target: help 88 | 89 | 90 | 91 | -------------------------------------------------------------------------------- /resourcebrowser.ui: -------------------------------------------------------------------------------- 1 | 2 | 3 | ResourceBrowser 4 | 5 | 6 | 7 | 0 8 | 0 9 | 683 10 | 579 11 | 12 | 13 | 14 | Resource Browser 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | Filter 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 0 36 | 0 37 | 38 | 39 | 40 | 41 | 42 | 43 | Qt::Horizontal 44 | 45 | 46 | 47 | false 48 | 49 | 50 | 51 | 1 52 | 53 | 54 | 55 | 56 | 57 | QListView::Adjust 58 | 59 | 60 | QListView::IconMode 61 | 62 | 63 | true 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 64 78 | 64 79 | 80 | 81 | 82 | 83 | 64 84 | 64 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse 99 | 100 | 101 | 102 | 103 | 104 | 105 | Qt::Horizontal 106 | 107 | 108 | 109 | 40 110 | 20 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | Qt::Horizontal 123 | 124 | 125 | 126 | 40 127 | 20 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | false 136 | 137 | 138 | Ok 139 | 140 | 141 | 142 | 143 | 144 | 145 | Cancel 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | okButton 157 | clicked() 158 | ResourceBrowser 159 | accept() 160 | 161 | 162 | 271 163 | 363 164 | 165 | 166 | 199 167 | 192 168 | 169 | 170 | 171 | 172 | cancelButton 173 | clicked() 174 | ResourceBrowser 175 | reject() 176 | 177 | 178 | 352 179 | 363 180 | 181 | 182 | 199 183 | 192 184 | 185 | 186 | 187 | 188 | 189 | -------------------------------------------------------------------------------- /resourcebrowserimpl.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import os 4 | 5 | from PyQt5.QtCore import ( 6 | QAbstractListModel, 7 | QResource, 8 | Qt, 9 | QModelIndex, 10 | QSortFilterProxyModel, 11 | QSize, 12 | ) 13 | from PyQt5.QtGui import QIcon, QGuiApplication 14 | from PyQt5.QtWidgets import QDialog, QTreeWidgetItem, QMenu 15 | 16 | from .resourcebrowser import Ui_ResourceBrowser 17 | 18 | 19 | class RessourceModel(QAbstractListModel): 20 | def __init__(self, extensions=None, parent=None): 21 | 22 | super().__init__(parent) 23 | self.ressource_root = "" 24 | self.icons = [] 25 | self.extensions = extensions 26 | 27 | def set_source(self, path): 28 | self.beginResetModel() 29 | self.ressource_root = path 30 | self.icons = sorted( 31 | [ 32 | name 33 | for name in QResource(self.ressource_root).children() 34 | if ( 35 | QResource(self.ressource_root + "/" + name).isFile() 36 | and ( 37 | self.extensions is None 38 | or os.path.splitext(name)[1].lower() in self.extensions 39 | ) 40 | ) 41 | ] 42 | ) 43 | self.endResetModel() 44 | 45 | def data(self, index, role=Qt.DisplayRole): 46 | if not index.isValid(): 47 | return 48 | 49 | name = self.icons[index.row()] 50 | if role in (Qt.DisplayRole, Qt.ToolTipRole): 51 | return name 52 | if role == Qt.EditRole: 53 | return f":{self.ressource_root}/{name}" 54 | if role == Qt.DecorationRole: 55 | return QIcon(f":{self.ressource_root}/{name}") 56 | 57 | return 58 | 59 | def rowCount(self, index=QModelIndex()): 60 | return len(self.icons) 61 | 62 | 63 | class ResourceBrowser(QDialog, Ui_ResourceBrowser): 64 | def __init__(self, parent=None): 65 | super().__init__(parent) 66 | self.setupUi(self) 67 | self.icon = None 68 | 69 | self.extensions = (".svg", ".png", ".jpg", ".gif", ".jpeg", ".bmp", ".ico") 70 | 71 | self.resource_model = RessourceModel(self.extensions, self) 72 | self.proxy_model = QSortFilterProxyModel() 73 | self.proxy_model.setFilterCaseSensitivity(Qt.CaseInsensitive) 74 | self.proxy_model.setSourceModel(self.resource_model) 75 | self.view.setModel(self.proxy_model) 76 | self.view.setContextMenuPolicy(Qt.CustomContextMenu) 77 | self.view.customContextMenuRequested.connect(self.on_context_menu) 78 | self.filterLineEdit.textChanged.connect(self.proxy_model.setFilterRegExp) 79 | self.view.clicked.connect(self.on_click) 80 | self.view.doubleClicked.connect(self.on_double_click) 81 | 82 | self.splitter.setStretchFactor(0, 0) 83 | self.splitter.setStretchFactor(1, 1) 84 | self.default_item = None 85 | self.ressourceTree.setColumnCount(2) 86 | self.build_resource_tree(self.ressourceTree.invisibleRootItem(), "") 87 | self.ressourceTree.setColumnHidden(1, True) 88 | self.ressourceTree.currentItemChanged.connect(self.on_ressource_changed) 89 | self.ressourceTree.expandItem(self.default_item) 90 | self.ressourceTree.setCurrentItem(self.default_item) 91 | 92 | def build_resource_tree(self, parent_item, parent_key): 93 | for key in QResource(parent_key).children(): 94 | full_key = f"{parent_key}/{key}" 95 | if QResource(full_key).isDir(): 96 | 97 | item = QTreeWidgetItem([key, full_key]) 98 | self.build_resource_tree(item, full_key) 99 | parent_item.addChild(item) 100 | if full_key == "/images/themes/default": 101 | self.default_item = item 102 | 103 | def on_ressource_changed(self, current_item, previous_item): 104 | self.resource_model.set_source(current_item.data(1, Qt.DisplayRole)) 105 | 106 | def set_icon(self, url): 107 | self.previewLabel.setPixmap(QIcon(url).pixmap(QSize(64, 64))) 108 | self.previewName.setText(url) 109 | self.icon = url 110 | self.okButton.setEnabled(True) 111 | 112 | def on_click(self, index): 113 | url = self.proxy_model.data(index, Qt.EditRole) 114 | self.set_icon(url) 115 | 116 | def on_double_click(self, index): 117 | self.on_click(index) 118 | self.accept() 119 | 120 | def on_context_menu(self, point): 121 | index = self.view.indexAt(point) 122 | if index.isValid(): 123 | menu = QMenu() 124 | menu.addAction( 125 | QIcon(":/images/themes/default/mActionEditCopy.svg"), 126 | self.tr("Copy resource path to clipboard"), 127 | ) 128 | menu.exec(self.view.mapToGlobal(point)) 129 | QGuiApplication.clipboard().setText( 130 | self.proxy_model.data(index, Qt.EditRole) 131 | ) 132 | -------------------------------------------------------------------------------- /resources.qrc: -------------------------------------------------------------------------------- 1 | 2 | 3 | icons/icon.svg 4 | icons/about.svg 5 | icons/wizard.svg 6 | icons/clear.svg 7 | icons/symbol-class.svg 8 | icons/symbol-enumerator.svg 9 | icons/symbol-key.svg 10 | icons/symbol-keyword.svg 11 | icons/symbol-method.svg 12 | icons/symbol-namespace.svg 13 | icons/symbol-variable.svg 14 | icons/folder.svg 15 | icons/file-1.svg 16 | 17 | 18 | -------------------------------------------------------------------------------- /settingsdialog.ui: -------------------------------------------------------------------------------- 1 | 2 | 3 | SettingsDialog 4 | 5 | 6 | 7 | 0 8 | 0 9 | 267 10 | 228 11 | 12 | 13 | 14 | Better Editor Settings 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | Hide old comment actions 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | true 33 | 34 | 35 | 36 | 37 | 38 | 39 | Max line length (black) 40 | 41 | 42 | 43 | 44 | 45 | 46 | 40 47 | 48 | 49 | 300 50 | 51 | 52 | 88 53 | 54 | 55 | 56 | 57 | 58 | 59 | Format on save 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | true 70 | 71 | 72 | 73 | 74 | 75 | 76 | Show ruler 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | true 87 | 88 | 89 | 90 | 91 | 92 | 93 | Ruler color 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 0 102 | 0 103 | 104 | 105 | 106 | 107 | 0 108 | 20 109 | 110 | 111 | 112 | 113 | 0 114 | 170 115 | 255 116 | 117 | 118 | 119 | 120 | 0 121 | 170 122 | 255 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | Folding indicator style 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | Autocomplete threshold 141 | 142 | 143 | 144 | 145 | 146 | 147 | 1 148 | 149 | 150 | 8 151 | 152 | 153 | 4 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | Qt::Vertical 163 | 164 | 165 | 166 | 20 167 | 40 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | Qt::Horizontal 178 | 179 | 180 | 181 | 40 182 | 20 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | Ok 191 | 192 | 193 | 194 | 195 | 196 | 197 | Restore default values 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | QgsColorButton 208 | QToolButton 209 |
qgscolorbutton.h
210 |
211 |
212 | 213 | 214 | 215 | okButton 216 | clicked() 217 | SettingsDialog 218 | accept() 219 | 220 | 221 | 96 222 | 200 223 | 224 | 225 | 133 226 | 110 227 | 228 | 229 | 230 | 231 |
232 | -------------------------------------------------------------------------------- /settingsdialogimpl.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from PyQt5.QtCore import pyqtSignal 4 | from PyQt5.QtGui import QColor, QIcon 5 | from PyQt5.QtWidgets import QDialog 6 | from PyQt5.Qsci import QsciScintilla 7 | 8 | from .settingsdialog import Ui_SettingsDialog 9 | 10 | 11 | class SettingsDialog(QDialog, Ui_SettingsDialog): 12 | 13 | settingsChanged = pyqtSignal() 14 | 15 | def __init__(self, settings, parent=None): 16 | super().__init__(parent) 17 | self.setupUi(self) 18 | 19 | self.resetting = False 20 | self.settings = settings 21 | self.setWindowIcon(QIcon(":/plugins/bettereditor/icons/icon.svg")) 22 | 23 | # Populate folding style combobox 24 | self.foldingStyleComboBox.addItem(self.tr("None"), QsciScintilla.NoFoldStyle) 25 | self.foldingStyleComboBox.addItem( 26 | self.tr("Plain"), QsciScintilla.PlainFoldStyle 27 | ) 28 | self.foldingStyleComboBox.addItem( 29 | self.tr("Circled"), QsciScintilla.CircledTreeFoldStyle 30 | ) 31 | self.foldingStyleComboBox.addItem( 32 | self.tr("Boxed"), QsciScintilla.BoxedTreeFoldStyle 33 | ) 34 | 35 | # Init dialog from settings 36 | self.hideCommentCheckBox.setChecked( 37 | self.settings.value("hide_old_comment_actions", True, bool) 38 | ) 39 | self.maxLineLengthSpinBox.setValue( 40 | self.settings.value("max_line_length", 88, int) 41 | ) 42 | self.formatOnSaveCheckBox.setChecked( 43 | self.settings.value("format_on_save", True, bool) 44 | ) 45 | self.autoCompleteSpinBox.setValue( 46 | self.settings.value("autocomplete_threshold", 4, int) 47 | ) 48 | 49 | self.rulerCheckBox.setChecked(self.settings.value("ruler_visible", True, bool)) 50 | self.rulerColorButton.setColor( 51 | self.settings.value("ruler_color", QColor("#00aaff"), QColor) 52 | ) 53 | 54 | self.foldingStyleComboBox.setCurrentIndex( 55 | self.foldingStyleComboBox.findData( 56 | self.settings.value( 57 | "folding_style", QsciScintilla.BoxedTreeFoldStyle, int 58 | ) 59 | ) 60 | ) 61 | 62 | # Connect signals 63 | self.hideCommentCheckBox.toggled.connect(self.on_hide_comment_actions_changed) 64 | self.maxLineLengthSpinBox.valueChanged.connect(self.on_max_length_changed) 65 | self.autoCompleteSpinBox.valueChanged.connect( 66 | self.on_autocomplete_threshold_changed 67 | ) 68 | self.formatOnSaveCheckBox.toggled.connect(self.on_format_on_save_changed) 69 | self.foldingStyleComboBox.currentIndexChanged.connect( 70 | self.on_folding_style_changed 71 | ) 72 | self.rulerCheckBox.toggled.connect(self.on_ruler_visible_changed) 73 | self.rulerColorButton.colorChanged.connect(self.on_ruler_color_changed) 74 | self.foldingStyleComboBox.currentIndexChanged.connect( 75 | self.on_folding_style_changed 76 | ) 77 | 78 | self.restoreButton.clicked.connect(self.restore_default_values) 79 | 80 | def on_max_length_changed(self, value): 81 | """ Called whenever the max line length changes """ 82 | self.settings.setValue("max_line_length", value) 83 | if not self.resetting: 84 | self.settingsChanged.emit() 85 | 86 | def on_autocomplete_threshold_changed(self, value): 87 | """ Called whenever the autocomplete threshold changes """ 88 | self.settings.setValue("autocomplete_threshold", value) 89 | if not self.resetting: 90 | self.settingsChanged.emit() 91 | 92 | def on_hide_comment_actions_changed(self, checked): 93 | """ Called whenever the hide comment actions state changes """ 94 | self.settings.setValue("hide_old_comment_actions", checked) 95 | if not self.resetting: 96 | self.settingsChanged.emit() 97 | 98 | def on_format_on_save_changed(self, checked): 99 | """ Called whenever the hide comment actions state changes """ 100 | self.settings.setValue("format_on_save", checked) 101 | if not self.resetting: 102 | self.settingsChanged.emit() 103 | 104 | def on_folding_style_changed(self): 105 | """ Called whenever the folding style changes """ 106 | self.settings.setValue("folding_style", self.foldingStyleComboBox.currentData()) 107 | if not self.resetting: 108 | self.settingsChanged.emit() 109 | 110 | def on_ruler_color_changed(self): 111 | """ Called whenever the ruler color changes """ 112 | self.settings.setValue("ruler_color", self.rulerColorButton.color()) 113 | if not self.resetting: 114 | self.settingsChanged.emit() 115 | 116 | def on_ruler_visible_changed(self, checked): 117 | """ Called whenever the ruler visible state changes """ 118 | self.settings.setValue("ruler_visible", checked) 119 | if not self.resetting: 120 | self.settingsChanged.emit() 121 | 122 | def restore_default_values(self): 123 | """ Restore the default value: BoxedTree folding indicator 124 | 88 character-long lines and hide comment/uncomment actions """ 125 | self.resetting = True 126 | self.hideCommentCheckBox.setChecked(True) 127 | self.maxLineLengthSpinBox.setValue(88) 128 | self.autoCompleteSpinBox.setValue(4) 129 | self.formatOnSaveCheckBox.setChecked(True) 130 | self.foldingStyleComboBox.setCurrentIndex(3) 131 | self.rulerCheckBox.setChecked(True) 132 | self.rulerColorButton.setColor(QColor("#00aaff")) 133 | self.resetting = False 134 | self.settingsChanged.emit() 135 | -------------------------------------------------------------------------------- /tests/test_monkeypatch.py: -------------------------------------------------------------------------------- 1 | from monkeypatch import Patcher, monkey, patch, unpatch, unpatched 2 | import monkeypatch 3 | import pytest 4 | 5 | 6 | def simple_classes(): 7 | class Foo: 8 | def __init__(self, stringvalue, boolvalue): 9 | self.stringvalue = stringvalue 10 | self.boolvalue = boolvalue 11 | 12 | def compute_string(self): 13 | return f"({self.stringvalue})" 14 | 15 | def compute_bool(self): 16 | return self.boolvalue 17 | 18 | class PatchedFoo: 19 | def compute_string(self): 20 | return unpatched().compute_string() + "_patched" 21 | 22 | def compute_bool(self): 23 | return not self.boolvalue 24 | 25 | def added_method(self): 26 | return 27 | 28 | return Foo, PatchedFoo 29 | 30 | 31 | def test_patch_class_after_construction(): 32 | 33 | Foo, PatchedFoo = simple_classes() 34 | f = Foo("val", True) 35 | 36 | assert f.compute_string() == "(val)" 37 | assert f.compute_bool() 38 | with pytest.raises(Exception): 39 | f.added_method() 40 | 41 | patch(Foo, PatchedFoo) 42 | 43 | assert f.compute_string() == "(val)_patched" 44 | assert not f.compute_bool() 45 | f.added_method() 46 | 47 | 48 | def test_patch_class_before_construction(): 49 | 50 | Foo, PatchedFoo = simple_classes() 51 | patch(Foo, PatchedFoo) 52 | 53 | f = Foo("val", True) 54 | 55 | assert f.compute_string() == "(val)_patched" 56 | assert not f.compute_bool() 57 | f.added_method() 58 | 59 | 60 | def test_unpatch(): 61 | 62 | Foo, PatchedFoo = simple_classes() 63 | f = Foo("val", True) 64 | 65 | patch(Foo, PatchedFoo) 66 | 67 | assert f.compute_string() == "(val)_patched" 68 | assert not f.compute_bool() 69 | f.added_method() 70 | 71 | unpatch(Foo) 72 | 73 | assert f.compute_string() == "(val)" 74 | assert f.compute_bool() 75 | with pytest.raises(Exception): 76 | f.added_method() 77 | 78 | 79 | def test_multiple_call(): 80 | 81 | Foo, PatchedFoo = simple_classes() 82 | f = Foo("val", True) 83 | 84 | patch(Foo, PatchedFoo) 85 | patch(Foo, PatchedFoo) 86 | patch(Foo, PatchedFoo) 87 | 88 | assert f.compute_string() == "(val)_patched" 89 | assert not f.compute_bool() 90 | f.added_method() 91 | 92 | unpatch(Foo) 93 | 94 | assert f.compute_string() == "(val)" 95 | assert f.compute_bool() 96 | with pytest.raises(Exception): 97 | f.added_method() 98 | 99 | unpatch(Foo) 100 | assert f.compute_string() == "(val)" 101 | assert f.compute_bool() 102 | with pytest.raises(Exception): 103 | f.added_method() 104 | 105 | 106 | def test_force_repatch(): 107 | 108 | Foo, PatchedFoo = simple_classes() 109 | 110 | class OtherPatch: 111 | def compute_string(self): 112 | return "second" 113 | 114 | f = Foo("val", True) 115 | 116 | patch(Foo, PatchedFoo) 117 | assert f.compute_string() == "(val)_patched" 118 | 119 | patch(Foo, OtherPatch) 120 | assert f.compute_string() == "(val)_patched" 121 | patch(Foo, OtherPatch, True) 122 | assert f.compute_string() == "second" 123 | 124 | unpatch(Foo) 125 | 126 | assert f.compute_string() == "(val)" 127 | 128 | 129 | def test_patch_instance(): 130 | 131 | Foo, PatchedFoo = simple_classes() 132 | f = Foo("val", True) 133 | f2 = Foo("val", True) 134 | 135 | patch(f, PatchedFoo) 136 | 137 | assert f.compute_string() == "(val)_patched" 138 | assert not f.compute_bool() 139 | f.added_method() 140 | 141 | assert f2.compute_string() == "(val)" 142 | assert f2.compute_bool() 143 | 144 | with pytest.raises(Exception): 145 | f2.added_method() 146 | 147 | unpatch(f) 148 | 149 | assert f.compute_string() == "(val)" 150 | assert f.compute_bool() 151 | 152 | with pytest.raises(Exception): 153 | f.added_method() 154 | 155 | 156 | def test_context_manager(): 157 | 158 | Foo, PatchedFoo = simple_classes() 159 | f = Foo("val", True) 160 | f2 = Foo("val", True) 161 | 162 | with monkey(Foo, PatchedFoo): 163 | assert f.compute_string() == "(val)_patched" 164 | assert not f.compute_bool() 165 | f.added_method() 166 | 167 | assert f.compute_string() == "(val)" 168 | assert f.compute_bool() 169 | with pytest.raises(Exception): 170 | f.added_method() 171 | 172 | with monkey(f2, PatchedFoo): 173 | assert f2.compute_string() == "(val)_patched" 174 | assert not f2.compute_bool() 175 | f2.added_method() 176 | 177 | assert f.compute_string() == "(val)" 178 | assert f.compute_bool() 179 | with pytest.raises(Exception): 180 | f.added_method() 181 | 182 | assert f2.compute_string() == "(val)" 183 | assert f2.compute_bool() 184 | with pytest.raises(Exception): 185 | f2.added_method() 186 | 187 | 188 | def test_decorator(): 189 | Foo, PatchedFoo = simple_classes() 190 | 191 | f = Foo("val", True) 192 | 193 | @monkeypatch.decorator(Foo, PatchedFoo) 194 | def check_foo(f): 195 | assert f.compute_string() == "(val)_patched" 196 | assert not f.compute_bool() 197 | f.added_method() 198 | 199 | check_foo(f) 200 | 201 | assert f.compute_string() == "(val)" 202 | assert f.compute_bool() 203 | with pytest.raises(Exception): 204 | f.added_method() 205 | 206 | 207 | def test_patcher_delay_patch(): 208 | Foo, PatchedFoo = simple_classes() 209 | f = Foo("Ok", True) 210 | 211 | patcher = Patcher(Foo, PatchedFoo, patch_now=False) 212 | 213 | assert f.compute_string() == "(Ok)" 214 | assert f.compute_bool() 215 | with pytest.raises(Exception): 216 | f.added_method() 217 | patcher.patch() 218 | 219 | assert f.compute_string() == "(Ok)_patched" 220 | assert not f.compute_bool() 221 | f.added_method() 222 | 223 | 224 | def test_patcher_no_unpatch(): 225 | Foo, PatchedFoo = simple_classes() 226 | f = Foo("Ko", True) 227 | 228 | def func1(): 229 | Patcher(f, PatchedFoo) 230 | 231 | def func2(): 232 | Patcher(f, PatchedFoo, unpatch_on_delete=False) 233 | 234 | func1() 235 | assert f.compute_string() == "(Ko)" 236 | assert f.compute_bool() 237 | with pytest.raises(Exception): 238 | f.added_method() 239 | 240 | func2() 241 | assert f.compute_string() == "(Ko)_patched" 242 | assert not f.compute_bool() 243 | f.added_method() 244 | 245 | monkeypatch.unpatch(f) 246 | assert f.compute_string() == "(Ko)" 247 | assert f.compute_bool() 248 | with pytest.raises(Exception): 249 | f.added_method() 250 | 251 | --------------------------------------------------------------------------------