File: console_sci.py

package info (click to toggle)
qgis 3.40.13%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 1,185,160 kB
  • sloc: cpp: 1,615,781; python: 372,865; xml: 23,474; sh: 3,761; perl: 3,664; ansic: 2,829; sql: 2,137; yacc: 1,068; lex: 577; javascript: 540; lisp: 411; makefile: 155
file content (495 lines) | stat: -rw-r--r-- 17,319 bytes parent folder | download | duplicates (8)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
"""
/***************************************************************************
Python Console for QGIS
                             -------------------
begin                : 2012-09-10
copyright            : (C) 2012 by Salvatore Larosa
email                : lrssvtml (at) gmail (dot) com
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
Some portions of code were taken from https://code.google.com/p/pydee/
"""

from __future__ import annotations

import code
import os
import re
import sys
import traceback
from typing import Optional, TYPE_CHECKING
from pathlib import Path
from tempfile import NamedTemporaryFile

from qgis.PyQt.Qsci import QsciScintilla
from qgis.PyQt.QtCore import Qt, QCoreApplication
from qgis.PyQt.QtGui import QKeySequence, QFontMetrics, QClipboard
from qgis.PyQt.QtWidgets import QShortcut, QApplication
from qgis.core import QgsApplication, Qgis, QgsProcessingUtils
from qgis.gui import QgsCodeEditorPython, QgsCodeEditor, QgsCodeInterpreter

from .process_wrapper import ProcessWrapper

if TYPE_CHECKING:
    from .console import PythonConsoleWidget

_init_statements = [
    # Python
    "import sys",
    "import os",
    "from pathlib import Path",
    "import re",
    "import math",
    # QGIS
    "from qgis.core import *",
    "from qgis.gui import *",
    "from qgis.analysis import *",
    # # 3D might not be compiled in
    """
try:
    from qgis._3d import *
except ModuleNotFoundError:
    pass
""",
    "import processing",
    "import qgis.utils",
    "from qgis.utils import iface",
    # Qt
    "from qgis.PyQt.QtCore import *",
    "from qgis.PyQt.QtGui import *",
    "from qgis.PyQt.QtWidgets import *",
    "from qgis.PyQt.QtNetwork import *",
    "from qgis.PyQt.QtXml import *",
    r"""
def __parse_object(object=None):
    if not object:
        return None
    import inspect
    if inspect.isclass(object):
        str_class = str(object)
    else:
        str_class = str(object.__class__)

    qgis_api_pattern = r".*qgis\._(\w+)\.(\w+).*"
    match = re.match(qgis_api_pattern, str_class)
    if match:
        module = match[1]
        obj = match[2]
        return 'qgis', module, obj

    pyqt_pattern = r".*PyQt5\.(\w+)\.(\w+).*"
    match = re.match(pyqt_pattern, str_class)
    if match:
        module = match[1]
        obj = match[2]
        return 'qt', module, obj
""",
    r"""
def _api(object=None):
    '''
    Link to the QGIS API documentation for the given object.
    If no object is given, the main API page is opened.
    If the object is not part of the QGIS API but is a Qt object the Qt documentation is opened.
    '''
    import webbrowser
    api = __parse_object(object)

    version = '' if 'master' in Qgis.QGIS_VERSION.lower() else re.findall(r'^\d.[0-9]*', Qgis.QGIS_VERSION)[0]

    if not api:
        webbrowser.open(f"https://qgis.org/api/{version}")
    elif api[0] == 'qgis':
        webbrowser.open(f"https://api.qgis.org/api/{version}/class{api[2]}.html")
    elif api[0] == 'qt':
        qtversion = '.'.join(qVersion().split(".")[:2])
        webbrowser.open(f"https://doc.qt.io/qt-{qtversion}/{api[2].lower()}.html")
""",
    r"""
def _pyqgis(object=None):
    '''
    Link to the PyQGIS API documentation for the given object.
    If no object is given, the main PyQGIS API page is opened.
    If the object is not part of the QGIS API but is a Qt object the Qt documentation is opened.
    '''
    import webbrowser
    api = __parse_object(object)

    version = 'master' if 'master' in Qgis.QGIS_VERSION.lower() else re.findall(r'^\d.[0-9]*', Qgis.QGIS_VERSION)[0]

    if not api:
        webbrowser.open(f"https://qgis.org/pyqgis/{version}")
    elif api[0] == 'qgis':
        webbrowser.open(f"https://qgis.org/pyqgis/{version}/{api[1]}/{api[2]}.html")
    elif api[0] == 'qt':
        qtversion = '.'.join(qVersion().split(".")[:2])
        webbrowser.open(f"https://doc.qt.io/qt-{qtversion}/{api[2].lower()}.html")
""",
]


# States of the interpreter
PS1 = 0  # Writing a new command
PS2 = 1  # Continuation of a multi-line command
SUBPROCESS = 2  # Sending input to a subprocess


class PythonInterpreter(QgsCodeInterpreter, code.InteractiveInterpreter):

    def __init__(self, shell: ShellScintilla):
        super(QgsCodeInterpreter, self).__init__()
        code.InteractiveInterpreter.__init__(self, locals=None)

        self.shell: ShellScintilla = shell
        self.sub_process = None
        self.buffer = []

        for statement in _init_statements:
            try:
                self.runsource(statement)
            except ModuleNotFoundError:
                pass

    def execCommandImpl(self, cmd, show_input=True):

        # Child process running, input should be sent to it
        if self.currentState() == SUBPROCESS:
            sys.stdout.write(cmd + "\n")
            self.sub_process.write(cmd)
            return 0

        if show_input:
            self.writeCMD(cmd)

        if self.currentState() == PS1:

            # This line makes single line commands with leading spaces work
            cmd = cmd.strip()

            # User entered: varname = !cmd
            # Run the command and assign the output to varname
            # Mimics IPython's behavior
            assignment_pattern = r"(\w+)\s*=\s*!(.+)"
            match = re.match(assignment_pattern, cmd)
            if match:
                varname = match[1]
                cmd = match[2]
                # Run the command in non-interactive mode
                self.sub_process = ProcessWrapper(cmd, interactive=False)
                # Concatenate stdout and stderr
                res = (self.sub_process.stdout + self.sub_process.stderr).strip()

                # Use a temporary file to communicate the result to the inner interpreter
                tmp = Path(NamedTemporaryFile(delete=False).name)
                tmp.write_text(res, encoding="utf-8")
                self.runsource(
                    f'{varname} = Path("{tmp}").read_text(encoding="utf-8").split("\\n")'
                )
                tmp.unlink()
                self.sub_process = None
                return 0

            # User entered: !cmd
            # Run the command and stream the output to the console
            # While the process is running, the console is in state 2 meaning
            # that all input is sent to the child process
            # Mimics IPython's behavior
            elif cmd.startswith("!"):
                cmd = cmd[1:]
                self.sub_process = ProcessWrapper(cmd)
                self.sub_process.finished.connect(self.processFinished)
                return 0

        res = 0

        import webbrowser

        version = (
            "master"
            if "master" in Qgis.QGIS_VERSION.lower()
            else re.findall(r"^\d.[0-9]*", Qgis.QGIS_VERSION)[0]
        )

        if cmd == "?":
            self.shell.console_widget.shell_output.insertHelp()
        elif cmd == "_pyqgis":
            webbrowser.open(f"https://qgis.org/pyqgis/{version}")
        elif cmd == "_api":
            webbrowser.open(
                "https://qgis.org/api/{}".format("" if version == "master" else version)
            )
        elif cmd == "_cookbook":
            webbrowser.open(
                "https://docs.qgis.org/{}/en/docs/pyqgis_developer_cookbook/".format(
                    "testing" if version == "master" else version
                )
            )
        else:
            self.buffer.append(cmd)
            src = "\n".join(self.buffer)
            res = self.runsource(src)
            if res == 0:
                self.buffer = []

        return res

    def writeCMD(self, txt):
        if sys.stdout:
            sys.stdout.fire_keyboard_interrupt = False
        if len(txt) > 0:
            sys.stdout.write(f"{self.promptForState()} {txt}\n")

    def runsource(self, source, filename="<input>", symbol="single"):
        if sys.stdout:
            sys.stdout.fire_keyboard_interrupt = False

        hook = sys.excepthook
        try:

            def excepthook(etype, value, tb):
                self.write("".join(traceback.format_exception(etype, value, tb)))

            sys.excepthook = excepthook

            return super().runsource(source, filename, symbol)
        finally:
            sys.excepthook = hook

    def currentState(self):
        if self.sub_process:
            return SUBPROCESS
        return super().currentState()

    def promptForState(self, state=-1):
        if state == -1:
            state = self.currentState()
        if state == SUBPROCESS:
            return " : "
        elif state == PS2:
            return "..."
        else:
            return ">>>"

    def processFinished(self, errorcode):
        self.sub_process = None
        self.shell.updatePrompt()


class ShellScintilla(QgsCodeEditorPython):

    def __init__(self, console_widget: PythonConsoleWidget):
        # We set the ImmediatelyUpdateHistory flag here, as users can easily
        # crash QGIS by entering a Python command, and we don't want the
        # history leading to the crash lost...
        super().__init__(
            console_widget,
            [],
            QgsCodeEditor.Mode.CommandInput,
            flags=QgsCodeEditor.Flags(
                QgsCodeEditor.Flag.CodeFolding
                | QgsCodeEditor.Flag.ImmediatelyUpdateHistory
            ),
        )

        self.console_widget: PythonConsoleWidget = console_widget
        self._interpreter = PythonInterpreter(shell=self)
        self.setInterpreter(self._interpreter)

        self.opening = ["(", "{", "[", "'", '"']
        self.closing = [")", "}", "]", "'", '"']

        self.setHistoryFilePath(
            os.path.join(QgsApplication.qgisSettingsDirPath(), "console_history.txt")
        )

        self.refreshSettingsShell()

        # Disable command key
        ctrl, shift = self.SCMOD_CTRL << 16, self.SCMOD_SHIFT << 16
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("L") + ctrl)
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("T") + ctrl)
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("D") + ctrl)
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Z") + ctrl)
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Y") + ctrl)
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("L") + ctrl + shift)

        # New QShortcut = ctrl+space/ctrl+alt+space for Autocomplete
        self.newShortcutCSS = QShortcut(
            QKeySequence(Qt.Modifier.CTRL | Qt.Modifier.SHIFT | Qt.Key.Key_Space), self
        )
        self.newShortcutCAS = QShortcut(
            QKeySequence(Qt.Modifier.CTRL | Qt.Modifier.ALT | Qt.Key.Key_Space), self
        )
        self.newShortcutCSS.setContext(Qt.ShortcutContext.WidgetShortcut)
        self.newShortcutCAS.setContext(Qt.ShortcutContext.WidgetShortcut)
        self.newShortcutCAS.activated.connect(self.autoComplete)
        self.newShortcutCSS.activated.connect(self.showHistory)

        self.sessionHistoryCleared.connect(self.on_session_history_cleared)
        self.persistentHistoryCleared.connect(self.on_persistent_history_cleared)

    def _setMinimumHeight(self):
        font = self.lexer().defaultFont(0)
        fm = QFontMetrics(font)

        self.setMinimumHeight(fm.height() + 10)

    def refreshSettingsShell(self):
        # Set Python lexer
        self.initializeLexer()

        # Sets minimum height for input area based of font metric
        self._setMinimumHeight()

    def on_session_history_cleared(self):
        msgText = QCoreApplication.translate(
            "PythonConsole", "Session history cleared successfully."
        )
        self.console_widget.callWidgetMessageBar(msgText)

    def on_persistent_history_cleared(self):
        msgText = QCoreApplication.translate(
            "PythonConsole", "History cleared successfully."
        )
        self.console_widget.callWidgetMessageBar(msgText)

    def keyPressEvent(self, e):

        if (
            e.modifiers()
            & (Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.MetaModifier)
            and e.key() == Qt.Key.Key_C
            and not self.hasSelectedText()
        ):
            if self._interpreter.sub_process:
                sys.stderr.write("Terminate child process\n")
                self._interpreter.sub_process.kill()
                self._interpreter.sub_process = None
                self.updatePrompt()
            return

        # update the live history
        self.updateSoftHistory()
        super().keyPressEvent(e)
        self.updatePrompt()

    def mousePressEvent(self, e):
        """
        Re-implemented to handle the mouse press event.
        e: the mouse press event (QMouseEvent)
        """
        self.setFocus()
        if e.button() == Qt.MouseButton.MiddleButton:
            stringSel = QApplication.clipboard().text(QClipboard.Mode.Selection)
            if not self.isCursorOnLastLine():
                self.moveCursorToEnd()
            self.insertFromDropPaste(stringSel)
            e.accept()
        else:
            QgsCodeEditorPython.mousePressEvent(self, e)

    def paste(self):
        """
        Method to display data from the clipboard.

        XXX: It should reimplement the virtual QScintilla.paste method,
        but it seems not used by QScintilla code.
        """
        stringPaste = QApplication.clipboard().text()
        if self.isCursorOnLastLine():
            if self.hasSelectedText():
                self.removeSelectedText()
        else:
            self.moveCursorToEnd()
        self.insertFromDropPaste(stringPaste)

    # Drag and drop
    def dropEvent(self, e):
        if e.mimeData().hasText():
            stringDrag = e.mimeData().text()
            self.insertFromDropPaste(stringDrag)
            self.setFocus()
            e.setDropAction(Qt.DropAction.CopyAction)
            e.accept()
        else:
            QgsCodeEditorPython.dropEvent(self, e)

    def insertFromDropPaste(self, textDP):
        pasteList = textDP.splitlines()
        if pasteList:
            for line in pasteList[:-1]:
                cleanLine = line.replace(">>> ", "").replace("... ", "")
                self.insert(cleanLine)
                self.moveCursorToEnd()
                self.runCommand(self.text())
            if pasteList[-1] != "":
                line = pasteList[-1]
                cleanLine = line.replace(">>> ", "").replace("... ", "")
                curpos = self.getCursorPosition()
                self.insert(cleanLine)
                self.setCursorPosition(curpos[0], curpos[1] + len(cleanLine))

    def insertTextFromFile(self, listOpenFile):
        for line in listOpenFile[:-1]:
            self.append(line)
            self.moveCursorToEnd()
            self.SendScintilla(QsciScintilla.SCI_DELETEBACK)
            self.runCommand(self.text())
        self.append(listOpenFile[-1])
        self.moveCursorToEnd()
        self.SendScintilla(QsciScintilla.SCI_DELETEBACK)

    def entered(self):
        self.moveCursorToEnd()
        self.runCommand(self.text())
        self.setFocus()
        self.moveCursorToEnd()

    def write(self, txt):
        if sys.stderr:
            sys.stderr.write(txt)

    def runFile(self, filename, override_file_name: str | None = None):
        filename = filename.replace("\\", "/")
        dirname = os.path.dirname(filename)

        # Append the directory of the file to the path and set __file__ to the filename
        self._interpreter.execCommandImpl(
            "sys.path.append({})".format(
                QgsProcessingUtils.stringToPythonLiteral(dirname)
            ),
            False,
        )
        self._interpreter.execCommandImpl(
            f"__file__ = {QgsProcessingUtils.stringToPythonLiteral(filename)}",
            False,
        )

        try:
            # Run the file

            self.runCommand(
                "exec(compile(Path({}).read_text(), {}, 'exec'))".format(
                    QgsProcessingUtils.stringToPythonLiteral(filename),
                    QgsProcessingUtils.stringToPythonLiteral(
                        override_file_name or filename
                    ),
                ),
                skipHistory=True,
            )
        finally:
            # Remove the directory from the path and delete the __file__ variable
            self._interpreter.execCommandImpl("del __file__", False)
            self._interpreter.execCommandImpl(
                "sys.path.remove({})".format(
                    QgsProcessingUtils.stringToPythonLiteral(dirname)
                ),
                False,
            )